-
[C++] 백준 7490 0 만들기알고리즘/백준 2023. 1. 6. 11:13반응형123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111#include <iostream>#include <vector>#include <string>#include <stack>#include <algorithm>using namespace std;int t, n;vector<string> result;void calculate(vector<string> vec, string str) {stack<int> stk;stack<string> op;for (int i = vec.size() - 1; i >= 0; i--) {if (vec[i] == "+" || vec[i] == "-") {op.push(vec[i]);}else {stk.push(stoi(vec[i]));}}int s = op.size();for (int i = 0; i < s; i++) {string c = op.top();op.pop();if (c == "+") {int a = stk.top();stk.pop();int b = stk.top();stk.pop();stk.push(a + b);}else if (c == "-") {int a = stk.top();stk.pop();int b = stk.top();stk.pop();stk.push(a - b);}}if (stk.top() == 0) {result.push_back(str);}}void dfs(string str, string a, int cnt) {if (cnt == n) {str = str + to_string(n);a = a + to_string(n);vector<string> vec;string b = "";for (int i = 0; i < str.length(); i++) {if (str[i] == '+' || str[i] == '-') {vec.push_back(b);string rem = "";rem = rem + str[i];vec.push_back(rem);b = "";}else {b = b + str[i];}}vec.push_back(b);calculate(vec, a);return;}// 0 == +, 1 == 공백, 2 == -for (int i = 0; i < 3; i++) {string tmp = str + to_string(cnt);string k = a + to_string(cnt);if (i == 0) {tmp = tmp + "+";k = k + "+";}else if (i == 1) {k = k + " ";}else if (i == 2) {tmp = tmp + "-";k = k + "-";}dfs(tmp, k, cnt + 1);}}void input() {cin >> t;for (int i = 0; i < t; i++) {cin >> n;dfs("", "", 1);sort(result.begin(), result.end());for (int i = 0; i < result.size(); i++) {cout << result[i] << endl;}result.clear();cout << '\n';}}int main() {input();}
cs 문자열 + 완전탐색을 이용하는 문제
N 의 값이 최대 9 이므로 최대 시간 복잡도는 O(3^9) 로 완전탐색이 가능하다
1. N 의 값을 입력받아 완전탐색 실행
12cin >> n;dfs("", "", 1);cs ** DFS 인자로 공백 문자열 두개를 주는 이유
문제에서 수식을 출력할때 공백을 포함하라 했는데 공백을 포함하게되면 스택을 이용한 계산에 문제가 생기기 때문에
첫번째 인자는 공백을 포함하지 않는 문자열 (스택 계산을 위함), 두번째 인자는 공백을 포함하는 문자열(출력을 위함)을 만들었다.
2. 완전탐색을 이용해 계산한 후 스택의 최종값이 0 이면 결과 벡터에 저장
3. sort 함수를 이용해 결과 메소드 정렬 후 출력
4. 테스트 케이스 수 만큼 반복
728x90반응형'알고리즘 > 백준' 카테고리의 다른 글
[C++] 백준 8972 미친 아두이노 (0) 2023.01.11 [C++] 백준 2638 치즈 (0) 2023.01.06 [C++] 백준 1976 여행 가자 (0) 2023.01.05 [C++] 백준 1043 거짓말 (1) 2023.01.04 [C++] 백준 10836 여왕벌 (0) 2023.01.04