Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9524 | Accepted: 3876 |
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 SUMKaka 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
题意:从左上角走到右下角,每次只能向右或向下走,走完就加上这个数字,只能加一次,一共可以走K次,问最大的和。
因为每个点走过只能加一次,所以要拆点,把1到1’建一条容量为1费用为-mp[i][j](因为是最大费用,最后取反)的和一条容量为k-1费用为0的,这样就能保证费用只加一次
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define N 10000
#define inf 0x3f3f3f3f
int mp[60][60];
int dist[N],vis[N],top,head[N],pre[N],ans;
int q[1123456];
struct node
{
int u,v,cap,cost,next;
}eg[510000];
void add(int u,int v,int cap,int cost)
{
eg[top].u=u;
eg[top].v=v;
eg[top].cap=cap;
eg[top].cost=cost;
eg[top].next=head[u];
head[u]=top++;
eg[top].u=v;
eg[top].v=u;
eg[top].cap=0;
eg[top].cost=-cost;
eg[top].next=head[v];
head[v]=top++;
}
bool spfa(int s,int t)
{
for(int i=s;i<=t;i++)
{
pre[i]=-1;
vis[i]=0;
dist[i]=inf;
}
dist[s]=0;
vis[s]=1;
int in=0,out=0;
q[in++]=s;
while(in>out)
{
//printf("b\n");
int u=q[out++];
vis[u]=0;
for(int i=head[u];~i;i=eg[i].next)
{
if(eg[i].cap>0)
{
int v=eg[i].v;
int cost=eg[i].cost;
if(dist[v]>dist[u]+cost)
{
pre[v]=i;
dist[v]=dist[u]+cost;
if(!vis[v])
{
vis[v]=1;
q[in++]=v;
}
}
}
}
}
if(dist[t]!=inf)
return true;
else
return false;
}
void mcmf(int s,int t)
{
int d,i;
while(spfa(s,t))
{
//printf("%d\n",dist[t]);
d=inf;
for(i=pre[t];i!=-1;i=pre[eg[i].u])
if(eg[i].cap<d)
d=eg[i].cap;
for(i=pre[t];i!=-1;i=pre[eg[i].u])
{
eg[i].cap-=d;
eg[i^1].cap+=d;
}
ans+=dist[t];
}
}
int main()
{
int n,m,k,i,j;
top=0;
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&k);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&mp[i][j]);
}
}
int s=0,t=2*n*n+1;
m=n*n;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
add((i-1)*n+j,(i-1)*n+j+m,1,-mp[i][j]);
add((i-1)*n+j,(i-1)*n+j+m,k-1,0);
if(i+1<=n)
{
add((i-1)*n+j+m,i*n+j,k,0);//走过这个点才能加上费用,所以要加m
}
if(j+1<=n)
{
add((i-1)*n+j+m,(i-1)*n+j+1,k,0);//走过这个点才能加上费用,所以要加m
}
}
}
add(0,1,k,0);
add(2*n*n,t,k,0);
ans=0;
mcmf(s,t);
printf("%d\n",-ans);
return 0;
}