Codeforces-GYM/101853:Maximum Sum(轮廓线DP)

E. Maximum Sum
time limit per test2.0 s
memory limit per test512 MB

inputstandard input
outputstandard output
You are given a grid consisting of n rows each of which is dived into n columns. The rows are numbered from 1 to n from top to bottom, and the columns are numbered from 1 to n from left to right. Each cell is identified by a pair ( x , y ) , which means that the cell is located in the row x and column y. All cells in the grid contain positive integers.

Your task is to choose a subset of the grid’s cells, such that their summation is as maximal as possible, and there are no two adjacent cells in that subset. Two cells are considered adjacent if they are horizontal, vertical, or diagonal neighbors.

Input
The first line contains an integer T ( 1 T 100 ) , in which T is the number of test cases.

The first line contains an integer n ( 1 n 16 ) , in which n is the number of rows and columns in the grid.

Then n lines follow, each line contains n integers, giving the grid. All values in the grid are between 1 and 1000 (inclusive).

Output
For each test case, print a single line containing the maximum sum of a subset of the grid’s cells. The chosen subset must not contain any adjacent cells.

Example
input
2
2
4 7
2 9
3
1 2 3
4 5 6
7 8 9
output
9
20

思路:轮廓线DP模版化的题。

#include<bits/stdc++.h>
using namespace std;
const int MAX=1e5+10;
const int MOD=998244353;
const int INF=1e9+7;
const double PI=acos(-1.0);
typedef long long ll;
int d[2][1<<17];    //二维滚动数组
int a[20][20];
int n;
int g(int x){return x&(1<<(n+1))?x^(1<<(n+1)):x;}//对1<<(n+1)取模
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        scanf("%d",&n);
        for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)scanf("%d",&a[i][j]);
        memset(d,0,sizeof d);
        int now=1,pre=0;
        for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
        {
            for(int k=0;k<(1<<(n+1));k++)
            {
                d[now][g(k<<1)]=max(d[now][g(k<<1)],d[pre][k]);//不选当前这个数
                //判断是否能选当前这个数
                int tag=0;
                if(i==0&&j==0)tag=1;
                if(i==0&&j&&(k&1)==0)tag=1;
                if(i&&j==0&&(k&(1<<(n-1)))==0&&(k&(1<<(n-2)))==0)tag=1;
                if(i&&j==n-1&&(k&1)==0&&(k&(1<<n))==0&&(k&(1<<(n-1)))==0)tag=1;
                if(i&&j&&j<n-1&&(k&1)==0&&(k&(1<<n))==0&&(k&(1<<(n-1)))==0&&(k&(1<<(n-2)))==0)tag=1;

                if(tag)d[now][g((k<<1)^1)]=max(d[now][g((k<<1)^1)],d[pre][k]+a[i][j]);//选当前这个数
            }
            memset(d[pre],0,sizeof d[pre]);
            now^=1;
            pre^=1;
        }
        printf("%d\n",*max_element(d[pre],d[pre]+(1<<(n+1))));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Mitsuha_/article/details/81663594