分析:构造字典树+深搜
采用刘汝佳的左儿子右兄弟的构树方式,节省了大量的空间。
代码如下:
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;typedef long long ll;
const int maxn = 1e6+10;
int head[maxn];
int Next[maxn];
int tot[maxn];
char ch[maxn],word[maxn];
int sz;
int n;
ll ans;void Clear(){sz = 1;tot[0] = head[0] = Next[0] = 0;
}void Insert(const char *s){int u = 0, len = strlen(s), v;bool found;tot[0]++;for (int i=0; i<len; i++) {found = 0;for (v = head[u]; v!=0; v=Next[v]){if (ch[v]==s[i]) {found = 1;break;}}if (!found){v = sz++;tot[v] = 0;ch[v] = s[i];Next[v] = head[u];head[u] = v;head[v] = 0;}u = v;tot[u]++;}
}void init(){Clear();scanf("%d",&n);for (int i=1; i<=n; i++) {scanf("%s",word);Insert(word);}ans = 0;
}void dfs(int depth, int u){if (tot[u]==1) {ans += depth; return;}for (int v=head[u]; v!=0; v=Next[v]) dfs(depth+1,v);
}int T;
int main(){scanf("%d",&T);while(T--){init();dfs(0,0);printf("%lld\n",ans);}return 0;
}