POJ3422 Kaka's Matrix Travels
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 4905 | Accepted: 1910 |
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
************************************************************
题目大意:一个n*n的方格,每个方格上面有数字,然后从左上角走到右下角,经过的方格的数字加在SUM里面并把这个方格的数字置零。问这样走K次能得到的最大的SUM。
解题思路:传说中的最大费用流。感觉心里毛毛的,一是用spfa求了最长路。。。不知道会不会有问题;二是第一次实现这种费用流算法。
拆点。一开始一直在纠结,到底x和x'连的边是怎样的捏。看了别人的解说才明白过来,嗯,原来可以这样连:x和x'连着两条边,一条容量为1,花费为数字,另一条容量为INF,花费为0. 懂这一点,AC就没什么问题了。
#include <stdio.h> #include <string.h> #include <queue> #define N 50050 #define M 10000005 #define INF 0x3f3f3f3f #define tk(a,b,c) ((a-1)*n+b+c*n*n) using namespace std; int tu[55][55]; int n,k,eid,sink,source; int head[N],ed[M],fee[M],nxt[M],up[M]; int pre[N],vis[N],dist[N],road[N]; void add_edge(int s,int e,int f,int u) { up[eid]=u; ed[eid]=e; nxt[eid]=head[s]; fee[eid]=f; head[s]=eid++; up[eid]=0; ed[eid]=s; fee[eid]=-f; nxt[eid]=head[e]; head[e]=eid++; } int spfa(void) { queue<int>que; memset(vis,0,sizeof(vis)); for(int i=1;i<=sink;i++) dist[i]=-1; dist[0]=0; vis[0]=1;que.push(0); while(!que.empty()) { int t=que.front(); que.pop(); vis[t]=0; for(int i=head[t];~i;i=nxt[i]) { if(up[i]==0)continue; int e=ed[i],f=fee[i]; if(dist[e]<dist[t]+f) { dist[e]=dist[t]+f; road[e]=i; pre[e]=t; if(!vis[e]) { vis[e]=1; que.push(e); } } } } if(pre[sink]!=-1&&dist[sink]>-1) return 1; return 0; } void re(void) { for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) scanf("%d",&tu[i][j]); } void run(void) { memset(head,-1,sizeof(head)); eid=0;source=0;sink=2*n*n+1; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { add_edge(tk(i,j,0),tk(i,j,1),tu[i][j],1); add_edge(tk(i,j,0),tk(i,j,1),0,k-1); } for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { if(n-i) add_edge(tk(i,j,1),tk(i+1,j,0),0,k); if(n-j) add_edge(tk(i,j,1),tk(i,j+1,0),0,k); } add_edge(source,tk(1,1,0),0,k); add_edge(tk(n,n,1),sink,0,k); int ans=0; int vis[N]; while(spfa()) for(int j=sink;j!=source;j=pre[j]) { up[road[j]]-=1; up[road[j]^1]+=1; ans+=fee[road[j]]; } printf("%d\n",ans); } int main() { while(scanf("%d%d",&n,&k)==2) { re(); run(); } return 0; }