当前位置: 代码迷 >> 综合 >> 方格取数 hdu 1565 最小割
  详细解决方案

方格取数 hdu 1565 最小割

热度:35   发布时间:2024-01-11 16:11:38.0


选取的格子不相邻,即可以在相邻的格子间连一条流量为inf的边,不能被割去


#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define maxn 444
#define maxm 33333
#define INF 0x3f3f3f3f
int head[maxn],cur[maxn],d[maxn],st[maxm],s,e,no,n;
struct point
{int u,v,flow,next;point(){};point(int x,int y,int z,int w):u(x),v(y),next(z),flow(w){};
}p[maxm];
void add(int x,int y,int z)
{p[no]=point(x,y,head[x],z);head[x]=no++;p[no]=point(y,x,head[y],0);head[y]=no++;
}
void init()
{memset(head,-1,sizeof(head));no=0;
}
bool bfs()
{int i,x,y;queue<int>q;memset(d,-1,sizeof(d));d[s]=0;q.push(s);while(!q.empty()){x=q.front();q.pop();for(i=head[x];i!=-1;i=p[i].next){if(p[i].flow&& d[y = p[i].v]<0){d[y]=d[x]+1;if(y==e)return true;q.push(y);}}}return false;
}
int dinic()
{int i,loc,top,x=s,nowflow,maxflow=0;while(bfs()){for(i=s;i<=e;i++)cur[i]=head[i];top=0;while(true){if(x==e){nowflow=INF;for(i=0;i<top;i++){if(nowflow>p[st[i]].flow){nowflow=p[st[i]].flow;loc=i;}}for(i=0;i<top;i++){p[st[i]].flow-=nowflow;p[st[i]^1].flow+=nowflow;}maxflow+=nowflow;top=loc;x=p[st[top]].u;}for(i=cur[x];i!=-1;i=p[i].next)if(p[i].flow&&d[p[i].v]==d[x]+1)break;cur[x]=i;if(i!=-1){st[top++]=i;x=p[i].v;}else{if(!top)break;d[x]=-1;x=p[st[--top]].u;}}}return maxflow;
}
int dx[4] = { -1 , 0 , 1 , 0 } ;
int dy[4] = { 0 , -1 , 0 , 1 } ;
int N,map[22][22];
int main()
{while( ~ scanf("%d", &N)){init();int sum = 0;for(int i = 1 ; i <= N ; i ++)for(int j = 1 ; j <= N ; j ++)scanf("%d", &map[i][j]) , sum += map[i][j] ;s = 0;e = N * N + 1;n = N * N;for(int i = 1 ; i <= N ; i ++)for(int j = 1 ; j <= N ; j ++){if((i + j) % 2){ /// odd gridsadd(s , (i - 1) * N + j , map[i][j]);for(int op = 0 ; op <= 3 ; op ++ ){int x = i + dx[op] , y = j + dy[op] ;if(x >= 1 && x <= N && y >= 1 && y <= N )add((i - 1) * N + j , (x - 1) * N + y , INF) ;}}elseadd((i - 1) * N + j , e , map[i][j]); /// even grids}printf("%d\n" , sum - dinic());}return 0;
}