单源最短路迪杰斯特拉算法

#include 
#include 
#include 
using namespace std;
static const int N = 1005;
static const int M = 5010;
static const int inf = 0x3f3f3f3f;

struct edge {
	int v, w, next;
	edge() {}
	edge(int _v, int _w, int _next) {
		v = _v;
		w = _w;
		next = _next;
	}
} e[M<<1];
int head[N], eid;
void init() {
	memset(head, -1, sizeof(head));
	eid = 0;
}
void insert1(int u, int v, int w) {
	e[eid] = edge(v, w, head[u]);
	head[u] = eid++;
}
void insert2(int u, int v, int w) {
	insert1(u, v, w);
	insert1(v, u, w);
}
int n, m;
int dis[N];
bool vis[N];
// struct node{
//     int u, dist;
//     node(int u, int dis):u()
// }
void dij(int u) {
	memset(dis, 0x3f, sizeof(dis));
	memset(vis, false, sizeof(vis));
	dis[u] = 0;
	for(int i = 0; i < n; i++) {
		int minval = inf;
		for(int j = 1; j <= n; j++) {
			if(!vis[j] && dis[j] < minval) {
				minval = dis[u = j];
			}
		}
		if(minval == inf) {
			return;
		}
		vis[u] = true;
		for(int j = head[u]; ~j; j = e[j].next) {
			int v = e[j].v;
			int w = e[j].w;
			**if(!vis[v] && dis[v] > dis[u] + w) {** //注意这里是对u可到达的v点进行膨胀操作
				dis[v] = dis[u] + w;
			}
		}
	}
}
int main() {
	init();
	cin>> n>> m;
	int a, b, c;
	while(m--) {
		cin>>a>>b>>c;
		insert2(a, b, c);
	}
	dij(1);
	cout<<dis[n];
	return 0;
}

你可能感兴趣的:(竞赛题思路)