zoukankan      html  css  js  c++  java
  • PJ2018T4 对称二叉树 树形结构

    题意:现在给出一棵二叉树,希望你找出它的一棵子树,该子树为对称二叉树,且节点数最多。请输出这棵子树的节点数。对称二叉树满足:将这棵树所有节点的左右子树交换后,新树和原树对应位置的结构相同且点权相等。

    (注意输入的是当前节点的左儿子和右儿子,若输入-1则表示该位置不存在点)

    数据范围:n <= 1000000.

    ------------------------------------------我是分割线------------------------------------

    题解: 首先预处理每棵子树的大小,用size[x]表示x的子树大小,接下来直接枚举每个点检验即可,非常简单。

    #include<bits/stdc++.h>
    
    #define ll long long
    #define mp make_pair
    #define rep(i, a, b) for(int i = (a); i <= (b); i++)
    #define per(i, a, b) for(int i = (a); i >= (b); i--)
    
    using namespace std;
    
    typedef pair<int, int> pii;
    typedef double db;
    const int N = 1e6 + 50;
    int n, head[N], cnt = 0, a[N];
    int size[N], f[N], lson[N], rson[N];
    int ans;
    inline int read(){
        int x = 0, f = 1;
        char ch = getchar();
        while(ch < '0' || ch > '9') { if(ch == '-') f = -1; ch = getchar();}
        while(ch >='0' && ch <='9') { x = (x<<3)+(x<<1)+(ch^48); ch = getchar();}
        return x*f;
    }
    void init(){
        n = read();
        rep(i, 1, n) a[i] = read();
        rep(i, 1, n) {
            lson[i] = read(); rson[i] = read();
        }
    }
    void dfs(int x){
        size[x] = 1;
        if(lson[x] != -1){
            dfs(lson[x]);
            size[x] += size[lson[x]];
        }
        if(rson[x] != -1){
            dfs(rson[x]);
            size[x] += size[rson[x]];
        }
        return;
    }
    bool check(int u, int v){
        if(u == -1 && v == -1) return true;
        if(u != -1 && v != -1 && a[u] == a[v] && check(lson[u], rson[v]) && check(rson[u], lson[v]))
            return true;
        return false; 
    }
    void work(){
        dfs(1); 
        rep(i, 1, n) {
            if(check(lson[i], rson[i]))
                ans = max(ans, size[i]);
        }
        printf("%d
    ", ans);
    }
    int main(){
        init();
        work();
        return 0;
    }
    View Code

    (刷水题不是我的本意,愉悦身心才是我的真正目的qwq).

  • 相关阅读:
    POJ 1862 Stripies (简单贪心)
    HDU 2181 哈密顿绕行世界问题(DFS)
    POJ 3262 Protecting the Flowers (贪心)
    Aizu 2249 Road Construction (最短路 SPFA)
    POJ 3484 Showstopper(二分)
    HDU 6235 2017-CCPC-哈尔滨站 Permutation(简单模拟)
    IDEA常用插件
    解决IDEA插件加载失败
    解决zsh无法使用maven
    Linux安装Maven
  • 原文地址:https://www.cnblogs.com/smilke/p/11580523.html
Copyright © 2011-2022 走看看