代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <functional>
#include <map>
#define N 220
#define INF 1000000
using namespace std;
bool dijkstra(void);
int dfs(int c, int num, int tmp_h, int tmp_cost);
int n, k, max_happiness = 0, min_cost = INF, tmp_h = 0;
double averg_happy = 0.0;
string start;
int matrix[N][N], happiness[N] = { 0 };
vector<int> v[N];
stack<int> path, tmp_path;
map<string, int> mp;
map<int, string> remp;
int main(int argc, const char * argv[]) {
cin >> n >> k >> start;
string city1, city2;
int happy, cost;
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
matrix[i][j] = INF;
}
}
mp[start] = 0;
remp[0] = start;
for(i = 1; i < n; i++){
cin >> city1 >> happy;
mp[city1] = i;
happiness[i] = happy;
remp[i] = city1;
}
for(i = 0; i < k; i++){
cin >> city1 >> city2 >> cost;
matrix[mp[city1]][mp[city2]] = cost;
matrix[mp[city2]][mp[city1]] = cost;
}
dijkstra();
int dest = mp[string("ROM")];
int cnt;
cnt = dfs(dest, 1, 0, 0);
printf("%d %d %d %d\n", cnt, min_cost, max_happiness, (int)averg_happy);
int tmp = path.top();
path.pop();
cout << remp[tmp];
while(!path.empty()){
tmp = path.top();
path.pop();
cout << "->" << remp[tmp];
}
cout << endl;
return 0;
}
bool dijkstra(void){
int i, j, k, min_cost, index = 0, dis[N];
bool isvisited[N];
size_t h1, h2;
string c1, c2;
for (i = 0; i < n; i++) {
dis[i] = INF;
isvisited[i] = false;
}
dis[mp[start]] = 0;
for(i = 0; i < n; i++){
min_cost = INF;
for(j = 0; j < n; j++){
if (!isvisited[j] && min_cost > dis[j]) {
min_cost = dis[j];
index = j;
}
}
isvisited[index] = true;
for(j = 0; j < n; j++){
if (!isvisited[j] && dis[index] + matrix[index][j] < dis[j]) {
dis[j] = dis[index] + matrix[index][j];
v[j].clear();
v[j].push_back(index);
}
else if (!isvisited[j] && dis[index] + matrix[index][j] == dis[j]) {
v[j].push_back(index);
}
}
}
return true;
}
int dfs(int c, int num, int tmp_h, int tmp_cost){
static int cnt = 0;
int i;
if (c == 0) {
cnt++;
tmp_path.push(c);
if (tmp_cost < min_cost || (tmp_cost == min_cost && tmp_h > max_happiness) || (tmp_cost == min_cost && tmp_h == max_happiness && (double)tmp_h / (num - 1) > averg_happy)) {
path = tmp_path;
min_cost = tmp_cost;
max_happiness = tmp_h;
averg_happy = tmp_h / (num - 1);
}
tmp_path.pop();
return cnt;
}
else {
tmp_h += happiness[c];
tmp_path.push(c);
for (i = 0; i < v[c].size(); i++) {
tmp_cost += matrix[c][v[c][i]];
dfs(v[c][i], num + 1, tmp_h, tmp_cost);
tmp_cost -= matrix[c][v[c][i]];
}
tmp_path.pop();
return cnt;
}
}