60pts求调
查看原帖
60pts求调
342941
ztjp13楼主2024/7/28 18:32

记录详情

#include<bits/stdc++.h>
using namespace std;

const int maxn=2*1000005;

int n,tot,ans,Root,flag,num;
int color[maxn],vis[maxn],dep[maxn];
int ver[maxn],head[maxn],Next[maxn];

inline int read(){
	int f=1,k=0;
	char c=getchar();
	while(c<'0'||c>'9'){
		if(c=='-') f=-1;
		c=getchar();
	}
	while(c>='0'&&c<='9'){
		k=k*10+c-'0';
		c=getchar();
	}
	return f*k;
}

void add(int x,int y){
	ver[++tot]=y; Next[tot]=head[x]; head[x]=tot;
} 

void dfs(int x,int step){
	vis[x]=true;
	for(int i=head[x];i;i=Next[i]){
		int y=ver[i];
		if(!vis[y]){
			if(color[y]>0){
				ans+=step;
				dfs(y,0);
			} 
			else dfs(y,step+1);
		}
	}
}

int main(){
	n=read();
	for(int i=1;i<=n;i++){
		color[i]=read();
		if(color[i]==0) num++;
	} 
	for(int i=1;i<n;i++){		
		int x=read(),y=read();
		add(x,y); add(y,x);
	}
	for(int i=1;i<=n;i++){
		if(color[i]>0){
			dfs(i,0); 
			break;
		}
	}
	cout<<ans<<endl;
	return 0;
}
2024/7/28 18:32
加载中...