题目等价于每个点可以走K次,但是只能取一次的价值。。。那么就拆点。。。。正点和负点连一条容量为1, 费用为权值的边,再连一条流量为k-1,费用为0的边就行了。。。。
#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 6005
#define maxm 100005
#define eps 1e-10
#define mod 1000000007
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid
#define rson o<<1 | 1, mid+1, R
#pragma comment(linker, "/STACK:16777216")
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
void scanf(int &__x){__x=0;char __ch=getchar();while(__ch==' '||__ch=='\n')__ch=getchar();while(__ch>='0'&&__ch<='9')__x=__x*10+__ch-'0',__ch = getchar();}
LL gcd(LL _a, LL _b){if(!_b) return _a;else return gcd(_b, _a%_b);}
// head
struct Edge
{
int v, c, w, next;
Edge() {}
Edge(int v, int c, int w, int next) : v(v), c(c), w(w), next(next) {}
}E[maxm];
queue<int> q;
int H[maxn], cntE;
int vis[maxn];
int cap[maxn];
int dis[maxn];
int cur[maxn];
int s, t, flow, cost, n, k, o, T;
void addedges(int u, int v, int c, int w)
{
E[cntE] = Edge(v, c, w, H[u]);
H[u] = cntE++;
E[cntE] = Edge(u, 0, -w, H[v]);
H[v] = cntE++;
}
bool spfa(void)
{
memset(dis, -1, sizeof dis);
dis[s] = 0;
cur[s] = -1;
cap[s] = INF;
vis[s] = ++T;
q.push(s);
while(!q.empty()) {
int u = q.front();
q.pop();
vis[u] = T - 1;
for(int e = H[u]; ~e; e = E[e].next) {
int v = E[e].v, c = E[e].c, w = E[e].w;
if(c && dis[v] < dis[u] + w) {
dis[v] = dis[u] + w;
cap[v] = min(cap[u], c);
cur[v] = e;
if(vis[v] != T) {
vis[v] = T;
q.push(v);
}
}
}
}
if(dis[t] == -1) return false;
flow += cap[t];
cost += cap[t] * dis[t];
for(int e = cur[t]; ~e; e = cur[E[e ^ 1].v]) {
E[e].c -= cap[t];
E[e ^ 1].c += cap[t];
}
return true;
}
int mcmf(void)
{
flow = cost = 0;
while(spfa());
return cost;
}
void init(void)
{
cntE = T = 0;
memset(H, -1, sizeof H);
memset(vis, 0, sizeof vis);
}
inline int calc(int i, int j)
{
return i * n + j;
}
void read(void)
{
int x;
o = n * n;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++) {
scanf("%d", &x);
addedges(calc(i, j), o + calc(i, j), 1, x);
addedges(calc(i, j), o + calc(i, j), k - 1, 0);
}
}
void work(void)
{
if(k == 0) {
printf("0\n");
return;
}
s = 2 * o + 1;
t = 2 * o + 2;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++) {
if(i != n - 1) addedges(o + calc(i, j), calc(i + 1, j), INF, 0);
if(j != n - 1) addedges(o + calc(i, j), calc(i, j + 1), INF, 0);
}
addedges(s, calc(0, 0), INF, 0);
addedges(o + calc(n-1, n-1), t, INF, 0);
printf("%d\n", mcmf());
}
int main(void)
{
while(scanf("%d%d", &n, &k)!=EOF) {
init();
read();
work();
}
return 0;
}