跳到正文

个人记录

Dij 迪杰斯特拉

AC_Seed约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1
C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxn=1e5+5;
struct node{
	int id;
	int dis;
};
vector<node>a[maxn];
bool operator < (node a,node b){
	return a.dis>b.dis;
}
priority_queue<node>q;
bool b[maxn];
int n,m,s,w[maxn];
inline int read() {
    int x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = x * 10 + (ch - '0');
        ch = getchar();
    }
    return x * f;
}

inline void write(int x) {
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if (x > 9) write(x / 10);
    putchar(x % 10 + '0');
}
void bfs(){
	q.push({s,0});
	while(!q.empty()){
		node x=q.top();
		q.pop();
		if(b[x.id]){
			continue;
		}
		b[x.id]=true;
	    w[x.id]=x.dis;
	    for(int i=0;i<a[x.id].size();i++){
	    	if(b[a[x.id][i].id]) continue;
	    	q.push({a[x.id][i].id,x.dis+a[x.id][i].dis});
		}
	}
}
signed main(){
	int u,v,d;
	n=read(),m=read(),s=read();
	for(int i=1;i<=m;i++){
		u=read(),v=read(),d=read();
		a[u].push_back({v,d});
	}
	bfs();
	for(int i=1;i<=n;i++){
		write(w[i]);
		printf(" ");
	}
	return 0;
}
原文