UVA 11488 Hyper Prefix Sets(字典树)

来源:互联网 发布:mac永恒战士2无限钻石 编辑:程序博客网 时间:2024/05/16 13:47
Prefix goodness of a set string is length of longest common prefix*number of strings in the set. For
example the prefix goodness of the set {000,001,0011} is 6.You are given a set of binary strings. Find
the maximum prefix goodness among all possible subsets of these binary strings.
Input
First line of the input contains T (≤ 20) the number of test cases. Each of the test cases start with n
(≤ 50000) the number of strings. Each of the next n lines contains a string containing only ‘0’ and ‘1’.
Maximum length of each of these string is 200.
Output
For each test case output the maximum prefix goodness among all possible subsets of n binary strings.
Sample Input
4
4
0000
0001
10101
010
2
01010010101010101010
11010010101010101010
3
010101010101000010001010
010101010101000010001000
010101010101000010001010
5
01010101010100001010010010100101
01010101010100001010011010101010
00001010101010110101
0001010101011010101
00010101010101001
Sample Output
6
20
66

44


题意:给你N个字符串,求最长公共前缀与字符串个数的乘积,举个例子


11111

11100

有2个字符串,他们的最长公共前缀为111,长度是3,那么答案是2*3=6



题解:开始我想把这些字符串插入字典树,然后每个字符串再遍历一遍,仔细想一下这其实是没有必要的,我们只要在插入的过程中更新最大值就可以了,即一个变量维护当前的字符串的长度,另一个变量维护当前的公共前缀字符串的个数,一边插入一边维护最大值

x->lg=i+1;x->val++;
lg为公共前缀字符串的长度,val是当前的公共前缀字符串的个数


#include<iostream>#include<cstdio>#include<cstring>using namespace std;#define inf 0x3f3f3f3fint ans;struct tire{int val,lg;tire *chd[3];tire(){lg=0;val=0;memset(chd,NULL,sizeof(chd));}}*root;void insert(char *s){tire *x=root;for(int i=0;s[i];i++){int d=s[i]-'0';if(x->chd[d]==NULL)x->chd[d]=new tire;x=x->chd[d];x->lg=i+1;x->val++;ans=max(ans,x->lg*x->val);}}void deal(tire *x){if(x==NULL)return ;for(int i=0;i<2;i++){if(x->chd[i]!=NULL)deal(x->chd[i]);}delete x;}int main(){#ifdef CDZSCfreopen("i.txt","r",stdin);#endifchar s[1000];int n,t;scanf("%d",&t);while(t--){ans=-inf;scanf("%d",&n);root=new tire;for(int i=0;i<n;i++){scanf("%s",s);insert(s);}printf("%d\n",ans);deal(root);}return 0;}





0 0