社区讨论
蒟蒻求助,堆优化Dijkstra,TLE3个点
P4779【模板】单源最短路径(标准版)参与者 6已保存回复 9
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 9 条
- 当前快照
- 1 份
- 快照标识符
- @lo2dc8fv
- 此快照首次捕获于
- 2023/10/23 11:59 2 年前
- 此快照最后确认于
- 2023/11/03 12:07 2 年前
rt,代码使用链式前向星存储,堆优化Dijkstra,但是仍然TLE3个点。提交记录。
CPP#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
#define INF 0x3f3f3f3f
#define N 100005
#define M 50*N
inline int read();
using namespace std;
int head[N], ver[M], edge[M], Next[M], n, m, tot;
void add(int x, int y, int z) {
ver[++tot] = y;
edge[tot] = z;
Next[tot] = head[x];
head[x] = tot;
}
priority_queue< pair<int, int> > Q;
bool vis[N];
int dist[N];
void dijkstra(int root) {
memset(dist, 0x3f, sizeof dist);
memset(vis, 0, sizeof vis);
dist[root] = 0;
Q.push(make_pair(0, root));
while(!Q.empty()) {
int x = Q.top().second;
vis[x] = 1;
Q.pop();
for(int i = head[x]; ~i; i = Next[i]) {
int t = ver[i];
if(dist[t] > dist[x] + edge[i]) {
dist[t] = dist[x] + edge[i];
Q.push(make_pair(-dist[t], t));
}
}
}
}
int main() {
memset(head, -1, sizeof(head));
tot = -1;
int n, m, s;
scanf("%d%d%d", &n, &m, &s);
int x, y, z;
for(int i = 1; i <= m; i++) {
scanf("%d%d%d", &x, &y, &z);
add(x, y, z);
}
dijkstra(s);
for(int i = 1; i <= n; i++) {
printf("%d ", dist[i]);
}
return 0;
}
inline int read() {
int x = 0, f = 1;
char ch;
ch = getchar();
while (ch > '9' || ch < '0') {
if (ch == '-')
f = -f;
ch = getchar();
}
while (ch <= '9' && ch >= '0') {
x = (x << 1) + (x << 3) + (ch & 15);
ch = getchar();
}
return x * f;
}
回复
共 9 条回复,欢迎继续交流。
正在加载回复...