40pts求hack
查看原帖
40pts求hack
388415
Sudohry楼主2023/3/28 13:54
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <ctime>
#include <vector>

#define rep(i, l, r) for (int i=(l); i<=(r); ++i)
#define per(i, r, l) for (int i=(r); i>=(l); --i)
#define LB() printf ("TAG\n")
#define N 510005
#define M 100005
#define INF 0x7fffffff

using namespace std;

template <typename Tp> inline void to_max (Tp &x, const Tp &y) { if (y > x) x = y; return ; }
template <typename Tp> inline void to_min (Tp &x, const Tp &y) { if (y < x) x = y; return ; }
inline int lowbit (const int &x) { return x & (-x) ; }

int n, len, tot = 1, cnt, c[N][30], h[N], s[N];
long long ans;
bool f[N];
char str[N];
vector <int> edge[N];

inline bool cmp (const int &x, const int &y) { return s[x] < s[y] ; }

void insert () {
    int u = 1, lst = 1;
    per (i, len, 1) {
        int e = str[i] - 'a';
        if (!c[u][e]) c[u][e] = ++tot;
        u = c[u][e];
        if (f[u]) lst = u;
    }
    edge[lst].push_back (u);
    f[u] = true;
    return ;
}

void pre (int pos) {
    s[pos] = 1;
    rep (i, 0, (int)edge[pos].size()-1) {
        int v = edge[pos][i];
        pre (v); s[pos] += s[v];
    }
    sort (edge[pos].begin(), edge[pos].end(), cmp);
    return ;
}

void dfs (int pos) {
    int dfn = cnt++;
    rep (i, 0, (int)edge[pos].size()-1) {
        ans += cnt - dfn;
        int v = edge[pos][i];
        dfs (v);
    }
    return ;
}

int main () {
    scanf ("%d", &n);
    rep (i, 1, n) {
        scanf ("%s", str+1);
        len = strlen (str+1); insert ();
    } pre (1);
    cnt = 0; dfs (1);
//  rep (i, 1, n) sort (edge[i].begin(), edge[i].end(), cmp);
    printf ("%lld\n", ans);
    return 0;
}

/*

5
x
xx
jopnx
jpnx
xxx

*/
2023/3/28 13:54
加载中...