Dijkstra's shortest path

Last knock the shortest distance has been nearly a year now.
Now and then knock, keep drawing mode also from the adjacent matrix, adjacency list into a better star forward chain. How time flies detained.

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;

const int maxn = 1e5 + 10;
const int inf = 1e9 + 7;
int head[maxn], d[maxn];
bool vis[maxn];
int n, m, cnt;
struct node{
	int v, nex, len;
}edge[maxn];

void addedge(int u, int v, int len)
{
	edge[cnt].v = v;
	edge[cnt].nex = head[u];
	edge[cnt].len = len;
	head[u] = cnt++;
}

void dijkstra(int s)
{
	fill(d, d + maxn, inf);
	d[s] = 0;
	for(int i = 1; i <= n; i++) {
		int u = -1, MIN = inf;
		for(int j = 1; j <= n; j++) {
			if(vis[j] == false && d[j] < MIN) {
				u = j;
				MIN = d[j];
			}
		}
		vis[u] = true;
		for(int j = head[u]; j != -1; j = edge[j].nex) {
			int v = edge[j].v;
			if(vis[v] == false && d[u] + edge[j].len < d[v]) {
				d[v] = d[u] + edge[j].len;
			}
		}
	}
}

void init()
{
	memset(head, -1, sizeof(head));
}

int main()
{
	ios::sync_with_stdio(false);
	init();
	int s, t;
	cin >> n >> m >> s >> t;
	int x, y, z;
	for(int i = 1; i <= m; i++) {
		cin >> x >> y >> z;
		addedge(x, y, z);
		addedge(y, x, z);
	}
	dijkstra(s);
	cout << d[t] << endl;
	return 0;
}
Published 73 original articles · won praise 15 · views 8091

Guess you like

Origin blog.csdn.net/ln2037/article/details/103497203