https://www.acmicpc.net/problem/7490
7490번: 0 만들기
각 테스트 케이스에 대해 ASCII 순서에 따라 결과가 0이 되는 모든 수식을 출력한다. 각 테스트 케이스의 결과는 한 줄을 띄워 구분한다.
www.acmicpc.net
생각해 보기
1. 연산자 순서는 | + | - 이다.
2. 다음 숫자를 계산하기 이전에 이전 연산의 결과를 처리해 버리면 안 된다.
3. 1-2 3 에서 1-2를 먼저 계산 해버리면 3을 사용하기 위해 이전 값을 더해주거나 빼주어야 하는 과정이 추가된다.
4. 마지막에는 남은 연산을 진행해주고 값을 확인하면 된다.
코드
#include<iostream>
#include<string>
using namespace std;
int T;
int N;
int cnt = 0;
void input(){
cin>>T;
}
int calc(int num1, int num2, char op){
switch (op)
{
case '+':
return num1 + num2;
break;
case '-':
return num1 - num2;
break;
default:
return -1;
break;
}
}
void dfs(int num, char op, int ret, string str, int space){
if(num == N){
if(calc(ret, space, op) == 0){
cout<<str<<'\n';
}
return;
}
int nnum=num+1;
int nret=calc(ret,space,op);
dfs(nnum, op ,ret,str+' '+to_string(nnum), space*10+nnum);
dfs(nnum, '+',nret ,str+'+'+to_string(nnum), nnum);
dfs(nnum, '-',nret ,str+'-'+to_string(nnum), nnum);
}
void solution(){
while(T--){
cin>>N;
cnt = 0;
dfs(1,'+', 0, "1",1);
cout<<'\n';
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
input();
solution();
return 0;
}

728x90
'알고리즘 > 백준 문제' 카테고리의 다른 글
| 3109 - 빵집 (0) | 2023.06.29 |
|---|---|
| 17182 - 우주 탐사선 (0) | 2023.06.26 |
| 4190 - 불! (0) | 2023.06.22 |
| 2304 - 창고 다각형 (0) | 2023.03.10 |
| 11501 - 주식 (0) | 2023.03.10 |
댓글