1087 All Roads Lead to Rome (30 point(s))

题解

dijkstra。

#include<iostream>
#include<cstdio>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 2e2 + 10;
int e[MAXN][MAXN], dis[MAXN], happy[MAXN];
bool vis[MAXN];
vector<int> pre[MAXN], tpath, path;
vector<string> id;
map<string, int> idcache;
int maxtotalhappy, num; 
double maxavghappy;
int ID(string name) {
	if(idcache.count(name)) return idcache[name];
	id.push_back(name);
	return idcache[name] = id.size() - 1;
}
string s, aa, bb;
int a, b, c, n, k;
void dfs(int u) {
	if(u == ID(s)) {
		int totalhappy = 0;
		for(int i = 0; i < tpath.size(); ++i) totalhappy += happy[tpath[i]];
		double avghappy = 1.0 * totalhappy / tpath.size();
		if(totalhappy > maxtotalhappy || totalhappy == maxtotalhappy && avghappy > maxavghappy) {
			maxtotalhappy = totalhappy;
			maxavghappy = avghappy;
			path = tpath;
			path.push_back(u); 
		}
		++num;
		return;
	}
	tpath.push_back(u);
	for(int v = 0; v < pre[u].size(); ++v) dfs(pre[u][v]);
	tpath.pop_back();
}
int main() {
	fill(dis, dis + MAXN, INF);
	fill(e[0], e[0] + MAXN * MAXN, INF);
	cin >> n >> k >> s;
	dis[ID(s)] = 0;
	for(int i = 1; i < n; ++i) {
		cin >> aa >> happy[i];	ID(aa);
	}
	for(int i = 0; i < k; ++i) {
		cin >> aa >> bb >> c;
		a = ID(aa); b = ID(bb);
		e[a][b] = e[b][a] = c;
	}
	for(int i = 0; i < n; ++i) {
		int u = -1, minn = INF;
		for(int j = 0; j < n; ++j) if(vis[j] == false && dis[j] < minn) {
			minn = dis[j];
			u = j;
		}
		if(u == -1) break;
		vis[u] = true;
		for(int v = 0; v < n; ++v) if(vis[v] == false) {
			if(dis[v] > dis[u] + e[u][v]) {
				dis[v] = dis[u] + e[u][v];
				pre[v].clear();
				pre[v].push_back(u);
			} else if(dis[v] == dis[u] + e[u][v]) pre[v].push_back(u);
		}
	}
	dfs(ID("ROM"));
	printf("%d %d %d %d\n", num, dis[ID("ROM")], maxtotalhappy, (int)maxavghappy);
	for(int i = path.size() - 1; i > 0; --i) cout << id[path[i]] << "->"; 
	cout << "ROM";
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值