zoj 3602 Count the Trees(二叉树性质)

本文介绍了一种通过编号和哈希映射来解决二叉树匹配问题的方法,旨在提高二叉树理解与操作能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:
给出两个二叉树A, B。找满足以下条件的pair的个数。
pair(T, F), T, F分别为A,B子树,且T=F。
思路:
不错的题目。。加强对二叉树的理解。。
两棵二叉树相同的充要条件是左右子树相同。
我们给每个形态一个编号。A的编号为id(A)
则每棵树可以表示为 (id(left_child), id(right_child))
然后统计一下就可以了。

struct node {
    int l, r;
};

bool operator < (const node &lhs, const node &rhs) {
    if (lhs.l != rhs.l) return lhs.l < rhs.l;
    return lhs.r < rhs.r;
}

int n, m, countor;
node ai[Maxn+5], bi[Maxn+5];

map<node, int> Hash;
map<int, int> cnt_a, cnt_b;

int get_hash(int l, int r) {
    node tmp = (node) {l, r};
    if (Hash.count(tmp)) return Hash[tmp];
    return Hash[tmp] = countor ++;
}

int gao(int x, node *arr, map<int, int> &cnt) {
    int l, r;
    if (arr[x].l > 0) {
        l = gao(arr[x].l, arr, cnt);
    } else
        l = -1;
    if (arr[x].r > 0) {
        r = gao(arr[x].r, arr, cnt);
    } else
        r = -1;
    int h = get_hash(l, r);
    cnt[h] += 1;
    return h;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.in", "r", stdin);
#endif
    SPEED_UP
    int t;
    cin >> t;
    while (t --) {
        cin >> n >> m;
        rep(i, 1, n) cin >> ai[i].l >> ai[i].r;
        rep(i, 1, m) cin >> bi[i].l >> bi[i].r;
        countor = 0;
        Hash.clear(); cnt_a.clear(); cnt_b.clear();

        gao(1, ai, cnt_a); gao(1, bi, cnt_b);
        LL ans = 0;
        for (map<int, int>::iterator it = cnt_a.begin(); it != cnt_a.end();++ it)
            if (cnt_b.count(it->first))
                ans += it->second * 1ll * cnt_b[it->first];
        cout << ans << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值