//堆优化版
#include <bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
#define fi first
#define se second
#define endl '\n'
#define IOS std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
const int N = 5e5 + 10;
int h[N], ne[N], e[N], w[N], bj[N], dis[N], idx;
int n,m;
void add(int a, int b, int c)
{
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx ++;
}
struct node
{
friend bool operator < (node a, node b)
{
return a.cost > b.cost; //记得>是小顶堆,<是大顶堆
}
int to;
int cost;
};
bool dji()
{
priority_queue<node> Q;
node head;
head.cost = 0;
head.to = 1;
dis[1] = 0;
Q.push(head);
while(Q.size())
{
node now = Q.top();
Q.pop();
if(bj[now.to]) continue;
bj[now.to] = 1;
for(int j = h[now.to]; ~j; j = ne[j]) //遍历所有从now.to出发的边
{
int x = e[j];
if(dis[x] > now.cost + w[j]) //松弛
{
node next;
dis[x] = now.cost + w[j];
next.cost = dis[x];
next.to = x;
Q.push(next);
}
}
}
return dis[n] == inf;
}
int main()
{
memset(h, -1, sizeof h); //初始化
memset(dis, inf, sizeof dis);
cin >> n >> m;
while(m --)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
add(b, a, c);
}
if(dji())
cout << "qwb baka" << endl;
else
cout << dis[n];
return 0;
}
稀疏图的Djikstra(堆优化 通用)
最新推荐文章于 2022-09-27 16:27:53 发布