반응형
문제 출처 :
https://www.acmicpc.net/problem/2257
알고리즘 분석 :
문제 해결에 필요한 사항
1. 재귀
재귀를 이용하여 문제를 풀 수 있다.
사실 이 문제는 stack을 이용하여 문제를 풀 수 있지만, 라이브러리를 사용 할 수 없는 환경이라면 다음과같이 내부 stack을 이용하여서도 풀 수 있다.
tmp는 이전 문자가 뭔지 의미해주고 있고, ret는 실제로 결과값에 영향을 끼치는 값이다.
'('를 만난다면 재귀 호출을 통해 ')'가 나오기 전까지 모든값을 담아내주고,
')'를 만날 때는 ')'이후에 숫자가 존재하는지 파악해준 후 있다면 곱해서 retrun을 그렇지 않다면 ret를 return해준다.
그 외 숫자는 그냥 ret에 계산을 해준다.
소스 코드 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #include <iostream> #include <cstdio> #include <string> #define H 1 #define C 12 #define O 16 using namespace std; bool visit[102]; int tmp; int dfs(string str, int pos, int len) { int ret = 0; for (int i = pos; i < len; i++) { if (visit[i]) continue; visit[i] = true; if (str[i] == 'H') ret += H, tmp = H; else if (str[i] == 'O') ret += O, tmp = O; else if (str[i] == 'C') ret += C, tmp = C; else if (str[i] == '(') { ret += dfs(str, i + 1, len); } else if (str[i] == ')') { if ('2' <= str[i + 1] && str[i + 1] <= '9') { visit[i + 1] = true; ret *= (str[i + 1] - '0'); } return ret; } else if ('2' <= str[i] && str[i] <= '9') { ret += (tmp * (str[i] - '0')) - tmp; } } return ret; } int main() { string str; cin >> str; int len = str.size(); cout << dfs(str, 0, len); return 0; } // This source code Copyright belongs to Crocus // If you want to see more? click here >> | Crocus |
반응형
'Applied > 알고리즘 문제풀이' 카테고리의 다른 글
[11651번] 좌표 정렬하기 2 (0) | 2018.02.19 |
---|---|
[10840번] 구간 성분 (0) | 2018.02.07 |
[9536번] 여우는 어떻게 울지? (0) | 2018.02.05 |
[11332번] 시간초과 (0) | 2018.02.05 |
[5670번] 휴대폰 자판 (0) | 2018.01.26 |