HDU 2112

HDU 2112

Dijsktra + map

把字符串映射成int型即可

注意起点和终点可能重合,这样之间输出0,或者输出 dist[0]

注意双向边,重边

#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
const int N = 200,INF = 0x3f3f3f3f;
int n,m,dist[N],g[N][N],a,b;
bool st[N];
void dij(int x){
    memset(dist,0x3f,sizeof dist);
    memset(st,0,sizeof st);
    dist[x] = 0;
    for(int i = 0;i < n; ++i){
        int t = -1;
        for(int j = 0;j < n; ++j){
            if(!st[j] && (t == -1 || dist[j] < dist[t]))
                 t = j;
        }
        st[t] = 1;
        for(int j = 0;j < n; ++j){
            dist[j] = min(dist[j],dist[t] + g[t][j]);
        }
    }
}
int main() {
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    while(cin >> m && m != -1) {
        n = 0;
        memset(g,0x3f,sizeof g);
        string starti,endi,s1,s2;
        map<string,int> dict;
        int time;
        cin >> starti >> endi;
        dict[starti] = n++;
        if(dict.count(endi) == 0) dict[endi] = n++;
        for(int i = 0;i < m; ++i) {
            cin >> s1 >> s2 >> time;
            if(dict.count(s1) == 0) dict[s1] = n++;
            if(dict.count(s2) == 0) dict[s2] = n++;
            a = dict[s1],b = dict[s2];
            g[a][b] = g[b][a] = min(g[a][b],time);
        }
        if(dict[starti] == dict[endi]) {
            cout << "0" << endl;
            continue;
        }
        dij(0);
        if(dist[1] < INF) cout << dist[1];
        else cout << "-1";
        cout << endl;
    }
    return 0;
}
posted @ 2020-03-05 20:07  南风--  阅读(65)  评论(0编辑  收藏  举报