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

在刷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;   
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值