UVA “strcmp()” Anyone?
题意:
Sample Input
2
a
b
4
cat
hat
mat
sir
0
Sample Output
Case 1: 1
Case 2: 6
题目链接:
https://odzkskevi.qnssl.com/d53d2ae0b0fc885d7fb0af4dcea1489e?v=1508641012
#include <bits/stdc++.h>
using namespace std;
const int maxn = 4e6 + 10;
long long ans;
struct Trie {
char ch[maxn];//第i结点的字符
int tot[maxn];//包括第i结点子结点数
int lch[maxn];//左孩子编号
int nxt[maxn];//兄弟结点链表
int sz = 1;
void clear() {
sz = 1;
ch[0] = tot[0] = lch[0] = nxt[0] = 0;
}
void insert(char *s) {
int u = 0, v, len = strlen(s);
for(int i = 0; i <= len; ++ i) {
for(v = lch[u]; v; v = nxt[v]) {
if(ch[v] == s[i]) break;
}
if(v == 0) {
v = sz++;
tot[v] = 0;
ch[v] = s[i];
nxt[v] = lch[u];
lch[u] = v;
lch[v] = 0;
}
ans += (tot[u] - tot[v]) * (2 * i + 1);
if(i == len) {
ans += tot[v] * (2 * i + 2); //最后一个字符'\0',所以这种情况是字符串相同的情况
}
tot[u]++;
u = v;
}
tot[u]++; //忘了最后一个字符
}
}trie;
int main() {
int n;
int cas = 1;
while(~scanf("%d", &n) && n) {
trie.clear();
ans = 0;
char str[1100];
while(n--) {
scanf("%s", str);
trie.insert(str);
}
printf("Case %d: %lld\n", cas++, ans);
}
}