题目
思路
hash字符串+图的最短路径(我使用DFS)
代码
#include <iostream>
#include <string>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
#define nmax 205
#define inf 999999
map<string, int> STOI;
map<int, string> ITOS;
string srcs, tar = "ROM";
int n, m;
int graph[nmax][nmax];
int hapi[nmax];
int visited[nmax];
int _index = 0;
int src, dest;
int mincost = inf;
vector<int> vec;
typedef struct info
{
int cost;
int hapi;
double averhapi;
vector<int> v;
};
vector <info> vs;
bool cmp(const info& a, const info& b) {
if (a.cost != b.cost)
return a.cost < b.cost;
else
if (a.hapi != b.hapi)
return a.hapi > b.hapi;
else
return a.averhapi > b.averhapi;
}
int StrToInt(string str) {
STOI.insert(pair<string, int>(str, _index));
ITOS.insert(pair<int, string>(_index,str));
int num = _index;
++_index;
return num;
}
void DFS(int cur,int cost,int hapio) {
if (cur == dest) {
if (cost <= mincost) {
info in;
in.cost = cost;
in.hapi = hapio;
in.averhapi = (double)hapio / (vec.size()-1);
in.v = vec;
vs.emplace_back(in);
}
return;
}
for (int i = 0; i < n; ++i) {
if (visited[i] == 0 && graph[cur][i] != 0) {
visited[i] = 1;
vec.emplace_back(i);
DFS(i, cost + graph[cur][i],hapio+hapi[i]);
vec.pop_back();
visited[i] = 0;
}
}
}
int main()
{
cin >> n >> m >> srcs;
src = StrToInt(srcs);
hapi[src] = 0;
for (int i = 0; i < n-1; ++i) {
string tmp;
int hapn;
cin >> tmp >> hapn;
int _index = StrToInt(tmp);
if (tmp == tar)
dest = _index;
hapi[_index] = hapn;
}
memset(graph, 0, sizeof(graph));
for (int i = 0; i < m; ++i) {
string u, v;
int cost;
cin >> u >> v >> cost;
int iu = STOI[u];
int iv = STOI[v];
graph[iu][iv] = graph[iv][iu] = cost;
}
memset(visited, 0, sizeof(visited));
visited[src] = 1;
vec.emplace_back(src);
DFS(src, 0,0);
sort(vs.begin(), vs.end(), cmp);
int num = 1;
int cost = vs[0].cost;
for (int i = 1; i < vs.size(); ++i) {
if (vs[i].cost != cost)
break;
num++;
}
cout << num <<" "<< cost <<" "<< vs[0].hapi <<" "<<(int)vs[0].averhapi << endl;
cout<<ITOS[vs[0].v[0]];
for (int i = 1; i < vs[0].v.size(); ++i)
cout << "->" << ITOS[vs[0].v[i]];
return 0;
}