注意INIFINTE 定义成32767已经不够了,有可能出现大于INIFINTE的distance,以后定义成0x7fffffff (7个f)
相同最短路径的个数等于父路径个数或父路径个数加一,而不是++
#include<stdio.h>
#include<vector>
#include<string.h>
#define SIZE 205
#define INIFINTE 0x7fffffff
using namespace std;
struct map{
int index;
int dist;
};
int dist[SIZE], name[SIZE], hh[18279], numofcost[SIZE], parent[SIZE],happiness[SIZE],numofcity[SIZE],flag[SIZE],h[SIZE];
vector<struct map> graph[SIZE];
int hashname(char str[]){
return (str[0]-'A') * 26 * 26 + (str[1] - 'A') * 26 + str[2] - 'A';
}
char s[4];
char *rehash(int n){
s[0] = n / (26 * 26) + 'A';
n = n % (26 * 26);
s[1] = n / 26 + 'A';
n = n % 26;
s[2] = n + 'A';
s[3] = '\0';
return s;
}
void Dij(int s,int n){
int i;
for (i = 0; i < n; i++){
dist[i] = INIFINTE;
flag[i] = 0;
h[i] = -1;
}
dist[s] = 0;
h[s] = 0;
numofcost[s] = 1;
int j,u,dis;
for (i = 0; i < n; i++){
dis = INIFINTE;
u = -1;
for (j = 0; j < n;j++)
if (!flag[j])
if (dist[j] < dis){
u = j;
dis = dist[j];
}
if (u == -1)
break;
flag[u] = 1;
int size = graph[u].size();
for (j = 0; j < size; j++){
struct map s = graph[u][j];
if (dist[s.index] > dist[u] + s.dist){
dist[s.index] = dist[u] + s.dist;
parent[s.index] = u;
numofcity[s.index] = numofcity[u] + 1;
h[s.index] = h[u] + happiness[s.index];
numofcost[s.index] = numofcost[u];
}
else if (dist[s.index] == dist[u] + s.dist){
if (h[s.index] == h[u] + happiness[s.index]){
if (numofcity[s.index] >= numofcity[u] + 1){
parent[s.index] = u;
numofcity[s.index] = numofcity[u] + 1;
}
}
else if (h[s.index] < h[u] + happiness[s.index]){
parent[s.index] = u;
numofcity[s.index] = numofcity[u] + 1;
h[s.index] = h[u] + happiness[s.index];
}
numofcost[s.index] += numofcost[u];
}
}
}
}
void PrintPath(int s, int d){
int i;
if (s == d)
printf("%s", rehash(name[s]));
else {
PrintPath(s, parent[d]);
printf("->%s", rehash(name[d]));
}
}
int main(){
freopen("1.in", "r", stdin);
int NumOfCity, NumOfRoad, start;
char startch[4];
memset(hh, -1, sizeof(hh));
scanf("%d%d%s", &NumOfCity, &NumOfRoad, &startch);
start = hashname(startch);
happiness[0] = 0;
name[0] = start;
hh[start] = 0;
int i;
char str[4],ch[4];
for (i = 1; i < NumOfCity; i++){
scanf("%s%d", &str, &happiness[i]);
name[i] = hashname(str);
hh[name[i]] = i;
}
struct map node;
int s, d;
for (i = 0; i < NumOfRoad; i++){
scanf("%s%s%d", &str, &ch, &node.dist);
s = hashname(str);
d = hashname(ch);
node.index = hh[d];
graph[hh[s]].push_back(node);
node.index = hh[s];
graph[hh[d]].push_back(node);
}
Dij(0,NumOfCity);
int aim;
aim = hh[hashname("ROM")];
printf("%d %d %d ", numofcost[aim], dist[aim], h[aim]);
printf("%d\n", h[aim] / numofcity[aim]);
PrintPath(0, aim);
putchar('\n');
return 0;
}