最短路(信息学奥赛一本通-T1382)

【题目描述】

给定 M 条边, N 个点的带权无向图。求 1 到 N 的最短路。

【输入】

第一行:N,M(N≤100000,M≤500000)

接下来M行3个正整数:ai,bi,ci表示ai,bi之间有一条长度为ci的路,ci≤1000。

【输出】

一个整数,表示 1 到 N 的最短距离。

【输入样例】

​4 4
1 2 1
2 3 1
3 4 1
2 4 1

【输出样例】

2

【源程序】

#include<iostream>
#include<cstdio>
#define INF 0x3f3f3f3f
#define N 100100
using namespace std;
struct node{
    int pre;
    int next;
    int w;
}a[N*10];
int q[N*10],head[N];
int vis[N],f[N];
int cnt;
void add(int x,int y,int w)
{
    cnt++;
    a[cnt].pre=y;
    a[cnt].next=head[x];
    a[cnt].w=w;
    head[x]=cnt;

    cnt++;
    a[cnt].pre=x;
    a[cnt].next=head[y];
    a[cnt].w=w;
    head[y]=cnt;
}
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y,w;
        cin>>x>>y>>w;
        add(x,y,w);
    }

    memset(f,INF,sizeof(f));
    f[1]=0;
    vis[1]=1;

    int headd=1,tail=1;
    q[tail]=1;
    tail++;
    while(headd<tail)
    {
        int x=q[headd];
        int temp=head[x];
        while(temp!=0)
        {
           int y=a[temp].pre;
            if(f[y]>f[x]+a[temp].w)
            {
                f[y]=f[x]+a[temp].w;
                if(vis[y]==0)
                {
                    vis[y]=1;
                    q[tail]=y;
                    tail++;
                }
            }
            temp=a[temp].next;
        }
        vis[x]=0;
        headd++;
    }
    cout<<f[n]<<endl;
    return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值