#include<bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
int n,m;
int vis[1005];
int ans[1005];
struct node{
int to; //终点
int next; //上一次起点在图中出现的位置
int w; //边权
}s[20005];
int head[20005];
int cnt;
void init(){ //初始化
cnt=0;
for(int i=0;i<n;i++){
head[i]=-1;
vis[i]=0;
ans[i]=inf;
}
}
void add_edge(int x,int y,int z){ //链式前向星存图
s[cnt].to=y;
s[cnt].w=z;
s[cnt].next=head[x];
head[x]=cnt++;
}
struct cmp{
bool operator()(pair<int,int>a,pair<int,int>b){ //重写优先队列排列规则
return a.first>b.first;
}
};
void dijkstra(int x){ //起点
priority_queue<pair<int,int>,vector<pair<int,int>>,cmp>q; //堆优化
q.push({0,x});
ans[x]=0;
while(!q.empty()){
int top=q.top().second;
q.pop();
vis[top]=1;
for(int i=head[top];i!=-1;i=s[i].next){
if(!vis[s[i].to]&&ans[s[i].to]>ans[top]+s[i].w){
ans[s[i].to]=ans[top]+s[i].w;
q.push({ans[s[i].to],s[i].to});
}
}
}
}
int main(){
while(cin>>n>>m){
init();
while(m--){
int a,b,c;
cin>>a>>b>>c;
add_edge(a,b,c);
add_edge(b,a,c);
}
int st,ed;
cin>>st>>ed;
dijkstra(st);
if(ans[ed]==inf)cout<<-1<<endl;
else cout<<ans[ed]<<endl;
}
return 0;
}
HDU 1874 畅通工程续 (链式前向星+堆优化Dijkstra)
于 2021-09-07 19:46:21 首次发布