Counting Offspring dfs order + tree array

Portal

Title description

Given a tree, the root number is p.
For each node, find how many nodes in the subtree rooted at it have a number less than it.

analysis

We can set the corresponding position to 1 according to the size of the node, and then when we ask for the answer to a node, we only need to ask for the value of the subtree

We can use dfs order and tree array to maintain the answer, and finally sum up

Code

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define _CRT_SECURE_NO_WARNINGS
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#pragma GCC option("arch=native","tune=native","no-zero-upper")
#pragma GCC target("avx2")
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 1e5 + 10,M = 2 * N;
int n,p;
int h[N],ne[M],e[M],idx;
int in[N],out[N];
int cnt;
int tr[N];

int lowbit(int x){
    
    
    return x & -x;
}

void add(int x,int y){
    
    
    ne[idx] = h[x],e[idx] = y,h[x] = idx++;
}

void ad(int x,int c){
    
    
    for(int i = x;i <= n;i += lowbit(i)) tr[i] += c;
}

int sum(int x){
    
    
    int res = 0;
    for(int i = x;i;i -= lowbit(i)) res += tr[i];
    return res;
}

void dfs(int u,int fa){
    
    
    in[u] = ++cnt;
    for(int i = h[u];~i;i = ne[i]){
    
    
        int j = e[i];
        if(j == fa) continue;
        dfs(j,u);
    }
    out[u] = cnt;
}

int main(){
    
    
    while(scanf("%d%d",&n,&p) && n && p){
    
    
        memset(h,-1,sizeof h);
        idx = cnt = 0;
        for(int i = 1;i < n;i++){
    
    
            int x,y;
            scanf("%d%d",&x,&y);
            add(x,y),add(y,x);
        }
        dfs(p,-1);
        memset(tr,0,sizeof tr);
        for(int i = 1;i <= n;i++){
    
    
            int ans = sum(out[i]) - sum(in[i]);
            if(i != n) printf("%d ",ans);
            else printf("%d\n",ans);
            ad(in[i],1);
        }
    }
    
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/


Guess you like

Origin blog.csdn.net/tlyzxc/article/details/111054252