提交时间:2024-08-29 17:01:36
运行 ID: 31998
#include<bits/stdc++.h> using namespace std; typedef long long ll; const ll INF=0x3f3f3f3f; ll Mod(ll x){ll y=0x3f3f3f3f;return (x+y)%y;} ll lowbit(ll x){return x&-x;} inline ll read(){ register ll x=0,f=1;register char c=getchar(); while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') x=(x<<3)+(x<<1)+(c^48),c=getchar(); return x*f; } const ll N=5e5+9; ll n,Q,t[N],a[N],m; struct Edge{ll u,nxt;} Eg[2*N]; ll tot,hd[N]; inline void add_edge(ll x,ll y){Eg[++tot]=(Edge){y,hd[x]}; hd[x]=tot;} #define MID ((l+r)>>1) #define ls (x<<1) #define rs (x<<1|1) #define pii pair<ll,ll> #define fi first #define se second #define mk make_pair vector<pii> e; ll f0[N<<2],f1[N<<2],sz[N<<2],t0[N<<2],t1[N<<2]; void brush(ll x,ll v0,ll v1){ f0[x]+=v0; f1[x]+=sz[x]*v1; t0[x]+=v0; t1[x]+=v1; } inline void push_up(ll x){ f0[x]=min(f0[ls],f0[rs]); f1[x]=sz[x]=0; if(f0[x]==f0[ls]) f1[x]+=f1[ls],sz[x]+=sz[ls]; if(f0[x]==f0[rs]) f1[x]+=f1[rs],sz[x]+=sz[rs]; } inline void push_down(ll x){ brush(ls,t0[x],t1[x]); brush(rs,t0[x],t1[x]); t0[x]=t1[x]=0; } void upd(ll x,ll l,ll r,ll L,ll R,ll v0,ll v1){ if(l>R || r<L) return; if(L<=l && r<=R){ brush(x,v0,v1); //cout<<"brush "<<l<<" "<<r<<" "<<v0<<" "<<v1<<endl; return; } push_down(x); upd(ls,l,MID,L,R,v0,v1); upd(rs,MID+1,r,L,R,v0,v1); push_up(x); } void build(ll x,ll l,ll r){ if(l==r){ sz[x]=1; f0[x]=(l==n); //cout<<"build "<<x<<" "<<l<<" "<<f0[x]<<endl; return; } build(ls,l,MID); build(rs,MID+1,r); push_up(x); } void print(ll x,ll l,ll r){ //cout<<x<<" "<<l<<" "<<r<<" "<<f0[x]<<" "<<sz[x]<<endl; if(l==r) return; push_down(x); print(ls,l,MID); print(rs,MID+1,r); } int main(){ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin>>n>>Q; t[1]=n; build(1,1,n); for(ll i=1;i<n;i++){ ll x,y; cin>>x>>y; e.push_back(mk(x,y)); } for(ll i=1;i<=n;i++) cin>>a[i]; for(ll i=1;i<=n;i++) t[a[i]]=i; for(ll i=1;i<=n;i++){ if(t[i]>1) upd(1,1,n,1,t[i]-1,1,0); upd(1,1,n,t[i],n,0,1); } for(pii c:e){ ll x=c.fi,y=c.se; if(t[x]>t[y]) swap(x,y); if(t[x]>1) upd(1,1,n,1,t[x]-1,-1,0); upd(1,1,n,t[y],n,0,-1); }upd(1,1,n,1,t[1]-1,-1,0); print(1,1,n); ll ans=(f0[1]==1)?f1[1]:0; while(Q--){ ll x,y; cin>>x>>y; if(t[x]>t[y]) swap(x,y); if(t[x]>1) upd(1,1,n,1,t[x]-1,1,0); upd(1,1,n,t[y],n,0,1); cin>>x>>y; if(t[x]>t[y]) swap(x,y); if(t[x]>1) upd(1,1,n,1,t[x]-1,-1,0); upd(1,1,n,t[y],n,0,-1); ans=(f0[1]==1)?f1[1]:1; cout<<ans<<'\n'; } return 0; }