zoukankan      html  css  js  c++  java
  • 2020年团体程序设计天梯赛 L2-3 完全二叉树的层序遍历

    思路:

    水题,略过

    Tip:

    满二叉树和完全二叉树的性质

    #include <bits/stdc++.h>
    
    using namespace std;
    typedef long long ll;
    const int maxn = 1000 + 5;
    
    struct point {
        int num;
        point *left;
        point *right;
    };
    int ceng[maxn];
    int a[maxn];
    int nowP = 1;
    int n;
    
    point *dfs(point *now, int nowCeng) {
        if (!ceng[nowCeng])
            return NULL;
        ceng[nowCeng]--;
        now = (point *) malloc(sizeof(point));
        now->left = NULL;
        now->right = NULL;
        now->left = dfs(now->left, nowCeng + 1);
        now->right = dfs(now->right, nowCeng + 1);
        now->num = a[nowP++];
        return now;
    }
    
    int main() {
        cin >> n;
        for (int i = 1; i <= n; i++)
            cin >> a[i];
        int i, j = 1, ans = 0;
        for (i = 1;; i *= 2, j++) {
            if (ans + i > n) {
                ceng[j] = n - ans;
                break;
            }
            ceng[j] = i;
            ans += i;
        }
        point *head;
        head = dfs(head, 1);
        queue<point *> que;
        que.push(head);
        vector<int> v;
        while (!que.empty()) {
            point *now = que.front();
            que.pop();
            v.push_back(now->num);
            if (now->left != NULL)
                que.push(now->left);
            if (now->right != NULL)
                que.push(now->right);
        }
        bool first = true;
        for (auto k:v) {
            if (first) {
                first = false;
                cout << k;
            } else
                cout << " " << k;
        }
        return 0;
    }
    

      

  • 相关阅读:
    [BZOJ4825][HNOI2017]单旋(线段树+Splay)
    [BZOJ4542][HNOI2016]大数(莫队)
    [LOJ6281]数列分块入门 5
    [LOJ6280]数列分块入门 4
    [LOJ6279]数列分块入门 3
    [LOJ6278]数列分块入门 2
    [LOJ6277]数列分块入门 1
    [BZOJ2120]数颜色
    [BZOJ3585]mex
    [ZJb417]区间众数
  • 原文地址:https://www.cnblogs.com/Whiteying/p/14056504.html
Copyright © 2011-2022 走看看