Link: http://acm.zju.edu.cn/onlinejudge/showProblem.do? Problemcode = 3602.
The provincial competition question. At that time, my teammates used a simple hash and completed wa's entire game. Today, I used map to rewrite it.
Easy to use --!
Q: I want to tell you how many sub-trees U V are homogeneous. U belongs to the first tree, and V belongs to the second tree.
Use a Map <pair <int, int>, int>.
Indicates that the Left and Right trees are merged and mapped to a new tree.
Each node records a value, corresponding to the type of the tree. Two Trees record two arrays, representing the type of the subtree of each node.
Sort the order and make statistics,
For example, for the tree in the second group of samples, the generation sequence is 0 0 0 1 2. There are three types of trees.
For details, see the code. I am a code controller --
#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>#include <map>using namespace std;const int maxn = 100010;map<pair<int,int>,int> mp;struct node{int lc,rc;}tree[maxn];int cnt;int get(pair<int,int>tmp){if(mp.find(tmp)!=mp.end()) return mp[tmp];else {mp[tmp]=cnt++;return cnt-1;}}int ans1[maxn],ans2[maxn],tot;int dfs(int rt,int ans[]){if(tree[rt].lc==-1 && tree[rt].rc==-1){ans[tot++]=get(make_pair(-1,-1));return ans[tot-1];}int l,r;if(tree[rt].lc==-1) l=-1;else l=dfs(tree[rt].lc,ans);if(tree[rt].rc==-1) r=-1;else r=dfs(tree[rt].rc,ans);ans[tot++]=get(make_pair(l,r));return ans[tot-1];}int main(){int t,m,n;scanf("%d",&t);while(t--){mp.clear();scanf("%d%d",&m,&n);for(int i=1;i<=m;i++)scanf("%d%d",&tree[i].lc,&tree[i].rc);cnt=tot=0;dfs(1,ans1);for(int i=1;i<=n;i++)scanf("%d%d",&tree[i].lc,&tree[i].rc);tot=0;dfs(1,ans2);sort(ans1,ans1+m);sort(ans2,ans2+n);long long ans=0,tmp=0;for(int i=0,j=0;i<m;i++){while(j<n && ans2[j]<ans1[i]) j++;if(j<n && ans2[j]==ans1[i]) tmp=0;while(j<n&&ans2[j]==ans1[i]) j++,tmp++;if(j>0 && ans2[j-1]==ans1[i])ans+=tmp;}printf("%lld\n",ans);}return 0;}