poj 1068 Parencodings(模拟)

来源:互联网 发布:双色球合数推算法 编辑:程序博客网 时间:2024/06/06 14:00

题目链接:http://poj.org/problem?id=1068


题目大意:

例如有一个关于括号的符号串(由'('和')'组成)S;

现在给出数列p代表,符号串中每个右括号的左边有几个左括号;

要求求出数列w代表,每个右括号和其相匹配的左括号中包含有几组匹配括号(包含自身);

思路:

利用栈存储字符串S,在利用一个临时的栈来倒序分组求出每个匹配括号中包含的匹配括号数;


#include<iostream>#include<stack>using namespace std;stack <char> temp;stack <char> S;int main(){int cas;int ret[21];scanf("%d",&cas);while(cas--){int n,i,num,t=0;scanf("%d",&n);int len=n;for(i=0;i<n;i++){scanf("%d",&num);while(t<num){S.push('(');t++;}S.push(')');}n--;while(!S.empty()){S.pop();int right=1,left=0;while(!S.empty()){if(S.top()==')')right++;elseleft++;temp.push(S.top());S.pop();if(right==left){ret[n--]=left;break;}}temp.pop();while(!temp.empty()){S.push(temp.top());temp.pop();}}for(i=0;i<len;i++){if(i==len-1)printf("%d\n",ret[i]);elseprintf("%d ",ret[i]);}}return 0;}