HDUOJ 3887 Counting Offspring ( DFS+BIT

Counting Offspring

题目描述

You are given a tree, it’s root is p, and the node is numbered from 1 to n. Now define f(i) as the number of nodes whose number is less than i in all the succeeding nodes of node i. Now we need to calculate f(i) for any possible i.

输入

Multiple cases (no more than 10), for each case:
The first line contains two integers n (0

输出

For each test case, output n integer in one line representing f(1), f(2) … f(n), separated by a space.

样例

Sample Input
15 7
7 10
7 1
7 9
7 3
7 4
10 14
14 2
14 13
9 11
9 6
6 5
6 8
3 15
3 12
0 0


Sample Output
0 0 0 0 0 1 6 0 3 1 0 0 0 2 0

题意

求一颗有根无向树的每个节点比子节点标号大的个数
DFS序模板题

AC代码

#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define LL long long
#define CLR(a,b) memset(a,(b),sizeof(a))

const int MAXN = 1e5+10;
vector<int> T[MAXN];
int vis[MAXN], res[MAXN];
int c[MAXN];
int n, root;

int lowbit(int x) {
    return x&(-x);
}
int query(int x) {
    int res = 0;
    while(x) {
        res += c[x];
        x -= lowbit(x);
    }
    return res;
}
void add(int x,int d) {
    while(x <= n) {
        c[x] += d;
        x += lowbit(x);
    }
}
void dfs(int u) {
    vis[u] = 1;
    res[u] = query(u);
    add(u,1);
    for(int i = 0; i < T[u].size(); i++) {
        int v = T[u][i];
        if(!vis[v])
            dfs(v);
    }
    res[u] = query(u)-res[u]-1;
}

int main() {
    ios::sync_with_stdio(false);
    while(cin >> n >> root, n, root) {
        CLR(vis,0);
        CLR(c,0);
        CLR(res,0);
        for(int i = 0; i < n-1; i++) {
            int u, v;
            cin >> u >> v;
            T[u].push_back(v);
            T[v].push_back(u);
        }
        dfs(root);
        for(int i = 1; i < n; i++) {
            cout << res[i] << ' ';
        }
        cout << res[n] << endl;
        for(int i = 1; i <= n; i++) T[i].clear();

    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值