BOJ 395 Tree

来源:互联网 发布:mac sass安装失败 编辑:程序博客网 时间:2024/06/06 04:01

时间限制 7000 ms 内存限制 65536 KB

题目描述

Given a rooted tree with values assigned on each node, you're required to answer how many nodes on the path from the root to u, that have a value strictly greater than value[u]. Node 1 is the root.

输入格式

An integer T(T20) will exist in the first line, indicating the number of test cases. For each test case, the first line will be the number of tree nodes N(1N100000). The following (N1) lines, each with a pair of integers (u,v), describe the edges of the tree. The values of nodes value[i](1value[i]109,1iN) will be put down on the next line.

输出格式

Output the answer for each node from node 1 to node N, one per line.

输入样例

141 21 34 24 1 5 0

输出样例

010 2



解题思路:

先将每一个节点离散化,再用一个数组C[x],记录value值为x的节点的个数(在这里我使用的是树状数组,貌似用一般的数组好像会超时),然后在dfs的同时,记录该点value值的C数组以及该点前面的大于它的value值的点的个数,回溯的时候再回复C数组。


#include <algorithm>#include <iostream>#include <iomanip>#include <cstring>#include <climits>#include <complex>#include <fstream>#include <cassert>#include <cstdio>#include <bitset>#include <vector>#include <deque>#include <queue>#include <stack>#include <ctime>#include <set>#include <map>#include <cmath>#define lowbit(x) x&(-x)using namespace std;const int MAXN=100010;vector<int> head[MAXN];int n,ans[MAXN];bool vis[MAXN];int c[MAXN];struct Con{int va,num;}a[MAXN];int tot=0,now[MAXN];//now表述压缩过的value,角标相同void update(int i,int v){for(;i<=tot;i+=lowbit(i))c[i]+=v;}int getsum(int i){int sum=0;for(;i>0;i-=lowbit(i))sum+=c[i];return sum;}void add(int a,int b){    head[a].push_back(b);    head[b].push_back(a);}void dfs(int x){vis[x]=true;update(now[x],1);    ans[x]=getsum(tot)-getsum(now[x]);for(int i=0;i<head[x].size();i++)    {        int temp=head[x][i];        if(!vis[temp])            dfs(temp);    }    update(now[x],-1);    return ;}bool cmp(Con a,Con b){    return a.va<b.va;}void compress(){    sort(a+1,a+n+1,cmp);    for(int i=1;i<=n;i++)    {        if(a[i].va==a[i-1].va&&i!=1)            now[a[i].num]=tot;        else            now[a[i].num]=++tot;    }}void init(){    memset(ans,0,sizeof(ans));    memset(c,0,sizeof(c));    memset(vis,0,sizeof(vis));    memset(now,0,sizeof(now));    for(int i=0;i<=n;i++)        head[i].clear();tot=0;}int main(){int T;scanf("%d",&T);while(T--){scanf("%d",&n);init();for(int i=1;i<n;i++)        {        int a,b;            scanf("%d %d",&a,&b);            add(a,b);        }        for(int i=1;i<=n;i++)        {            int value;            scanf("%d",&value);            a[i].num=i;a[i].va=value;        }        compress();        dfs(1);        for(int i=1;i<=n;i++)            printf("%d\n",ans[i]);}return 0;}














0 0
原创粉丝点击