您的位置:首页 > 其它

[HDU] 1565 方格取数(1) [插头dp]

2017-08-27 15:51 225 查看
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

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int dp[2][1<<20], arr[20][20];

int main()
{
int n;
while(scanf("%d", &n) != EOF) {
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
scanf("%d", &arr[i][j]);
}
}
memset(dp, 0, sizeof(dp));
int *crt = dp[0], *next = dp[1];
for(int i = 0; i < n; ++i) {
for(int j = n - 1; ~j; --j) {
for(int s = 0; s < 1<<n; ++s) {
if(s>>j&1) {
if(j + 1 < n && s>>(j + 1)&1) continue;
next[s] = crt[s^(1<<j)] + arr[i][j];
} else {
next[s] = max(crt[s], crt[s^(1<<j)]);
}
}
swap(crt, next);
}
}
int ans = 0;
for(int s = 0; s < 1<<n; ++s) {
if(s&(s<<1)) continue;
ans = max(ans, crt[s]);
}
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: