POJ 2817 WordStack(状态压缩DP)
以前的坑,以前做的时候,用暴力各种跪,其实是状态压缩DP。暴力处理出来后,状态+标记最后一个单词。
1 #include <cstdio> 2 #include <cstring> 3 #include <cmath> 4 #include <iostream> 5 using namespace std; 6 char p[12][12]; 7 int o[12][12]; 8 int dp[1026][12]; 9 int dfs(int x,int y) 10 { 11 int i,j,k,len1,len2,ret,ans; 12 len1 = strlen(p[x]); 13 len2 = strlen(p[y]); 14 ans = 0; 15 for(i = 0; i <= len1-1; i ++) 16 { 17 ret = 0; 18 for(j = 0,k = i; j <= len2-1&&k <= len1-1; j ++,k ++) 19 { 20 if(p[x][k] == p[y][j]) 21 ret ++; 22 } 23 if(ans < ret) 24 ans = ret; 25 } 26 for(i = 0; i <= len2-1; i ++) 27 { 28 ret = 0; 29 for(j = 0,k = i; j <= len1-1&&k <= len2-1; j ++,k ++) 30 { 31 if(p[y][k] == p[x][j]) 32 ret ++; 33 } 34 if(ans < ret) 35 ans = ret; 36 } 37 return ans; 38 } 39 int main() 40 { 41 int i,j,num,temp,n,u,k; 42 while(scanf("%d%*c",&n)!=EOF) 43 { 44 if(!n) break; 45 memset(dp,-1,sizeof(dp)); 46 for(i = 0; i < n; i ++) 47 scanf("%s",p[i]); 48 for(i = 0; i < n-1; i ++) 49 { 50 for(j = i+1; j < n; j ++) 51 { 52 o[i][j] = o[j][i] = dfs(i,j); 53 } 54 } 55 for(i = 0; i < n; i ++) 56 { 57 dp[1<<i][i] = 0; 58 } 59 num = n; 60 for(i = 1; i < n; i ++) 61 { 62 temp = 0; 63 for(j = 1; j < 1<<n; j ++) 64 { 65 for(u = 0; u < n; u ++) 66 { 67 for(k = 0; k < n; k ++) 68 { 69 if(j&(1<<k)) continue; 70 if(dp[j][u] == -1) continue; 71 if(dp[j+(1<<k)][k] < dp[j][u] + o[u][k]) 72 dp[j+(1<<k)][k] = dp[j][u] + o[u][k]; 73 } 74 } 75 } 76 } 77 int maxz = 0; 78 for(i = 0;i < n;i ++) 79 maxz = max(dp[(1<<n)-1][i],maxz); 80 printf("%d\n",maxz); 81 } 82 return 0; 83 }