题解: 遍历每个单词,插入到字典树中,插入的过程中根据每个节点处的信息来计算比较次数,注意如果用指针来表示字典树的话会超时,估计是因为构造Trie的时候会遍历next数组,导致时间复杂度增加一个数量级。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 4010;
int get_index(char ch) {
if(ch>='0'&&ch<='9') return ch-'0';
else if(ch>='a'&&ch<='z') return 10+ch-'a';
else return 36+ch-'A';
}
// struct Trie {
// int cnt;
// Trie *next[62];
// Trie() {
// cnt = 0;
// for(int i = 0;i < 62;i++) next[i] = NULL;
// }
// };
int Trie[4000010][62];
int cnt[4000010];
int tot;
// void destroy(Trie *root) {
// if(root == NULL) return;
// for(int i = 0;i < 62;i++)
// destroy(root->next[i]);
// delete root;
// }
int main() {
int n;
int kase = 1;
// freopen("out.txt","w",stdout);
while(scanf("%d",&n) != EOF && n) {
tot = 1;
memset(cnt,0,sizeof(cnt));
memset(Trie,0,sizeof(Trie));
int root = 0;
ll ans = 0;
for(int i = 0;i < n;i++) {
ll temp = ans;
char str[1010];
scanf("%s",str);
int cur = root;
int len = strlen(str);
int t = i;
for(int j = 0;j < len;j++) {
char ch = str[j];
int index = get_index(ch);
if(Trie[cur][index]==0) {
cnt[tot] = 1;
Trie[cur][index] = tot++;
ans += t;
t = 0;
cur = Trie[cur][index];
} else {
cur = Trie[cur][index];
ans += cnt[cur]+t;
t = cnt[cur];
cnt[cur]++;
}
}
int tt = 0;
for(int j = 0;j < 62;j++) {
if(Trie[cur][j] != NULL) tt += cnt[Trie[cur][j]];
}
ans += (t-tt)*2+tt;
// printf("delta : %lld\n",ans-temp);
}
printf("Case %d: %lld\n",kase++,ans);
// destroy(root);
}
return 0;
}