POJ 3422 Kaka's Matrix Travels

来源:互联网 发布:java对象锁和类锁 编辑:程序博客网 时间:2024/05/18 19:46

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 21 2 30 2 11 4 2

Sample Output

15

Source

POJ Monthly--2007.10.06, Huang, Jinsong
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

费用流+拆点~

经典建图,把每一个点拆成两个点,然后两点之间连边流量1,费用aa[i][j];所有右连、下连的点也连边,流量inf,费用0,然后向源汇连边,流量k,费用0。这样就能限制每个点只经过一次,总共走k次。

然后跑费用流就好了!我改进了一下费用流模板,这样要好看不少啊~


#include<cstdio>#include<cstring>#include<iostream>#include<queue>using namespace std;#define inf 707406378#define d(u,v) ((u-1)*n+v)int n,k,aa[51][51],a[10005],fi[10005],ne[100001],w[100001],w1[100001];int cos[100001],cnt,las[10005],S,T,dis[10005],totflow,totcost,vall[100001];bool b[10005];queue<int> q;int read(){int x=0,f=1;char ch=getchar();while(ch<'0' || ch>'9') {if(ch=='-') f=-1;ch=getchar();}while(ch>='0' && ch<='9') {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}return x*f; }void add(int u,int v,int vv,int cost){w[++cnt]=v;w1[cnt]=u;ne[cnt]=fi[u];fi[u]=cnt;vall[cnt]=vv;cos[cnt]=cost;w[++cnt]=u;w1[cnt]=v;ne[cnt]=fi[v];fi[v]=cnt;vall[cnt]=0;cos[cnt]=-cost;}bool findd(){memset(dis,127/3,sizeof(dis));dis[S]=0;q.push(S);a[S]=inf;b[S]=1;while(!q.empty()){int k=q.front();q.pop();for(int i=fi[k];i;i=ne[i])  if(vall[i]>0 && dis[w[i]]>dis[k]+cos[i])  {  dis[w[i]]=dis[k]+cos[i];  a[w[i]]=min(a[k],vall[i]);  las[w[i]]=i;  if(!b[w[i]])  {  b[w[i]]=1;q.push(w[i]);  }  }b[k]=0;}if(dis[T]==inf) return 0;totflow+=a[T];totcost+=a[T]*dis[T];for(int i=T;i!=S;i=w1[las[i]]){vall[las[i]]-=a[T];vall[las[i]^1]+=a[T];}return 1;}int main(){n=read();k=read();cnt=1;for(int i=1;i<=n;i++)  for(int j=1;j<=n;j++) aa[i][j]=read();for(int i=1;i<=n;i++)  for(int j=1;j<=n;j++)    add(d(i,j),d(i,j)+n*n,1,-aa[i][j]),add(d(i,j),d(i,j)+n*n,inf,0);for(int i=1;i<=n;i++)  for(int j=1;j<=n;j++)  {  if(i<n) add(d(i,j)+n*n,d(i+1,j),inf,0);  if(j<n) add(d(i,j)+n*n,d(i,j+1),inf,0);  }add(0,1,k,0);add(2*n*n,2*n*n+1,k,0);S=0;T=2*n*n+1;while(findd());printf("%d\n",-totcost);return 0;}


1 0