ZOJ 3602 Count the Trees(二叉树)

计算两棵二叉树构造相同的子树有几对

但一个节点的左右节点都有对应的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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值