题目链接:http://poj.org/problem?id=3422
思路:求从起点到终点走k次获得的最大值,最小费用最大流的应用:将点权转化为边权,需要拆点,边容量为1,费用为该点的点权,表示该点的权值只能获取一次,另外,应该连一条容量为inf,费用为0的边,因为每条边都可以走多次。另外就是增加源点和汇点了,源点与起点连容量为k,费用为0的边,表示可以走k次,同理终点与汇点也如此。然后就是求最大费用了,这与求最小费用类似,只需将spfa函数稍作修改即可。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<queue> 6 using namespace std; 7 #define MAXN 8888 8 #define MAXM 4444444 9 #define inf 1<<30 10 11 struct Edge { 12 int v,cap,cost,next; 13 } edge[MAXM]; 14 15 int n,m,vs,vt,NE; 16 int head[MAXN]; 17 18 void Insert(int u,int v,int cap,int cost) 19 { 20 edge[NE].v=v; 21 edge[NE].cap=cap; 22 edge[NE].cost=cost; 23 edge[NE].next=head[u]; 24 head[u]=NE++; 25 26 edge[NE].v=u; 27 edge[NE].cap=0; 28 edge[NE].cost=-cost; 29 edge[NE].next=head[v]; 30 head[v]=NE++; 31 } 32 33 int cur[MAXN],pre[MAXN]; 34 bool mark[MAXN]; 35 int dist[MAXN]; 36 37 bool spfa(int vs,int vt) 38 { 39 memset(mark,false,sizeof(mark)); 40 fill(dist,dist+vt+1,-inf); 41 dist[vs]=0; 42 queue<int>que; 43 que.push(vs); 44 while(!que.empty()) { 45 int u=que.front(); 46 que.pop(); 47 mark[u]=false; 48 for(int i=head[u]; i!=-1; i=edge[i].next) { 49 int v=edge[i].v,cost=edge[i].cost; 50 if(edge[i].cap>0&&dist[u]+cost>dist[v]) { 51 dist[v]=dist[u]+cost; 52 pre[v]=u; 53 cur[v]=i; 54 if(!mark[v]) { 55 mark[v]=true; 56 que.push(v); 57 } 58 } 59 } 60 } 61 return dist[vt]!=-inf; 62 } 63 64 65 int MinCostFlow(int vs,int vt) 66 { 67 int flow=0,cost=0; 68 while(spfa(vs,vt)) { 69 int aug=inf; 70 for(int u=vt; u!=vs; u=pre[u]) { 71 aug=min(aug,edge[cur[u]].cap); 72 } 73 flow+=aug; 74 cost+=dist[vt]*aug; 75 for(int u=vt; u!=vs; u=pre[u]) { 76 edge[cur[u]].cap-=aug; 77 edge[cur[u]^1].cap+=aug; 78 } 79 } 80 return cost; 81 } 82 83 int map[55][55]; 84 int dir[2][2]= {{1,0},{0,1}}; 85 86 int main() 87 { 88 // freopen("1.txt","r",stdin); 89 while(~scanf("%d%d",&n,&m)) { 90 NE=0; 91 vs=0,vt=2*n*n+1; 92 memset(head,-1,sizeof(head)); 93 for(int i=1; i<=n; i++) 94 for(int j=1; j<=n; j++) 95 scanf("%d",&map[i][j]); 96 for(int i=1; i<=n; i++) { 97 for(int j=1; j<=n; j++) { 98 Insert((i-1)*n+j,(i-1)*n+j+n*n,1,map[i][j]); 99 Insert((i-1)*n+j,(i-1)*n+j+n*n,inf,0); 100 for(int k=0; k<2; k++) { 101 int x=i+dir[k][0],y=j+dir[k][1]; 102 if(x<=n&&y<=n) 103 Insert((i-1)*n+j+n*n,(x-1)*n+y,inf,0); 104 } 105 } 106 } 107 Insert(vs,1,m,0); 108 Insert(2*n*n,vt,m,0); 109 printf("%d ",MinCostFlow(vs,vt)); 110 } 111 return 0; 112 }