当前位置: 代码迷 >> 综合 >> 费用流 poj3422 Kaka's Matrix Travels
  详细解决方案

费用流 poj3422 Kaka's Matrix Travels

热度:95   发布时间:2023-12-14 03:54:09.0

传送门:点击打开链接

题意:从(1,1)出发k次,到达(n,n),求经过的数字之和最大,如果多次经过某一个点,那个点的权值只被算一次

最经典的一道拆点的题

把点拆分成两层,对于(i,j)这个点,第一层和第二层直接添加一条费用为-A[i][j]容量为1的边,表示通过了就能加上这个点的权值

然后把每个点的第二层的点再连回到下一个点的第一层。

因为一个点可以被多次经过,只是权值只算一次而已,所以在第一层上也要连接到下一个点的第一层,只是费用设置为0容量设置为INF


这样就不会有负环,而且满足题意了~

#include<map>
#include<set>
#include<cmath>
#include<stack>
#include<queue>
#include<cstdio>
#include<string>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#define FIN freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w+",stdout)using namespace std;
typedef long long LL;
typedef pair<int, int> PII;const int MX = 40000 + 5;//都开4倍把..
const int MM = 40000 + 5;
const int INF = 0x3f3f3f3f;struct Edge {int to, next, cap, flow, cost;Edge() {}Edge(int _to, int _next, int _cap, int _flow, int _cost) {to = _to; next = _next; cap = _cap; flow = _flow; cost = _cost;}
} E[MM];int Head[MX], tol;
int pre[MX]; //储存前驱顶点
int dis[MX]; //储存到源点s的距离
bool vis[MX];
int N;//节点总个数,节点编号从0~N-1void init(int n) {tol = 0;N = n + 2;memset(Head, -1, sizeof(Head));
}
void edge_add(int u, int v, int cap, int cost) {E[tol] = Edge(v, Head[u], cap, 0, cost);Head[u] = tol++;E[tol] = Edge(u, Head[v], 0, 0, -cost);Head[v] = tol++;
}
bool spfa(int s, int t) {queue<int>q;for (int i = 0; i < N; i++) {dis[i] = INF;vis[i] = false;pre[i] = -1;}dis[s] = 0;vis[s] = true;q.push(s);while (!q.empty()) {int u = q.front();q.pop();vis[u] = false;for (int i = Head[u]; i != -1; i = E[i].next) {int v = E[i].to;if (E[i].cap > E[i].flow && dis[v] > dis[u] + E[i].cost) {dis[v] = dis[u] + E[i].cost;pre[v] = i;if (!vis[v]) {vis[v] = true;q.push(v);}}}}if (pre[t] == -1) return false;else return true;
}//返回的是最大流, cost存的是最小费用
int minCostMaxflow(int s, int t, int &cost) {int flow = 0;cost = 0;while (spfa(s, t)) {int Min = INF;for (int i = pre[t]; i != -1; i = pre[E[i ^ 1].to]) {if (Min > E[i].cap - E[i].flow)Min = E[i].cap - E[i].flow;}for (int i = pre[t]; i != -1; i = pre[E[i ^ 1].to]) {E[i].flow += Min;E[i ^ 1].flow -= Min;cost += E[i].cost * Min;}flow += Min;}return flow;
}int dist[][2] = {
   {1, 0}, {0, 1}};int main() {int n, k; //FIN;while(~scanf("%d%d", &n, &k)) {int s = 0, t = 2 * n * n + 1;init(t);edge_add(s, 1, k, 0);edge_add(n * n, t, INF, 0);edge_add(2 * n * n, t, INF, 0);for(int i = 1; i <= n; i++) {for(int j = 1; j <= n; j++) {int cost; scanf("%d", &cost);edge_add((i - 1)*n + j, n * n + (i - 1)*n + j, 1, -cost);for(int k = 0; k < 2; k++) {int nx = dist[k][0] + i;int ny = dist[k][1] + j;if(nx <= n && ny <= n) {edge_add((i - 1)*n + j, (nx - 1)*n + ny, INF, 0);edge_add(n * n + (i - 1)*n + j, (nx - 1)*n + ny, INF, 0);}}}}int ans = 0;minCostMaxflow(s, t, ans);printf("%d\n", -ans);}return 0;
}


  相关解决方案