社区讨论
求助全源最短路
P5905【模板】全源最短路(Johnson)参与者 2已保存回复 3
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 3 条
- 当前快照
- 1 份
- 快照标识符
- @lo18l9bo
- 此快照首次捕获于
- 2023/10/22 16:58 2 年前
- 此快照最后确认于
- 2023/11/02 16:48 2 年前
样例1的输出第一行不正确,代码中有调试代码,可以看到结点1出发的最短路不正确。
CPP#include <bits/stdc++.h>
#define pii pair<int, int>
using namespace std;
const int MAXN = 3e3 + 5;
int n, m, u, v, w, h[MAXN], cnt[MAXN], dist[MAXN];
vector<pii> graph[MAXN];
bool visited[MAXN];
bool SPFA(){
fill(h, h + MAXN, 1e9);
queue<int> q;
q.push(0);
h[0] = 0, cnt[0] = 1;
while(!q.empty()){
auto nownode = q.front();
q.pop();
if(cnt[nownode] > n) return false;
for(auto i : graph[nownode]){
int e = i.first, w = i.second;
if(h[e] > h[nownode] + w){
h[e] = h[nownode] + w;
q.push(e);
cnt[e] ++;
}
}
}
return true;
}
void dijkstra(int st){
fill(dist, dist + MAXN, 1e9);
memset(visited, 0, sizeof(visited));
dist[st] = 0;
priority_queue<pii, vector<pii>, greater<pii>> pq;
pq.push({0, st});
while(!pq.empty()){
auto nownode = pq.top();
pq.pop();
if(visited[nownode.second]) continue;
visited[nownode.second] = true;
for(auto nextnode : graph[nownode.second]){
if(visited[nextnode.first]) continue;
if(dist[nownode.second] + nextnode.second < dist[nextnode.first]){
dist[nextnode.first] = dist[nownode.second] + nextnode.second;
pq.push({dist[nextnode.first], nextnode.first});
}
}
}
}
int main(){
cin >> n >> m;
for(int i = 1; i <= m; i ++){
cin >> u >> v >> w;
graph[u].push_back({v, w});
}
for(int i = 1; i <= n; i ++) graph[0].push_back({i, 0});
if(SPFA() == false){
cout << -1 << endl;
return 0;
}
for(int i = 1; i <= n; i ++){
for(auto node : graph[i]){
node.second = node.second + h[i] - h[node.first];
}
}
for(int i = 1; i <= n; i ++){
dijkstra(i);
int sum = 0;
for(int j = 1; j <= n; j ++){
sum += j * dist[j];
}
cout << sum << endl;
// for(int j = 1; j <= n; j ++){
// cout << dist[j] << " ";
// }
// cout << endl;
}
// for(int i = 1; i <= n; i ++) cout << h[i] << " ";
// cout << endl;
return 0;
}
回复
共 3 条回复,欢迎继续交流。
正在加载回复...