정신과 시간의 방

전체 글 306

카테고리 설명
게임 프로그래머가 되기 위한 청춘의 기록
  • 문제 풀이#include using namespace std;int main(){ int diceInput[3] = {}; int valueCount[7] = {}; int result = 0; int maxIndex = 0; for (int i = 0; i > diceInput[i]; } for (int i = 0; i  메모중복 되는 숫자를 찾기 위해 valueCount를 사용했다. 이때 diceInput[i] 에 해당하는 주사위 값 자체를 인덱스로 사용해서 입력받은 값을 쉽게 비교할 수 있도록 만들었다.

  • 문제 풀이#include using namespace std;int main(){ int a = 0, b = 0, bCopy = 0, result = 0; int B[3] = {}; cin >> a >> b; bCopy = b; int index = 0; while (bCopy) { B[index] = bCopy % 10; bCopy /= 10; index++; } for (int i = 0; i  메모b를 각 자리수별로 배열에 저장해서 순차적으로 a와 곱해주는 방식으로 풀었다.

  • 문제 풀이#include #include using namespace std;int main() { int n = 0; cin >> n; queue st; string str; for (int i = 0; i > str; if (str == "push") { int input = 0; cin >> input; st.push(input); } else if (str == "pop") { if (false == st.empty()) { cout

  • 문제 풀이#include #include using namespace std;int main() { int n = 0; cin >> n; stack st; string str; for (int i = 0; i > str; if (str == "push") { int input = 0; cin >> input; st.push(input); } else if (str == "pop") { if (false == st.empty()) { cout   메모front, pop 함수를 실행하기 전에 empty 함수로 스택 내부가 비어있는지 확인하는 것을 주의해야 한다.

  • 문제 풀이#include using namespace std; int factorial(int t) { // 초기값이 0이면 곱한 결과가 0이 되므로 반드시 1로 초기화 해주어야 한다. int result = 1; // 해당 값부터 하나씩 줄여가며 곱해간다. for (int i = t; i > 0; i--) { result *= i; } return result;} int main() { int n, k; cin >> n >> k; int result = factorial(n) / (factorial(k) * factorial(n - k)); cout  메모이항 계수를 구하기 위해 팩토리얼을 사용했다.팩토리얼 공식은 facto..

  • 문제 풀이#include #include #include using namespace std;int main() { std::ios::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); while (true) { string str = ""; getline(cin, str); if (str == ".") { break; } int flag = 0; stack s; int strLength = str.length(); for (int i = 0; i  다시 풀이 (24-11-10)#include #include #include using namespace std;int main(){ ios::sync_with_stdi..

  • 문제 풀이#include using namespace std;int main() { std::ios::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); int n = 0, m = 0, totalSum = 0, resultMax = 0; int arr[101] = {}; cin >> n >> m; for (int i = 0; i > arr[i]; } for (int i = 0; i resultMax) { resultMax = totalSum; } } } } cout   메모이 문제 역시 브루트 포스 문제에 해당한다. 모든 경우의 수를 다 따져보는데다 3중 for문을 사용하는 경우가 거의 없어서 성능적으로 문제가 되지..

  • 문제 풀이#include #include #include #include using namespace std;bool compare(string str1, string str2){ // 길이가 같은 경우 사전 순으로 정렬하고 if (str1.size() == str2.size()) { return str1 > n; vector str; string input; for (int i = 0; i > input; str.push_back(input); } sort(str.begin(), str.end(), compare); str.erase(unique(str.begin(), str.end()), str.end()); vector::iterator iter; for (iter = str.begin(); i..

작성일
2024. 7. 23. 15:48
작성자
risehyun
  • 문제

 

  • 풀이
#include <iostream>

using namespace std;

int main()
{
	int diceInput[3] = {};
	int valueCount[7] = {};
	int result = 0;
	int maxIndex = 0;

	for (int i = 0; i < 3; i++)
	{
		cin >> diceInput[i];
	}

	for (int i = 0; i < 3; i++)
	{
		valueCount[diceInput[i]]++;
	}

	for (int i = 1; i < 7; i++)
	{
		// case 1. 같은 눈이 3개가 나오는 경우
		if (valueCount[i] == 3)
		{
			result = 10000 + (i * 1000);
			break;
		}
		// case 2. 같은 눈이 2개만 나오는 경우
		else if (valueCount[i] == 2)
		{
			result = 1000 + (i * 100);
			break;
		}
		// case 3. 모두 다른 눈이 나오는 경우
		else
		{
			// 그 중 가장 큰 눈을 골라냄
			// 반복문을 돌다보면 maxIndex에 가장 마지막으로 1로 카운팅 된 값이 
			// 들어가게 되므로 가장 큰 눈의 index이 max값이 됨
			if (valueCount[i] == 1)
			{
				maxIndex = i;
			}

			result = maxIndex * 100;
		}

	}

	cout << result;

	return 0;
}

 

  • 메모
    중복 되는 숫자를 찾기 위해 valueCount를 사용했다.
    이때 diceInput[i] 에 해당하는 주사위 값 자체를 인덱스로 사용해서 입력받은 값을 쉽게 비교할 수 있도록 만들었다.
