[NOIP2017] 时间复杂度 (模拟,栈)

题目链接


Solution

用栈进行模拟.
记录一个 \(map\) 来看循环变量有没有用过.
对于每一次入栈都加信息.
出栈直接将 \(top\) 减一下.
反正一堆乱七八糟的东西瞎搞...
注意条件如果循环内均为常数,算作 \(O(1)\).

Code

#include<bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
map<char,bool>v;
int sta[108],top,sum[108];
char k[108];

int cal(string s)
{
    if(s=="n")return inf;
    int w=0,i=0;
    while(s[i]>='0'&&s[i]<='9')
    w=w*10+s[i]-'0',i++;
    return w;
}

int work(int n)
{
    top=0; int flag=0,ans=1;
    for(char i='a';i<='z';i++)v[i]=0;
    while(n--)
    {
        char ch,i; string x,y;
        cin>>ch; sum[0]=1;
        if(ch=='F')
        {
            cin>>i;
            if(v[i])flag=-1; v[i]=1;
            cin>>x; cin>>y;
            if(flag==-1)continue;
            int w,x1=cal(x),y1=cal(y);

            if(x1==y1)w=1;
            if(x1>y1)w=0;
            if(x1<y1)
            {
              if(x1==inf||y1==inf)
                w=2;
              else w=1;
            }
            sta[++top]=w; k[top]=i;
            if(w==1)sum[top]=sum[top-1];
            if(w==2)sum[top]=sum[top-1]+1;
            if(w==0)sum[top]=0;
            if(sum[top-1]==0)sum[top]=0;
            flag=max(flag,sum[top]);
        }
        if(ch=='E')
        {
            if(flag==-1)continue;
            v[k[top]]=0;
            top--;
        }
    }
    if(flag==0)flag++;
    if(top!=0)flag=-1;
    return flag-1;
}

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int L,cost=0; string T;
        cin>>L>>T;
        if(T[2]=='1')cost=0;
        else{
          int i=0;
          while(T[i]>'9'||T[i]<'0')i++;
            while(T[i]>='0'&&T[i]<='9'){cost=cost*10+T[i]-'0';i++;}
        }
        int flag=work(L);
        if(flag<0)cout<<"ERR"<<endl;
        else
        if(flag==cost)cout<<"Yes"<<endl;
        else cout<<"No"<<endl;
    }
}

猜你喜欢

转载自www.cnblogs.com/Kv-Stalin/p/9661110.html
今日推荐