题解:CF1800G Symmetree

· · 题解

考虑先对树上每个子树处理出树哈希值。

然后对于一个点不断的取出两个哈希值相同也就是同构的子树删掉,表示将这两个子树作为镜像,直到不可再消。

然后如果没剩下子树就是合法,剩下一个子树就去递归判定这个子树是否合法,否则一定不合法。

#include<bits/stdc++.h>
using namespace std;
#define int long long
//#define lowbit(x) (x&(-x))
//#define bp push_back
//#define sz size
//#define cl clear
const int maxn = 2e5+114;
const int mod[2] = {1145141,998244353};
mt19937 rd(time(0));
vector<int> E[maxn];
int n;
int C1[2],C2[2];
pair<int,int> Hash(pair<int,int> c){
    return make_pair((c.first*C1[0]%mod[0]+(c.first^C1[0]%mod[0]))%mod[0],(c.second*C1[1]%mod[1]+(c.second^C1[1]%mod[1]))%mod[1]);
}
vector< pair<int,int> > son[maxn];
pair<int,int> dp[maxn];
void dfs(int u,int fa){
    dp[u]=make_pair(114,514);
    for(int v:E[u]){
        if(v!=fa){
            dfs(v,u);
            pair<int,int> s=Hash(dp[v]);
            dp[u]=make_pair((dp[u].first+s.first)%mod[0],(dp[u].second+s.second)%mod[1]);
            son[u].push_back(dp[v]);
        }
    } 
} 
map< pair<int,int> ,int> mp;
bool solve(int u,int fa){
    if(son[u].size()==0) return true;
    mp.clear();
    for(pair<int,int> now:son[u]){
        mp[now]^=1;
    }
    vector< pair<int,int> > vec;
    for(pair<int,int> now:son[u]){
        if(mp[now]==1){
            vec.push_back(now);
            mp[now]^=1;
        }
    }
    if(vec.size()==1){
        for(int v:E[u]){
            if(v!=fa&&dp[v]==vec[0]) return solve(v,u);
        }
    }else if(vec.size()>=2) return false;
    return true;
}
void work(){
    cin>>n;
    for(int i=1;i<n;i++){
        int u,v;
        cin>>u>>v;
        E[u].push_back(v);
        E[v].push_back(u);
    }
    dfs(1,0);
    cout<<(solve(1,0)==true?"YES\n":"NO\n");
    for(int i=1;i<=n;i++) dp[i]=make_pair(0,0),E[i].clear(),son[i].clear();
    return ;
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    C1[0]=rd()%mod[0],C1[1]=rd()%mod[1],C2[0]=rd()%mod[0],C2[1]=rd()%mod[1];
    int t;
    cin>>t;
    while(t--) work();
    return 0;
}
/*
1
6
1 5
1 6
1 2
2 3
2 4
*/