HDU 2112 (Today,无向图最短路)

版权声明: https://blog.csdn.net/weixin_39778570/article/details/82027333

题目链接
字符串起点和终点,可以用map映射成数字,注意题目说的是输入两个站点,而不是输入起点和终点,所以是无向图

AC code

#include <iostream>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#define LL long long
#define INF 0x3f3f3f3f
#define maxn 10024
#define Pair pair<int, int>
#define mem(a, b) memset(a, b, sizeof(a))
#define _  ios_base::sync_with_stdio(0),cin.tie(0)
//freopen("1.txt", "r", stdin);
using namespace std;

typedef pair<int, int> P;
struct edge
{
    int to, cost;
};
int V=1;
vector<edge> G[maxn];
int d[maxn];
map<string, int> mp;
void dijkstra(int s)
{
    priority_queue<Pair, vector<Pair>, greater<Pair> > que;
    fill(d, d + V + 2, INF);
    d[s] = 0;
    que.push(Pair(0, s));
    while (!que.empty()) {
        Pair p = que.top();
        que.pop();
        int v = p.second;
        if (d[v] < p.first) continue;//到v点的距离如果已经被更新 这无须执行以下操作
        for (int i = 0; i < G[v].size(); ++i) {
            edge e= G[v][i];
            if (d[e.to] > d[v] +e.cost) {
                d[e.to] = d[v] + e.cost;
                que.push(P(d[e.to], e.to));
            }
        }
    }
}
int main()
{
    int m;
    string str, end;
    while(scanf("%d", &m) && m!=-1){
        for(int i=0; i<maxn; i++) G[i].clear();
        mp.clear();
        V=1;
        cin >> str >> end;
        if(!mp[str]) mp[str] = V++;
        if(!mp[end]) mp[end] = V++;
        for (int i = 0; i < m; ++i) {
            string from, to;
            int cost;
            cin >> from >> to >> cost;
            if(!mp[from]) mp[from] = V++;
            if(!mp[to]) mp[to] = V++;
            //cout<< mp[from] << " " << mp[to] << endl;
            edge var;
            var.to = mp[to];
            var.cost = cost;
            G[mp[from]].push_back(var);
            var.to = mp[from];
            G[mp[to]].push_back(var);//无向图
        }
        dijkstra(mp[str]);
        if(d[mp[end]]!=INF) printf("%d\n", d[mp[end]]);
        else printf("%d\n",-1);
        //for(int i=0; i<=V; i++) printf("%d\n", d[i]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_39778570/article/details/82027333