分析:根据题意DFS即可,只不过城市名是字符串,用map。
#include <iostream>
#include<cstring>
#include<vector>
#include<stdio.h>
#include<queue>
#include<math.h>
#include<stack>
#include<algorithm>
#include<map>
#include<set>
#include<iostream>
using namespace std;
#define MAX 999999999
typedef long long ll;
int n,m,k;
map<string,int>hap;
map<string,int>visi;
map<string,map<string,int>>road;
map<string,vector<string>>city;
int min_cost = MAX;
int max_hap = -1;
int num;
vector<string>ans;
double avg_hap;
int c_cost ;
int c_hap ;
int c_num;
vector<string>c_ans;
void dfs(string root)
{
visi[root] = 1;
if(root == "ROM" ){
if(c_cost < min_cost){
min_cost = c_cost;
max_hap = c_hap;
num = c_num;
ans = c_ans;
}
else if(c_cost == min_cost && c_hap > max_hap){
max_hap = c_hap;
num = c_num;
ans = c_ans;
}
else if(c_cost == min_cost && c_hap == max_hap && c_num < num){
num = c_num;
ans = c_ans;
}
}
else{
for(int i = 0; i < city[root].size();i++)
{
if(!visi[city[root][i]] )
{
c_cost += road[root][city[root][i]];
c_num++;
c_hap += hap[city[root][i]];
c_ans.push_back(city[root][i]);
dfs(city[root][i]);
c_cost -= road[root][city[root][i]];
c_num--;
c_hap -= hap[city[root][i]];
c_ans.pop_back();
}
}
}
visi[root] = 0;
}
int cnt;
void dfs2(string root)
{
visi[root] = 1;
if(root == "ROM" && c_cost == min_cost)
cnt++;
else{
for(int i = 0; i < city[root].size();i++)
{
if(!visi[city[root][i]] )
{
c_cost += road[root][city[root][i]];
c_num++;
c_hap += hap[city[root][i]];
c_ans.push_back(city[root][i]);
dfs2(city[root][i]);
c_cost -= road[root][city[root][i]];
c_num--;
c_hap -= hap[city[root][i]];
c_ans.pop_back();
}
}
}
visi[root] = 0;
}
int main()
{
string sta;
cin>>n>>m>>sta;
for(int i = 0; i < n - 1; i ++)
{
string x;int p;
cin>>x>>p;
hap[x] = p;
}
for(int i = 0 ; i < m ; i++)
{
string a,b;
int x;
cin>>a>>b>>x;
road[a][b] = road[b][a] = x;
city[a].push_back(b);
city[b].push_back(a);
}
dfs(sta);
dfs2(sta);
cout<<cnt<<" "<<min_cost<<" "<<max_hap<<" "<<max_hap/num<<endl;
cout<<sta;
for(int i = 0 ; i < ans.size();i++)
cout<<"->"<<ans[i];
return 0;
}