Submission #1304357

#TimeUsernameProblemLanguageResultExecution timeMemory
1304357KietJTwo Currencies (JOI23_currencies)C++17
10 / 100
5096 ms53904 KiB
#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define pii pair<int,int>
#define fi first
#define se second

const int N = 1e6 + 5;

int n, m, q;
vector<pii> g[N];
vector<int> c[N];

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  
  cin >> n >> m >> q;
  
  for (int i = 1; i <= n - 1; i++) {
    int u, v; 
    cin >> u >> v;
    g[u].push_back({v, i});
    g[v].push_back({u, i});
  }

  for (int i = 0; i < m; i++) {
    int p; ll w;
    cin >> p >> w;
    c[p].push_back(w);
  }

  while (q--) {
    int s, t; ll x, y;
    cin >> s >> t >> x >> y;

    vector<int> par(n + 1, -1), pe(n + 1, -1);
    stack<int> st;
    st.push(s);
    par[s] = s;

    while (!st.empty()) {
      int u = st.top(); st.pop();
      if (u == t) break;
      for (auto e : g[u]) {
        int v = e.first, id = e.second;
        if (par[v] == -1) {
          par[v] = u;
          pe[v] = id;
          st.push(v);
        }
      }
    }

    if (par[t] == -1) {
      cout << -1 << "\n";
      continue;
    }

    vector<ll> a;
    int cur = t;
    while (cur != s) {
      for (ll w : c[pe[cur]]) a.push_back(w);
      cur = par[cur];
    }

    sort(a.begin(), a.end());

    ll sy = 0;
    int cnt = 0;
    for (ll w : a) {
      if (sy + w <= y) {
        sy += w;
        cnt++;
      } else break;
    }

    ll res = (ll)(a.size() - cnt);
    if (res <= x) cout << x - res << '\n';
    else cout << -1 << '\n';
  }
}

#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...