题意
给定一棵节点度数不超过4的无根树(无环烷烃)
现要求在要在树上添加一个结点,且之后每个节点度数依然不超过4(用氯取代一个氢)
问有多少不同构的加法
n≤105
题解
让我们回忆一下高中化学题
我们必须注意到添加的这个节点是和原树的节点不同的(一个是氯一个是碳),于是每种加法我们都把添加的这个节点当做树根,这样再找出不同构的树。
怎样找不同构的呢?我们都知道要用最小表示法,那么怎么最小表示法呢?
这里可以用STL来快速hash一下,并记忆化。
具体是树形dp时传两个参,当前节点和父亲节点,用vector存下儿子几点们的dp值,并将此vector用map进行hash,再将当前状态(当前节点和当前节点的父亲)的dp值记忆化。
复杂度
O(nlogn)
代码
/// by ztx
/// blog.csdn.net/hzoi_ztx
#define Rep(i,l,r) for(i=(l);i<=(r);i++)
#define rep(i,l,r) for(i=(l);i< (r);i++)
#define Rev(i,r,l) for(i=(r);i>=(l);i--)
#define rev(i,r,l) for(i=(r);i> (l);i--)
#define Each(i,v) for(i=v.begin();i!=v.end();i++)
#define r(x) read(x)
typedef long long ll ;
typedef double lf ;
int CH , NEG ;
template <typename TP>inline void read(TP& ret) {
ret = NEG = 0 ; while (CH=getchar() , CH<'!') ;
if (CH == '-') NEG = true , CH = getchar() ;
while (ret = ret*10+CH-'0' , CH=getchar() , CH>'!') ;
if (NEG) ret = -ret ;
}
#define maxn 100010LL
#define pb push_back
using namespace std;
int n, idx = 0;
int ans[maxn];
vector<int> G[maxn];
map<int,int> R[maxn];
map<int,int>::iterator it;
map<vector<int>,int> H;
map<vector<int>,int>::iterator it2;
set<int> S;
int dp(int u,int fa) {
if (it=R[u].find(fa), it!=R[u].end()) return it->second;
vector<int>now; int i;
rep (i,0,G[u].size())
if (G[u][i] != fa)
now.pb(dp(G[u][i],u));
sort(now.begin(),now.end());
if (it2=H.find(now), it2==H.end()) return R[u][fa] = H[now] = ++idx;
else return R[u][fa] = it2->second;
}
int main() {
int i, n, u, v;
r(n);
rep (i,1,n)
r(u), r(v), G[u].pb(v), G[v].pb(u);
Rep (i,1,n)
if (G[i].size() < 4) S.insert(dp(i,0));
printf("%d\n", S.size());
END: getchar(), getchar();
return 0;
}