您的位置:首页 > 其它

lightoj 1224(trie)

2015-11-03 19:47 316 查看
题意:有n个字符串,要求输出一个最大的值是公共前缀×其长度。

题解:把字符串都拿去建字典树,val[i]存节点i是多少个串的前缀,这个最大的值就是节点深度depth[u]×val[u]的最大值。这题好坑,数组开小了给的是wa。。。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
const int N = 2500000;
int Next
[4], sz, n, depth
, val
, res;
char str[55];
map<char, int> mp;

void init() {
memset(Next[0], 0, sizeof(Next[0]));
val[0] = 0;
depth[0] = 0;
sz = 1;
}

void insert(char *s) {
int u = 0, len = strlen(s);
for (int i = 0; i < len; i++) {
int k = mp[s[i]];
if (!Next[u][k]) {
memset(Next[sz], 0, sizeof(Next[sz]));
val[sz] = 1;
Next[u][k] = sz++;
depth[Next[u][k]] = depth[u] + 1;
}
else
val[Next[u][k]]++;
u = Next[u][k];
res = max(res, depth[u] * val[u]);
}
}

int main() {
int t, cas = 1;
scanf("%d", &t);
mp['A'] = 0;
mp['C'] = 1;
mp['G'] = 2;
mp['T'] = 3;
while (t--) {
init();
scanf("%d", &n);
res = 0;
for (int i = 0; i < n; i++) {
scanf("%s", str);
insert(str);
}
printf("Case %d: %d\n", cas++, res);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: