5 條題解

  • 1
    @ 2025-11-21 15:45:43

    对于区间 [l,r]\lbrack l,r \rbrack 内的每个字符串,若该区间符合条件,那么其中所有的字符串一定都是该区间内最长的字符串的前缀。

    那么我们可以枚举区间右端点。

    如果该字符串可以被整合进之前的区间,就不管,否则我们以该字符串为右端点,看之前最多到哪个字符串不能整合进现在的区间里。最后是计数算贡献,一定要减去重复的贡献。

    最后一步,分析时间复杂度:因为每一次都被区间中最大的字符串给阻隔,所以我们最多把每个字符串枚举 2 次,所以最后时间复杂度为 O(2∑∣s∣)O(2 \sum|s|)。

    #include<bits/stdc++.h>
    #define ll long long
    using namespace std;
    const int N = 1e6 + 15;
    int n;
    bool check(const string &s,const string &t){
        int n = min(s.size(),t.size());
        for(int i = 0;i < n;i ++){
            if(s[i] != t[i]) return false;
        }return true;
    }
    string str[N];
    void solve(){
        cin >> n;
        ll ans = 0;int cnt = 0;
        string last = "";
        for(int i = 1;i <= n;i ++){
            string s;cin >> s;str[i] = s;
            if(check(s,last)){
                if(s.size() > last.size()) last = s;
                cnt ++;
            }else{
                ans += 1ll * cnt * (cnt + 1) / 2;
                last = s;cnt = 1;
                for(int j = i - 1;j;j --){
                    if(check(last,str[j])){
                        if(str[j].size() > last.size())
                            last = str[j];
                        cnt ++;
                    }else break;
                }ans -= cnt * (cnt - 1) / 2;
            }
        }ans += 1ll * cnt * (cnt + 1) / 2;
        cout << ans << '\n';
    }
    signed main(){
        freopen("string.in","r",stdin);
        freopen("string.out","w",stdout);
        ios::sync_with_stdio(false);
        cin.tie(0);cout.tie(0);
        int T = 1;
        while(T --) solve();
        return 0;
    }
    /*
    每个点至多被扫两次,所以复杂度为 O(sum|s|)
    */
    

    資訊

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