上古NOI原题,刚学搜索时完全没头绪,过了几个月之后倒是很顺利的做出来了。
题目:
思路:
首先我们需要通过需处理出每个字符串对应每个字符串能接的后缀长度(可以有效地降低时间复杂度),此时就需要使用到字符串截取函数 substr (底部附有用法) ,由于我们需要找到最长的“龙”长度,所以我们在预处理时只需要找到最小的可接上的长度即可。之后便是找到首字母之后进行搜索,答案可以设置一个全局变量进行更新。
1 #include <iostream>
2 #include <cstring>
3 #include <cstdio>
4 #include <algorithm>
5
6 using namespace std;
7
8 const int N = 25;
9
10 string str[N];
11 int n;
12 string start, end;
13 int cnt[N][N];
14 int res;
15 int st[N];
16
17 void dfs(string start, int last)
18 {
19 res = max(res, (int)start.size());
20
21 for (int i = 0; i < n; i ++ )
22 if (st[i] < 2 && cnt[last][i])
23 {
24 st[i] ++ ;
25 dfs(start + str[i].substr(cnt[last][i]), i);
26 st[i] -- ;
27 }
28 }
29
30 int main()
31 {
32 cin >> n;
33 char c;
34 for (int i = 0; i < n; i ++ ) cin >> str[i];
35 cin >> c;
36
37 for (int i = 0; i < n; i ++ )
38 for (int j = 0; j < n; j ++ )
39 {
40 string a = str[i], b = str[j];
41 for (int k = 1; k <= a.size(); k ++ )
42 if (a.substr(a.size() - k) == b.substr(0, k))
43 {
44 cnt[i][j] = k;
45 break;
46 }
47 }
48
49 for (int i = 0; i < n; i ++ )
50 if (str[i][0] == c)
51 {
52 st[i] ++ ;
53 dfs(str[i], i);
54 st[i] -- ;
55 }
56
57 cout << res << endl;
58
59 return 0;
60 }
字符串截取函数 substr 用法:
s.substr(pos, n) 截取s中从pos开始(包括0)的n个字符的子串,并返回。
s.substr(pos) 截取s中从从pos开始(包括0)到末尾的所有字符的子串,并返回。