HDU2112 Today

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

本就是裸的单源最短路,只是地名是字符串而已,开个map对字符串编个号就好.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;

const int Mx=1010;
const int inf=0x7ffffff;
int d[Mx],head[Mx];
int cnt,n;
bool v[Mx];
struct node
{
    int from,to,v,next;
} p[Mx*100];
map <string,int> Map;

void add(int u,int v,int w)
{
    p[cnt].from= u;
    p[cnt].to= v;
    p[cnt].v= w;
    p[cnt].next= head[u];
    head[u]= cnt++;
}
void spfa(int s)
{
    for(int i=0;i<Mx;i++) d[i]=inf;
    memset(v,false,sizeof(v));
    queue<int> q;
    d[s]=0;v[s]=true;
    q.push(s);
    while (!q.empty())
    {
        int u=q.front();
        q.pop();
        v[u]=true;
        for (int i=head[u];i!=-1;i=p[i].next)
        {
            int t=p[i].to;
            if (d[t]>d[u]+p[i].v)
            {
                d[t]=d[u]+p[i].v;
                if (!v[t])
                {
                    v[t]=true;
                    q.push(t);
                }
            }
        }
        v[u]=false;
    }
}
int main()
{
    string st,ed,s1,s2;
    int w,m;
    while(~scanf("%d",&n)&&(n!=-1))
    {
        m=1;cnt=0;
        memset(head,-1,sizeof(head));
        Map.clear();
        cin>>st>>ed;
        if (Map[st]==0) Map[st]=m++;
        if (Map[ed]==0) Map[ed]=m++;
        for (int i=1;i<=n;i++)
        {
            cin>>s1>>s2>>w;
            if (Map[s1]==0) Map[s1]=m++;
            if (Map[s2]==0) Map[s2]=m++;
            add(Map[s1],Map[s2],w);
            add(Map[s2],Map[s1],w);
        }
        spfa(Map[st]);
        if (d[Map[ed]]>=inf) printf("-1\n");
        else printf("%d\n",d[Map[ed]]);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值