UVA 11488 Hyper Prefix Sets (字典树)

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2483

 组织一棵Trie 记录每个节点有多少串经过 统计最大值

由于只出现0,1,于是建立一个字典树,每一次到达一个节点,就在这个节点加上深度,然后ans求解最大的节点附加值就可以了。注意初始化

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 #include <vector>
 6 #include <cstdlib>
 7 #include <iomanip>
 8 #include <cmath>
 9 #include <ctime>
10 #include <map>
11 #include <set>
12 #include <queue>
13 using namespace std;
14 #define lowbit(x) (x&(-x))
15 #define max(x,y) (x>y?x:y)
16 #define min(x,y) (x<y?x:y)
17 #define MAX 100000000000000000
18 #define MOD 1000000007
19 #define pi acos(-1.0)
20 #define ei exp(1)
21 #define PI 3.141592653589793238462
22 #define INF 0x3f3f3f3f3f
23 #define mem(a) (memset(a,0,sizeof(a)))
24 #define maxnode 100000
25 typedef long long ll;
26 ll gcd(ll a,ll b){
27     return b?gcd(b,a%b):a;
28 }
29 bool cmp(int x,int y)
30 {
31     return x>y;
32 }
33 const int N=10005;
34 const int mod=1e9+7;
35 int n;
36 struct Trie
37 {
38     int ch[maxnode][3];
39     int val[maxnode];
40     int sz=1,ans=0;
41     void init(){sz=1;
42         ans=0;
43         memset(ch[0],0,sizeof(ch[0]));
44         memset(val,0,sizeof(val));
45     }
46     int idx(char c){
47         return c-'0';
48     }
49     void insert(char* s,int len){
50         int u=0;
51         for(int i=0;i<len;i++){
52             int v=idx(s[i]);
53             if(!ch[u][v]){
54                 memset(ch[sz],0,sizeof(ch[sz]));
55                 ch[u][v]=sz++;
56             }
57             u=ch[u][v];
58             val[u]+=(i+1);
59             ans=max(ans,val[u]);
60         }
61     }
62 };
63 struct Trie trie;
64 char s[maxnode];
65 int main()
66 {
67     int t;
68     cin>>t;
69     while(t--){
70         trie.init();
71         cin>>n;
72         while(n--){
73             cin>>s;
74             trie.insert(s,strlen(s));
75         }
76         cout<<trie.ans<<"\n";
77     }
78     return 0;
79 }
posted @ 2017-08-04 11:28  wydxry  阅读(332)  评论(0编辑  收藏  举报
Live2D