카테고리
작성일
2024. 7. 21. 21:49
작성자
risehyun
  • 문제

 

  • 풀이
#include <iostream>

using namespace std;
int main()
{
	int a = 0, b = 0, bCopy = 0, result = 0;
	int B[3] = {};

	cin >> a >> b;

	bCopy = b;

	int index = 0;

	while (bCopy)
	{
		B[index] = bCopy % 10;
		bCopy /= 10;
		index++;
	}

	for (int i = 0; i < 3; i++)
	{
		result = B[i] * a;

		cout << result << '\n';
	}

	result = a * b;

	cout << result;


	return 0;
}

 

  • 메모
    b를 각 자리수별로 배열에 저장해서 순차적으로 a와 곱해주는 방식으로 풀었다.

카테고리
작성일
2024. 7. 16. 23:12
작성자
risehyun
  • 문제

 

  • 풀이
#include <iostream>
#include <queue>

using namespace std;

int main() 
{
	int n = 0;

	cin >> n;

	queue<int> st;
	string str;

	for (int i = 0; i < n; i++)
	{
		cin >> str;

		if (str == "push")
		{
			int input = 0;

			cin >> input;

			st.push(input);
		}
		else if (str == "pop")
		{
			if (false == st.empty())
			{
				cout << st.front() << '\n';
				st.pop();
			}
			else
			{
				cout << "-1" << '\n';
			}
		}
		else if (str == "size")
		{
			cout << st.size() << '\n';
		}
		else if (str == "empty")
		{
			if (true == st.empty())
			{
				cout << "1" << '\n';
			}
			else
			{
				cout << "0" << '\n';
			}
		}
		else if (str == "front")
		{
			if (false == st.empty())
			{
				cout << st.front() << '\n';
			}
			else
			{
				cout << "-1" << '\n';
			}
		}
		else if (str == "back")
		{
			if (false == st.empty())
			{
				cout << st.back() << '\n';
			}
			else
			{
				cout << "-1" << '\n';
			}
		}
	}

	return 0;
}

'코딩테스트' 카테고리의 다른 글

[백준/10811번/C++] 바구니 뒤집기  (0) 2024.07.25
[백준/2588번/C++] 곱셈  (0) 2024.07.21
★ [백준/11050번/C++] 이항 계수 1  (0) 2024.07.12
[백준/2798번/C++] 블랙잭  (0) 2024.07.08
[백준/1181번/C++] 단어 정렬  (0) 2024.07.03
작성일
2024. 7. 16. 16:23
작성자
risehyun
  • 문제

 

  • 풀이
#include <iostream>
#include <stack>

using namespace std;

int main() 
{
	int n = 0;

	cin >> n;

	stack<int> st;
	string str;

	for (int i = 0; i < n; i++)
	{
		cin >> str;

		if (str == "push")
		{
			int input = 0;

			cin >> input;

			st.push(input);
		}
		else if (str == "pop")
		{
			if (false == st.empty())
			{
				cout << st.top() << '\n';
				st.pop();
			}
			else
			{
				cout << "-1" << '\n';
			}
		}
		else if (str == "size")
		{
			cout << st.size() << '\n';
		}
		else if (str == "empty")
		{
			if (true == st.empty())
			{
				cout << "1" << '\n';
			}
			else
			{
				cout << "0" << '\n';
			}
		}
		else if (str == "top")
		{
			if (false == st.empty())
			{
				cout << st.top() << '\n';
			}
			else
			{
				cout << "-1" << '\n';
			}
		}
	}

	return 0;
}

 

 

  • 메모

front, pop 함수를 실행하기 전에 empty 함수로 스택 내부가 비어있는지 확인하는 것을 주의해야 한다.

카테고리
작성일
2024. 7. 12. 14:27
작성자
risehyun
  • 문제

 

  • 풀이
#include <iostream>
using namespace std;
 
