## 【PAT甲级 单源最短路径】1087 All Roads Lead to Rome (30 分)

``````
struct defaultCost{

int cost;
defaultCost():cost(INF){

}; // 更改不存在key的map的默认value值为INF
defaultCost(int c):cost(c){

}
};
map<string, defaultCost> cost; // 之前的dist数组，改名了
``````

``````map<string, vector<Node> > G;  // 边权
map<string, int> V;    // 点权
map<string, defaultCost> cost; // 之前的dist数组，改名了
map<string, bool> vis;
map<string, vector<string>> pre;
``````

### Dijkstra + DFS

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

const int MAXV = 210;
const int INF  = 0xffffff;

struct Node{

string name;
int cost;
};
// 设一个结构体并赋予初值就可以设定访问map不存在的key时的默认value值
struct defaultCost{

int cost;
defaultCost():cost(INF){

}; // 更改不存在key的map的默认value值为INF
defaultCost(int c):cost(c){

}
};

map<string, vector<Node> > G;  // 边权
map<string, int> V;    // 点权
map<string, defaultCost> cost; // 之前的dist数组，改名了
map<string, bool> vis;
map<string, vector<string>> pre;

int N, K;
string st, ed = "ROM";

void Dijsktra(string s){

cost[s] = 0;
for(int i = 0;i < N;++i){

string u = "000";
int MIN = INF;
for(auto p: V){

string j = p.first;
if(vis[j] == false && cost[j].cost < MIN){

u = j;
MIN = cost[j].cost;
}
}
if(u == "000") return;
vis[u] = true;
for(Node next: G[u]){

string v = next.name;
int uv_cost = next.cost;
if(vis[v] == false){

if(cost[u].cost + uv_cost  < cost[v].cost){

cost[v].cost = cost[u].cost + uv_cost;
pre[v].clear();
pre[v].push_back(u);
}
else
if(cost[u].cost + uv_cost == cost[v].cost){

pre[v].push_back(u);
}
}
}
}

}

vector<string> path, tempPath;
int routes = 0; // 相等cost的路径数量
int maxSumHappyness = -1; // 最大快乐值;
double maxAvgHappyness = -1; // 最大平均快乐值
void DFS(string v){

if(v == st){

routes++;
tempPath.push_back(st);

int sumhappyness = 0;
double avghappyness = 0.0;
for(string id: tempPath){

sumhappyness += V[id];
}
avghappyness = sumhappyness / (tempPath.size() - 1);
if(sumhappyness > maxSumHappyness){

maxSumHappyness = sumhappyness;
maxAvgHappyness = avghappyness;
path = tempPath;
}
else
if(sumhappyness == maxSumHappyness){

if(avghappyness > maxAvgHappyness){

maxAvgHappyness = avghappyness;
path = tempPath;
}
}

tempPath.pop_back();
return;
}

tempPath.push_back(v);
for(string u: pre[v]){

DFS(u);
}
tempPath.pop_back();
}

int main(){

cin >> N >> K >> st;
for(int i = 0;i < N-1;++i){

// 不输入起点的开心值，所以要N-1，并且给起点得到开心值初始化为0（被坑了）
string city;
int happy;
cin >> city >> happy;
V[city] = happy;
}V[st] = 0;
for(int i = 0;i < K;++i){

string city1, city2;
int cost;
cin >> city1 >> city2 >> cost;
G[city1].push_back({

city2, cost});
G[city2].push_back({

city1, cost});
}
Dijsktra(st);
DFS(ed);
printf("%d %d %d %.0f\n",routes, cost[ed].cost, maxSumHappyness, maxAvgHappyness);
for(int i = path.size() - 1;i >= 0;--i){

cout << path[i];
if(i != 0)
cout << "->";
else
cout << "\n";
}

return 0;
}
``````