首页 > 其他 > 详细

Shortest Prefixes (最短前缀且不重复)

时间:2019-07-19 00:59:22      阅读:87      评论:0      收藏:0      [点我收藏+]

题目链接:http://poj.org/problem?id=2001

 

思路:

从根结点开始遍历,如果找到一个点它只被访问了一次,那么到它一定就是最短的而且不会重复的前缀。

 

具体代码:

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <string>
 4 #include <iostream>
 5 #include <stdlib.h>
 6 #include <algorithm>
 7 
 8 using namespace std;
 9 const int MAX_NODE = 300001;
10 const int CHARSET = 26;
11 
12 int trie[MAX_NODE][CHARSET]={0};
13 //int color[MAX_NODE]={0};
14 int vis[MAX_NODE]={0};
15 int k = 1;
16 char s[MAX_NODE][1000];
17 
18 void insert(char w[])
19 {
20     int len = strlen(w);
21     int p = 0;  // 根结点
22     for (int i=0;i<len;i++)
23     {
24         int c = w[i] - a;
25         if (!trie[p][c])
26         {
27             trie[p][c] = k;
28             k++;
29         }
30         p = trie[p][c];
31         vis[p]++;
32     }
33     //color[p] = 1;
34 }
35 
36 
37 void search(char s[])
38 {
39     int len = strlen(s);
40     int p = 0;
41     for (int i=0;i<len;i++)
42     {
43         if (vis[p] == 1)
44             break;
45         int c = s[i]-a;
46         printf("%c",s[i]);
47         p = trie[p][c];
48 
49     }
50 }
51 
52 
53 int main()
54 {
55 #ifndef ONLINE_JUDGE
56     freopen("../in.txt", "r", stdin);
57 #endif
58     int t = 0;
59     while (scanf("%s",s[t])!=EOF)
60     {
61         insert(s[t]);
62        // cout << s[t] << endl;
63         t++;
64     }
65     //cout << t << endl;
66     for (int i=0;i<t;i++)
67     {
68         printf("%s ",s[i]);
69         search(s[i]);
70         printf("\n");
71     }
72     return 0;
73 }

 

 

Shortest Prefixes (最短前缀且不重复)

原文:https://www.cnblogs.com/-Ackerman/p/11209998.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!