Time Limit: 1000MS |
| Memory Limit: 65536K |
Total Submissions: 5821 |
| Accepted: 2275 |
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 SUM he 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
#include<iostream> #include<algorithm> #include<cstring> #include<cstdio> #include<cstring> #include<queue> using namespace std; #define MAXN 5500 #define MAXM 999999 #define INF 0x3FFFFFF struct edge { int to,c,w,next; }; edge e[MAXM]; bool in[MAXN]; int n,k,st,ed,vn,en,maxflow,maxcost; int dis[MAXN],pre[MAXN],head[MAXN]; int map[60][60]; void add(int a,int b,int c,int d) { e[en].to=b; e[en].c=c; e[en].w=d; e[en].next=head[a]; head[a]=en++; e[en].to=a; e[en].c=0; e[en].w=-d; e[en].next=head[b]; head[b]=en++; } bool spfa(int s) { queue<int> q; for(int i=0;i<=vn;i++) { dis[i]=-1; in[i]=false; pre[i]=-1; } dis[s]=0; in[s]=true; q.push(s); while(!q.empty()) { int tag=q.front(); in[tag]=false; q.pop(); for(int i=head[tag];i!=-1;i=e[i].next) { int j=e[i].to; if( e[i].w+dis[tag]>dis[j] && e[i].c ) { dis[j]=e[i].w+dis[tag]; pre[j]=i; if(!in[j]) { q.push(j); in[j]=true; } } } } if(dis[ed]==-1) return false; return true; } void update() { int flow=INF; for (int i=pre[ed];i!=-1;i=pre[e[i^1].to]) if(e[i].c<flow) flow=e[i].c; for (int i=pre[ed];i!=-1;i=pre[e[i^1].to]) { e[i].c-=flow,e[i^1].c+=flow; } maxflow+=flow; maxcost+=flow*dis[ed]; } void maxcostmaxflow() { maxflow=0,maxcost=0; while(spfa(st)) update(); } void solve() { for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) scanf("%d",&map[i][j]); en=0,st=0,ed=n*n*2+1,vn=n*n*2+2; memset(head,-1,sizeof(head)); add(st,1,k,0); add(n*n*2,ed,k,0); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { int tag=(i-1)*n+j; int down=tag+n,right=tag+1; add(tag,tag+n*n,1,map[i][j]); if(i!=n) { add(tag,down,INF,0); add(tag,down+n*n,INF,0); add(tag+n*n,down,INF,0); add(tag+n*n,down+n*n,INF,0); } if(j!=n) { add(tag,right,INF,0); add(tag,right+n*n,INF,0); add(tag+n*n,right,INF,0); add(tag+n*n,right+n*n,INF,0); } } } maxcostmaxflow(); printf("%d\n",maxcost); } int main() { while(scanf("%d%d",&n,&k)!=EOF) solve(); return 0; }