大意: 给定$n*m$棋盘, 每个格子有权值, 不能选择相邻格子, 求能选出的最大权值.
二分图带权最大独立集, 转化为最小割问题.
S与$X$连边权为权值的边, $X$与$Y$之间连$INF$, $Y$与$T$连边权为权值的边.
则最大权值为总权值-最小割. 残量网络中与$S$相连的或与$T$相连的表示选择, 否则表示不选.
#include <iostream> #include <sstream> #include <algorithm> #include <cstdio> #include <math.h> #include <set> #include <map> #include <queue> #include <string> #include <string.h> #include <bitset> #include <unordered_map> #define REP(i,a,n) for(int i=a;i<=n;++i) #define PER(i,a,n) for(int i=n;i>=a;--i) #define hr putchar(10) #define pb push_back #define lc (o<<1) #define rc (lc|1) #define mid ((l+r)>>1) #define ls lc,l,mid #define rs rc,mid+1,r #define x first #define y second #define io std::ios::sync_with_stdio(false) #define endl ' ' #define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;}) using namespace std; typedef long long ll; typedef pair<int,int> pii; const int P = 1e9+7, P2 = 998244353, INF = 0x3f3f3f3f; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;} ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;} inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;} //head const int N = 1e6+10; const int dx[]={0,0,1,-1}; const int dy[]={1,-1,0,0}; int n, m, S, T; struct edge { int v,w,next; } e[N]; int head[N], dep[N], vis[N], cur[N], cnt=1; queue<int> Q; void add(int u, int v, int w) { e[++cnt] = {v,w,head[u]}; head[u] = cnt; e[++cnt] = {u,0,head[v]}; head[v] = cnt; } int bfs() { REP(i,1,T) dep[i]=INF,vis[i]=0,cur[i]=head[i]; dep[S]=0,Q.push(S); while (Q.size()) { int u = Q.front(); Q.pop(); for (int i=head[u]; i; i=e[i].next) { if (dep[e[i].v]>dep[u]+1&&e[i].w) { dep[e[i].v]=dep[u]+1; Q.push(e[i].v); } } } return dep[T]!=INF; } int dfs(int x, int w) { if (x==T) return w; int used = 0; for (int i=cur[x]; i; i=e[i].next) { cur[x] = i; if (dep[e[i].v]==dep[x]+1&&e[i].w) { int flow = dfs(e[i].v,min(w-used,e[i].w)); if (flow) { used += flow; e[i].w -= flow; e[i^1].w += flow; if (used==w) break; } } } return used; } int dinic() { int ans = 0; while (bfs()) ans+=dfs(S,INF); return ans; } int get(int x, int y) { return m*(x-1)+y; } int main() { scanf("%d%d", &n, &m); S = n*m+1, T = S+1; int tot = 0; REP(i,1,n) REP(j,1,m) { int t; scanf("%d", &t); if (i+j&1) { add(S,get(i,j),t); REP(k,0,3) { int ii=i+dx[k],jj=j+dy[k]; if (1<=ii&&ii<=n&&1<=jj&&jj<=m) { add(get(i,j),get(ii,jj),INF); } } } else add(get(i,j),T,t); tot += t; } printf("%d ",tot-dinic()); }