poj 3422 Kaka‘s Matrix Travels — K取方格数(最大费用最大流)
Posted jpphy0
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj 3422 Kaka‘s Matrix Travels — K取方格数(最大费用最大流)相关的知识,希望对你有一定的参考价值。
问题
K取方格数 - http://poj.org/problem?id=3422
分析
代码
/* K取方格 poj3422 */
#include<bits/stdc++.h>
using namespace std;
const int mxv = 210, mxe = 210<<2, inf = 0x3f3f3f3f, mxn = 10;
int n, m, k, ver[mxn][mxn][2];
int pre[mxv], head[mxv], tot, d[mxe], flow[mxv], v[mxe];
struct Edge{ int to, nxt, cap, w;}edge[mxe];
void addEdge(int u, int v, int cap, int w){
Edge &e = edge[++tot];
e.nxt = head[u], e.to = v, e.cap = cap, e.w = w, head[u] = tot;
}
void add(int u, int v, int cap, int w){
addEdge(u, v, cap, w), addEdge(v, u, 0, -w);
}
bool spfa(int s, int t){
queue<int> q;
int f;
memset(d, 0xcf, sizeof d), memset(v, 0, sizeof v);
v[s] = 1, d[s] = 0, flow[s] = inf, q.push(s);
while(!q.empty()){
f = q.front(), q.pop(), v[f] = 0;
for(int to, i = head[f]; ~i; i = edge[i].nxt){
if(!edge[i].cap) continue;
to = edge[i].to;
if(d[to] < d[f] + edge[i].w){
d[to] = d[f] + edge[i].w;
flow[to] = min(flow[f], edge[i].cap);
pre[to] = i;
if(!v[to]) v[to] = 1, q.push(to);
}
}
}
return d[t] != 0xcfcfcfcf;
}
void update(int s, int t){
for(int i, now = t; now != s; now = edge[i^1].to)
i = pre[now], edge[i].cap -= flow[t], edge[i^1].cap += flow[t];
}
int main(){
int t = 0, S = 201, T = S+1, w, ans;
for(int i = 0; i < mxn; ++i)
for(int j = 0; j < mxn; ++j)
for(int k = 0; k <= 1; ++k) ver[i][j][k] = ++t;
scanf("%d", &t);
while(t--){
tot = 1, ans = 0, memset(head, -1, sizeof head);
scanf("%d%d%d", &n, &m, &k);
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j){
scanf("%d", &w);
add(ver[i][j][0], ver[i][j][1], 1, w), add(ver[i][j][0], ver[i][j][1], k, 0);
if(j) add(ver[i][j-1][1], ver[i][j][0], k, 0);
if(i) add(ver[i-1][j][1], ver[i][j][0], k, 0);
}
}
add(S, ver[0][0][0], k, 0), add(ver[n-1][m-1][1], T, k, 0);
while(spfa(S, T)) ans += flow[T]*d[T], update(S, T);
printf("%d\\n", ans);
}
return 0;
}
以上是关于poj 3422 Kaka‘s Matrix Travels — K取方格数(最大费用最大流)的主要内容,如果未能解决你的问题,请参考以下文章
POJ3422 Kaka's Matrix Travels 最大费用最大流
POJ3422:Kaka's Matrix Travels——题解
POJ3422 Kaka's Matrix Travels[?????????]