记录编号 | 187209 | 评测结果 | AAAAAAAAAA | ||
---|---|---|---|---|---|
题目名称 | 树的统计 | 最终得分 | 100 | ||
用户昵称 | 是否通过 | 通过 | |||
代码语言 | C++ | 运行时间 | 1.159 s | ||
提交时间 | 2015-09-17 21:08:18 | 内存使用 | 18.39 MiB | ||
#include<cstdio> #include<deque> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> using namespace std; const int SIZEN=110000; int N,father[SIZEN]={0},root=0,tot=0; int pos[SIZEN]={0};//dfs序 int tree[SIZEN]={0};//树状数组 int ans[SIZEN]={0}; deque<int> w[SIZEN]; void read() { scanf("%d",&N); for(int i=1;i<=N;i++) { scanf("%d",&father[i]); if(father[i]==0) root=i; else w[father[i]].push_back(i); } } int lowbit(int x) { return x&(-x); } int sum(int x) { int re=0; while(x>0){re+=tree[x];x-=lowbit(x);} return re; } void add(int x,int y) { while(x<=N){tree[x]+=y;x+=lowbit(x);} } void dfs1(int x) { ans[x]+=sum(x); add(x,1); for(int i=0;i<w[x].size();i++) { dfs1(w[x][i]); } add(x,-1); } void dfs2(int x) { pos[++tot]=x; for(int i=0;i<w[x].size();i++) { dfs2(w[x][i]); } } void dfs3(int x) { pos[++tot]=x; for(int i=w[x].size()-1;i>=0;i--) { dfs3(w[x][i]); } } void get() { for(int i=N;i>=1;i--) { ans[pos[i]]+=sum(pos[i]); add(pos[i],1); } } void work() { memset(tree,0,sizeof(tree));dfs1(root); memset(tree,0,sizeof(tree));dfs2(root);get(); memset(pos,0,sizeof(pos));memset(tree,0,sizeof(tree));tot=0; dfs3(root);get(); for(int i=1;i<=N;i++) ans[i]=ans[i]-i+1; for(int i=1;i<=N;i++) printf("%d ",ans[i]); } int main() { freopen("counttree.in","r",stdin); freopen("counttree.out","w",stdout); read(); work(); return 0; }