C--最短路
Time Limit: 7000MS MemoryLimit: 65536KB
ProblemDescription
给出一个带权无向图,包含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
对于每组数据输出一个整数代表答案。
ExampleInput
3 1
1 2 3
1 2
ExampleOutput
3
Hint
Author
zmx
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
#define inf 99999999
struct node
{
int v,w;
int next;
}edge[4000010];
int dis[500010],vis[500010],head[500010];
int cnt,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=1;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]==0)
{
vis[v] = 1;
q.push(v);
}
}
}
}
}
int main()
{
int m,v,w,s,e,u;
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;
}
/***************************************************
User name: jk160505徐红博
Result: Accepted
Take time: 1316ms
Take Memory: 3368KB
Submit time: 2017-02-16 20:21:16
****************************************************/