POJ 2817 WordStack(状态压缩DP)

#include<iostream> #include<cstdio> #include<cstring> using namespace std; int pow[15]; int dp[1<<12][10],N; char word[15][25]; int W[15][15]; void init() { int w; memset(W,0,sizeof(W)); for(int i = 0;i < N;++i) { for(int j = 0;j < N;++j) { if(i == j) continue; int len1 = strlen(word[i]); int len2 = strlen(word[j]); for(int k = 0;k < len1;++k) { w = 0; for(int h = 0;h < len2;++h) { if(k + h >= len1) break; if(word[i][k+h] == word[j][h]) ++w; } if(W[i][j] < w) W[i][j] = W[j][i] = w; } } } } int DP() { int ans = 0; memset(dp,0,sizeof(dp)); for(int S = 1;S < pow[N];++S) { for(int i = 0;i < N;++i) { if((S & pow[i]) == 0) continue; int pS = S ^ pow[i]; for(int j = 0;j < N;++j) { if((pS & pow[j]) == 0) continue; dp[S][i] = max(dp[S][i],dp[pS][j] + W[j][i]); } } } for(int i = 0;i < N;++i) if(dp[pow[N]-1][i] > ans) ans = dp[pow[N]-1][i]; return ans; } int main() { //freopen("in.txt","r",stdin); pow[0] = 1; for(int i = 1;i <= 12;++i) pow[i] = pow[i-1] * 2; while(scanf("%d",&N) && N) { for(int i = 0;i < N;++i) scanf("%s",word[i]); init(); printf("%d/n",DP()); } }  

你可能感兴趣的:(POJ 2817 WordStack(状态压缩DP))