C--最短路

来源:互联网 发布:js修改placeholder值 编辑:程序博客网 时间:2024/06/05 19:31

C--最短路

Time Limit: 7000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

给出一个带权无向图,包含n个点,m条边。求出s,e的最短路。保证最短路存在。

Input

 多组输入。
对于每组数据。
第一行输入n,m(1<= n && n<=5*10^5,1 <= m && m <= 2*10^6)。
接下来m行,每行三个整数,u,v,w,表示u,v之间有一条权值为w(w >= 0)的边。
最后输入s,e。

Output

 对于每组数据输出一个整数代表答案。

Example Input

3 11 2 31 2

Example Output

3

Hint

 

Author

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
using namespace std;
#define inf 999999999
struct node
{
    int v,w;
    int next;
}edge[4000010];
int dis[500010];
int vis[500010];
int head[500010];
int cnt;
int n;


void add(int u,int v,int w)
{
    edge[cnt].v=v;
    edge[cnt].w=w;
    edge[cnt].next=head[u];
    head[u]=cnt++;
}
void SPFA(int s,int e)
{
     int i;
    queue<int>q;
    memset(vis,0,sizeof(vis));
    for(i=0; i<=n; i++)
    {
        dis[i]=inf;
    }
    dis[s]=0;
    vis[s]=1;
    q.push(s);
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        vis[u]=0;
        for(i=head[u];i!=-1;i=edge[i].next)
        {
            int v=edge[i].v;
            if(dis[v]>dis[u]+edge[i].w)
            {
                dis[v]=dis[u]+edge[i].w;
                if(!vis[v])
                {
                    vis[v]=1;
                    q.push(v);
                }
            }
        }
    }
}
int main()
{
    int m;
    int u,v,w;
    int s,e;
    while(~scanf("%d %d",&n,&m))
    {
        memset(head,-1,sizeof(head));
        cnt=0;


        while(m--)
        {


            scanf("%d %d %d",&u,&v,&w);
            add(u,v,w);
            add(v,u,w);
        }
        scanf("%d %d",&s,&e);
        SPFA(s,e);
        printf("%d\n",dis[e]);
    }
    return 0;
}




0 0
原创粉丝点击