1
0

POJ-3169.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <limits>
  4. #include <vector>
  5. using namespace std;
  6. struct Edge { int from, to; long long weight; };
  7. int main() {
  8. ios::sync_with_stdio(false);
  9. cin.tie(nullptr);
  10. int n, like_count, dislike_count;
  11. cin >> n >> like_count >> dislike_count;
  12. vector<Edge> edges;
  13. for (int i = 0; i + 1 < n; ++i) edges.push_back({i + 1, i, 0});
  14. while (like_count--) {
  15. int a, b; long long d; cin >> a >> b >> d; --a; --b;
  16. edges.push_back({a, b, d});
  17. }
  18. while (dislike_count--) {
  19. int a, b; long long d; cin >> a >> b >> d; --a; --b;
  20. edges.push_back({b, a, -d});
  21. }
  22. vector<long long> all(n, 0);
  23. for (int iteration = 0; iteration < n; ++iteration) {
  24. bool changed = false;
  25. for (Edge e : edges) if (all[e.to] > all[e.from] + e.weight) {
  26. all[e.to] = all[e.from] + e.weight; changed = true;
  27. }
  28. if (!changed) break;
  29. if (iteration == n - 1) { cout << "-1\n"; return 0; }
  30. }
  31. const long long inf = numeric_limits<long long>::max() / 4;
  32. vector<long long> dist(n, inf); dist[0] = 0;
  33. for (int iteration = 0; iteration + 1 < n; ++iteration) {
  34. bool changed = false;
  35. for (Edge e : edges) if (dist[e.from] != inf &&
  36. dist[e.to] > dist[e.from] + e.weight) {
  37. dist[e.to] = dist[e.from] + e.weight; changed = true;
  38. }
  39. if (!changed) break;
  40. }
  41. cout << (dist[n - 1] == inf ? -2 : dist[n - 1]) << '\n';
  42. }