题目链接 AcWing 850
这里的add函数里面的意义不是很明确,请问是我注释写的这个意思吗
这个链表感觉跟之前的写的单链表不太一样
#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 1e6 + 10;
int n, m;
int h[N], w[N], e[N], ne[N], idx;
int dist[N];
bool st[N];
void add(int a, int b, int c)
{
//e[idx]存储第idx个加入的节点,w存储对应权重
//h[a]存储节点a指向的节点编号,如1->0(对应2),但会覆盖,比如后面又有1->2(对应3),即表示最新的指向的节点。
//ne[idx]存储第a节点指向的其他节点,按输入顺序,逆向回溯。
//比如1->2,1->3,用h[1]取出节点3,ne[3]取出节点2(节点1一开始指向的节点)
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
int dijkstra()
{
memset(dist, 0x3f ,sizeof dist);
dist[1] = 0;
//默认是最大堆,改成最小堆
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, 1});
while(heap.size())
{
auto t = heap.top();
heap.pop();
int ver = t.second, distance = t.first;
if(st[ver]) continue;
st[ver] = true;
for(int i = h[ver]; i != -1; i = ne[i])
{
int j = e[i];
if(dist[j] > dist[ver] + w[i])
{
dist[j] = dist[ver] + w[i];
heap.push({dist[j], j});
}
}
}
if(dist[n] == 0x3f3f3f3f) return -1;
return dist[n];
}
int main()
{
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while(m--)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
printf("%d", dijkstra());
return 0;
}
感谢各位解答!
提问于6天前
246