状态dp-创新互联

成都创新互联公司是一家专业提供松滋企业网站建设,专注与成都做网站、网站建设、H5开发、小程序制作等业务。10年已为松滋众多企业、政府机构等服务。创新互联专业网站建设公司优惠进行中。方格取数(1)

Time Limit : 10000/5000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 3   Accepted Submission(s) : 1

Font: Times New Roman | Verdana | Georgia

Font Size: ← →

Problem Description

给你一个n*n的格子的棋盘,每个格子里面有一个非负数。
从中取出若干个数,使得任意的两个数所在的格子没有公共边,就是说所取的数所在的2个格子不能相邻,并且取出的数的和大。

Input

包括多个测试实例,每个测试实例包括一个整数n 和n*n个非负数(n<=20)

Output

对于每个测试实例,输出可能取得的大的和

Sample Input

3
75 15 21 
75 15 28 
34 70 5

Sample Output

188

View Code
#include <stdio.h>
#include<stack>

using std::stack;
const int INF = 0x3f3f3f3f ;
const int MAXN = 1<<19 ;
int okay[MAXN/2], valid, n, cnt;
int g[25][25];
int dp[2][MAXN/2];
void judge()
{
for(int i=0; i<=valid; i++)
if(!(i&(i<<1)))
            okay[++cnt] = i;
}
int sum(int x, int row)
{
int times = n, res = 0 ;
while( x )
    {
if( x%2 )
            res+= g[row][times];
        x= x/2 ;
        times-- ;
    }
return res;
}
int max(int a, int b)
{return a>=b ?a :b ;  }
int main()
{
int i, j, row;
bool flag ;
while(scanf("%d", &n)!=EOF)
    {
        cnt= 0;
        valid= (1<<n) -1;
        judge();
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
                scanf("%d", &g[i][j]);
        flag= 1;
        memset(dp,0, sizeof(dp));
for(row = 1; row <=n; row++)
        {
for(i=1; i<=cnt; i++)
            {
                dp[flag][i]= 0 ;
for(j=1; j<=cnt; j++)
                {
if( (okay[j] & okay[i]) == 0 )
                        dp[flag][i]= max(dp[flag][i], dp[!flag][j]);
                }
                dp[flag][i]+= sum(okay[i], row); //这里加!不然超时            }
            
            flag= !flag ;
        }
int ans = 0 ;
for(i=1; i<=cnt; i++)
if(ans < dp[!flag][i])
                ans= dp[!flag][i];
        printf("%d
", ans);
    }
return 0;
}


本文名称:状态dp-创新互联
网页URL:https://www.cdcxhl.com/article32/doispc.html

成都网站建设公司_创新互联,为您提供移动网站建设微信小程序全网营销推广品牌网站设计营销型网站建设搜索引擎优化

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

外贸网站制作