int factorial(int t) 
{
	// 초기값이 0이면 곱한 결과가 0이 되므로 반드시 1로 초기화 해주어야 한다.
    int result = 1;
    
    // 해당 값부터 하나씩 줄여가며 곱해간다.
    for (int i = t; i > 0; i--) 
    {
        result *= i;
    }
    return result;
}
 
int main() 
{
    int n, k;
    cin >> n >> k;
 
    int result = factorial(n) / (factorial(k) * factorial(n - k));
 
    cout << result;
}

 

  • 메모
    이항 계수를 구하기 위해 팩토리얼을 사용했다.
    팩토리얼 공식은 factorial(n) / (factorial(k) * factorial(n - k))이고, 아래의 함수로 구현할 수 있다.
int factorial(int t) 
{
    // 초기값이 0이면 곱한 결과가 0이 되므로 반드시 1로 초기화 해주어야 한다.
    int result = 1;
    
    // 해당 값부터 하나씩 줄여가며 곱해간다.
    for (int i = t; i > 0; i--) 
    {
        result *= i;
    }
    return result;
}

'코딩테스트' 카테고리의 다른 글

[백준/2588번/C++] 곱셈  (0) 2024.07.21
☆ [백준/10847번/C++] 큐  (0) 2024.07.16
[백준/2798번/C++] 블랙잭  (0) 2024.07.08
[백준/1181번/C++] 단어 정렬  (0) 2024.07.03
[백준/10814번/C++] 나이순 정렬  (0) 2024.06.30
작성일
2024. 7. 10. 17:20
작성자
risehyun
  • 문제

 

  • 풀이
#include <iostream>
#include <stack>
#include <string>

using namespace std;

int main() 
{
	std::ios::sync_with_stdio(false);
	std::cin.tie(NULL);
	std::cout.tie(NULL);

	while (true)
	{
		string str = "";
		getline(cin, str);

		if (str == ".")
		{
			break;
		}

		int flag = 0;
		stack<char> s;

		int strLength = str.length();

		for (int i = 0; i < strLength; i++)
		{
			if ((str[i] == '(') || (str[i] == '['))
			{
				s.push(str[i]);
			}
			else if (str[i] == ')') 
			{
				if (!s.empty() && s.top() == '(') 
				{
					s.pop();
				}
				else {
					flag = 1;
					break;
				}
			}
			else if (str[i] == ']') 
			{
				if (!s.empty() && s.top() == '[') 
				{
					s.pop();
				}
				else 
				{
					flag = 1;
					break;
				}
			}
		}

		if (flag == 0 && s.empty()) 
		{
			cout << "yes" << endl;
		}
		else {
			cout << "no" << endl;
		}
	}

	return 0;
}

 

  • 다시 풀이 (24-11-10)
#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main()
{

    ios::sync_with_stdio(false);
    cin.tie(0);

    while (true)
    {
        int flag = 0;
        stack<char> s;

        string input = "";
        getline(cin, input);  // 전체 입력을 받기

        if (input == ".")  // 입력이 온점(.)만 있을 경우 종료
        {
            break;
        }

        // 입력 문자열에서 괄호에 대한 처리를 시작
        for (char c : input)
        {
            if (c == ')')
            {
                if (s.empty() || s.top() != '(') // 짝이 맞는 열린괄호가 없다면 flag = 1
                {
                    flag = 1;
                    break;
                }
                else
                {
                    s.pop();
                }
            }
            else if (c == ']')
            {
                if (s.empty() || s.top() != '[')
                {
                    flag = 1;
                    break;
                }
                else
                {
                    s.pop();
                }
            }
            else if (c == '(' || c == '[')  // 열린 괄호일 경우에만 push
            {
                s.push(c);
            }
        }

        // 스택이 비어있지 않으면 짝이 맞지 않으므로 flag = 1
        if (!s.empty())
        {
            flag = 1;
        }

        if (flag == 1)
        {
            cout << "no" << '\n';
        }
        else
        {
            cout << "yes" << '\n';
        }
    }

    return 0;
}

 

  • 메모
    지난번에 풀었던 괄호 문제와 동일한 문제인데 괄호의 종류가 2가지라는 차이가 있다.
    stack을 사용해서 여는 괄호일 때만 push를 해서 체크하고, 닫는 괄호일 때 안을 조사해서 안에 push된 것이 없거나 push는 되어 있으나 해당하는 괄호의 여는 괄호가 아닌 경우에는 flag를 1로 체크해서 틀린 경우를 판별한다.

    https://risehyun.tistory.com/422
 

[백준/9012번/C++] 괄호

