POJ2001+字典树

简单的字典树

View Code
 1 /*

 2 字典树

 3 */

 4 #include<stdio.h>

 5 #include<string.h>

 6 #include<stdlib.h>

 7 #include<algorithm>

 8 #include<iostream>

 9 #include<queue>

10 #include<map>

11 #include<vector>

12 #include<math.h>

13 using namespace std;

14 typedef long long ll;

15 //typedef __int64 int64;

16 const int maxn = 26;

17 const int inf = 0x7FFFFFFF;

18 const int CLEAR = 0x7F;

19 const double pi=acos(-1.0);

20 const double eps = 1e-8;

21 struct tree{

22     int lev;

23     tree* next[ maxn ];

24 };

25 tree root;

26 char ch[ 1005 ][ maxn ];

27 

28 void build( char str[] ){

29     tree *p = &root;

30     tree *tmp;

31     int len = strlen( str );

32     for( int i=0;i<len;i++ ){

33         int id = str[ i ]-'a';

34         if( p->next[ id ]==NULL ){

35             tmp = ( tree * )malloc( sizeof(root) );

36             tmp->lev = 1;

37             for( int j=0;j<maxn;j++ ){

38                 tmp->next[j]=NULL;

39             }

40             p->next[ id ] = tmp;

41             p = p->next[ id ];

42         }

43         else{

44             p->next[ id ]->lev++;

45             p = p->next[ id ];

46         }

47     }

48 }//建树

49 int find( char str[] ){

50     int len = strlen( str );

51     tree *p = &root;

52     for( int i=0;i<len;i++ ){

53         int id = str[ i ]-'a';

54         if( p->next[id]==NULL ){

55             return -1;

56         }

57         p = p->next[id];

58         if( p->lev==1 ) return i;

59     }

60     return len-1;

61 }//查找

62 

63 int main(){

64     int cnt = 0;

65     while( scanf("%s",ch[ cnt ])!=EOF ){

66         build( ch[ cnt ] );

67         cnt++;

68     }

69     for( int i=0;i<cnt;i++ ){

70         int pos;

71         pos = find( ch[i] );

72         printf("%s ",ch[ i ]);

73         for( int j=0;j<=pos;j++ ){

74             printf("%c",ch[ i ][ j ]);

75         }

76         printf("\n");

77     }

78     delete (&root);

79     return 0;

80 }

 

你可能感兴趣的:(poj)