P9518题解

· · 题解

思路

按题意模拟即可。

实现

使用队列进行模拟:

时间复杂度:O(n \log n)。

代码

#include<bits/stdc++.h>
using namespace std;
map<string,int>mp,mp2;
int cnt,n;
string s,nw;
string nw1="?",nw2="?";
deque<string>q;
int main()
{
    n=read();
    while(n--)
    {
        cin>>s;
        if(s=="start")
        {
            if(cnt==0)
            {
                puts("Error");
                continue;
            }
            if(nw1!="?")
            {
                q.push_back(nw1);
                mp[nw1]=2;
                mp2[nw2]++;
            }
            if(nw2!="?")
            {
                q.push_back(nw2);
                mp[nw2]=2;
                mp2[nw2]++;
            }
            while(!q.empty()&&(mp[q.front()]!=2||(mp[q.front()]==2&&mp2[q.front()]>1)))
                mp2[q.front()]--,q.pop_front();
            if(!q.empty())
            {
                nw1=q.front();
                mp[nw1]=1;
                q.pop_front();
                mp2[nw2]--;
            }
            else
                nw1=="?";
            while(!q.empty()&&(mp[q.front()]!=2||(mp[q.front()]==2&&mp2[q.front()]>1)))
                mp2[q.front()]--,q.pop_front();
            if(!q.empty())
            {
                nw2=q.front();
                mp[nw2]=1;
                q.pop_front();
                mp2[nw2]--;
            }
            else
                nw2=="?";
            if(nw1!="?")
                cout<<nw1<<" ";
            if(nw2!="?")
                cout<<nw2;
            cout<<endl;
        }
        if(s=="arrive")
        {
            cin>>nw;
            if(mp[nw]!=0)
            {
                puts("Error");
                continue;
            }
            mp[nw]=2;
            q.push_back(nw);
            mp2[nw]++;
            cnt++;
            puts("OK");
        }
        if(s=="leave")
        {
            cin>>nw;
            if(mp[nw]==2)
            {
                mp[nw]=0;
                cnt--;
                puts("OK");
            }
            else
            {
                puts("Error");
                continue;
            }
        }
    }
    return 0;
}