#include <iostream> #include <vector> #include <cstring> #include <cmath> using namespace std; const double eps = 1e-6; const int INF = 0x3f3f3f3f; struct Edge { int from, to; double rate, commission; }; vector<Edge> edges; double dis[105]; int n, m, s; double v; bool bellman_ford() { memset(dis, 0, sizeof(dis)); dis[s] = v; for (int i = 1; i <= n; i++) { for (int j = 0; j < edges.size(); j++) { Edge e = edges[j]; if (dis[e.from] > eps && dis[e.from] * e.rate - e.commission > dis[e.to]) { dis[e.to] = dis[e.from] * e.rate - e.commission; if (i == n) return true; } } } return false; } int main() { cin >> n >> m >> s >> v; for (int i = 1; i <= m; i++) { int a, b; double rab, cab, rba, cba; cin >> a >> b >> rab >> cab >> rba >> cba; edges.push_back({a, b, rab, cab}); edges.push_back({b, a, rba, cba}); } if (bellman_ford()) { cout << "YES" << endl; } else { cout << "NO" << endl; } //system("pause"); return 0; }修改这段代码
时间: 2024-02-16 12:27:17 浏览: 188
#include_iostream.h_
4星 · 用户满意度95%
这段代码可能存在的问题是在处理浮点数比较时使用了eps常量,但是在Bellman-Ford算法中,当存在负权环时,dis数组会被更新无限次,eps可能会导致算法提前退出。另外,这段代码中将dis数组初始化为0,但是对于起始点s应该将其初始化为v。
以下是修改后的代码:
```
#include <iostream>
#include <vector>
#include <cstring>
#include <cmath>
using namespace std;
const double eps = 1e-8;
const int INF = 0x3f3f3f3f;
struct Edge {
int from, to;
double rate, commission;
};
vector<Edge> edges;
double dis[105];
int n, m, s;
double v;
bool bellman_ford() {
memset(dis, -1, sizeof(dis));
dis[s] = v;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < edges.size(); j++) {
Edge e = edges[j];
if (dis[e.from] > eps && (dis[e.from] - e.commission) * e.rate > dis[e.to] + eps) {
dis[e.to] = (dis[e.from] - e.commission) * e.rate;
if (i == n) return true;
}
}
}
return false;
}
int main() {
cin >> n >> m >> s >> v;
for (int i = 1; i <= m; i++) {
int a, b;
double rab, cab, rba, cba;
cin >> a >> b >> rab >> cab >> rba >> cba;
edges.push_back({a, b, rab, cab});
edges.push_back({b, a, rba, cba});
}
if (bellman_ford()) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
return 0;
}
```
修改后的代码将dis数组初始化为-1,并且在更新dis数组时使用eps进行浮点数比较。同时,在计算dis[e.to]时先减去手续费再乘以汇率,避免精度问题。
阅读全文