1. 程式人生 > >HDU - 2112 HDU Today(最短路 dijkstra)

HDU - 2112 HDU Today(最短路 dijkstra)

題目連結

題意:找兩個城市之間的最短路,沒有就輸出-1;

簡單題,把城市轉成數字做就行,但有坑點:起點和終點可以相同;

 

#include <iostream>
#include <cstdio>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
typedef long long ll;

const int INF = 0x3f3f3f3f;
int dis[200][200];
int n=190,m;

void dijkstra(){
    int v[200] = {0};//標記有沒走到過

    while(1){
        int mmin = INF,k;
        for(int j = 1;j <= n;j++)//每次找距離最近且未走過的點
            if(!v[j] && dis[1][j] < mmin)
                k = j, mmin = dis[1][j];
        if(mmin == INF) break;//找不到距離近且沒走過的點了,退出

        v[k] = 1;//標記
        for(int j = 1;j <= n;j++)
            dis[1][j] = min(dis[k][j]+dis[1][k],dis[1][j]);//不停的優化
    }
    if(dis[1][2] != INF) cout<<dis[1][2]<<endl;
    else cout<<-1<<endl;
}

map <string,int>mp;//把城市對映成id,就是普通的最短路
string s1,s2,s3,s4;
int main()
{
    while(cin>>m && m != -1){
    mp.clear();
    cin>>s3>>s4;
    mp[s3] = 1,mp[s4] = 2;
    for(int i = 0;i <= n;i++)
        for(int j = 0;j <= n;j++)
            dis[i][j] = (i==j?0:INF);
    int a,b,c;
    while(m--){
        cin>>s1>>s2>>c;
        if(mp[s1]) a = mp[s1];
        else{
            a = mp.size();
            mp[s1] = a;
        }
        if(mp[s2]) b = mp[s2];
        else{
            b = mp.size();
            mp[s2] = b;
        }
        dis[a][b] = dis[b][a] = min(dis[a][b],c);
    }
    if(s3 == s4){//注意!!!!起點終點可能相等
        cout<<0<<endl;
        continue;
    }
    dijkstra();
    }
    return 0;
}