题意思路:见这个,写的很详细了,题解,主要难在建图和流量大于等于0的时候就停止增广
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
#define LL long long
const int maxn = 2005;
#define INF 1e9
struct Edge
{
int from,to,cap,flow,cost;
Edge(int u,int v,int c,int f,int w):from(u),to(v),cap(c),flow(f),cost(w){}
};
struct MCMF
{
int n,m;
vector<Edge>edges;
vector<int>G[maxn];
int inq[maxn];
int d[maxn];
int p[maxn];
int a[maxn];
void init(int n)
{
this->n=n;
for (int i =0;i<n;i++)
G[i].clear();
edges.clear();
}
void AddEdge(int from,int to,int cap,int cost)
{
edges.push_back(Edge(from,to,cap,0,cost));
edges.push_back(Edge(to,from,0,0,-cost));
m = edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
bool BellmanFord(int s,int t,int &flow,LL &cost)
{
for (int i = 0;i<n;i++)
d[i]=INF;
memset(inq,0,sizeof(inq));
d[s]=0;
inq[s]=1;
p[s]=0;
a[s]=INF;
queue<int>q;
q.push(s);
while (!q.empty())
{
int u = q.front();
q.pop();
inq[u]=0;
for (int i =0;i<G[u].size();i++){
Edge&e = edges[G[u][i]];
if (e.cap>e.flow&&d[e.to]>d[u]+e.cost){
d[e.to]=d[u]+e.cost;
p[e.to]=G[u][i];
a[e.to]=min(a[u],e.cap-e.flow);
if (!inq[e.to])
{
q.push(e.to);
inq[e.to]=1;
}
}
}
}
if (d[t]>=0)
return false;
if (d[t]==INF)
return false;
flow+=a[t];
cost+=(LL)d[t]*(LL)a[t];
for (int u = t;u!=s;u=edges[p[u]].from){
edges[p[u]].flow+=a[t];
edges[p[u]^1].flow-=a[t];
}
return true;
}
int MincostMaxflow(int s,int t,LL &cost)
{
int flow = 0;
cost = 0;
while (BellmanFord(s,t,flow,cost));
return flow;
}
}mc;
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int main()
{
int T,cas=1;
scanf("%d",&T);
while (T--)
{
int n,m,k;
scanf("%d%d%d",&n,&m,&k);
mc.init(n*m+2);
int s = n*m;
int t = n*m+1;
int ans = 0;
for (int i = 0;i<n;i++)
for (int j = 0;j<m;j++)
{
int temp;
scanf("%d",&temp);
ans+=temp*temp;
if ((i+j)%2==0)
{
for (int kk = 1;kk<=k;kk++)
mc.AddEdge(s,i*m+j,1,2*kk-1-2*temp);
for (int kk = 0;kk<4;kk++)
{
int dx = i + dir[kk][0];
int dy = j + dir[kk][1];
if (dx>=0 && dx<n&&dy>=0&&dy<m)
mc.AddEdge(i*m+j,dx*m+dy,INF,0);
}
}
else
{
for (int kk = 1;kk<=k;kk++)
mc.AddEdge(i*m+j,t,1,2*kk-1-2*temp);
}
}
LL cost=0;
mc.MincostMaxflow(s,t,cost);
printf("Case %d: %d\n",cas++,cost+ans);
}
}