Problem Description
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.
Input
Multiple cases (no more than 10), for each case:
The first line contains two integers n (0<n<=10^5) and p, representing this tree has n nodes, its root is p.
Following n-1 lines, each line has two integers, representing an edge in this tree.
The input terminates with two zeros.
Output
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
Author
bnugong
Source
2011 Multi-University Training Contest 5 - Host by BNU
Recommend
lcy | We have carefully selected several similar problems for you: 3450 3030 1541 3743 1394
题意:就每个节点为根节点的树中,有多少个编号比根小的值。
思路:开始用树上启发式合并超时了,因为找有多少个小,需要排序,复杂度O(nlogn^2),因为这个有多种案例,所以过不了,然后第二种思路就是将树型结构转换为线型结构,然后用主席树维护,交了13次,全部爆内存,最后发现只要将建空树删掉就能过了。
代码:
//#pragma GCC optimize(2)
//#include<bits/stdc++.h>
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<vector>
#include<algorithm>
#define ULL unsigned long long
#define LL long long
#define Max 1000005
#define mem(a,b) memset(a,b,sizeof(a));
#define pb push_back
#define mp make_pair
#define input ios::sync_with_stdio(false);cin.tie(0);
#define debug printf("debug!!!\n");
const LL mod=1e9+7;
const ULL base=131;
const LL LL_MAX=9223372036854775807;
using namespace std;
struct node{
int to,next;
}edge[Max];
struct zxs{
int l,r,sum;
}tree[Max*20];
int head[Max],tot,link;
int num[Max],in[Max],out[Max],tim;
int n,p,root[Max];
void init(){
mem(head,-1);
tot=0;
tim=0;
link=0;
}
inline void addedge(int u,int v){
edge[tot].to=v;
edge[tot].next=head[u];
head[u]=tot++;
}
void dfs(int u,int fa){
in[u]=++tim;
num[tim]=u;
for(int t=head[u];t!=-1;t=edge[t].next){
if(edge[t].to!=fa)
dfs(edge[t].to,u);
}
out[u]=tim;
}
void build(int& root,int l,int r){
root=++link;
if(l==r)
return ;
int mid=(l+r)/2;
build(tree[root].l,l,mid);
build(tree[root].r,mid+1,r);
}
void update(int l,int r,int& now,int last,int index){
now=++link;
tree[now]=tree[last];
tree[now].sum++;
if(l==r)
return ;
int mid=(l+r)/2;
if(index<=mid)
update(l,mid,tree[now].l,tree[last].l,index);
else
update(mid+1,r,tree[now].r,tree[last].r,index);
}
int query(int l,int r,int L,int R,int k){
if(l>=k)
return 0;
if(r<k)
return tree[R].sum-tree[L].sum;
int mid=(l+r)/2;
return query(l,mid,tree[L].l,tree[R].l,k)+query(mid+1,r,tree[L].r,tree[R].r,k);
}
int main()
{
while(scanf("%d%d",&n,&p)==2 && n!=0){
init();
for(int i=1;i<n;i++){
int u,v;
scanf("%d%d",&u,&v);
addedge(u,v);
addedge(v,u);
}
dfs(p,0);
for(int i=1;i<=n;i++)
update(1,n,root[i],root[i-1],num[i]);
for(int i=1;i<=n;i++)
printf(i==n?"%d\n":"%d ",query(1,n,root[in[i]-1],root[out[i]],i));
}
return 0;
}