Algo-Trian
This commit is contained in:
48
Algorithm/Graph/Bellman-Ford有负边的最短路径.cpp
Normal file
48
Algorithm/Graph/Bellman-Ford有负边的最短路径.cpp
Normal file
@@ -0,0 +1,48 @@
|
||||
#include <iostream>
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
#include <climits>
|
||||
using namespace std;
|
||||
const int INF = INT_MAX >> 1;
|
||||
int main(){
|
||||
int n, edge_num, start;
|
||||
cin >> n >> edge_num >> start;
|
||||
|
||||
//<2F><><EFBFBD><EFBFBD>Ҫadj, <20><>Ҫdp <20><> edges
|
||||
vector<tuple<int, int , int>> edges(edge_num);// p1, p2, w
|
||||
vector<int> dp(n, INF);
|
||||
dp[start] = 0;
|
||||
|
||||
//<2F><><EFBFBD><EFBFBD>
|
||||
for(int i = 0; i < edge_num; i++){
|
||||
int a, b, w;
|
||||
cin >> a >> b >> w;
|
||||
edges[i] = {a, b, w};
|
||||
}
|
||||
|
||||
//<2F>Ƚ<EFBFBD><C8BD><EFBFBD>n - 1<><31><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
for(int i = 0; i < n - 1; i++){
|
||||
for(auto [p1, p2, w] : edges){
|
||||
if(dp[p2] > dp[p1] + w){
|
||||
dp[p2] = dp[p1] + w;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//<2F>Ƿ<EFBFBD><C7B7>и<EFBFBD><D0B8><EFBFBD>
|
||||
bool negcc = false;
|
||||
for(auto [p1, p2, w] : edges){
|
||||
if(dp[p2] > dp[p1] + w){
|
||||
negcc = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if(negcc) cout << "Negative Circle Detected" << endl;
|
||||
else{
|
||||
for(auto x : dp){
|
||||
cout << x << " ";
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user