费用流
又是一道网络流的模型,对于这种费用与经过次数有关的边,我们经常把边拆成多条,比如这个题,第一次费用是x,第二次是0,我们就可以先把点拆成入点和出点,入点和出点又连两条边,第一条容量为1,费用为x;第二天容量为k-1,费用为0,意思很明确,第一次的流量可以得到费用,其他的流量都得不到费用。
原图坐标与坐标之间也连上容量为k,费用为0的边。
这样能保证网络中的最大流一定是k。(因为把源点当成(1,1)的入点,那么源点与他的出点只有k的容量)。
我们在这个网络中跑最大费用最大流即可。
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
int X = 0, w = 0; char ch = 0;
while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
A ans = 1;
for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
return ans;
}
const int N = 5005;
int n, k, cnt, head[N<<4], s, t, incf[N<<4], dist[N<<4], pre[N<<4];
bool inq[N<<4];
struct { int v, next, f, cost; } edge[N<<10];
void addEdge(int a, int b, int f, int c){
edge[cnt].v = b, edge[cnt].f = f, edge[cnt].cost = c, edge[cnt].next = head[a], head[a] = cnt ++;
edge[cnt].v = a, edge[cnt].f = 0, edge[cnt].cost = -c, edge[cnt].next = head[b], head[b] = cnt ++;
}
int hashpos(int x, int y, int d){
return (x - 1) * n + y + d * n * n;
}
bool spfa(){
full(inq, false), full(incf, INF);
full(dist, -INF), full(pre, -1);
queue<int> q;
dist[s] = 0, inq[s] = true;
q.push(s);
while(!q.empty()){
int cur = q.front(); q.pop(); inq[cur] = false;
for(int i = head[cur]; i != -1; i = edge[i].next){
int u = edge[i].v;
if(edge[i].f > 0 && dist[u] < dist[cur] + edge[i].cost){
//cout << dist[u] << " " << dist[cur] << " " << edge[i].cost << endl;
incf[u] = min(incf[cur], edge[i].f);
dist[u] = dist[cur] + edge[i].cost;
pre[u] = i; //cout << i << endl;
if(!inq[u]) inq[u] = true, q.push(u);
}
}
}
return dist[t] != -1044266559;
}
int mcmf(){
int ret = 0, mf = 0;
while(spfa()){
int cur = t;
while(cur != s){
int i = pre[cur];
//cout << i << endl;
edge[i].f -= incf[t], edge[i^1].f += incf[t];
cur = edge[i^1].v;
}
mf += incf[t];
ret += dist[t] * incf[t];
}
return ret;
}
int main(){
full(head, -1);
n = read(), k = read();
s = 1, t = 2 * n * n;
for(int i = 1; i <= n; i ++){
for(int j = 1; j <= n; j ++){
int x = read();
addEdge(hashpos(i, j, 0), hashpos(i, j, 1), 1, x);
addEdge(hashpos(i, j, 0), hashpos(i, j, 1), k - 1, 0);
if(j < n) addEdge(hashpos(i, j, 1), hashpos(i, j + 1, 0), k, 0);
if(i < n) addEdge(hashpos(i, j, 1), hashpos(i + 1, j, 0), k, 0);
}
}
printf("%d
", mcmf());
return 0;
}