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;
}