悬关求助10tps 下了测试点发现第一个输出比答案输出大1
查看原帖
悬关求助10tps 下了测试点发现第一个输出比答案输出大1
1286488
Xuan3579楼主2024/7/22 21:55
#include<bits/stdc++.h>
using namespace std;

const int N = 3e5 + 3;

int n, m, size[N], son[N], f[N], dep[N], top[N], vel[N], a[N], ans[N];

int read(){
	int x = 1, s = 0;
	char ch = getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')x=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){s=s*10+ch-'0';ch=getchar();}
	return x * s;
}

vector <int> e[N];

void dfs1(int x, int fa){
	size[x] = 1; f[x] = fa; dep[x] = dep[fa] + 1;
	for(auto to : e[x]){
		if(to == fa)continue;
		dfs1(to, x);
		size[x] += size[to];
		if(size[to] > size[son[x]])
			son[x] = to;
	}
}

void dfs2(int x, int rt){
	top[x] = rt;
	if(!son[x])return ;
	dfs2(son[x], rt);	
	for(auto to : e[x]){
		if(to == f[x] || to == son[x])
			continue;
		dfs2(to, to);
	}
}

int LCA(int x, int y){
	while(top[x] != top[y]){
		if(dep[top[x]] < dep[top[y]])
			swap(x, y);
		x = f[top[x]];
	}
	if(dep[x] < dep[y])return x;
	return y; 
}

void dfs3(int x){
	for(auto to : e[x]){
		if(to == f[x])continue;
		dfs3(to);
		vel[x] += vel[to];
	}
	ans[x] = vel[x];
}

int main(){
//	freopen("P3258_1.in", "r", stdin);
//	freopen("ans.out", "w", stdout);
	n = read();
	for(int i = 1; i <= n; i++)
		a[i] = read();
	for(int i = 1, x, y; i < n; i++){
		x = read(); y = read();
		e[x].push_back(y);
		e[y].push_back(x); 
	}
	dfs1(1, 0);
	dfs2(1, 1);
	int x, y;
	for(int i = 1; i < n; i++){
		x = a[i]; y = a[i + 1];
		int lca = LCA(x, y);
		vel[x]++; vel[y]++;	
		vel[lca]--;
		vel[f[lca]]--;
	}
	dfs3(1);
	int maxx = 0;
	cout << ans[1] << "\n";
	for(int i = 2; i <= n; i++){
		cout << ans[i] - 1 << "\n";
	}
	return 0;
}
2024/7/22 21:55
加载中...