A1087 All Roads Lead to Rome (30 分)

#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
const int INF = 1e9;
const int maxv = 210;
vector<int> pre[maxv],temppath,path;
map<string, int> strtonum;
map<int, string> numtostr;
int n, k,num=0;
int weight[maxv],G[maxv][maxv],d[maxv];
bool vis[maxv] = { 0 };
int change(string s)
{
	if (strtonum.find(s) != strtonum.end()) return strtonum[s];
	else
	{
		strtonum[s] = num;
		numtostr[num] = s;
		num++;
		return strtonum[s];
	}
}
int diff[maxv] = { 0 };
void dijkstra(int s)
{
	fill(d, d + maxv, INF);
	d[s] = 0;
	diff[s] = 1;
	for (int i = 0; i < n; i++)
	{
		int u = -1, min = INF;
		for (int j = 0; j < n; j++)
		{
			if (vis[j] == 0 && d[j] < min)
			{
				u = j;
				min = d[j];
			}
		}
		if (u == -1) return;
		vis[u] = 1;
		for (int v = 0; v < n; v++)
		{
			if (vis[v] == 0 && G[u][v] != INF)
			{
				if (d[u] + G[u][v] < d[v])
				{
					d[v] = d[u] + G[u][v];
					pre[v].clear();
					pre[v].push_back(u);
					diff[v] = diff[u];
				}
				else if (d[u] + G[u][v] == d[v])
				{
					pre[v].push_back(u);
					diff[v] += diff[u];
				}
			}
		}
	}
}
int h=-1, averh;
void dfs(int d,int count,int temp)//count记录经过城市数量
{
	if (pre[d].size()==0)//即遍历到起点
	{
		temppath.push_back(d);
		if (temp > h)
		{
			h = temp;
			averh= temp/count;
			path = temppath;
		}
		else if (temp == h)
		{
			int taver = temp / count;
			if (taver > averh)
			{
				h = temp;
				averh = taver;
				path = temppath;
			}
		}
		temppath.pop_back();
		return;
	}
	temppath.push_back(d);
	for (int i = 0; i < pre[d].size(); i++)
	{
		dfs(pre[d][i], count + 1,temp+weight[d]);
	}
	temppath.pop_back();//不要忘记pop出输入的值
}
int main()
{
	string str;
	string str1, str2;
	int w;
	fill(G[0], G[0] + maxv * maxv, INF);
	cin >> n >> k >> str;
	int st = change(str);
	weight[st] = 0;//单独赋值
	for (int i = 0; i < n - 1; i++)
	{
		cin >> str >> w;
		weight[change(str)] = w;
	}
	for (int i = 0; i < k; i++)
	{
		cin >> str1 >> str2 >> w;
		int id1 = change(str1), id2 = change(str2);
		G[id1][id2] = G[id2][id1] = w;
	}
	dijkstra(st);
	int de = strtonum["ROM"];
	dfs(de,0,0);
	cout << diff[de] << " " << d[de] << " " << h << " " << (int)averh << endl;
	for (int i = path.size() - 1; i >= 0; i--)
	{
		cout << numtostr[path[i]];
		if (i != 0) cout << "->";
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值