Total passenger garlic Informatics popular group before the analog # 1 D ancestors

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Glynn/article/details/102760843

Total passenger garlic Informatics popular group before the analog # 1

D ancestors

show me the code.

#include<cstdio>
#include<cctype>

template<typename T>inline void read(T &a){
    char c=getchar();T x=0,f=1;
    while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
    while( isdigit(c)){x=(x<<1)+(x<<3)+(c^48);c=getchar();}
    a=f*x;
}

const int N=1000005;
const int mod=1e9+7; 
int n,m,root,p;
long long siz[N],sum[N],ans[N];
struct node{ int next,to; } edge[N<<1];
int idx=0,head[N];

inline void add(int u,int v){
    edge[++idx].next=head[u];
    edge[idx].to=v;
    head[u]=idx;
}

inline void dfs(int x,int f){
    siz[x]=1;
    for(int i=head[x];i;i=edge[i].next){
        int t=edge[i].to;
        if(t==f)continue;
        dfs(t,x);
        siz[x]+=siz[t];
        sum[x]+=siz[t]*siz[t];
    }
    ans[x]=siz[x]*siz[x]-sum[x];
}

int main(){
    read(n);read(m);read(root);
    for(int i=1,u,v;i<n;i++) read(u),read(v),add(u,v),add(v,u);
    dfs(root,0);
    while(m--) read(p),printf("%d\n",ans[p]%mod);
    return 0;
}

 

Guess you like

Origin blog.csdn.net/Glynn/article/details/102760843
Recommended