HDU 2112 HDU Today

hdu 2112 HDU Today

裸的最短路,只是记录节点的时候利用map来存储。特判,起点和终点相同的时候输出0。

#include <stdio.h>
#include <queue>
#include <map>
#include <string>
#include <string.h>
#include <algorithm>
using namespace std;
const int INF=10000000;
int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
        if(n==-1) break;
        map<string,int>m;
        m.clear();
        char st[155],ed[155],s1[155],s2[155];
        bool tag=false,ff1=false,ff2=false;
        int tot=0,edge[155][155];
        for(int i=0;i<155;i++)
            for(int j=0;j<155;j++)
                edge[i][j]=i==j?0:INF;
        scanf("%s%s",st,ed);
        if(strcmp(st,ed)==0)
            tag=true;//判断起点和终点是否相同
        if(!m.count(st))
            m[st]=tot++;
        if(!m.count(ed))
            m[ed]=tot++;
        for(int i=0;i<n;i++){
            int d;
            scanf("%s%s%d",s1,s2,&d);
            if(!strcmp(s1,st)||!strcmp(s2,st))
                ff1=true;
            if(!strcmp(s1,ed)||!strcmp(s2,ed))
                ff2=true;//判断是否存在起点或终点
            if(!m.count(s1))
                m[s1]=tot++;
            if(!m.count(s2))
                m[s2]=tot++;
            edge[m[s1]][m[s2]]=min(edge[m[s1]][m[s2]],d);
            edge[m[s2]][m[s1]]=edge[m[s1]][m[s2]];
        }
        if(tag){
            printf("0\n");
            continue;
        }
        if(!ff1||!ff2){
            printf("-1\n");
            continue;
        }
        int d[150];
        bool vis[150];
        fill(d,d+tot,INF);
        fill(vis,vis+tot,false);
        d[0]=0;
        for(int i=0;i<tot;i++){
            int tt,minh=INF;
            for(int j=0;j<tot;j++){
                if(!vis[j]&&d[j]<minh){
                    minh=d[j];
                    tt=j;
                }
            }
            vis[tt]=true;
            for(int j=0;j<tot;j++)
                d[j]=min(d[j],d[tt]+edge[tt][j]);
        }
        if(d[1]==INF)
            printf("-1\n");
        else
            printf("%d\n",d[1]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值