只用dijistr一次性通过,还是挺爽的。
附本人AC代码:
#include<iostream>
#include<vector>
#include<string>
#include<map>
using namespace std;
int N, K;
const int inf = 100000000;
map<string, int>Ma;
map<int, string>Mb;
vector<int>Happy, chappy, res;
int G[210][210], dis[210], father[210], countl[210], cnum[210];
bool flag[210];
void dijistra(int x) {
fill(dis, dis + 210, inf);
dis[0] = 0;
countl[0] = 0;
cnum[0] = 1;
for (int i = 0; i < N; i++) {
int index = -1, mini = inf;
for (int j = 0; j < N; j++) {
if (dis[j] < mini&&flag[j] == false) {
mini = dis[j];
index = j;
}
}
if (index == -1)return;
flag[index] = true;
for (int j = 0; j < N; j++) {
if (G[index][j] != inf) {
if (dis[index] + G[index][j] < dis[j]) {
dis[j] = dis[index] + G[index][j];
chappy[j] = chappy[index] + Happy[j];
father[j] = index;
countl[j] = countl[index] + 1;
cnum[j] = cnum[index];
}
else if (dis[index] + G[index][j] == dis[j]) {
cnum[j] += cnum[index];
if (chappy[index] + Happy[j] > chappy[j]) {
chappy[j] = chappy[index] + Happy[j];
father[j] = index;
countl[j] = countl[index] + 1;
}
else if (chappy[index] + Happy[j] == chappy[j]) {
if (countl[index] + 1 < countl[j]) {
countl[j]=countl[index] + 1;
father[j] = index;
}
}
}
}
}
}
}
int main() {
fill(G[0], G[0] + 210 * 210, inf);
string s1, s2, s3;
scanf("%d%d", &N, &K);
cin.ignore();
cin >> s1;
Happy.resize(N);
chappy.resize(N);
chappy[0] = 0;
int index = 1, val;
Ma[s1] = 0;
Mb[0] = s1;
for (int i = 1; i < N; i++) {
cin >> s1 >> val;
if (Ma[s1] == 0) {
Ma[s1] = index;
Mb[index] = s1;
index++;
}
Happy[Ma[s1]] = val;
}
for (int i = 0; i < K; i++) {
cin >> s1 >> s2 >> val;
G[Ma[s1]][Ma[s2]] = G[Ma[s2]][Ma[s1]] = val;
}
dijistra(0);
printf("%d %d %d %d\n", cnum[Ma["ROM"]],dis[Ma["ROM"]],chappy[Ma["ROM"]],chappy[Ma["ROM"]]/countl[Ma["ROM"]]);
s3 = "ROM";
while (Ma[s3] != 0) {
res.push_back(Ma[s3]);
s3 = Mb[father[Ma[s3]]];
}
printf("%s", Mb[0].c_str());
for (int i = res.size() - 1; i >= 0; i--) {
printf("->%s", Mb[res[i]].c_str());
}
return 0;
}