Codeforces——914F Substrings in a String

大致題意:給一個字符串str,再給n次操作,其中1操作是改變str中pos位置的字符,2操作是查詢 [l,r] 中字符串s出現的次數。第一次用bitset,感覺真是個好東西。真好用。

洛谷上面有人寫了題解,但是沒有寫的很具體,所以從來沒寫過bitset的我就只能一直猜他代碼的意思,花了一點時間才搞懂了bitset,其實就是先暴力統計每種字符的位置,然後再用一個temp(bitset類型)去統計每次要查詢的字符串。就是代碼中 位運算的部分。那裏就是整道題的精髓了。

最後,代碼:(有空我再用其他方法把他過了)。

 

#include<bits/stdc++.h>
using namespace std;
bitset<101000>bitset1[27],temp;
int main()
{
    int n;
    string str;
    string s;
    cin>>str;
    for(int i=0;i<str.size();++i)
    {
        bitset1[str[i]-'a'][i]=1;
    }
    cin>>n;
    int opt;
    int pos;
    int l,r;
    char ch;
    for(int i=0;i<n;++i)
    {
        cin>>opt;
        if(opt==1)
        {
            cin>>pos>>ch;
            bitset1[str[pos-1]-'a'][pos-1]=0;
            bitset1[ch-'a'][pos-1]=1;
            str[pos-1]=ch;
        }
        else
        {
            cin>>l>>r>>s;
            temp.set();
            for(int j=0;j<s.size();++j)
            {
                temp&=(bitset1[s[j]-'a']>>j);
            }
            int Left=(temp>>l-1).count();
            
            int Right=(temp>>r-s.size()+1).count();
            if(Left<Right)
                Left=Right;
            //當s.size()>(r-l+1)的時候,如果沒有這句話,那麼就會有錯誤
            cout<<Left-Right<<endl;
        }
    }
    return 0;
}

 

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