您的位置:首页 > 其它

关于利用Dijkstra和DFS进行多条件选择路径问题范例

2017-12-04 18:39 295 查看
在刷PAT甲级题目时,发现有好几题都是设计到Dijkstra+DFS来解决多条件选择路径的问题。本文利用PAT甲级1087作为列题进行分析:

首先放上代码:

#include <bits/stdc++.h>
#define INF 65535
using namespace std;

map<string,int> M;
map<int,string> M2;
int happy[205];
int cost[205][205];
int visit[205];
int dist[205]; //确定节点i到0的距离
vector<int> pre[205],temppath,path;
int maxvalue = 0 , cntpath = 0;
double maxavg;

void dfs(int v){
temppath.push_back(v);
if(v == 0){
int temphappy = 0;
double tempavg;
for(int i = 0 ; i < temppath.size() ; i++){
temphappy += happy[temppath[i]];
}
tempavg = temphappy * 1.0 / (temppath.size()-1);
if(temphappy > maxvalue){
maxvalue = temphappy;
maxavg = tempavg;
path = temppath;
}else if(temphappy == maxvalue && tempavg > maxavg){
maxavg = tempavg;
path = temppath;
}
temppath.pop_back();
cntpath++;
return ;
}
for(int i = 0 ; i < pre[v].size() ; i++){
dfs(pre[v][i]);
}
temppath.pop_back();
}

int main(){
fill(dist,dist+205,INF);
fill(cost[0],cost[0]+205*205,INF);
int N,K,Cost;
string city,c1,c2;
cin >> N >> K >> city;
M[city] = 0;
M2[0] = city;
for(int i = 1 ; i < N ; i++){
cin >> city >> happy[i];
M[city] = i;
M2[i] = city;
}
for(int i = 0 ; i < K ; i++){
cin >> c1 >> c2 >> Cost;
cost[M[c1]][M[c2]] = Cost;
cost[M[c2]][M[c1]] = Cost;
}
//下面进行dijkstra
dist[0] = 0;
for(int i = 0 ; i < N ; i++){
int u = -1,Min = 65535;
for(int j = 0 ; j < N ; j++){
if(!visit[j] && dist[j] < Min){
Min = dist[j];
u = j;
}
}
if(u == -1) break;
visit[u] = 1;
for(int j = 0 ; j < N ; j++){
if(!visit[j] && cost[u][j] != INF){
if(dist[j] > Min+cost[u][j]){
dist[j] = Min+cost[u][j];
pre[j].clear();
pre[j].push_back(u);
}else if(dist[j] == Min+cost[u][j]){
pre[j].push_back(u);
}
}
}
}
int rom = M["ROM"];
dfs(rom);
printf("%d %d %d %d\n", cntpath, dist[rom], maxvalue, (int)maxavg);
for(int i = path.size()-1 ; i >= 1 ; i--){
cout << M2[path[i]] << "->";
}
cout << "ROM";
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: