UVA 11111 - Generalized Matrioshkas

相當於括號匹配問題,負數入棧,正數出棧並定義一個數組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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章