网络流24题9
把棋盘的相邻关系转化为二分图做
然后就是最大独立点集
然后带权的就用网络流
因为每个割对应一种取独立点集的方案
跑一边最小割
https://loj.ac/problem/6007
#include <iostream> #include <queue> #include <cstring> #include <stdio.h> using namespace std; const int maxn = 109; int a[maxn][maxn]; int dir[4][2] = {1,0,-1,0,0,1,0,-1}; int head[maxn*maxn]; int tot; struct edge{ int v,nex,w; }e[maxn*maxn*8]; void addedge(int u,int v,int w){ e[tot] = (edge){v,head[u],w}; head[u] = tot++; e[tot] = (edge){u,head[v],0}; head[v] = tot++; } int deep[maxn*maxn]; bool bfs(int S,int T){ memset(deep,0,sizeof(deep)); deep[S] = 1; queue<int> q; q.push(S); while(!q.empty()){ int now = q.front(); q.pop(); for(int i=head[now];i!=-1;i=e[i].nex){ int v = e[i].v; int w = e[i].w; if(w<=0 || deep[v]!=0) continue; deep[v] = deep[now]+1; q.push(v); } } return deep[T]; } int dfs(int now,int T,int maxflow){ if(now==T) return maxflow; int all = 0; for(int i=head[now];i!=-1 && all<maxflow;i=e[i].nex){ int v = e[i].v; int w = e[i].w; if(w<=0 || deep[v]!=deep[now]+1) continue; int tt =dfs(v,T,min(maxflow-all,w)); e[i].w-=tt; e[i^1].w+=tt; all+=tt; } return all; } int dinic(int S,int T){ int ret = 0; while(bfs(S,T)){ ret+=dfs(S,T,0x3f3f3f3f); } return ret; } int main() { int n,m; scanf("%d%d",&m,&n); memset(head,-1,sizeof(head)); int T=(n+1)*m+1; tot = 0; int all = 0; for(int i=1;i<=m;i++){ for(int j=1;j<=n;j++){ int t; scanf("%d",&t); all +=t; if((i+j)%2==0){ addedge(0,i*n+j,t); for(int k=0;k<4;k++){ int nx = i+dir[k][0]; int ny = j+dir[k][1]; if(nx<=m && nx>=1 && ny<=n&&ny>=1){ addedge(i*n+j,nx*n+ny,0x3f3f3f3f); } } }else{ addedge(i*n+j,T,t); } } } int ans = all-dinic(0,T); printf("%d\n",ans); return 0; }