Phone List--POJ 3630

1、题目类型:字符串、字典树、排序查找。

2、解题思路:找寻字符串的字串。

3、注意事项:trie树Insert()时后继数组的更新,注意考虑对比当前数据和字典中数据长、短、相等这三种情况,注意控制静态开辟结构体数组的长度。

4、实现方法:(trie树:Memory: 26108K、Time: 641MS)

  
    
1 #include < iostream >
2 #include < string >
3   using namespace std;
4
5 struct Trie
6 {
7 bool end;
8 Trie * nxt[ 10 ];
9 };
10
11 Trie root,Arr[ 600000 ];
12 int num;
13 bool flag;
14
15 void Insert( char str[])
16 {
17 Trie * Current =& root;
18 int i;
19 for (i = 0 ;i < strlen(str);i ++ )
20 {
21 if (Current -> nxt[str[i] - ' 0 ' ] == NULL)
22 {
23 Current -> nxt[str[i] - ' 0 ' ] =& Arr[num ++ ];
24 // 当前比字典中数长
25 if (Current -> end)
26 flag = 1 ;
27 }
28 Current = Current -> nxt[str[i] - ' 0 ' ];
29 }
30
31 // 当前和字典中数相等
32 if (i == strlen(str) && Current -> end)
33 flag = 1 ;
34 Current -> end = true ;
35
36 // 当前比字典中数短
37 for ( int j = 0 ;j < 10 ;j ++ )
38 {
39 if (Current -> nxt[j] != NULL)
40 {
41 flag = 1 ;
42 break ;
43 }
44 }
45 }
46
47 int main()
48 {
49 int i,j,k,n,m;
50 char str[ 10010 ];
51 cin >> n;
52 for (i = 0 ;i < n;i ++ )
53 {
54 flag = 0 ;
55 num = 0 ;
56 root.end = false ;
57 memset(Arr, 0 , sizeof (Arr));
58
59 for (k = 0 ;k < 10 ;k ++ )
60 root.nxt[k] = NULL;
61 cin >> m;
62 for (j = 0 ;j < m;j ++ )
63 {
64 scanf( " %s " ,str);
65 if ( ! flag)
66 Insert(str);
67 }
68 if ( ! flag)
69 cout << " YES " << endl;
70 else
71 cout << " NO " << endl;
72 }
73 return 0 ;
74 }

5、实现方法:(排序查找:Memory:  836K、Time: 391MS)

  
    
1 #pragma warning (disable:4786)
2 #include < iostream >
3 #include < string >
4 #include < vector >
5 #include < algorithm >
6 using namespace std;
7
8 vector < string > v;
9
10 bool Match( string a, string b)
11 {
12 int i = 0 ;
13 while (a[i] != ' \0 ' && b[i] != ' \0 ' )
14 {
15 if (a[i] == b[i])
16 i ++ ;
17 else
18 return 0 ;
19 }
20 return 1 ;
21 }
22
23 int main()
24 {
25 int t,n,i;
26 bool flag;
27 cin >> t;
28 string tmp;
29 while (t -- )
30 {
31 v.clear();
32 cin >> n;
33 while (n -- )
34 {
35 cin >> tmp;
36 v.push_back(tmp);
37 }
38 sort(v.begin(),v.end());
39 i = 0 ; flag = 0 ;
40 while (i < v.size() - 1 && ! flag)
41 {
42 flag = Match(v[i],v[i + 1 ]);
43 i ++ ;
44 }
45 if (flag)
46 cout << " NO " << endl;
47 else
48 cout << " YES " << endl;
49 }
50 return 0 ;
51 }

 

你可能感兴趣的:(list)