HDU2112(hash+dijkstra)

#include<iostream>
#include<cstdio>
#include<string>
#include<map>
#include<cstring>
#define inf (0x3f3f3f3f)
using namespace std;
const int maxn = 150 + 15;
int Grape[maxn][maxn];
map<string,int> m;
int d[maxn];// s 到每个节点的距离
bool vis[maxn];
string startPos,endPos;
int cnt;
void  dijkstra()
{
    memset(vis,false,sizeof(vis));
    memset(d,inf,sizeof(d));
    int start = m[startPos];
    int end = m[endPos];//start to end 单源最短距离
    d[start] = 0;
    while(true)
    {
        int mincost = inf,u = 0;
        for(int v=1;v<=cnt;++v)
        {
            if(!vis[v]&&d[v]<mincost)
            {
                mincost = d[v];
                u = v;
            }
        }
        if(mincost==inf)
            break;
        vis[u] = true;
        for(int v=1;v<=cnt;++v)
        {
            if(!vis[v]&&d[u]+Grape[u][v]<d[v])
            {
                d[v] = Grape[u][v] + d[u];
            }
        }
    }
    if(d[end]==inf)
        cout<<"-1"<<endl;
    else
        cout<<d[end]<<endl;
}
int main()//hash 建Grape 求单源最短路径
{
    int n;
    while(cin>>n&&n!=-1)
    {
        memset(Grape,inf,sizeof(Grape));//inf 代表 u-v 节点不连通
        cnt = 0;//构建 s - e双向图
        m.clear();
        cin>>startPos>>endPos;
        m[startPos] = ++cnt;
        m[endPos] = ++cnt;
        string pos1,pos2;//pos1 to pos2距离并建边
        if(n==0)
        {
            if(startPos==endPos)
                cout<<0<<endl;
            else
                cout<<-1<<endl;
            continue;
        }
        while(n--)
        {
            cin>>pos1>>pos2;
            int u,v;
            if(!m.count(pos1))
                m[pos1] = ++cnt;//从1节点开始建节点
            if(!m.count(pos2))
                m[pos2] = ++cnt;
            u = m[pos1];
            v = m[pos2];
            int w;//边的权值
            cin>>w;
            Grape[u][v] = Grape[v][u] = w;
        }//构建图
        dijkstra();
    }
}

 

posted on 2019-09-21 17:00  chengyulala  阅读(157)  评论(0编辑  收藏  举报

导航