Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 8050 | Accepted: 3224 |
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
Source
#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define maxn 6000
#define maxm 24000
#define INF 0x3f3f3f3f
using namespace std;
struct Edge
{
int from,to,next,f,c;
}es[maxm];
int cnt,p[maxn],inq[maxn];
int dis[maxn],ff[maxn],q[maxn],pre[maxn];
int n,m;
int s,t,ans_c;
void add(int x,int y,int f,int c)
{
es[cnt].from = x;
es[cnt].to = y;
es[cnt].f = f;
es[cnt].c = c;
es[cnt].next = p[x];
p[x] = cnt++;
es[cnt].from = y;
es[cnt].to = x;
es[cnt].f = 0;
es[cnt].c = -c;
es[cnt].next = p[y];
p[y] = cnt++;
}
bool bfs()
{
memset(dis,63,sizeof dis);
memset(ff,0,sizeof ff);
memset(inq,0,sizeof inq);
dis[s] = 0;
int head = 0,tail = 0;
q[tail++] = s;
inq[s] = true;
ff[s] = INF;
while(head != tail)
{
int u = q[head++];
if(head == maxn)
head = 0;
inq[u] = false;
for(int i = p[u];~i;i = es[i].next)
{
int v = es[i].to;
if(es[i].f<= 0) continue;
if(dis[v] > dis[u]+es[i].c)
{
dis[v] = dis[u]+ es[i].c;
pre[v] = i;
ff[v] = min(ff[u],es[i].f);
if(!inq[v])
{
q[tail++] = v;
inq[v] = true;
if(tail == maxn) tail = 0;
}
}
}
}
if(dis[t] == INF) return false;
ans_c += ff[t]*dis[t];
int u = t;
while(u != s)
{
es[pre[u]].f -= ff[t];
es[pre[u]^1].f += ff[t];
u = es[pre[u]].from;
}
return true;
}
void Min_Cost()
{
ans_c = 0;
while(bfs())
;
}
void init()
{
cnt = 0;
memset(p,-1,sizeof p);
}
int a[51][51];
int ID(int i,int j)
{
return (i-1)*n+j;
}
int main()
{
while(scanf("%d %d",&n,&m) != EOF)
{
int tmp = n*n;
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++)
{
scanf("%d",&a[i][j]);
}
}
init();
s = 0,t = 2*tmp+1;
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++)
{
add(ID(i,j),ID(i,j)+tmp,1,-a[i][j]);
add(ID(i,j),ID(i,j)+tmp,INF,0);
if(i != n)
{
add(ID(i,j)+tmp,ID(i+1,j),INF,0);
}
if(j != n)
{
add(ID(i,j)+tmp,ID(i,j+1),INF,0);
}
}
}
add(s,ID(1,1),m,0);
add(ID(n,n)+tmp,t,m,0);
/*for(int i = 0;i < cnt;i+=2)
printf("%d %d\n",es[i].from,es[i].to);*/
Min_Cost();
printf("%d\n",-ans_c);
}
return 0;
}