BuringStraw

BuringStraw

Dijkstra's brand new notation

Dijkstra, well, it's about finding the shortest path from the unfixed points in the shortest path and fixing the point with the shortest known shortest path, and then updating the shortest path of the other points connected to this point. At the beginning, the shortest path from the source point to the source point is 0.
So, after reviewing Dijkstra, I found a few functions:

  • make_heap (first, last, comp): Turns an array into a heap
  • push_heap (first, last, comp): Makes the last number in the array float to the correct position in the heap
  • pop_heap (first, last, comp): Throws the head of the heap to the end of the array

So, simply encapsulate it as follows:

void push (int x) {
	heap[++hsize] = x;
	std::push_heap(heap + 1, heap + 1 + hsize, cmp1);
}
void pop (void) {
	std::pop_heap(heap + 1,heap + 1 + hsize--, cmp1);
}

The heap implemented using an array runs faster than Hong Kong reporters, I don't know how much faster it is than the priority queue implemented using vector.
As shown in the figure

The code for the template problem is as follows:

#include <cstdio>
#include <algorithm>

const int MAXM = 500000 + 5, MAXN = 100000 + 5, INF = 2147483647;

int n, m, s;

struct ed {
	int to, nex, w;
} e[MAXM];

int head[MAXN], dis[MAXN], hsize;
bool v[MAXN];
int newp;

struct node {
	int id, v;
} heap[MAXN];

void insert (int p1, int p2, int w) {
	++newp;
	e[newp].to = p2;
	e[newp].w = w;
	e[newp].nex = head[p1];
	head[p1] = newp;
}

bool cmp1 (node x, node y) {
	return x.v > y.v;
}

void push (node x) {
	heap[++hsize] = x;
	std::push_heap(heap + 1, heap + 1 + hsize, cmp1);
}

void pop (void) {
	std::pop_heap(heap + 1,heap + 1 + hsize--, cmp1);
}

void dij (int s) {
	for (int i = 1; i <= n; ++i) {
		dis[i] = INF;
		v[i] = 0;
	}
	dis[s] = 0;
	hsize = 0;
	push((node){s, 0});
	
	while (hsize) {
		node u = heap[1];
		pop();
		if (v[u.id]) continue;//Fixed point
		v[u.id] = 1;
		for (int i = head[u.id]; i; i = e[i].nex) {
			int y = e[i].to;
			if (dis[y] > u.v + e[i].w) {
				dis[y] = u.v + e[i].w;
				push((node){y, dis[y]});
			}
		}
	}
}

int main (void) {
	scanf("%d%d%d", &n, &m, &s);
	
	for (int i = 1; i <= n; ++i) {
		head[i] = 0;
		heap[i] = (node){0, 0};
	}
	
	for (int i = 1; i <= m; ++i) {
		e[i] = (ed){0, 0, 0};
	}
	
	{
		int p1, p2, w;
		for (int i = 1; i <= m; ++i) {
			scanf("%d%d%d", &p1, &p2, &w);
			insert(p1, p2, w);
		}
	}
	
	dij(s);
	
	for (int i = 1; i <= n; ++i) {
		printf("%d ", dis[i]);
	}
	putchar('\n');
	
	return 0;
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.