题目链接
http://poj.org/problem?id=2135
题意
起点在1,终点在N,FJ需要从1走到N再回到1,1->N和N->1的路径不能重复,求总路线最短的
思路
只需要找2条从1->N的总路径最短的即可
考虑构图:
S = 1, T = N;
其中每条边的容量cap = 1, 费用cost = 路径长度;
则只需要求流量为2的最小费用即可
代码
#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <deque>
#include <bitset>
#include <algorithm>
using namespace std;
#define PI acos(-1.0)
#define LL long long
#define PII pair<int, int>
#define PLL pair<LL, LL>
#define mp make_pair
#define IN freopen("in.txt", "r", stdin)
#define OUT freopen("out.txt", "wb", stdout)
#define scan(x) scanf("%d", &x)
#define scan2(x, y) scanf("%d%d", &x, &y)
#define scan3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define sqr(x) (x) * (x)
#define pr(x) cout << #x << " = " << x << endl
#define lc o << 1
#define rc o << 1 | 1
#define pl() cout << endl
//固定流量的最小费用流
const int MAXN = 1000 + 5;
const int INF = 0x3e3e3e3e;
struct Edge {
int from, to, cap, flow, cost;
};
struct MCMF {
int s, t, n, m;
int d[MAXN], p[MAXN], inq[MAXN], a[MAXN];
vector<int> G[MAXN];
vector<Edge> edges;
void init(int n) {
this->n = n;
for (int i = 0; i < n; i++) G[i].clear();
edges.clear();
}
void addedge(int from, int to, int cap, int cost) {
edges.push_back((Edge){from, to, cap, 0, cost});
edges.push_back((Edge){to, from, 0, 0, -cost});
m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
bool bellman_ford(int s, int t, int &flow, int &cost) {
memset(inq, 0, sizeof(inq));
for (int i = 0; i < n; i++) d[i] = INF;
d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF;
queue<int> Q;
Q.push(s);
while (!Q.empty()) {
int u = Q.front(); Q.pop();
inq[u] = 0;
for (int i = 0; i < G[u].size(); i++) {
Edge &e = edges[G[u][i]];
if (e.cap > e.flow && d[e.to] > d[u] + e.cost) {
d[e.to] = d[u] + e.cost;
p[e.to] = G[u][i];
a[e.to] = min(a[u], e.cap - e.flow);
if (!inq[e.to]) {
Q.push(e.to);
inq[e.to] = 1;
}
}
}
}
if (d[t] == INF) return false;
if (flow + a[t] > 2) a[t] = 2 - flow;
flow += a[t];
cost += d[t] * a[t];
if (flow == 2) return false;
int u = t;
while (u != s) {
edges[p[u]].flow += a[t];
edges[p[u] ^ 1].flow -= a[t];
u = edges[p[u]].from;
}
return true;
}
int min_cost(int s, int t) {
int flow = 0, cost = 0;
while (bellman_ford(s, t, flow, cost));
return cost;
}
};
int main() {
//IN;
int n, m;
scan2(n, m);
MCMF F;
F.init(n);
for (int i = 0; i < m; i++) {
int a, b, c;
scan3(a, b, c);
F.addedge(--a, --b, 1, c);
F.addedge(b, a, 1, c);
}
int S = 0, T = n - 1;
printf("%d\n", F.min_cost(S, T));
return 0;
}
该博客介绍了POJ2135题目——Farm Tour,要求从1到N再到1的最短总路线,不重复路径。博主通过构建网络流图,每条边容量1,费用为路径长度,寻找流量为2的最小费用路径来解决问题。
&spm=1001.2101.3001.5002&articleId=52241353&d=1&t=3&u=3f4462720ba54013be908b3ad1516530)
1572

被折叠的 条评论
为什么被折叠?



