题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1565
方格取数(1)
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 8655 Accepted Submission(s): 3298
Problem Description
给你一个n*n的格子的棋盘,每个格子里面有一个非负数。
从中取出若干个数,使得任意的两个数所在的格子没有公共边,就是说所取的数所在的2个格子不能相邻,并且取出的数的和最大。
从中取出若干个数,使得任意的两个数所在的格子没有公共边,就是说所取的数所在的2个格子不能相邻,并且取出的数的和最大。
Input
包括多个测试实例,每个测试实例包括一个整数n 和n*n个非负数(n<=20)
Output
对于每个测试实例,输出可能取得的最大的和
Sample Input
3 75 15 21 75 15 28 34 70 5
Sample Output
188
题解:
…………
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <sstream>
#include <algorithm>
using namespace std;
#define ms(a, b) memset((a), (b), sizeof(a))
#define eps 0.0000001
typedef long long LL;
const int INF = 2e9;
const LL LNF = 9e18;
const int mod = 1e9+7;
const int maxn = 17711+10;
int n, a[25][25], sta[maxn], val[maxn], dp[25][maxn];
int tot;
void input()
{
for(int i = 1; i<=n; i++)
for(int j = 1; j<=n; j++)
scanf("%d",&a[i][j]);
}
void init()
{
tot = 0;
for(int i = 0; i<(1<<n); i++)
{
if((i&(i<<1))==0)
sta[++tot] = i;
}
ms(dp,0);
}
int cal(int r, int state)
{
int sum = 0;
for(int i = 1; state>0; state>>=1, i++)
{
if(state&1)
sum += a[r][i];
}
return sum;
}
void solve()
{
for(int r = 1; r<=n; r++)
{
for(int j = 1; j<=tot; j++)
for(int k = 1; k<=tot; k++)
{
if((sta[j]&sta[k])==0)
dp[r][j] = max(dp[r][j], dp[r-1][k]+ cal(r,sta[j]));
}
}
int ans = 0;
for(int i = 1; i<=tot; i++)
if(dp[n][i]>ans)
ans = max(ans, dp[n][i]);
printf("%d\n",ans);
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
input();
init();
solve();
}
return 0;
}
本文介绍了一道经典的动态规划问题——方格取数,旨在最大化非相邻元素之和。通过递推公式与状态转移矩阵,实现了高效求解。适用于初学者理解DP核心思想。
327

被折叠的 条评论
为什么被折叠?



