This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define ld long double
#define mp make_pair
#define pb push_back
#define pii pair<int,int>
#define fi first
#define se second
#define all(x) x.begin(), x.end()
#define ar array
const int N=1e5+500,K=25;
int cnt = 0, cur = 0, tin[N], tout[N], sp[N][K];
vector<pair<int,int>> g[N];
int dep[N], w[N];
void dfs(int u, int p){
tin[u] = cur++;
sp[u][0] = p;
for(int i = 1; i < K; i++)
sp[u][i] = sp[sp[u][i-1]][i-1];
for(auto x : g[u]){
if(x.fi == p) continue;
dep[x.fi] = dep[u]+w[x.se];
dfs(x.fi,u);
}
tout[u] = cur++;
}
bool is_anc(int u, int v){
return (tin[u] <= tin[v] && tout[v] <= tout[u]);
}
int lca(int u, int v){
if(is_anc(u,v)) return u;
if(is_anc(v,u)) return v;
for(int i = K-1; i >= 0; i--)
if(!is_anc(sp[u][i], v)) u = sp[u][i];
return sp[u][0];
}
void solve(){
int n,m,q; cin >> n >> m >> q;
for (int i = 0; i < n-1; ++i)
{
int a,b; cin >> a >> b;
a--,b--;
g[a].pb(mp(b,i));
g[b].pb(mp(a,i));
}
for (int i = 0; i < m; ++i)
{
int p, c;
cin >> p >> c;
p--;
cnt = c;
w[p] += c;
}
dfs(0,0);
while(q--){
int s,t,au_have,ag;
cin >> s >> t >> au_have >> ag;
s--,t--;
int l = lca(s,t);
int sm = dep[s]+dep[t]-2*dep[l];
int au = sm/cnt - ag/cnt;
if(au <= 0) cout << au_have <<'\n';
else if(au <= au_have) cout << au_have-au << '\n';
else cout << -1 << '\n';
}
}
signed main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
clock_t tStart = clock();
int local=0,multi=0,debug=1,tt=1;
if(local){
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
}
if(multi) cin>>tt;
for(int i=1;i<=tt;i++){
if(debug && multi && local) cout<<"样例 "<<i<<'\n';
solve();
}
fprintf(stderr, "\n>> Runtime: %.10fs\n", (double) (clock() - tStart) / CLOCKS_PER_SEC);
}
Compilation message (stderr)
currencies.cpp: In function 'int main()':
currencies.cpp:74:13: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
74 | freopen("input.txt","r",stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
currencies.cpp:75:13: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
75 | freopen("output.txt","w",stdout);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |