5 條題解

  • 2
    @ 2025-11-21 15:43:49

    单调队列写法:

    发现我们需要将新加入的字符串需要和已经加入的所有字符串比对是否是包含关系。

    显然所有已加入字符串都是其中最长的字符串的前缀,所以和最长的字符串比对即可。

    但是匹配失败后区间右指针会移动到最大串的右侧,但此时加入新字符串并不一定合法,此时我们需要知道在最长的之后的次长串,同理进行匹配。

    发现在最长串左侧的短串与匹配无关,最长串右侧的需要等最长串弹出后才有可能有用,显然单调队列。

    checkcheck 函数用于检测下标为 xx 和 yy 的字符串是否互为前缀(此处使用字符串哈希处理),用数组模拟双端队列可解(不推荐使用 STLSTL 中的 dequedeque ,常数极大)

    #include<bits/stdc++.h>
    using namespace std;
    #define debug(x); cerr<<__LINE__<<" : "<<#x<<" "<<x<<"\n";
    typedef long long ll;
    typedef pair<int, int> PII;
    const int N=2e5+5,mod=999999937,base=233;
    
    int n;
    vector<vector<ll>> hah;
    
    bool check(int x, int y){
        if(hah[x].size() < hah[y].size()){swap(x, y);}
        int op = hah[y].size() - 1;
        return hah[x][op] == hah[y][op];
    }
    
    int main(){
        freopen("string.in", "r", stdin);
        freopen("string.out", "w", stdout);
        ios::sync_with_stdio(false);
        cin.tie(0); cout.tie(0);
        cin>>n; hah.resize(n + 1);
        for(int i=1;i<=n;i++){
            string s; cin>>s;
            ll last = 0;
            for(int j=0;j<(int)s.size();j++){
                last = (last * base % mod + s[j] - 'a') % mod;
                hah[i].push_back(last);
            }
        }
        ll ans = 0;
        vector<int> q(N); int f = 0, e = 0; q[0] = 1;
        for(int l=1,r=2;r<=n;r++){
            while(e - f >= 0 && !check(q[f], r)){l = q[f] + 1; f ++;}
            while(e - f >= 0 && hah[r].size() >= hah[q[e]].size()){e --;}
            q[++ e] = r; ans += r - l;
        }
        cout<<ans + n<<"\n";
        return 0;
    }
    

    資訊

    ID
    21
    時間
    1000ms
    記憶體
    512MiB
    難度
    6
    標籤
    遞交數
    40
    已透過
    12
    上傳者