标签:
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1504 Accepted Submission(s): 865
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; int dp[17][1<<17]; int cnt[17][1<<17]; int a[17][17],n; char s[50]; int vis[20]; int maxx = 0; void dfs(int i,int now,int state,int sumstate) { maxx = max(maxx,dp[i][sumstate]); if(vis[now]==0) { if(now<n-1) { dfs(i,now+1,1,sumstate); } else { return; } } else if(vis[now]==1) { if(now>=n-1&&state==1) dfs(i,now+1,0,sumstate+(1<<now)); else if(now>=n-1&&state==0) return ; else if(now<n-1&&state==1) { dfs(i,now+1,0,sumstate+(1<<now)); dfs(i,now+1,1,sumstate); } else if(now<n-1&&state==0) { dfs(i,now+1,1,sumstate); } } return; } int cal(int c1,int c2) { return ((c1-‘0‘)*10+c2-‘0‘); } bool judge(int state) //判断此状态是否符合 { for(int i=0;i<n-1;i++) { if(((1<<i)&state)>0&&((1<<(i+1))&state)>0) return 0; } return 1; } int main() { while(gets(s)) { int len = strlen(s); n = (len+1)/3; int ans = 0; for(int i=0;i<len;i+=3) { a[0][ans++] = cal(s[i],s[i+1]); } for(int i=1;i<n;i++) { for(int j=0;j<n;j++) { scanf("%d",&a[i][j]); } } for(int i=0;i<n;i++) //预处理记录cnt[i][j] { for(int j=0;j<(1<<(n));j++) { int sum = 0; for(int k=0;k<n;k++) { if(((1<<k)&j)>0) { sum += a[i][k]; } } cnt[i][j] = sum; } } for(int j=0;j<(1<<n);j++) dp[0][j] = cnt[0][j]; for(int i=1;i<n;i++) //枚举每一行,枚举每个状态,判断可行性。 { for(int j=0;j<(1<<n);j++) { if(!judge(j)) continue; memset(vis,0,sizeof(vis)); for(int k=0;k<n;k++) { if(k==0) { if(((1<<k)&j)==0&&((1<<(k+1))&j)==0) { vis[k] = 1; } } else if(k==n-1) { if(((1<<k)&j)==0&&((1<<(k-1))&j)==0) { vis[k] = 1; } } else { if(((1<<k)&j)==0&&((1<<(k-1))&j)==0&&((1<<(k+1))&j)==0) { vis[k] = 1; } } } maxx = 0; //dfs寻找i-1行的最大值 if(vis[0]==0) dfs(i-1,0,0,0); else { dfs(i-1,0,1,0); dfs(i-1,0,0,0); } dp[i][j] = maxx+cnt[i][j]; } } getchar(); gets(s); int maxn = 0; for(int i=0;i<(1<<n);i++) maxn = max(maxn,dp[n-1][i]); printf("%d\n",maxn); memset(dp,0,sizeof(dp)); } return 0; } /* 10 20 30 10 20 30 10 20 30 */
标签:
原文地址:http://www.cnblogs.com/littlepear/p/5747723.html