POJ 2135 Farm Tour (最小费用最大流)
Description
给出一张\(N\)个点\(M\)条边的带权无向图,结点编号从\(1\)到\(N\),求从\(1\)到\(N\)再到\(1\)的最短路,每条边最多走一次。
Input
第一行给出两个整数\(N\)和\(M\),表示结点数和边数。
接下来的\(M\)行每行给出三个整数\(u\),\(v\)和\(w\),表示一边的两个端点和边权。
\(1 \leqslant N \leqslant 1000\),\(1 \leqslant M \leqslant 10000\)。
Output
输出一个整数表示最短路径的长度。
Sample Input
4 5
1 2 1
2 3 1
3 4 1
1 3 2
2 4 2
Sample Output
6
Solution
要求两条不重叠的最短路就不能用简单最短路算法了,先求最短路,删边再求最短路也不行,于是用最小费用最大流。对于一条权重为\(w\)的无向边,花费为\(w\)的有向边,因为每条边最多走一次,因此容量设为\(1\),又因为只求两条路径,故添加额外源点\(0\),与结点\(1\)建一条容量为\(2\)花费为\(0\)的边,从源点\(0\)到汇点\(N\)跑最小费用最大流即可。
Code
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 1e3 + 10;
const int M = 4e4 + 10;
struct Edge
{
int from, to, next, cap, cost;
Edge() {}
Edge(int from, int to, int next, int cap, int cost) :
from(from), to(to), next(next), cap(cap), cost(cost) {}
} edge[M];
int head[N], tot;
void add(int from, int to, int cap, int cost)
{
edge[tot] = Edge(from, to, head[from], cap, cost);
head[from] = tot++;
edge[tot] = Edge(to, from, head[to], 0, -cost);
head[to] = tot++;
}
void init()
{
memset(head, -1, sizeof(head));
tot = 0;
}
int dis[N], pre[N];
bool vis[N];
queue<int> q;
bool spfa(int s, int t)
{
while (!q.empty()) q.pop();
memset(dis, 0x3f, sizeof(dis));
memset(vis, false, sizeof(vis));
memset(pre, -1, sizeof(pre));
q.push(s); vis[s] = true; dis[s] = 0;
while (!q.empty())
{
int u = q.front(); q.pop(); vis[u] = false;
for (int i = head[u]; i != -1; i = edge[i].next)
if (edge[i].cap && dis[u] + edge[i].cost < dis[edge[i].to])
{
int v = edge[i].to;
dis[v] = dis[u] + edge[i].cost;
pre[v] = i;
if (!vis[v]) q.push(v), vis[v] = true;
}
}
return dis[t] < INF;
}
int mcmf(int s, int t)
{
int mincost = 0, maxflow = 0;
while (spfa(s, t))
{
int flow = INF;
for (int i = pre[t]; i != -1; i = pre[edge[i].from])
flow = min(flow, edge[i].cap);
for (int i = pre[t]; i != -1; i = pre[edge[i].from])
{
edge[i].cap -= flow;
edge[i ^ 1].cap += flow;
mincost += edge[i].cost * flow;
}
maxflow += flow;
}
return mincost;
}
int main()
{
int n, m;
scanf("%d%d", &n, &m);
init();
while (m--)
{
int u, v, c;
scanf("%d%d%d", &u, &v, &c);
add(u, v, 1, c);
add(v, u, 1, c);
}
add(0, 1, 2, 0);
int ans = mcmf(0, n);
printf("%d\n", ans);
return 0;
}