树哈希方法,好像挺简单的一个东西。

#include <bits/stdc++.h>
/*
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
*/
using namespace std;

const double eps = 1e-10;
const double pi = 3.1415926535897932384626433832795;
const double eln = 2.718281828459045235360287471352;

#define f(i, a, b) for (int i = a; i <= b; i++)
#define scan(x) scanf("%d", &x)
#define mp make_pair
#define pb push_back
#define lowbit(x) (x&(-x))

#define fi first
#define se second
#define SZ(x) int((x).size())
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define summ(a) (accumulate(all(a), 0ll))

typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef vector<int> vi;

using ll=long long;

ll tt,n;
ull hsh[(int)2e5+9];
vector<int> g[(int)2e5+9];

ll h(ll x) {
    return x * x * x * 1237123 + 19260817;
}

ll ff(ll x) {
    ll cur = h(x & ((1ll << 31) - 1)) + h(x >> 31);
    return cur;
}

void dfs(int u,int fa){
    for(auto it:g[u])if(it!=fa){
        dfs(it,u);
        hsh[u]+=ff(hsh[it]);
    }
}

bool check(int u,int fa){
    map<ull,vi> wz;
    ll cnt=0;
    for(auto it:g[u])if(it!=fa){
        wz[hsh[it]].push_back(it);
        //cerr<<hsh[it]<<"<--"<<it<<"---"<<u<<"\n";
    }
    for(auto [aa,bb]:wz)cnt+=(((int)bb.size())&1);
    if(cnt>1)return false;
    if(cnt<1)return true;
    for(auto [_,bb]:wz){
        if(bb.size()&1){
            bool ok=false;
            for(auto it:bb)ok|=check(it,u);
            return ok;
        }
    }
    return false;
}

bool solve(){
    cin>>n;
    for(int i=1;i<=n;++i)g[i].clear(),hsh[i]=1;
    for(int i=1,x,y;i<n;++i){
        cin>>x>>y;
        g[x].push_back(y),g[y].push_back(x);
    }
    dfs(1,0);
    return check(1,0);
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin>>tt;
    f(sb,1,tt)cout<<(solve()?"YES\n":"NO\n");
    return 0;
}
此文章已被阅读次数:正在加载...更新于