洛谷 #3020. 包快递Package Delivery

版权声明:转载请注明出处 https://blog.csdn.net/qq_41593522/article/details/84196514

题意

最短路

题解

SPFA

调试记录

#include <cstdio>
#include <cstring>
#include <queue>
#define maxn 50005

using namespace std;

struct node{
	int to, next, l;
}e[maxn << 1];
int head[maxn], tot = 0;
void addedge(int u, int v, int l){
	e[++tot].to = v, e[tot].next = head[u], e[tot].l = l;
	head[u] = tot;
}

int dis[maxn];
bool inq[maxn];
void SPFA(){
	memset(dis, 0x3f, sizeof dis);
	dis[1] = 0;
	queue <int> q; while (!q.empty()) q.pop();
	q.push(1);
	inq[1] = true;
	
	while (!q.empty()){
		int cur = q.front(); inq[cur] = false; q.pop();
		
		for (int i = head[cur]; i; i = e[i].next){
			if (dis[e[i].to] > dis[cur] + e[i].l){
				dis[e[i].to] = dis[cur] + e[i].l;
				if (!inq[e[i].to]){
					q.push(e[i].to);
					inq[e[i].to] = true;
				}
			}
		}
	}
}

int n, m;
int main(){
	scanf("%d%d", &n, &m);
	
	for (int u, v, l, i = 1; i <= m; i++){
		scanf("%d%d%d", &u, &v, &l);
		addedge(u, v, l);
		addedge(v, u, l);
	}
	
	SPFA();
	printf("%d\n", dis[n]);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41593522/article/details/84196514