POJ3422 Kaka's Matrix Travels[费用流]

时间:2021-09-10 14:04:24
Kaka's Matrix Travels
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 9522   Accepted: 3875

Description

On an N × N chessboard with a non-negative number in each grid, Kaka starts his matrix travels with SUM = 0. For each travel, Kaka moves one rook from the left-upper grid to the right-bottom one, taking care that the rook moves only to the right or down. Kaka adds the number to SUM in each grid the rook visited, and replaces it with zero. It is not difficult to know the maximum SUM Kaka can obtain for his first travel. Now Kaka is wondering what is the maximum SUMhe can obtain after his Kth travel. Note the SUM is accumulative during the K travels.

Input

The first line contains two integers N and K (1 ≤ N ≤ 50, 0 ≤ K ≤ 10) described above. The following N lines represents the matrix. You can assume the numbers in the matrix are no more than 1000.

Output

The maximum SUM Kaka can obtain after his Kth travel.

Sample Input

3 2
1 2 3
0 2 1
1 4 2

Sample Output

15

Source

POJ Monthly--2007.10.06, Huang, Jinsong

方格取数加强版
每个格子拆成两个点,连一条(1,-a[i][j])的边,在连一条(k-1,0)的边【注意我的t是格子(n,n),k-1是为了防止走了k+1多条边到(n,n)】
格子向右和下连一条(k,0)的边
最小费用然后取负(当然直接spfa跑最大也可以)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
const int N=,M=2e4+,INF=1e9;
int read(){
char c=getchar();int x=,f=;
while(c<''||c>''){if(c=='-')f=-; c=getchar();}
while(c>=''&&c<=''){x=x*+c-''; c=getchar();}
return x*f;
}
int n,k,a[N][N],s,t,num;
struct edge{
int v,ne,c,f,w;
}e[M<<];
int cnt,h[N];
inline void ins(int u,int v,int c,int w){
cnt++;
e[cnt].v=v;e[cnt].c=c;e[cnt].f=;e[cnt].w=w;
e[cnt].ne=h[u];h[u]=cnt;
cnt++;
e[cnt].v=u;e[cnt].c=;e[cnt].f=;e[cnt].w=-w;
e[cnt].ne=h[v];h[v]=cnt;
}
inline int id(int i,int j){return (i-)*n+j;}
void build(){
for(int i=;i<=n;i++)
for(int j=;j<=n;j++){
int t=id(i,j);
ins(t,num+t,,-a[i][j]);//printf("%d %d %d %d\n",i,j,t,a[i][j]);
ins(t,num+t,k-,);
if(i!=n) ins(num+t,id(i+,j),k,);
if(j!=n) ins(num+t,id(i,j+),k,);
}
}
int d[N],q[N],head,tail,inq[N],pre[N],pos[N];
inline void lop(int &x){if(x==N)x=;}
bool spfa(){
memset(d,,sizeof(d));
memset(inq,,sizeof(inq));
head=tail=;
d[s]=;inq[s]=;q[tail++]=s;
pre[t]=-;
while(head!=tail){
int u=q[head++];inq[u]=;lop(head);
for(int i=h[u];i;i=e[i].ne){
int v=e[i].v,w=e[i].w;
if(d[v]>d[u]+w&&e[i].c>e[i].f){
d[v]=d[u]+w;
pre[v]=u;pos[v]=i;
if(!inq[v])q[tail++]=v,inq[v]=,lop(tail);
}
}
}
return pre[t]!=-;
}
int mcmf(){
int flow=,cost=;
while(spfa()){
int f=INF;
for(int i=t;i!=s;i=pre[i]) f=min(f,e[pos[i]].c-e[pos[i]].f);
flow+=f;cost+=d[t]*f;
for(int i=t;i!=s;i=pre[i]){
e[pos[i]].f+=f;
e[((pos[i]-)^)+].f-=f;
}
}//printf("mcmf %d %d\n",flow,cost);
return cost;
}
int main(int argc, const char * argv[]){
n=read();k=read();num=n*n;
s=;t=num+num;
for(int i=;i<=n;i++)
for(int j=;j<=n;j++) a[i][j]=read();
build();
printf("%d",-mcmf());
}