Advertisement
Guest User

Rudnick

a guest
Dec 18th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <utility>
  4. #include <queue>
  5. #include <set>
  6. #include <map>
  7. #include <algorithm>
  8.  
  9. using namespace std;
  10.  
  11. using LL = long long;
  12.  
  13. vector < vector < int > > gr;
  14. vector < int > pr;
  15. vector < map < int, int > > weight;
  16.  
  17. const LL ADD = 1e16;
  18. int n;
  19.  
  20. LL dfs(int v, int p) {
  21.     LL ans = 0;
  22.     if (v == n - 1) {
  23.         ans += ADD;
  24.     }
  25.     pr[v] = p;
  26.     if (p != -1) {
  27.         ans += weight[v][p];
  28.         ans += weight[p][v];
  29.     }
  30.     for (auto to: gr[v]) {
  31.         if (to == p) {
  32.             continue;
  33.         }
  34.         LL res = dfs(to, v);
  35.         if (res > 0) {
  36.             ans += res;
  37.         }
  38.     }
  39.     return ans;
  40. }
  41.  
  42. int main() {
  43.     cin.tie(nullptr);
  44.     std::ios_base::sync_with_stdio(false);
  45.     cout.setf(std::ios_base::fixed);
  46.     cout.precision(24);
  47.     // freopen("input.txt", "r+", stdin);
  48.     cin >> n;
  49.     weight.resize(n);
  50.     pr.resize(n, -1);
  51.     gr.resize(n);
  52.     for (int i = 0; i < n - 1; ++i) {
  53.         int from, to;
  54.         cin >> from >> to;
  55.         from--; to--;
  56.         int pw, qw;
  57.         cin >> pw >> qw;
  58.         weight[from][to] = pw;
  59.         weight[to][from] = qw;
  60.         gr[from].push_back(to);
  61.         gr[to].push_back(from);
  62.     }
  63.     LL ans = dfs(0, -1);
  64.     int v = n - 1;
  65.     while (pr[v] != -1) {
  66.         int from = pr[v];
  67.         ans -= weight[v][from];
  68.         v = from;
  69.     }
  70.     cout << ans - ADD;
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement