【DFS序+树状数组】HDU 3887 Counting Offspring
生活随笔
收集整理的這篇文章主要介紹了
【DFS序+树状数组】HDU 3887 Counting Offspring
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
http://acm.hdu.edu.cn/showproblem.php?pid=3887
【題意】
- 給定一棵樹,給定這棵樹的根
- 對于每個結點,統計子樹中編號比他小的結點個數
- 編號從小到大一次輸出
【思路】
- 從小到大處理每個結點,即統計當前結點的結果后,把當前結點插入到樹狀數組中
【AC】
#include<bits/stdc++.h>
using namespace std;
typedef long long ll; const int maxn=1e5+;
const int maxm=*maxn;
int n,rt;
struct edge
{
int to;
int nxt;
}e[maxm];
int head[maxn];
int tot;
int cid;
int l[maxn],r[maxn];
int tree[maxm];
int lowbit(int x)
{
return x&(-x);
}
void add(int k,int x)
{
while(k<=cid)
{
tree[k]+=x;
k+=lowbit(k);
}
}
int query(int k)
{
int ans=;
while(k)
{
ans+=tree[k];
k-=lowbit(k);
}
return ans;
}
void init()
{
memset(head,-,sizeof(head));
tot=;
cid=;
memset(tree,,sizeof(tree));
} void addedge(int u,int v)
{
e[tot].to=v;
e[tot].nxt=head[u];
head[u]=tot++;
}
void dfs(int u,int pa)
{
l[u]=++cid;
for(int i=head[u];i!=-;i=e[i].nxt)
{
int v=e[i].to;
if(v==pa) continue;
dfs(v,u);
}
r[u]=++cid;
} int main()
{
while(~scanf("%d%d",&n,&rt))
{
if(n+rt==) break;
init();
int u,v;
for(int i=;i<=n-;i++)
{
scanf("%d%d",&u,&v);
addedge(u,v);
addedge(v,u);
}
dfs(rt,-);
for(int i=;i<=n;i++)
{
int ans=query(r[i])-query(l[i]-);
if(i==) printf("%d",ans);
else printf(" %d",ans);
add(l[i],);
}
puts("");
}
return ;
}
樹狀數組
總結
以上是生活随笔為你收集整理的【DFS序+树状数组】HDU 3887 Counting Offspring的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 检测汽车减震器示功疲劳综合性能的仪器介绍
- 下一篇: 【Linux入门】