題解: 遍歷每個單詞,插入到字典樹中,插入的過程中根據每個節點處的信息來計算比較次數,注意如果用指針來表示字典樹的話會超時,估計是因爲構造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;
}