相当于括号匹配问题,负数入栈,正数出栈并定义一个数组level存当前的数(外层减去里层数)。思考了好久,终于。。。AC
#include <cstdio>
#include <iostream>
#include <ctype.h>
#include <cstring>
#include <string>
#include <cstdlib>
#include <stack>
#include <queue>
#include <algorithm>
using namespace std;
int a[30000],level[30000];
int main()
{
char ch;
while(cin>>a[0])
{
int n=1;
while((ch=getchar())!='\n')
{
cin>>a[n++];
}
stack<int> st;
int flag=1,level_x=0;
if(n%2==1)
{flag=0;}
for(int i=0; i<n; i++)
{
if(a[i]<0)
{
st.push(a[i]);
level[level_x++]=-a[i];
}
else if(a[i]>0)
{
if(!st.empty()&&a[i]+st.top()==0)
{
if(st.size()==1)
{
if(level[0]<=0)
{
flag=0;
break;
}
else
st.pop();
}
else
{
st.pop();
--level_x;
level[st.size()-1]-=a[i];
if(level[st.size()-1]<=0)
{
flag=0;
break;
}
}
}
else
{
flag=0;
break;
}
}
}
if(flag==0)
cout<<":-( Try again."<<endl;
else
cout<<":-) Matrioshka!"<<endl;
}
return 0;
}