思路:
我们倒过来想,如果把两颗树合并,那么肯定在原树与目标数中都有一条连边的,所以直接看成一个点来做。
c o d e code code
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 10;
int t;
int n;
map<pair<int, int>, int> a;
queue<pair<int, int> > q;
multiset<int> b[MAXN];
void add(int x, int y) {
if(x < y) swap(x, y);
if(x == y) return ;
a[make_pair(x, y)] ++;
b[x].insert(y), b[y].insert(x);
if(a[make_pair(x, y)] == 2) q.push(make_pair(x, y));
}
int main() {
scanf("%d", &t);
while(t --) {
scanf("%d", &n);
a.clear();
for(int i = 1; i <= n; i ++) b[i].clear();
q = queue<pair<int, int> >();
for(int i = 1; i < n * 2 - 1; i ++) {
int x, y;
scanf("%d%d", &x, &y);
add(x, y);
}
int s = 0;
while(!q.empty() && s < n - 1) {
int x = q.front().first, y = q.front().second;
q.pop();
if(!a[make_pair(x, y)]) continue;
if(b[x].size() < b[y].size()) swap(x, y);
for (multiset<int>::iterator iter = b[y].begin(); iter != b[y].end(); iter ++) {
int z = *iter;
a[make_pair(max(z, y), min(z, y))] --;
b[z].erase(b[z].find(y));
add(x, z);
}
b[y].clear();
s ++;
}
if(s == n - 1) printf("YES\n");
else printf("NO\n");
}
return 0;
}