洛谷4779 Dijkstra+堆优化

#include<bits/stdc++.h>
#define LL long long
#define GG long long 
#define For(i, j, k) for(int i=j; i<=k; i++)
#define Dow(i, j, k) for(int i=j; i>=k; i--)
using namespace std;
inline GG read() { 
    GG 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-48; ch = getchar(); }
    return x * f;
}
inline void write(GG x) {
    if(x<0) putchar('-'), x = -x;
    if(x>9) write(x/10);
    putchar(x%10+48);
}
inline void writeln(GG x) {
    write(x); puts("");
}

const int N = 100011,M = 200011;  
const LL INF = 1e16; 

int n, m, S, nedge; 
int head[N], vis[N]; 
LL dist[N]; 
struct edge{
	int to, pre, val; 
}e[M];
struct node{
	int id; 
	LL val; 
	friend bool operator <(node a, node b) {
		return a.val > b.val; 
	}
};
priority_queue<node> Q; 

inline void add(int x, int y, int v) {
	e[++nedge].to = y; 
	e[nedge].pre = head[x]; 
	e[nedge].val = v; 
	head[x] = nedge; 
}

inline void Dijkstra(int S) {
	For(i, 0, n) dist[i] = INF; 
	For(i, 0, n) vis[i] = 0; 
	dist[S] = 0; 
	Q.push((node){ S, 0}); 
	while(!Q.empty()) {
		node p = Q.top(); Q.pop(); 
		int u = p.id; 
		if(vis[u]) continue; 
		vis[u] = 1; 
		for(int i=head[u]; i; i=e[i].pre) {
			int v = e[i].to; 
			if(dist[u]+e[i].val < dist[v]) {
				dist[v] = dist[u]+e[i].val;
				Q.push((node){ v, dist[v]}); 
			}
		} 
	}
}

int main() {
	n = read(); m = read(); S = read(); 
	For(i, 1, m) {
		int x = read(), y = read(), v = read(); 
		add(x, y, v); 
	}
	Dijkstra(S); 
	For(i, 1, n) 
		if(dist[i]!=INF) write(dist[i]), putchar(' '); 
		else printf("2147483647 "); 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值