strcmp() Anyone?

时间:2023-03-10 07:21:47
strcmp() Anyone?

uva11732:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=2832&mosmsg=Submission+received+with+ID+13889354

题意:给你n个串,串之间两两进行比较,计算字符被比较的总次数。

题解:这里注意,'\0'也会被比较。这一题,看的是刘汝佳的代码,才知道怎么统计比较的次数。下面的代码,是刘汝佳的代码。

 #include<cstring>
#include<vector>
using namespace std;
const int maxnode = * + ;
const int sigma_size = ;
// 字母表为全体小写字母的Trie
struct Trie {
int head[maxnode]; // head[i]为第i个结点的左儿子编号
int next[maxnode]; // next[i]为第i个结点的右兄弟编号
char ch[maxnode]; // ch[i]为第i个结点上的字符
int tot[maxnode]; // tot[i]为第i个结点为根的子树包含的叶结点总数
int sz; // 结点总数
long long ans; // 答案
void clear() {
sz = ;
tot[] = head[] = next[] = ;
} // 初始时只有一个根结点 // 插入字符串s(包括最后的'\0'),沿途更新tot
void insert(const char *s) {
int u = , v, n = strlen(s);
tot[]++;
for(int i = ; i <= n; i++) {
// 找字符a[i]
bool found = false;
for(v = head[u]; v != ; v = next[v])
if(ch[v] == s[i]) { // 找到了
found = true;
break;
}
if(!found) {
v = sz++; // 新建结点
tot[v] = ;
ch[v] = s[i];
next[v] = head[u];
head[u] = v; // 插入到链表的首部
head[v] = ;
}
u = v;
tot[u]++;
}
} // 统计LCP=u的所有单词两两的比较次数之和
void dfs(int depth, int u) {
if(head[u] == ) // 叶结点
ans += tot[u] * (tot[u] - ) * depth;
else {
int sum = ;
for(int v = head[u]; v != ; v = next[v])
sum += tot[v] * (tot[u] - tot[v]); // 子树v中选一个串,其他子树中再选一个
ans += sum / * ( * depth + ); // 除以2是每种选法统计了两次
for(int v = head[u]; v != ; v = next[v])
dfs(depth+, v);
}
} // 统计
long long count() {
ans = ;
dfs(, );
return ans;
}
};
#include<cstdio>
const int maxl = + ; // 每个单词最大长度
int n;
char word[maxl];
Trie trie;
int main() {
int kase = ;
while(scanf("%d", &n) == && n) {
trie.clear();
for(int i = ; i < n; i++) {
scanf("%s", word);
trie.insert(word);
}
printf("Case %d: %lld\n", kase++, trie.count());
}
return ;
}