版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36616023/article/details/82533636
给你一个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<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100;
const int maxm=maxn*maxn;
const int inf=0x3f3f3f3f;
int head[maxm],cnt=0;
int mapp[maxn][maxn];
struct edge
{
int v,nxt,w;
}edge[maxm*3+100];
int dir[4][2]={0,1,1,0,0,-1,-1,0};
void add_edge(int u,int v,int w)
{
edge[cnt].v=v;
edge[cnt].w=w;
edge[cnt].nxt=head[u];
head[u]=cnt++;
//edge[cnt].u=v;
edge[cnt].v=u;
edge[cnt].w=0;
//edge[cnt].cost=-cost;
edge[cnt].nxt=head[v];
head[v]=cnt++;
}
int numh[maxm],h[maxm],curedge[maxm],pre[maxm];
int sap(int s,int t,int n)
{
memset(numh,0,sizeof(numh));
memset(h,0,sizeof(h));
memset(pre,-1,sizeof(pre));
int cur_flow,flow_ans=0,u,tmp,neck,i;
for(i=1;i<=n;i++)
{
curedge[i]=head[i];
}
numh[0]=n;
u=s;
while(h[s]<n)
{
//printf("%d\n",h[s]);
//printf("1111\n");
if(u==t)
{
cur_flow=inf;
for(i=s;i!=t;i=edge[curedge[i]].v)
{
if(cur_flow>edge[curedge[i]].w)
{
neck=i;
cur_flow=edge[curedge[i]].w;
}
}
for(i=s;i!=t;i=edge[curedge[i]].v)
{
tmp=curedge[i];
edge[tmp].w-=cur_flow;
edge[tmp^1].w+=cur_flow;
}
flow_ans+=cur_flow;
u=neck;
}
for(i=curedge[u];i!=-1;i=edge[i].nxt)
{
if(edge[i].w&&h[u]==h[edge[i].v]+1)
{
break;
}
}
if(i!=-1)
{
curedge[u]=i;
pre[edge[i].v]=u;
u=edge[i].v;
}
else
{
if(0==--numh[h[u]])
break;
curedge[u]=head[u];
for(tmp=n,i=head[u];i!=-1;i=edge[i].nxt)
{
if(edge[i].w)
{
tmp=min(tmp,h[edge[i].v]);
}
}
h[u]=tmp+1;
++numh[h[u]];
if(u!=s)
u=pre[u];
}
}
return flow_ans;
}
int nn;
int getpos(int x,int y)
{
return ((x-1)*nn+y);
}
int main ()
{
while(~scanf("%d",&nn))
{
int sum=0;
for(int i=1;i<=nn;i++)
{
for(int j=1;j<=nn;j++)
{
scanf("%d",&mapp[i][j]);
sum+=mapp[i][j];
}
}
memset(head,-1,sizeof(head));
cnt=0;
int s=nn*nn+1;
int t=s+1;
for(int i=1;i<=nn;i++)
{
for(int j=1;j<=nn;j++)
{
if((i+j)%2==0)
{
add_edge(s,getpos(i,j),mapp[i][j]);
}
else if((i+j)%2==1)
{
add_edge(getpos(i,j),t,mapp[i][j]);
}
}
}
for(int i=1;i<=nn;i++)
{
for(int j=1;j<=nn;j++)
{
if((i+j)%2==0)
{
for(int k=0;k<4;k++)
{
int xx,yy;
xx=i+dir[k][0];
yy=j+dir[k][1];
if(xx>=1&&yy>=1&&xx<=nn&&yy<=nn)
{
add_edge(getpos(i,j),getpos(xx,yy),inf);
}
}
}
}
}
int answer=sap(s,t,t);
printf("%d\n",sum-answer);
}
}
/*
*/