第一行输出小了很多
查看原帖
第一行输出小了很多
526629
Bot_wxt1221楼主2022/10/27 09:24

求调

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
inline int read(){
	int temp;
    scanf("%d",&temp);
    return temp;
}
int now;
int fir[600005];
int nxt[600005];
int v[600005];
int ans[600005];
void add(int a,int b){
    now++;
    v[now]=b;
    nxt[now]=fir[a];
    fir[a]=now;
    return ;
}
int a[6000005];
int to[6000005][30];
int dep[6000005];
void dfs(int now,int fa);
void dfs2(int now,int fa);
int getfa(int a,int b){
    if(dep[a]>dep[b]){
		swap(a,b);
	}//de[a]<de[b]
	while(dep[a]!=dep[b]){
		int i=0;
		while(dep[to[b][i+1]]>dep[a]){
			i++;
		}
		b=to[b][i];
	}
	if(a==b){
		return a;
	}
	int i=1;
	while(1){
		if(to[a][i]==to[b][i]){
			if(i==0){
				break;
			}
			a=to[a][i-1];
			b=to[b][i-1];
			i=0;
		}else{
			i++;
		}
	}
    return a;
}
int temp[3000005];

int main(){
	#ifdef ONLINE_JUDGE=LUOGU
	#else
	freopen("P3258_1.in","r",stdin);
	freopen(".out","w",stdout);
	#endif
	int n=read();
    for(int i=1;i<=n;i++){
        fir[i]=-1;
        a[i]=read();
    }
    for(int i=1;i<n;i++){
        int a=read();
        int b=read();
        add(a,b);
        add(b,a);
    }
    dfs(1,0);
    to[1][0]=1;
    for(int i=1;i<=log2(n);i++){
        for(int j=1;j<=n;j++){
            to[j][i]=to[to[j][i-1]][i-1];
        }
    }
    for(int i=1;i<n;i++){
        int temp=getfa(a[i],a[i+1]);
        ::temp[temp]+=-1;
        if(temp!=1)
           ::temp[to[temp][0]]+=-1;
        else
            ::temp[0]--;
        ::temp[a[i]]++;
        ::temp[a[i+1]]++;
    }
    dfs2(1,0);
    for(int i=2;i<=n;i++){
		ans[a[i]]--;
	}
    for(int i=1;i<=n;i++){
        printf("%d\n",ans[i]);
    }
	return 0;
}
void dfs(int now,int fa){
    to[now][0]=fa;
    dep[now]=dep[fa]+1;
    for(int i=fir[now];i!=-1;i=nxt[i]){
        if(v[i]!=fa)
            dfs(v[i],now);
    }
    return ;
}
void dfs2(int now,int fa){
    ans[now]=temp[now];
    for(int i=fir[now];i!=-1;i=nxt[i]){
        if(v[i]!=fa){
            dfs2(v[i],now);
            ans[now]+=ans[v[i]];
        }
    }
    return ;
}
/*
Anything about this program:
Type:

Description:

Example:
	1:
		In:

		Out:
More:

*/

2022/10/27 09:24
加载中...