跳到正文

个人记录

2025.11.8

swordofsky约 3 分钟
原文

这是 2026年2月22日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年11月8日
收录
2026年2月22日
更新
2026年11月13日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

A - 1092f(AC)

B - 1294f(AC)

C - 1794e

正解:换根+哈希

因为需要让当前状态跟题目给出的状态差一个数,用哈希就可以用哈希值差base的幂次来O(logn)O(logn)实现快速判断,套在换根DP上注意初始化,另外base和模数在CF100多个点上极易被卡,一般三哈希

C++
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N=200005,B=99824353;//base大一点
ll n,a[N],c[N],x,y,f[N],ans[N],sum,hs,pw,M;
unordered_map<ll,bool>mp;
vector<ll>g[N];
void Dfs(ll x,ll ls){
	f[x]=0;
	for(auto i:g[x]){
		if(i==ls) continue;
		Dfs(i,x);
		f[x]=(f[x]+f[i]*B%M)%M;//子树哈希值
	}
	f[x]=(f[x]+1)%M;
}
void dfs(ll x,ll ls){
	f[x]=(f[x]+f[ls]*B%M)%M;
	if(mp[(f[x]-hs+M)%M]) ans[x]++;//记录答案
	for(auto i:g[x]){
		if(i==ls) continue;
		f[x]=(f[x]-f[i]*B%M+M)%M;//转移
		dfs(i,x);
		f[x]=(f[x]+f[i]*B%M)%M;
	}
	f[x]=(f[x]-f[ls]*B%M+M)%M;
}
void sol(){
	mp.clear();
	hs=0;pw=1;
	for(int i=0;i<n;i++){
		c[i]=f[i]=0;
	}
	for(int i=1;i<n;i++){
		c[a[i]]++;
	}
	for(int i=0;i<n;i++){
		hs=(hs+c[i]*pw%M)%M;
		mp[pw]=1;
		pw=pw*B%M;
	}
	Dfs(1,0);
	dfs(1,0);
}
int main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	cin>>n;
	for(int i=1;i<n;i++){
		cin>>a[i];
	}
	for(int i=1;i<n;i++){
		cin>>x>>y;
		g[x].push_back(y);
		g[y].push_back(x);
	} 
	M=114917813;//猎奇模数,单哈希到第7点
	sol();
	M=998244353;//99824353+998244353,双哈希到第35点
	sol();
	M=1000000007;//再加普通模数,过了
	sol();
	ll sum=0;
	for(int i=1;i<=n;i++){
		if(ans[i]==3) sum++;//三哈希
	}
	cout<<sum<<"\n";
	for(int i=1;i<=n;i++){
		if(ans[i]==3) cout<<i<<' ';
	}
	return 0;
}

时间复杂度:O(nlogn)O(nlogn)