1087. All Roads Lead to Rome (30)
来源:互联网 发布:云计算工程师好干吗 编辑:程序博客网 时间:2024/06/08 02:59
//dijstra#include<cstdio>#include<algorithm>#include<string>#include<map>#include<vector>#include<iostream>using namespace std;#define maxn 1000#define INF 1000000000map<string, int> cityToNum;map<int, string> NumTocity;int n,m,G[maxn][maxn];int vis[maxn]={false},pre[maxn]={0};int num[maxn]={0},d[maxn],weight[maxn]={0},w[maxn],pt[maxn]={0};string st;void init(){ fill(G[0],G[0]+maxn*maxn,INF); fill(d, d+maxn, INF); fill(w,w+maxn, INF);}void Dijstra(int s){ d[s] = 0; num[s] = 1; w[s] = 0; //n次循环 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 && G[u][v]!=INF) { //找到了话费最小的,全部更新 if(d[u]+G[u][v]<d[v]) { d[v] = d[u]+G[u][v]; w[v] = w[u]+weight[v]; num[v] = num[u]; pre[v] = u; pt[v] = pt[u] + 1; } else if(d[u]+G[u][v]==d[v]) { num[v] += num[u]; //如果幸福值最多,选择更新 if(w[u]+weight[v]>w[v]) { w[v] = w[u]+weight[v]; pre[v] = u; pt[v] = pt[u]+1; } //如果等于,计算平均点权 else if(w[u]+weight[v]==w[v]) { double uavg = (w[u]+weight[v])*1.0/(pt[u]+1); double vavg = (w[v])*1.0/pt[v]; if(uavg>vavg) { pt[v] = pt[u]+1; pre[v] = u; } } } } } }}void showPath(int s, int v){ while (s == v) { cout<<NumTocity[s]; return; } showPath(s,pre[v]); cout<<"->"<<NumTocity[v];}int main(){ string city1,city2; //输入数据 cin>>n>>m>>st; init(); cityToNum[st] = 0; NumTocity[0] = st; //构造图 for(int i=1; i<n; i++) { cin>>city1>>weight[i]; cityToNum[city1] = i; NumTocity[i] = city1; } for(int i=0; i<m; i++) { int x; cin>>city1>>city2>>x; int a = cityToNum[city1]; int b = cityToNum[city2]; G[a][b] = x; G[b][a] = x; } //遍历 Dijstra(0); //输出结果 int ed = cityToNum["ROM"]; printf("%d %d %d %d\n",num[ed],d[ed],w[ed],w[ed]/pt[ed]); showPath(0,ed); return 0;}
0 0
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087. All Roads Lead to Rome (30)
- 1087.All Roads Lead to Rome (30)
- 1086. Tree Traversals Again (25)
- 图 续2
- 不用额外变量交换两个整数的值
- 3Dmax快捷键
- 深度学习:梯度消失和梯度爆炸
- 1087. All Roads Lead to Rome (30)
- 1088. Rational Arithmetic (20)
- Train Problem I (栈的模拟)
- npm安装
- 冒泡排序
- iptable使用笔记
- 1090. Highest Price in Supply Chain (25)
- Python中的新奇玩意
- POSIX(Portable Operating System Interface )信号处理