POJ 3068 Shortest pair of paths (最小费用最大流)

Description

给出一个\(N\)个点\(M\)条边的有向图,结点编号从\(0\)\(N-1\),每条边有一个花费,求从结点\(0\)\(N-1\)的花费和最小两条路径,每条边最多走一次,每个点也最多走一次。

Input

多组用例,每组用例的第一行给出两个整数\(N\)\(M\),表示节点数和边数,接下来的\(M\)行,每行给出三个数\(u\)\(v\)\(c\),表示从\(u\)点到\(v\)点有一条花费为\(c\)的边。\(0\)\(0\)表示输入结束。

Output

对于每组用例,输出"Instance #x: y",x表示用例序号,从1开始,y表示最短路径。否则输出"Instance #1: Not possible"。

Sample Input

2 1
0 1 20
2 3
0 1 20
0 1 20
1 0 10
4 6
0 1 22
1 3 11
0 2 14
2 3 26
0 3 43
0 3 58
0 0

Sample Output

Instance #1: Not possible
Instance #2: 40
Instance #3: 73

Solution

两条路径花费和最小,最小费用最大流。每条边的花费为\(c\),因为每条边最多走一次,所以容量设为\(1\),因为每个点最多走一次,故拆点,把\(i\)点拆为\(i\)\(i+n\)\(i\)\(i+n\)建一条容量为\(1\)花费为\(0\)的边,但结点\(0\)\(n-1\)的容量设为\(2\),从源点\(0\)到汇点\(n-1+n\)跑最小费用最大流,如果达到满流\(2\),输出最小花费,否则输出"Not possible"。

Code

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 150;
const int M = 3e4 + 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 &maxflow) 
{
	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, cas = 0;
	while (scanf("%d%d", &n, &m), n)
	{
		init();
		add(0, n, 2, 0);
		for (int i = 1; i <= n - 2; i++) add(i, n + i, 1, 0);
		add(n - 1, n + n - 1, 2, 0);
		while (m--)
		{
			int a, b, c;
			scanf("%d%d%d", &a, &b, &c);
			add(n + a, b, 1, c);
		}
		int flow;
		int ans = mcmf(0, 2 * n - 1, flow);
		printf("Instance #%d: ", ++cas);
		if (flow < 2) printf("Not possible\n");
		else printf("%d\n", ans);
	}
	return 0;
}

http://poj.org/problem?id=3068

posted @ 2017-08-14 16:11  达达Mr_X  阅读(306)  评论(0)    收藏  举报