이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
#define f first
#define s second
#define ll long long
#define pb push_back
#define pii pair<int,int>
#define pll pair<ll,ll>
#define sz(x) (int)x.size()
#define all(x) x.begin(),x.end()
#define vi vector<ll>
using namespace std;
const int N=1e5+5;
struct node{
ll cnt,tt;
node *l,*r;
node (ll x=0,ll y=0) : cnt(x),tt(y),l(NULL),r(NULL){};
node (node* le,node*re) : cnt(le->cnt+re->cnt),tt(le->tt+re->tt),l(le),r(re){};
};
vector<pair<int,vi>>g[N];
pii road[N];
vi w[N];
vi we;int M;
node *root[N];
int pr[N][20]{0};
int dep[N]{0};
node* build(int l,int r){
if(l==r)return new node();
int m=(l+r)>>1;
return new node(build(l,m),build(m+1,r));
}
node* upd(node*t,int l,int r,int pos,ll val){
if(l==r){
return new node(t->cnt+1,t->tt+val);
}int m=(l+r)>>1;
if(m>=pos)return new node(upd(t->l,l,m,pos,val),t->r);
else return new node(t->l,upd(t->r,m+1,r,pos,val));
}
void dfs(int u,int p,int l){
pr[u][0]=p;
dep[u]=l;
for(auto v:g[u]){
if(v.f==p)continue;
root[v.f]=root[u];
for(auto it : v.s)root[v.f]=upd(root[v.f],1,M,lower_bound(all(we),it)-we.begin()+1,it);
dfs(v.f,u,l+1);
}
}
int lc(int a,int b){
if(dep[a]>dep[b])swap(a,b);
for(int i=19;i>=0;i--)if(dep[b]-(1<<i)>=dep[a])b=pr[b][i];
if(a==b)return a;
for(int i=19;i>=0;i--)if(pr[a][i]!=pr[b][i])a=pr[a][i],b=pr[b][i];
return pr[a][0];
}
int qr(node*tl,node*tr,node*ta,int l,int r,ll k){
if(l==r){
return min(k,tl->tt+tr->tt-2*ta->tt)/we[l-1];
}
int m=(l+r)>>1;
ll lcnt=tl->l->tt+tr->l->tt-2*ta->l->tt;//cout<<lcnt<<" "<<tl->cnt+tr->cnt-2*ta->cnt<<"\n";
if(lcnt>k)return qr(tl->l,tr->l,ta->l,l,m,k);
else return tl->l->cnt+tr->l->cnt-2*ta->l->cnt+qr(tl->r,tr->r,ta->r,m+1,r,k-lcnt);
}
int main(){
ios_base::sync_with_stdio(0);cin.tie(0);
int n,m,q;cin>>n>>m>>q;M=m;
for(int i=1;i<=n-1;i++)cin>>road[i].f>>road[i].s;
for(int i=0;i<m;i++){
int p;ll c;cin>>p>>c;
we.pb(c);w[p].pb(c);
}sort(we.begin(),we.end());
for(int i=1;i<=n-1;i++){
g[road[i].f].pb({road[i].s,w[i]});
g[road[i].s].pb({road[i].f,w[i]});
}
root[1]=build(1,m);
dfs(1,1,0);
for(int j=1;j<20;j++)for(int i=1;i<=n;i++)pr[i][j]=pr[pr[i][j-1]][j-1];
while(q--){
int u,v;ll x,y;cin>>u>>v>>x>>y;
int lca=lc(u,v);
int all = root[u]->cnt+root[v]->cnt-2*root[lca]->cnt;
int cur = qr(root[u],root[v],root[lca],1,m,y);
cout<<(x+cur-all>=0?x+cur-all:-1)<<"\n";
}
}
# | 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... |