首页 > 代码库 > POJ3422 Kaka's Matrix Travels[费用流]
POJ3422 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 21 2 30 2 11 4 2
Sample Output
15
Source
方格取数加强版
#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>using namespace std;typedef long long ll;const int N=5005,M=2e4+5,INF=1e9;int read(){ char c=getchar();int x=0,f=1; while(c<‘0‘||c>‘9‘){if(c==‘-‘)f=-1; c=getchar();} while(c>=‘0‘&&c<=‘9‘){x=x*10+c-‘0‘; c=getchar();} return x*f;}int n,k,a[N][N],s,t,num;struct edge{ int v,ne,c,f,w;}e[M<<1];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=0;e[cnt].w=w; e[cnt].ne=h[u];h[u]=cnt; cnt++; e[cnt].v=u;e[cnt].c=0;e[cnt].f=0;e[cnt].w=-w; e[cnt].ne=h[v];h[v]=cnt;}inline int id(int i,int j){return (i-1)*n+j;}void build(){ for(int i=1;i<=n;i++) for(int j=1;j<=n;j++){ int t=id(i,j); ins(t,num+t,1,-a[i][j]);//printf("%d %d %d %d\n",i,j,t,a[i][j]); ins(t,num+t,k-1,0); if(i!=n) ins(num+t,id(i+1,j),k,0); if(j!=n) ins(num+t,id(i,j+1),k,0); }}int d[N],q[N],head,tail,inq[N],pre[N],pos[N];inline void lop(int &x){if(x==N)x=1;}bool spfa(){ memset(d,127,sizeof(d)); memset(inq,0,sizeof(inq)); head=tail=1; d[s]=0;inq[s]=1;q[tail++]=s; pre[t]=-1; while(head!=tail){ int u=q[head++];inq[u]=0;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]=1,lop(tail); } } } return pre[t]!=-1;}int mcmf(){ int flow=0,cost=0; 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]-1)^1)+1].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=1;t=num+num; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) a[i][j]=read(); build(); printf("%d",-mcmf());}
POJ3422 Kaka's Matrix Travels[费用流]