hihoCoder#1036 Trie图

原题地址

 

看了这篇博文,总算是把Trie图弄明白了

Runtime Error了无数次,一直不知道为什么,于是写了个脚本生成了一组大数据,发现果然段错误了。

调试了一下午,总算闹明白了,为什么呢?

1. 空间超大的变量不要放在函数里,会爆栈,应该弄成全局变量或者是从堆上动态分配。

2. 看清题目的数据范围,一开始我的MAX_NODE设的是1024。。。

代码:

 1 #include <iostream>

 2 #include <cstring>

 3 

 4 using namespace std;

 5 

 6 #define MAX_NODE 1000010

 7 #define SIGMA_SIZE 32

 8 

 9 int q[MAX_NODE];

10 

11 struct TrieGraph {

12   int f[MAX_NODE];

13   int g[MAX_NODE][SIGMA_SIZE];

14   int m[MAX_NODE];

15   int size;

16 

17   void init() {

18     size = 1;

19     memset(f, 0, sizeof(f));

20     memset(g[0], 0, sizeof(g[0]));

21   }

22 

23   int index(char c) {

24     return c - 'a';

25   }

26 

27   void insert(const char *s) {

28     int u = 0;

29     while (*s) {

30       int i = index(*s);

31       if (!g[u][i]) {

32         memset(g[size], 0, sizeof(g[size]));

33         m[size] = 0;

34         g[u][i] = size++;

35       }

36       u = g[u][i];

37       s++;

38     }

39     m[u] = 1;

40   }

41 

42   void build() {

43     int qh = 0, qt = 0;

44     f[0] = 0;

45     for (int i = 0; i < 26; i++) {

46       int &p = g[0][i];

47       if (p) {

48         f[p] = 0;

49         q[qt++] = p;

50       }

51       else

52         p = 0;

53     }

54     while (qh < qt) {

55       int u = q[qh++];

56       for (int i = 0; i < 26; i++) {

57         int &v = g[u][i];

58         if (v) {

59           q[qt++] = v;

60           f[v] = g[f[u]][i];

61           m[u] |= m[f[u]];

62         }

63         else

64           v = g[f[u]][i];

65       }

66     }

67   }

68 

69   bool find(const char *s) {

70     int u = 0;

71     while (*s) {

72       int i = index(*s);

73       while (u && !g[u][i])

74         u = f[u];

75       u = g[u][i];

76       if (m[u])

77         return true;

78       s++;

79     }

80     return false;

81   }

82 } tg;

83 

84 int main() {

85   int N;

86   string s;

87 

88   tg.init();

89   cin >> N;

90   for (int i = 0; i < N; i++) {

91     cin >> s;

92     tg.insert(s.c_str());

93   }

94   tg.build();

95   cin >> s;

96   cout << (tg.find(s.c_str()) ? "YES" : "NO") << endl;

97   return 0;

98 }

 

你可能感兴趣的:(code)