PAT A1087(使用Dijkstra,容易理解系列)

#include<iostream>
#include<map>
#include<algorithm>
#include<vector>
using namespace std;

const int maxn = 210;
const int INF = 1 << 31 - 1;
int n, k;
string stCity;
int weight[maxn], w[maxn], d[maxn], num[maxn];
int cost[maxn][maxn], pre[maxn];
bool vis[maxn] = { false };
map<string, int> cityToInt;
map<int, string> intToCity;
vector<int> path;
void Dijkstra(int st) {
	fill(d, d + maxn, INF);
	d[st] = 0;
	w[st] = 0;
	num[st] = 1;
	for(int i = 0; i < n; i++) {
		int u = -1, MIN = INF;
		for(int j = 0; j < n; j++) {
			if(vis[j] == false && d[j] < MIN) {
				u = j;
				MIN = d[j];
			}
		}
		if(u == -1) return;
		vis[u] = true;
		for(int v = 0; v < n; v++) {
			if(vis[v] == false && cost[u][v] != INF) {
				if(d[u] + cost[u][v] < d[v]) {
					d[v] = d[u] + cost[u][v];
					w[v] = w[u] + weight[v];
					num[v] = num[u];
					pre[v] = u;
				} else if(d[u] + cost[u][v] == d[v]) {
					if(w[u] + weight[v] > w[v]) {
						w[v] = w[u] + weight[v];
						pre[v] = u;
					}
					num[v] += num[u];
				}
			}
		} 
	}
}

void print() {   // 打印路径
	for(int i=0;i<path.size();i++) {
		if(i) cout << "->";
		cout << intToCity[path[i]];
	}
}

void DFS(int st) {   // 记录路径, 同时可以由w[x] / path.size()-1 得到maxinum average happiness
	if(st == 0) {
		path.push_back(st);
		return;
	}
	DFS(pre[st]);
	path.push_back(st);
}

int main() {
	cin >> n >> k >> stCity;
	fill(cost[0], cost[0] + maxn * maxn, INF);
	for(int i = 1; i <= n-1; i++) {
		string temp;
		cin >> temp >> weight[i];
		cityToInt[temp] = i;
		intToCity[i] = temp;
	}
	cityToInt[stCity] = 0;
	intToCity[0] = stCity;
	for(int i = 0; i < k; i++) {
		string a, b;
		int id1, id2;
		cin >> a >> b;
		id1 = cityToInt[a];
		id2 = cityToInt[b];
		cin >> cost[id1][id2];
		cost[id2][id1] = cost[id1][id2];
	}
	Dijkstra(cityToInt[stCity]);
	int dest = cityToInt["ROM"]; 
	DFS(cityToInt["ROM"]);
	cout << num[dest] << " " << d[dest] << " " << w[dest] << " " << w[dest] / (path.size() - 1) << endl;
	print();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值