5 条题解
-
1
链式前向星:
#include <iostream> #include <algorithm> #include <queue> #include <vector> #include <cstring> #define MAXN (100010) #define MAXM (200010) using namespace std; typedef long long LL; int n, m, s; int head[MAXN], E_cnt; struct Edge { LL w; int v, next; } E[MAXM]; void Addedge(int u, int v, LL w) { int p = ++ E_cnt; E[p].v = v; E[p].w = w; E[p].next = head[u]; head[u] = p; } struct Node { int ind; LL dis; bool operator < (const Node& A) const { return dis > A.dis; } }; LL dis[MAXN]; void Dijkstra() { memset(dis, 0x3f, sizeof dis); priority_queue<Node> PQ; dis[1] = 0; PQ.push({1, 0}); while (!PQ.empty()) { int u = PQ.top().ind; LL disu = PQ.top().dis; PQ.pop(); if (disu > dis[u]) continue; for (int i = head[u]; i; i = E[i].next) { int v = E[i].v; LL w = E[i].w; if (disu + w < dis[v]) { dis[v] = disu + w; PQ.push({v, dis[v]}); } } } } int main() { cin.tie(0)->sync_with_stdio(0); cin >> n >> m >> s; for (int i = 1; i <= m; i++) { int u, v; LL w; cin >> u >> v >>w; Addedge(u, v, w); } Dijkstra(); for (int i = 1; i <= n; i++) cout << dis[i] << " "; return 0; }vector:
#include <iostream> #include <algorithm> #include <queue> #include <vector> #include <cstring> #define MAXN (100010) #define MAXM (200010) using namespace std; typedef long long LL; int n, m, s; vector<pair<LL, int> > E[MAXN]; LL dis[MAXN]; void Dijkstra() { memset(dis, 0x3f, sizeof dis); priority_queue<pair<LL, int> > PQ; dis[s] = 0; PQ.push({0, s}); while (!PQ.empty()) { int u = PQ.top().second; LL disu = PQ.top().first; PQ.pop(); if (disu > dis[u]) continue; for (auto v : E[u]) { if (disu + v.first < dis[v.second]) { dis[v.second] = disu + v.first; PQ.push({dis[v.second], v.second}); } } } } int main() { cin.tie(0)->sync_with_stdio(0); cin >> n >> m >> s; for (int i = 1; i <= m; i++) { int u, v; LL w; cin >> u >> v >>w; E[u].push_back({w, v}); } Dijkstra(); for (int i = 1; i <= n; i++) cout << dis[i] << " "; return 0; }
信息
- ID
- 223
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 7
- 标签
- (无)
- 递交数
- 346
- 已通过
- 75
- 上传者