Codeforces 965E Short Code 启发式合并 (看题解)

Short Code

我的想法是建出字典树, 然后让后面节点最多的点优先向上移到不能移为止, 然后gg。

正确做法是对于当前的节点如果没有被占, 那么从它的子树中选出一个深度最大的点换到当前位置。

用set启发式合并维护一下。

#include<bits/stdc++.h>
#define LL long long
#define fi first
#define se second
#define mk make_pair
#define PLL pair<LL, LL>
#define PLI pair<LL, int>
#define PII pair<int, int>
#define SZ(x) ((int)x.size())
#define ull unsigned long long

using namespace std;

const int N = 2e5 + 7;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
const double eps = 1e-8;
const double PI = acos(-1);

string s[N];
int depth[N], ch[N][26], cnt, n;
LL ans;
bool val[N];
multiset<int> Set[N];

void Insert(const string& s) {
    int u = 0;
    for(int i = 0; i < SZ(s); i++) {
        if(!ch[u][s[i] - 'a']) {
            ch[u][s[i] - 'a'] = ++cnt;
            depth[cnt] = depth[u] + 1;
        }
        u = ch[u][s[i] - 'a'];
    }
    val[u] = true;
}

void dfs(int u) {
    for(int i = 0; i < 26; i++) {
        int v = ch[u][i];
        if(v) {
            dfs(ch[u][i]);
            if(SZ(Set[u]) < SZ(Set[v])) Set[u].swap(Set[v]);
            for(auto& x : Set[v]) Set[u].insert(x);
        }
    }
    if(u) {
        if(val[u]) Set[u].insert(depth[u]);
        else {
            if(SZ(Set[u])) {
                int val = *Set[u].rbegin();
                Set[u].erase(Set[u].lower_bound(val));
                Set[u].insert(depth[u]);
            }
        }
    }
}

int main() {
    cin >> n;
    for(int i = 1; i <= n; i++) cin >> s[i];
    for(int i = 1; i <= n; i++) Insert(s[i]);
    dfs(0);
    for(auto& x : Set[0]) ans += x;
    printf("%lld
", ans);
    return 0;
}

/*
*/
原文地址:https://www.cnblogs.com/CJLHY/p/10498247.html