最短路模板

Dijkstra:

#include<bits/stdc++.h>
using namespace std;
const int inf = 2147483647;
priority_queue <pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > >q;
int n,m,s,u,v,w;
long long z[1000001],qz[1000001],cnt,d[10000001],next[10000001],f[10000001];
bool visited[1000001];
void add(int a,int b,int c){
	cnt++;
	z[cnt] = b;
	qz[cnt] = c;
	next[cnt] = f[a];
	f[a] = cnt;
}
int main(){
	cin >> n >> m >> s;
	for(int i = 1;i <= m;i++){
		cin >> u >> v >> w;
		add(u,v,w);
	}
	for(int i = 1;i <= n;i++){
		d[i] = inf;
	}
	d[s] = 0;
	q.push(make_pair(0,s));
	while(q.size()){
		int x = q.top().second;
		q.pop();
		if(visited[x]){
			continue;
		}
		visited[x] = 1;
		for(int i = f[x];i;i = next[i]){
			if(d[z[i]] > d[x] + qz[i]){
				d[z[i]] = d[x] + qz[i];
				q.push(make_pair(d[z[i]],z[i]));
			}
		}
	}
	for(int i = 1;i <= n;i++){
		cout << d[i] << " ";
	}
	return 0;
}

SPFA:

#include <bits/stdc++.h>
using namespace std;
int n,m;
const int inf = 0x7fffffff;
int zx,ev;
struct abc{
	int next,ww,vv;
}e[100001];
int cnt,f[1000001],d[1000001];
int visited[10000001];
void add(int a,int b,int c){
	cnt++;
	e[cnt].vv = b;
	e[cnt].ww = c;
	e[cnt].next = f[a];
	f[a] = cnt;
	return ;
}
void spfa(int s){
	for(int i = 1;i <= n;i++){
		d[i] = inf;
		visited[i] = 1;
	}
	d[s] = 0;
	queue <int> q;
	q.push(s);
	visited[s] = 0;
	while(!q.empty()){
		zx = q.front();
		q.pop();
		visited[zx] = 1;
		for(int i = f[zx];i;i = e[i].next){
			ev = e[i].vv;
			if(d[zx] + e[i].ww < d[ev]){
				d[ev] = d[zx] + e[i].ww;
				if(visited[ev]){
					q.push(ev);
					visited[ev] = 0;
				}
			}
		}
	}
}
int main() {
	cin >> n >> m;
	for(int i = 1;i <= m;i++){
		int u,v;
		cin >> u >> v;
		add(u,v,1);
		add(v,u,1);
	}
	spfa(1);
	int maxn = -999999999;
	int maxx;
	int maxa;
	for(int i = 1;i <= n;i++){
		if(maxn == d[i]){
			maxa++;
		}
		if(maxn < d[i]){
			maxn = d[i];
			maxx = i;
			maxa = 1;
		}
	}
	cout << maxx << " " << maxn << " " << maxa;
	return 0;
}
上一篇:Leetcode---3.BFS篇


下一篇:407. 接雨水 II