一直没好好整理优先队列的dijkstra算法,特此整理
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
对于每组数据输出一个整数代表答案。
Sample Input
3 1
1 2 3
1 2
Sample Output
3
#include<bits/stdc++.h>
using namespace std;
int n,m;
struct node
{
int v;
int w;
bool operator < (const node &b)const//重载小于号
{
return w>b.w;//STL库中涉及到排序都是按小于号排的,这里就是把小于号重载为特殊的大于号,所以这里是 >
}
}now,tmp;
#define INF 0x3f3f3f
vector<node>MAP[500001];
bool vis[500001];
int d[500001];
void dijkstra(int s,int e)
{
memset(d,INF,sizeof(d));
memset(vis,false,sizeof(vis));
d[s]=0;
now.v=s;
now.w=0;
priority_queue<node>q;
q.push(now);
while(!q.empty())
{
now=q.top();
q.pop();
if(vis[now.v]==true)//如果已经被访问过,那么跳过
{
continue;
}
vis[now.v]=true;
int len=MAP[now.v].size();
for(int i=0;i<len;i++)
{
tmp=MAP[now.v][i];
if(d[now.v]+tmp.w<d[tmp.v])
{
d[tmp.v]=d[now.v]+tmp.w;
q.push((node){tmp.v,d[tmp.v]});
}
}
}
}
int main()
{
while(cin>>n>>m)
{
for(int i=1;i<=n;i++)
{
MAP[i].clear();
}
while(m--)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
MAP[u].push_back((node){v,w});
MAP[v].push_back((node){u,w});
}
int s,e;
cin>>s>>e;
dijkstra(s,e);
cout << d[e] << endl;
}
return 0;
}