计算两棵二叉树构造相同的子树有几对
但一个节点的左右节点都有对应的hash值的时候,才可以对其赋值,否则 对未赋值的子树进行dfs,最后统计个数,用乘法定理
#include<iostream>
#include<cstdio>
#include<set>
#include<string>
#include<string.h>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<cctype>
#include<algorithm>
#include<sstream>
#include<utility>
#include<cmath>
#include<functional>
#define mt(a) memset(a,0,sizeof (a))
#define fl(a,b,c) fill(a,b,c)
#define SWAP(a,b,t) (t=a,a=b,b=t)
#define inf 1000000000+7
using namespace std;
typedef long long ll;
typedef short si;
class node{
public:
ll lc, rc,head;
friend bool operator<(const node &x, const node &y)
{
if (x.lc != y.lc)return x.lc < y.lc;
return x.rc < y.rc;
}
};
node tree[120000];
map<node, ll>ha;
ll ta[120000];
ll tb[120000];
ll cnt;
void dfs(int x,ll *ta)
{
node temp;
if (tree[x].lc == -1 && tree[x].rc == -1)
{
temp.lc = -1, temp.rc = -1; tree[x].head = ha[temp];
ta[tree[x].head]++; return;
}
if (tree[tree[x].lc].head == -1&&tree[x].lc!=-1)dfs(tree[x].lc,ta);
if (tree[tree[x].rc].head == -1&&tree[x].rc!=-1)dfs(tree[x].rc,ta);
temp.lc = tree[tree[x].lc].head;
temp.rc = tree[tree[x].rc].head;
if (!ha[temp])ha[temp] = cnt++;
tree[x].head = ha[temp];
ta[tree[x].head]++;
}
int main()
{
int T;
cin >> T;
while (T--)
{
node temp;
ha.clear();
cnt = 1;
temp.lc = -1, temp.rc = -1;
ha[temp] = cnt++;
int n, m;
cin >> n >> m;
mt(ta); mt(tb);
memset(tree, -1, sizeof tree);
for (int i = 1; i <= n; i++)
{
cin >> tree[i].lc >> tree[i].rc;
}
dfs(1,&ta[0]);
memset(tree, -1, sizeof tree);
for (int i = 1; i <= m; i++)
{
cin >> tree[i].lc >> tree[i].rc;
}
dfs(1, &tb[0]);
ll ans = 0;
for (int i = 0; i < cnt + 10; i++)
{
ans += (ta[i] * tb[i]);
}
cout << ans << endl;
}
return 0;
}