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>
#define ll long long
#define fi first
#define se second
using namespace std ;
const ll N = 1e5 ;
bool flag1 ;
ll n, m, q, p[N + 1], c[N + 1], ind[N + 1], pw[2 * N + 1], dist1[N + 1], dist[N + 1] ;
pair<ll, ll> mn[2 * N + 1][20] ;
vector<pair<pair<ll, ll>, ll>> road ;
vector<pair<ll, ll>> v1, v[N + 1] ;
void dfs_for_st(ll city, ll last)
{
ind[city] = v1.size() ;
v1.push_back({city, dist1[city]}) ;
for(auto i : v[city])
{
if(i.fi == last)
continue ;
dist[i.fi] = dist[city] + i.se ;
dist1[i.fi] = dist1[city] + 1 ;
dfs_for_st(i.fi, city) ;
v1.push_back({city, dist1[city]}) ;
}
}
void build_sparce_table()
{
for(ll i = 2 ; i <= (ll)v1.size() ; i++)
pw[i] = pw[i / 2] + 1 ;
for(ll i = 0 ; i < (ll)v1.size() ; i++)
mn[i][0] = v1[i] ;
for(ll i = 1 ; i < 20 ; i++)
for(ll j = 0 ; j <= (ll)v1.size() - (1 << i) ; j++)
mn[j][i] = min(mn[j][i - 1], mn[j + (1 << (i - 1))][i - 1]) ;
}
ll get_lca(ll a, ll b)
{
a = ind[a] ;
b = ind[b] ;
if(a > b)swap(a, b) ;
ll num = pw[b - a + 1] ;
return min(mn[a][num], mn[b - (1 << num) + 1][num]).se ;
}
ll get_dist(ll a, ll b)
{
ll lc = get_lca(a, b) ;
return dist[a] + dist[b] - dist[lc] * 2 ;
}
signed main()
{
ios_base::sync_with_stdio( 0 ) ;
cin.tie( 0 ) ;
cout.tie( 0 ) ;
cin >> n >> m >> q ;
for(ll i = 1 ; i < n ; i++)
{
ll a, b ;
cin >> a >> b ;
road.push_back({{a, b}, 0}) ;
}
for(ll i = 1 ; i <= m ; i++)
{
cin >> p[i] >> c[i] ;
if(c[i] != c[1])
flag1 = 1 ;
}
// if(n <= 2000 && m <= 2000 && q <= 2000)
// {
// return 0 ;
// }
if(!flag1)
{
for(ll i = 1 ; i <= m ; i++)
road[p[i] - 1].se += c[i] ;
for(auto i : road)
v[i.fi.fi].push_back({i.fi.se, i.se}), v[i.fi.se].push_back({i.fi.fi, i.se}) ;
dfs_for_st(1, 0) ;
build_sparce_table() ;
while(q--)
{
ll s, t, x, y ;
cin >> s >> t >> x >> y ;
ll ds = get_dist(s, t) ;
ds /= c[1] ;
y /= c[1] ;
ds -= y ;
cout << max(-1ll, x - ds) << '\n' ;
}
return 0 ;
}
return 0 ;
}
# | 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... |