原题地址
P3371 【模板】单源最短路径(标准版)
注意的点:
- 边有重复,选择最小边!
- 对于SPFA算法容易出现重大BUG,没有负权值的边时不要使用!!!
70分代码 朴素板dijsktra
- 爆空间
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int n, m, s, u, v, w;
void solve() {cin >> n >> m >> s;vector<vector<int>>grid(n + 9, vector<int>(n + 9, INT_MAX));vector<int>dist(n + 9, INT_MAX);vector<bool>visited(n + 9, false);while (m--) {cin >> u >> v >> w;grid[u][v] = min(grid[u][v], w);}dist[s] = 0;for (int i = 1; i <= n; i++) {int cur = 1;int minDist = INT_MAX;for (int j = 1; j <= n; j++) {if (!visited[j] && dist[j] < minDist) {minDist = dist[j];cur = j;}}visited[cur] = true;for (int j = 1; j <= n; j++) {if (!visited[j] && grid[cur][j] != INT_MAX && dist[cur] + grid[cur][j] < dist[j]) {dist[j] = dist[cur] + grid[cur][j];}}/*cout << "select " << cur << endl;for (int i = 1; i <= n; i++) {cout << dist[i] << " ";}cout << endl;*/}for (int i = 1; i <= n; i++) {cout << dist[i] << " ";}
}
int main() {std::ios::sync_with_stdio(false);std::cin.tie(0); std::cout.tie(0);solve();return 0;
}
32分代码 BPFS
- 因为有重复指向的边,所有理论上边数可以无穷大,O(KM)的时间复杂度不确定性极大!
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int n, m, s, u, v, w;
struct Edge {int v, w;Edge(int a, int b) :v(a), w(b) {}
};
void solve() {cin >> n >> m >> s;vector<list<Edge>>grid(n + 9, list<Edge>());vector<int>dist(n + 9, INT_MAX); dist[s] = 0;queue<Edge>q;while (m--) {cin >> u >> v >> w;grid[u].push_back(Edge(v, w));}q.push({ s,0 });while (!q.empty()) {Edge cur = q.front();q.pop();for (auto item : grid[cur.v]) {if (item.w + dist[cur.v] < dist[item.v]) {dist[item.v] = dist[cur.v] + item.w;q.push(item);}}}for (int i = 1; i <= n; i++) {cout << dist[i] << " ";}
}
int main() {std::ios::sync_with_stdio(false);std::cin.tie(0); std::cout.tie(0);solve();return 0;
}
AC代码 堆优化dijsktra
- 重复的边不影响
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int n, m, s, u, v, w;
struct Edge {int v, w;Edge(int a, int b) :v(a), w(b) {}
};
class cmp {
public:bool operator()(const Edge& a, const Edge& b) {return a.w > b.w;//从小排序}
};void solve() {cin >> n >> m >> s;vector<list<Edge>>grid(n + 9, list<Edge>());vector<int>dist(n + 9, INT_MAX); dist[s] = 0;vector<bool>visited(n + 9, false);priority_queue<Edge, vector<Edge>, cmp>q;while (m--) {cin >> u >> v >> w;grid[u].push_back(Edge(v, w));}q.push({ s,0 });while (!q.empty()) {Edge cur = q.top();q.pop();if (visited[cur.v]) {continue;}visited[cur.v] = true;for (auto item : grid[cur.v]) {if (!visited[item.v]&&item.w + dist[cur.v] < dist[item.v]) {dist[item.v] = item.w + dist[cur.v];q.push({ item.v,dist[item.v] });}}}for (int i = 1; i <= n; i++) {cout << dist[i] << " ";}
}
int main() {std::ios::sync_with_stdio(false);std::cin.tie(0); std::cout.tie(0);solve();return 0;
}