PAT A1087 All Roads Lead to Rome(30 分)----最短路徑(加篩選條件)
總結:
1.圖中的點名稱為字母,所以用兩個map來進行轉換
2.先求最短路徑集合,再求符合要求的最短路徑
程式碼:
#include<iostream>
#include<vector>
#include<map>
#include<string>
using namespace std;
int weight[500];
int vi[500];
int n, k;
string st1;
int g = 1;
int G[500][500];
map<string, int> stoint1;
map<int, string> itostr1;
string des = "ROM";
int minlen = 999999;
int totalen = 0;
map<int,vector<vector<int> > > pp;
int getid(string s)
{
if (stoint1[s]== 0){
stoint1[s] = g++;
itostr1[g - 1] = s;
}
return stoint1[s];
}
void dfs(int index,vector<int>route)
{
if (index == stoint1[des])
{
if (minlen > totalen){ minlen = totalen; pp[minlen].push_back(route); }
else if (minlen==totalen){ minlen = totalen; pp[minlen].push_back(route); }
}
vi[index] = 1;
for (int i = 1; i <= n; i++)
{
if (G[index][i] != 0 && vi[i] == 0)
{
route.push_back(i);
totalen += G[index][i];
dfs(i,route);
totalen -= G[index][i];
route.pop_back();
vi[i] = 0;
}
}
}
int main()
{
cin >> n >> k >> st1;
int st = getid(st1);
for (int i = 2; i <= n; i++)
{
string p; int w;
cin >> p >> w;
int id = getid(p);
weight[id] = w;
}
for (int i = 0; i < k; i++)
{
int c1, c2,cost;
string cc1, cc2;
cin >> cc1 >> cc2>>cost;
c1 = getid(cc1); c2 = getid(cc2);
G[c1][c2] = cost; G[c2][c1] = cost;
}
vector<int> route;
route.push_back(st);
dfs(st,route);
int maxha = 0, totalha = 0; double maxavr = 0.0; int index = -1; double avr = 0;
for (int i = 0; i < pp[minlen].size(); i++)
{
totalha = 0; avr = -1;
for (int j = 0; j < pp[minlen][i].size(); j++)
{
totalha += weight[pp[minlen][i][j]];
}
avr = (1.0*totalha) / (pp[minlen][i].size()-1);
if (totalha>maxha){ maxha = totalha; index = i; maxavr = avr; }
else if (totalha == maxha&&avr>maxavr){ maxavr = avr; index = i; }
}
cout << pp[minlen].size() << " " << minlen << " " << maxha << " "; int p = maxavr; printf("%d",p); cout << endl;
for (int i = 0; i < pp[minlen][index].size(); i++)
{
cout<<itostr1[pp[minlen][index][i]];
if(i!=pp[minlen][index].size()-1)printf("->");
}
return 0;
}