Parentheses Column Values
2015-07-08 16:10 kingshow 阅读(311) 评论(0) 编辑 收藏 举报Parentheses Column Values
Between the columns using four parentheses ‘(‘, ‘)’, ‘[‘, ‘]’, a correct parentheses column is defined as below: 28 Case #2 |
代码:
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; int result = 0; char chars[30]; int num[30]; int st[30]; int po; void pushSt(int v); int popSt(); int emptySt(); int beforeP(int v); int endP(int v); int matchP(int v); int main() { //freopen("input.txt","r",stdin); int N; cin >> N; int flag,correct,ch,ch1,ch2,match; for(int t=1; t<=N; t++) { scanf("%s",chars); int s = strlen(chars); //cout<<s<<endl; for(int i=0; i<s; i++) { if(chars[i] == '(') { num[i] = -1; } else if(chars[i] == ')') { num[i] = -2; } else if(chars[i] == '[') { num[i] = -3; } else if(chars[i] == ']') { num[i] = -4; } } result = 0; po = flag = 0; correct = 1; if(endP(num[0])) { correct = 0; } else { pushSt(num[0]); } for(int i=1; i<s; i++) { if(beforeP(num[i])) { pushSt(num[i]); } else { match = matchP(num[i]); ch1 = 1; while(!emptySt() && ((ch = popSt()) != match)) { if(beforeP(ch)) { correct = 0; break; } if(flag == 0) { flag = 1; ch1 = ch; } else{ ch2 = ch; ch = ch1 + ch2; pushSt(ch); flag = 0; ch1 = 1; } } if(ch == match) { flag = 0; if(num[i] == -2) { ch = ch1 * 2; pushSt(ch); } else { ch = ch1 * 3; pushSt(ch); } } else { correct = 0; break; } } } ch = 0; if(correct == 1) { for(int i=0; i<po; i++) { if(beforeP(st[i])) { correct = 0; break; } else { ch += st[i]; } } } if(correct) { result = ch; } cout<<"Case #"<<t<<endl; cout<<ch<<endl; } //cout << "Hello world!" << endl; return 0; } void pushSt(int v) { st[po] = v; po++; } int popSt() { int t = st[po-1]; po--; return t; } int emptySt() { if(po == 0) return 1; else return 0; } int beforeP(int v) { if(v == -1 || v == -3) { return 1; } else return 0; } int endP(int v) { if(v == -2 || v == -4) return 1; else return 0; } int matchP(int v) { if(v == -2) return -1; else if(v == -4) return -3; }