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 int long long
#define all(x) x.begin(),x.end()
#define ff first
#define ss second
#define pb push_back
using namespace std;
const int N=12e4+5;
vector <int> g[N],g2[N];
int p[N],d[N],jmp[20][N],cl[N];
void dfs(int v,int par){
p[v]=par;
jmp[0][v]=par;
for(auto to : g[v]){
if(!p[to]){
d[to]=d[v]+1;
dfs(to,v);
}
}
}
int lca(int v,int u){
if(d[v]<d[u])swap(v,u);
for(int k=19;k>=0;k--){
if(d[jmp[k][v]]>=d[u]){
v=jmp[k][v];
}
}
if(u==v)return u;
for(int k=19;k>=0;k--){
if(jmp[k][v]!=jmp[k][u]){
v=jmp[k][v];
u=jmp[k][u];
}
}
return p[v];
}
bool dfs2(int v){
cl[v]=1;
for(auto to : g2[v]){
if(cl[to]==1)return true;
if(!cl[to]){
if(dfs2(to))return true;
}
}
cl[v]=2;
return false;
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
int q;
cin>>q;
while(q--){
int n;
cin>>n;
for(int i=0;i<n-1;i++){
int u,v;
cin>>u>>v;
g[u].pb(v);
g[v].pb(u);
}
int m;
cin>>m;
vector <int> s(m+1),t(m+1),st(n+1),ed(n+1);
for(int i=1;i<=m;i++){
cin>>s[i]>>t[i];
st[s[i]]=i;
ed[t[i]]=i;
}
dfs(1,1);
for(int k=1;k<20;k++){
for(int i=1;i<=n;i++){
jmp[k][i]=jmp[k-1][jmp[k-1][i]];
}
}
for(int i=1;i<=m;i++){
int l=lca(s[i],t[i]);
int x=s[i];
while(x!=l){
if(st[x] && i!=st[x]){
g2[st[x]].pb(i);
}
else if(ed[x] && i!=ed[x]){
g2[i].pb(ed[x]);
}
x=p[x];
}
x=t[i];
while(x!=l){
if(st[x] && i!=st[x]){
g2[st[x]].pb(i);
}
else if(ed[x] && i!=ed[x]){
g2[i].pb(ed[x]);
}
x=p[x];
}
if(st[l] && st[l]!=i){
g2[st[l]].pb(i);
}
else if(ed[l] && ed[l]!=i){
g2[i].pb(ed[l]);
}
}
bool ok=1;
for(int i=1;i<=m;i++){
if(!cl[i]){
if(dfs2(i))ok=0;
}
}
if(ok)cout<<"Yes\n";
else cout<<"No\n";
for(int i=1;i<=n;i++){
g[i].clear();
g2[i].clear();
p[i]=0;d[i]=0;cl[i]=0;
for(int k=0;k<20;k++)jmp[k][i]=0;
}
}
}
/*
1
8
1 2
2 3
3 4
4 5
5 6
6 7
7 8
2
3 4
4 8
*/
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |