Optimal Bus Route Design UVA 1349

将每个点分成两个点,然后再来建立相应的有向边,转换为最小完美匹配问题,按照最小费用最大流问题来求解即可,具体实现见如下代码:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;

class Edge{
public:
	int from, to, cap, flow, cost;
	Edge(int fr, int t, int ca, int fl, int c):from(fr),to(t),cap(ca),flow(fl),cost(c){}
};

class Solve{
public:
	int n;
	vector<Edge> edge;
	vector<int> G[210];
	const int Inf = 0x3f3f3f3f;

	void addEgde(int from,int to,int cap,int flow,int cost){
		edge.push_back(Edge(from,to,cap,flow,cost));
		edge.push_back(Edge(to,from,0,0,-cost));
		int m = edge.size();
		G[from].push_back(m-2);
		G[to].push_back(m - 1);
	}

	void Init(){
		edge.clear();
		for (int i = 0; i < 210; i++) G[i].clear();
		for (int i = 1; i <= n; i++){
			addEgde(0,i,1,0,0);
			addEgde(n + i, 2 * n + 1, 1, 0, 0);
		}
		for (int i = 1; i <= n; i++){
			while (true){
				int a, b;
				cin >> a;
				if (a == 0) break;
				cin >> b;
				addEgde(i, a + n, 1, 0, b);
			}
		}
	}

	bool BellmanFloyd(int start,int end,int &flow,int &cost){
		int price[210];
		memset(price, Inf, sizeof(price));
		price[start] = 0;
		int parent[210];
		int Flow[210],inq[210];
		Flow[start] = Inf;
		memset(inq, 0, sizeof(inq));
		queue<int> q;
		q.push(start);
		inq[start] = 1;
		while (!q.empty()){
			int id = q.front();
			q.pop();
			inq[id] = 0;
			for (int i = 0; i < G[id].size(); i++){
				int ide = G[id][i];
				int to = edge[ide].to;
				if (edge[ide].cap > edge[ide].flow&&price[to] > price[id] + edge[ide].cost){
					Flow[to] = min(Flow[id], edge[ide].cap - edge[ide].flow);
					price[to] = price[id] + edge[ide].cost;
					parent[to] = ide;
					if (!inq[to]){
						q.push(to);
						inq[to] = 1;
					}
				}
			}
		}
		if (price[end] == Inf) return false;
		flow += Flow[end];
		cost += price[end] * Flow[end];
		for (int i = end; i != start; i = edge[parent[i]].from){
			edge[parent[i]].flow += Flow[end];
			edge[parent[i] ^ 1].flow -= Flow[end];
		}
		return true;
	}

	void MaxFlow(int start,int end){
		int flow = 0, cost = 0;
		while (BellmanFloyd(start, end, flow, cost));
		if (flow < n) cout << "N" << endl;
		else cout << cost << endl;
	}

	void Deal(){
		Init();
		MaxFlow(0, 2 * n + 1);
	}
};

int main(){
	Solve a;
	while (cin >> a.n){
		if (a.n == 0) break;
		a.Deal();
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值