P1278 单词游戏 - DFS

P1278 单词游戏

传送门

Sol:

枚举词典中的每个单词,然后跑DFS。再加个记忆化就不会T了。

AC Code:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 16 + 4,M = 100 + 10;
int n;
char S[N][M];
int len[N];
int f[N][1<<N];
int dfs(int x,int ud){
	if(f[x][ud]) return f[x][ud];
	for(int i=0;i<n;i++){
		if((ud>>i)&1) continue;
		if(S[x][len[x]]!=S[i][1]) continue;
		f[x][ud]=max(f[x][ud],dfs(i,ud|(1<<i))+len[i]);
	}
	return f[x][ud];
}
int main(){
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		scanf("%s",S[i]+1);len[i]=strlen(S[i]+1);
	}
	int ans=-(1<<30);
	for(int i=0;i<n;i++){
		ans=max(ans,dfs(i,(1<<i))+len[i]);
	}
	printf("%d",ans);
	return 0;
}
posted @ 2018-10-05 12:41  dprswdr  阅读(163)  评论(0)    收藏  举报