문제 풀이#include #include #includeusing namespace std;int main() { int cnt = 0; int flag = 0; // 중간에 스택이 비어있는 경우를 체크하기 위한 변수 string str; cin >> cnt; for (int i = 0; i buffer; cin >> str; int strLength = str.l

risehyun.tistory.com

 

카테고리
작성일
2024. 7. 8. 21:38
작성자
risehyun
  • 문제

 

  • 풀이
#include <iostream>

using namespace std;

int main() 
{
	std::ios::sync_with_stdio(false);
	std::cin.tie(NULL);
	std::cout.tie(NULL);

	int n = 0, m = 0, totalSum = 0, resultMax = 0;

	int arr[101] = {};

	cin >> n >> m;

	for (int i = 0; i < n; i++)
	{
		cin >> arr[i];
	}

	for (int i = 0; i < n - 2; i++)
	{
		for (int j = i + 1; j < n - 1; j++)
		{
			for (int k = j + 1; k < n; k++)
			{
				totalSum = arr[i] + arr[j] + arr[k];

				if (totalSum <= m && totalSum > resultMax)
				{
					resultMax = totalSum;
				}
			}
		}
	}

	cout << resultMax;

	return 0;
}

 

 

  • 메모
    이 문제 역시 브루트 포스 문제에 해당한다. 모든 경우의 수를 다 따져보는데다 3중 for문을 사용하는 경우가 거의 없어서 성능적으로 문제가 되지 않을까 생각했지만 다행히도 n이 3 ~ 100 사이의 작은 값이 되기 때문에 시간 복잡도는 O(n^3)이여도 빠르게 연산된다.

    3중 for문에서 i, j, k가 오름차순을 유지하게끔 범위 설정을 해주는 것이 중요하다.
    이를 위해서 2가지 조건을 만족해야 하는데,

    1. i -> j -> k의 순서를 유지하기 위해서 다음에 뽑을 숫자는 이전의 숫자 이후의 값으로 뽑아야 한다.
    2. 앞의 숫자가 범위 끝 부분에 근접하면 뒤에 올 숫자를 뽑을 수 없게 되는 경우가 생기므로, 각 숫자의 범위는 뒤에 올 숫자의 자리를 유지하기 위해 n-2, n-1, n 순서로 반복되어야 한다.

    이를 적용하면 아래와 같은 결론이 내려진다.

    i는 0부터 시작해서 n - 2까지의 범위로 반복한다.
    그 다음에 뽑을 숫자 j는 i + 1부터 시작해서 n - 1의 범위로 반복되고,
    마지막으로 뽑게 되는 숫자 k는 j + 1에서 시작해서 n까지의 범위로 반복된다.

    문제에서 제시한 출력 조건이 m을 넘지않으면서 m에 가장 가까운 숫자의 합을 출력하는 것이므로
    반복문 3개를 중첩해서 돌면서 각각의 값을 더해 totalSum 변수에 저장한다.
    이렇게 합산한 결과를 m과 비교해서 m보다 작으면서 현재 기준 max인 결과값을 resultMax에 저장한다.

    반복문이 모두 돌아가고 나면 자연스럽게 resultMax에는 모든 경우의 수 중에서 가장 크면서 m보다 작은 값이 저장되므로 최종적으로 이 값을 출력해주면 된다.
카테고리
작성일
2024. 7. 3. 21:04
작성자
risehyun
  • 문제

 

  • 풀이
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

bool compare(string str1, string str2)
{
	// 길이가 같은 경우 사전 순으로 정렬하고
	if (str1.size() == str2.size())
	{
		return str1 < str2;
	}
	// 길이가 다른 경우 짧은 순으로 정렬한다.
	else
	{
		return str1.size() < str2.size();
	}
}

int main() 
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);

	int n = 0;
	cin >> n;

	vector<string> str;
	string input;

	for (int i = 0; i < n; i++)
	{
		cin >> input;
		str.push_back(input);
	}

	sort(str.begin(), str.end(), compare);
	str.erase(unique(str.begin(), str.end()), str.end());

	vector<string>::iterator iter;

	for (iter = str.begin(); iter != str.end(); ++iter)
	{
		cout << *iter << '\n';
	}
	
	return 0;
}

 

  • 메모
    중복을 삭제하기 위해서 unique를 사용해서 erase 해주었다.
    이전엔 list에서 unique를 사용하는 법에 대해서만 알고 있었는데 vector에서도 이런 방식으로 간단하게 중복되는 원소를 제거할 수 있다는 걸 알게 되었다.