HDU2112 Dijsktra (add a special condition)

http://acm.hdu.edu.cn/showproblem.php?pid=2112



#include<bits/stdc++.h>
using namespace std;
const int maxn=155;
#define inf 0x3f3f3f3f
int mmp[maxn][maxn],dist[maxn],vis[maxn],n;
void dijst(int start)
{
    int temp, k;
    memset(vis, false, sizeof(vis));
    for(int i = 1; i <= n; ++i)
        dist[i] = mmp[start][i];
    dist[start] = 0;
    vis[start] = 1;
    for(int i = 1; i <= n; ++i)
    {
        temp = inf;
        for(int j = 1; j <= n; ++j)
            if(!vis[j] && temp > dist[j])
                temp = dist[k = j];
        if(temp == inf) break;//加了特殊判断。!!!!!!
        vis[k] = 1;
        for(int j = 1; j <= n; ++j)
            if(!vis[j] && dist[j] > dist[k] + mmp[k][j])
                dist[j] = dist[k] + mmp[k][j];
    }
}
int main()
{
    int star,over,m,a,b,p;
    char aa[35],bb[35];
    map<string,int>loc;
    while(cin>>m&&m!=-1)
    {
        for(int i=0; i<=154; i++)
            for(int j=0; j<=154; j++)
                mmp[i][j]=(i==j?0:inf);
        loc.clear();
        cin>>aa>>bb;
        n=3;
        loc[aa]=star=1;
        if(!loc[bb])loc[bb]=2;
        over=loc[bb];
        while(m--)
        {
            cin>>aa>>bb>>p;
            if(!loc[aa])
                loc[aa]=n++;
            a=loc[aa];
            if(!loc[bb])
                loc[bb]=n++;
            b=loc[bb];
            if(mmp[a][b]>p)
                mmp[a][b]=mmp[b][a]=p;
        }
        if(star==over)
        {
            cout<<0<<endl;
            continue;
        }
        dijst(star);
        if(dist[over]==inf) dist[over]=-1;
        cout<<dist[over]<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/beposit/article/details/80557048