题面链接
https://www.acwing.com/problem/content/description/852/
思路
和朴素版的Dijkstra类似,只不过我们对边的存储进行堆优化,优先将短的边先更新(基于贪心策略)
代码
#include<bits/stdc++.h>
using namespace std;
//----------------自定义部分----------------
#define ll long long
#define mod 1000000007
#define endl "\n"
#define PII pair<int,int>
#define INF 0x3f3f3f3f
int dx[4]={0,-1,0,1},dy[4]={-1,0,1,0};
ll ksm(ll a,ll b) {
ll ans = 1;
for(;b;b>>=1LL) {
if(b & 1) ans = ans * a % mod;
a = a * a % mod;
}
return ans;
}
ll lowbit(ll x){return -x & x;}
const int N = 2e6+10;
//----------------自定义部分----------------
int n,m,q;
vector<PII> E[N];
int dis[N];
bool vis[N];
void slove(){
memset(dis,INF,sizeof dis);
dis[1] = 0;
priority_queue<PII,vector<PII>,greater<PII> >que;
que.push({0,1});
while(!que.empty()){
PII t = que.top();
que.pop();
int p = t.second;
if(vis[p]) continue;
vis[p] = true;
for(int i = 0,l = E[p].size(); i < l; ++i){
int j = E[p][i].first,k = E[p][i].second;
if(dis[j] > dis[p] + k){
dis[j] = dis[p] + k;
que.push({dis[j],j});
}
}
}
if(dis[n] == INF)
cout<<-1<<endl;
else cout<<dis[n]<<endl;
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
cin>>n>>m;
int u,v,w;
for(int i = 0;i < m; ++i) {
cin>>u>>v>>w;
E[u].push_back({v,w});
}
slove();
return 0;
}