深度优先搜索 之 CODE[VS] 1018 单词接龙 2000年NOIP全国联赛普及组NOIP全国联赛提高组

/*
dfs即可AC。
注意:
	在清澄oj(http://www.tsinsen.com/A1126)评测时,测试数据中应该有非小写英文字母开头的字符串。
	codevs中的测试数据应该都是小写英文字母开头的字符串。
	所以注意数据结构的设计。
*/
 1 #include <iostream>
 2 #include <cstdlib>
 3 #include <cstdio>
 4 #include <cstddef>
 5 #include <iterator>
 6 #include <algorithm>
 7 #include <string>
 8 #include <locale>
 9 #include <cmath>
10 #include <vector>
11 #include <cstring>
12 #include <map>
13 #include <utility>
14 #include <queue>
15 #include <stack>
16 #include <set>
17 using namespace std;
18 const int INF = -0x3f3f3f3f;
19 const int MaxN = 55;
20 const int modPrime = 3046721;
21 
22 struct Node
23 {
24     string str;
25     int cnt;
26 };
27 
28 int n;
29 size_t answer = 0;
30 map<char, vector<Node> > wordSource;
31 
32 void Solve(string goalStr, bool isFirst)
33 {
34     for (size_t m = 0; m < goalStr.size(); ++m)
35     {
36         if ((m != 0) || (m == 0 && isFirst))
37         {
38             for (size_t i = 0; i < wordSource[goalStr[m]].size(); ++i)
39             {
40                 if (wordSource[goalStr[m]][i].cnt < 2)
41                 {
42                     string word = wordSource[goalStr[m]][i].str;
43                     size_t matchCnt = 0;
44                     while ((matchCnt < word.size()) && (m + matchCnt < goalStr.size())
45                         && (word[matchCnt] == goalStr[m + matchCnt]))
46                     {
47                         ++matchCnt;
48                     }
49                     if ((matchCnt > 0) && (matchCnt < word.size()) && (m + matchCnt == goalStr.size()))
50                     {
51                         ++wordSource[goalStr[m]][i].cnt;
52                         word.replace(0, matchCnt, goalStr);
53                         answer = max(answer, word.size());
54                         //cout << word << endl;
55                         Solve(word, false);
56                         --wordSource[goalStr[m]][i].cnt;
57                     }
58                 }
59             }
60         }
61     }
62 }
63 
64 
65 int main()
66 {
67 #ifdef HOME
68     freopen("in", "r", stdin);
69     //freopen("out", "w", stdout);
70 #endif
71 
72     cin >> n;
73     Node node;
74     for (int i = 0; i < n; ++i)
75     {
76 
77         cin >> node.str;
78         node.cnt = 0;
79         wordSource[node.str[0]].push_back(node);
80     }
81     string startStr;
82     cin >> startStr;
83     Solve(startStr, true);
84     cout << answer << endl;
85 
86 
87 #ifdef HOME
88     cerr << "Time elapsed: " << clock() / CLOCKS_PER_SEC << " ms" << endl;
89     _CrtDumpMemoryLeaks();
90 #endif
91     return 0;
92 }

 

 
posted @ 2015-12-04 12:09  JmingS  阅读(421)  评论(0编辑  收藏  举报