Queries on a String Gym - 101755L (栈模拟+二分查找)

A string s is given. Also there is a string p, and initially it is empty. You need to perform q operations of kind «add a letter to the end of the string p» and «remove a letter from the end of the string p», and after performing each operation you must say whether or not s contains p as a subsequence.

Input

The first line contains the string s of length from 1 to 200000, consisting of lowercase Latin letters.

The second line contains a single integer q (1 ≤ q ≤ 200000) — the number of operations.

Each of the next q lines describes an operation in the format «push c», which means «add letter c to the end of the string p» (c is lowercase Latin letter), or «pop», which means «remove letter from the end of the string p». The «pop» operations is guaranteed never to be applied to the empty string p.

Output

Output q lines, each of which equals «YES» or «NO», depending on whether or not the string p is contained in the string s as a subsequence after performing the corresponding operation.

思路:要询问是不是子串,其实只要考虑字母个数到底够不够就行,比如原字符串中有2个a,那么当你连续push3个a的时候,就不在是子串了。

所以考虑对原串每种字母都统计其个数并记录下标,upper_bound()总是去找到比查找数字大的位置,利用这一点,只要返回的位置有效,说明还是子串。

对于不是子串,则在栈中加入inf,表示这个位置找不到即可。

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <math.h>
#include <stack>
const int maxn=3e3+6;
const int INF=1e8;
typedef long long ll;
using namespace std;
int main(int argc, char const *argv[])
{
    /* code */
    vector<int> vec[maxn];
    stack<int> sta;
    sta.push(-1);
    string s;
    cin>>s;
    for(int i=0;i<s.size();i++)
    {
        vec[s[i]-'a'].push_back(i);
    }
    int n;
    cin>>n;
    cin.ignore();
    for(int i=0;i<n;i++)
    {
        char s2[maxn];
        gets(s2);
        //cout<<s2<<endl;
        if(s2[1]=='u')
        {
            char ch=s2[5];
            //cin>>ch;
            int t=upper_bound(vec[ch-'a'].begin(),vec[ch-'a'].end(),sta.top())-vec[ch-'a'].begin();
             //cout<<t<<endl;
             //cout<<vec[ch-'a'].size()<<endl;
            if(t!=vec[ch-'a'].size())
            {
                printf("YES\n");
                sta.push(vec[ch-'a'][t]);
                //cout<<vec[ch-'a'][t]<<endl;
            }
            else
            {
                printf("NO\n");
                sta.push(INF);
            }
        }
        else
        {
           // cout<<sta.top()<<endl;
            sta.pop();
            if(sta.top()==INF)
            {
                printf("NO\n");
            }
            else
            {
                printf("YES\n");
            }
        }
    }
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40774175/article/details/81747925