【UOJ 579】树上的颜色

【题目描述】:

给出一棵有N个点的有根树,结点编号为1,2,3,……,N,根结点编号为1,编号为i的结点涂上颜色Ci。现在有M个询问,每个询问要求求出以结点u为根的子树上涂有此种颜色的结点个数不小于k的颜色个数有多少。

【输入描述】:

第一行包含两个正整数N和M。

第二行包含N个正整数,C1,C2,…,CN。

接下来的N-1行每行有两个正整数x和y,表示结点x和y有边相连。

再接下来的M行每行有两个正整数u和k,表示一个询问。

【输出描述】:

输出M行,每行一个非负整数,对应每个询问的答案。

【样例输入1】:

4 1
1 2 3 4
1 2
2 3
3 4
1 1

【样例输出1】:

4

【样例输入2】:

8 5
1 2 2 3 3 2 3 3
1 2
1 5
2 3
2 4
5 6
5 7
5 8
1 2
1 3
1 4
2 3
5 3

【样例输出2】:

2
2
1
0
1

【时间限制、数据范围及描述】:

时间:1s 空间:256M

对于10%的数据,N≤100,M≤100,Ci≤100;

对于30%的数据,N≤500,M≤100;

对于60%的数据,N≤2000,M≤100000;

对于100%的数据,N≤100000,M≤100000,Ci≤100000。

题解:为啥我暴力分都拿不到……百思不得其解,如果有dalao看出错误,就留个言吧,谢谢您了

#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;
const int N=100002;
int n,ques,x,y;
struct node{
    int u,v,next;
}a[N];
int h[N],cnt,ans;
int c[N];
int z,fj[N],biu[N];

void add(int u,int v){
    a[++cnt].u=u; a[cnt].v=v;
    a[cnt].next=h[u]; h[u]=cnt;
}

void init(){
    scanf("%d %d",&n,&ques);
    for(int i=1;i<=n;i++)
        scanf("%d",&c[i]);
    for(int i=1;i<n;i++){
        scanf("%d %d",&x,&y); 
        add(x,y);
    }
}

void dfs(int x){
    for(int i=h[x];i;i=a[i].next) 
        { int v=a[i].v; fj[c[v]]++; dfs(v); }
}

void work(){
    while(ques--){
        scanf("%d %d",&x,&y);
        int ans=0;
        memset(fj,0,sizeof(fj));
        memset(biu,0,sizeof(biu));
        fj[c[x]]++; dfs(x);
        for(int i=1;i<=n;i++){
            if(fj[c[i]]>=y && biu[c[i]]==0) 
               { ans++; biu[c[i]]=1; }
        }
        printf("%d\n",ans);
    }
    
}
int main(){
    freopen("579.in","r",stdin);
    freopen("579.out","w",stdout);
    init(); work();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wuhu-JJJ/p/11518014.html