Codevs Word Solitaire (DFS, substr)

Word Solitaire

analysis:

Deep search and the use of substr() function.

Since the connected words will only be connected one by one, it is impossible to connect two words separated by one word (so that the middle one is useless), so there is no need to store the connected "dragon", just know any two words Can they be connected? At least a few letters are connected, and then you can use DFS to search for the longest "dragon".

Although it will be overtime in theory, the data is relatively watery. From the problem, n<=20 should be associated with violent solution through traversal (it seems that there is really no clever way).

Code:

#include <bits/stdc++.h>
using namespace std;

string str[23];
int link[23][23] = {
    
     0 }, used[23] = {
    
     0 }, ans = 1, n;

void dfs(int a, int len)
{
    
    
	used[a]++;
	for (int i = 1; i <= n; i++){
    
    
		if (used[i]<2 && link[a][i]){
    
    
			dfs(i, len + str[i].length() - link[a][i]);
		}
	}
	used[a]--;
	ans = max(ans, len);
}

int main()
{
    
    
	char start;

	cin >> n;
	for (int i = 1; i <= n; i++) cin >> str[i];
	cin >> start;//输入数据

	for (int i = 1; i <= n; i++){
    
    
		for (int j = 1; j <= n; j++){
    
    
			for (int k = 1; k<str[i].length() && k<str[j].length(); k++){
    
    
				if (str[i].substr(str[i].length() - k, k) == str[j].substr(0, k)){
    
    
					link[i][j] = k;
					break;
				}
			}
		}
	}//迭代来找公共部分

	for (int i = 1; i <= n; i++){
    
    
		if (str[i][0] == start){
    
    
			dfs(i, str[i].length());
		}
	}//深搜来遍历每一种情况

	cout << ans;
	return 0;
}

Function record:

str.substr(start,len); The
function return value is a string (string), start is the starting position, starting from 0, and len is the length of the returned string.
The len can be left blank and the default is to the end.

Guess you like

Origin blog.csdn.net/qq_43700916/article/details/88647093