優先隊列優化dij算法


之前已經弄過模板了,但那個復雜一點,這個就是裸的dij,用起來更方便

輸入格式:n,m,s,d分別是點數,邊數,起點,終點

之后m行,輸入x,y,z分別是兩點即權值

題目鏈接:https://www.luogu.org/problemnew/show/P1339

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int inf=1<<30;
 4 typedef long long ll;
 5 typedef pair<int,int> P;
 6 const double pi=acos(-1);
 7 const int mod=1e8+7;
 8 const int maxn=2600;
 9 const int maxm=6300;
10 int dis[maxn];
11 struct edge{
12     int to,cost;
13 };
14 vector<edge> g[maxm];
15 void dij(int s){
16     priority_queue<P,vector<P>,greater<P> > que;
17     fill(dis,dis+maxn,inf);
18     dis[s]=0;
19     que.push({0,s});
20     while(!que.empty()){
21         P p=que.top();que.pop();
22         int v=p.second;
23         if(dis[v]<p.first) continue;
24         for(int i=0;i<g[v].size();i++){
25             edge e=g[v][i];
26             if(dis[e.to]>dis[v]+e.cost){
27                 dis[e.to]=dis[v]+e.cost;
28                 que.push({dis[e.to],e.to});
29             }
30         }
31     }
32 }
33 int main(){
34     int x,y,z,n,m,s,d;scanf("%d%d%d%d",&n,&m,&s,&d);
35     for(int i=0;i<m;i++){
36         scanf("%d%d%d",&x,&y,&z);
37         g[x].push_back({y,z});
38         g[y].push_back({x,z});
39     }
40     dij(s);
41     cout<<dis[d]<<endl;
42     return 0;
43 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM