2021-08-01
22:17:41
链接:
https://www.luogu.com.cn/problem/P1339
题目描述
有一个 n 个点 m 条边的无向图,请求出从 s 到 t 的最短路长度。
输入格式
第一行四个正整数 n,m,s,t。 接下来 m 行,每行三个正整数 u,v,w,表示一条连接 u,v,长为 w 的边。
输出格式
输出一行一个整数,表示答案。
输入输出样例
输入 #1
7 11 5 4
2 4 2
1 4 3
7 2 2
3 4 3
5 7 5
7 3 3
6 1 1
6 3 4
2 4 3
5 6 3
7 2 1
输出 #1
7
说明/提示
【数据范围】
对于 100\%100% 的数据,1≤n≤2500,1≤m≤6200,1≤w≤1000。
【样例说明】
5→6→1→4 为最短路,长度为 3+1+3 = 7。
标准的模板题:
此次使用Dijkstra堆优化算法,时间复杂度O(mlogn)
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef pair<int,int>PII;
const int INF=1e8;
const int N=1e5+5;
int h[N],ne[N],e[N],w[N],idx;
int n,m,s,goal;
int dist[N];//d[i]表示从起点s到终点i的最短距离
bool st[N];//st[i]是否已经确定最短距离
void add(int a,int b,int c){
e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
int dijkstra(){
memset(dist,0x3f,sizeof dist);
priority_queue< PII,vector<PII>,greater<PII> >heap;
heap.push(PII(0,s));
dist[s]=0;
while(heap.size()){
PII t=heap.top();
heap.pop();
int distance=t.first,ver=t.second;
if(st[ver])continue;
st[ver]=true;
for(int i=h[ver];i!=-1;i=ne[i])
{
int j=e[i];
if(dist[j]>distance+w[i])
{
dist[j]=distance+w[i];
heap.push(PII(dist[j],j));
}
}
}
return dist[goal];
}
int main()
{
cin>>n>>m>>s>>goal;
memset(h, -1, sizeof h);
for(int i=0;i<m;i++){
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
add(b,a,c);
}
cout<<dijkstra();
return 0;
}
2021-08-01
22:19:49
浙公网安备 33010602011771号