算法
堆优化的dijkstra算法
这题用小根堆进行优化, 但是注意堆里面放的pair的话有限从第一个first进行排序,所以为了保证每次从堆中的点出来的距离最近第一个位置必须为距离,一定不要为点。~~~~~~
时间复杂度
参考文献
C++ 代码
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 1e5 + 10;
int h[N], e[N], ne[N], w[N], idx, d[N];
bool st[N];
void add(int a, int b, int c)
{
e[++ idx] = b;
ne[idx] = h[a];
h[a] = idx;
w[idx] = c;
}
int n, m;
int dijkstra()
{
priority_queue<PII, vector<PII>, greater<PII>> q;
memset(d, 0x3f, sizeof d);
d[1] = 0;
q.push({0, 1});
while(q.size())
{
auto t = q.top();
q.pop();
int distance = t.x, point = t.y;
if(st[point])continue;
st[point] = true;
for(int i = h[point]; ~i; i = ne[i])
{
int j = e[i];
if(d[j] > distance + w[i])
{
d[j] = distance + w[i];
q.push({d[j], j});
}
}
}
if(d[n] == 0x3f3f3f3f)return -1;
return d[n];
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m;
for(int i = 0; i < m; i ++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
cout << dijkstra() << endl;
return 0;
}