5 條題解

  • 1
    @ 2025-11-21 15:38:22

    众所周知,字典树中任意节点的任意祖先对应的字符串一定是该节点对应字符串的前缀,所以可以把所有字符串插入字典树,在结尾位置记录该字符串下标

    接着,遍历字典树,记录从根到当前节点的路径中的节点对应字符串的下标,那么显然,恰好与当前节点对应字符串的下标相邻的段才能产生贡献,那么用 set 维护就可以了

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    typedef pair<int,int> PII;
    const int N = 2e5 + 5;
    const int M = 1e6 + 5;
    int n;
    ll ans;
    string s;
    set<PII> se;
    int tr[26][M],tot;
    vector<int> pos[M];
    void insert(string &s,int id) {
    	int p = 0;
    	for(char c : s) {
    		c -= 'a';
    		if(!tr[c][p]) tr[c][p] = ++ tot;
    		p = tr[c][p];
    	}
    	pos[p].push_back(id);
    }
    void dfs(int p) {
    	for(int x : pos[p]) {
    		auto it = se.lower_bound({x,0});
    		int l = x,r = x;
    		if(it != se.end() && it->first == x + 1) {
    			r = it->second,it = se.erase(it);
    		} 
    		if(it != se.begin() && (-- it)->second == x - 1) {
    			l = it->first,it = se.erase(it);
    		}
    		ans += 1LL * (x - l + 1) * (r - x + 1);
    		se.insert({l,r});
    	}
    	for(int c = 0;c < 26;c ++) {
    		if(tr[c][p]) dfs(tr[c][p]);
    	}
    	for(int x : pos[p]) {
    		auto it = -- se.lower_bound({x + 1,0});
    		int l = it->first,r = it->second;
    		se.erase(it);
    		if(l != x) se.insert({l,x - 1});
    		if(r != x) se.insert({x + 1,r});
    	}
    }
    void solve() {
    	cin >> n;
    	for(int i = 1;i <= n;i ++) {
    		cin >> s;
    		insert(s,i);
    	}
    	dfs(0);
    	cout << ans << "\n";
    }
    signed main() {
    	freopen("string.in","r",stdin);
    	freopen("string.out","w",stdout);
    	ios::sync_with_stdio(0);
    	cin.tie(0),cout.tie(0);
    	int t = 1;
    //	cin >> t;
    	while(t --) solve();
    	return 0;
    }
    
    

    資訊

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