HDU 2112 HDU Today

转载请注明该文链接


题意:给一些结点,一些无向边,给起点a终点b(字母输入),求最短距离。


思路:直接建图跑一遍SPFA。这里学习了map的一些用法。


代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<queue>
#include<map>
#include<algorithm>

using namespace std;

typedef __int64 ll;

const int N=160;
const int M=10010;
const ll inf=1LL<<60;

struct node
{
    int v;
    ll dis;
    node *next;
}E[M<<1],*G[N],*head;

inline void add(int a,int b,ll c,node *G[])
{
    head->v=b;
    head->dis=c;
    head->next=G[a];
    G[a]=head++;
}

int m,num;
ll d[N];
bool inq[N];
map<string,int> dict;

void init()
{
    fill(d,d+N,inf);
    memset(G,0,sizeof(G));
    memset(inq,false,sizeof(inq));
    dict.clear();
    head=E;
    num=0;
}

inline int change(char *s)
{
    if(dict.count(s)) return dict[s];
    else return dict[s]=num++;
}

void SPFA(int s,ll d[],node *G[])
{
    d[s]=0;
    deque<int> Q;
    Q.push_front(s);
    while(!Q.empty())
    {
        int u=Q.front();
        Q.pop_front();
        inq[u]=false;
        for(node *p=G[u];p;p=p->next)
        {
            int v=p->v;
            ll dis=p->dis;
            if(d[v]>d[u]+dis)
            {
                d[v]=d[u]+dis;
                if(!inq[v])
                {
                    inq[v]=true;
                    if(!Q.empty() && d[v]<=d[Q.front()]) Q.push_front(v);
                    else Q.push_back(v);
                }
            }
        }
    }
}

int main()
{
    char s1[40],s2[40];
    while(scanf("%d",&m),m+1)
    {
        init();
        int s,t;
        scanf("%s %s",s1,s2);
        s=change(s1),t=change(s2);
        int a,b;
        ll c;
        for(int i=0;i<m;i++)
        {
            scanf("%s %s %I64d",s1,s2,&c);
            a=change(s1),b=change(s2);
            add(a,b,c,G);
            add(b,a,c,G);
        }
        SPFA(s,d,G);
        if(d[t]==inf) printf("-1\n");
        else printf("%I64d\n",d[t]);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值