24分求助!!!
查看原帖
24分求助!!!
371168
Peter2020楼主2023/8/10 18:24
#include <iostream>
#include <vector>
#include <algorithm>
#define int long long
using namespace std;
const int N = 1e5+10;
int read(){
	int a = 0, f = 1;
	char c = getchar();
	while(c>'9'||c<'0'){
		if(c == '-')
			f = -1;
		c = getchar();
	}
	while(c>='0'&&c<='9'){
		a = a*10+c-'0';
		c = getchar();
	}
	return a*f;
}
void write(int x){
	if(x < 0){
		putchar('-');
		x = -x;
	}
	if(x > 9) write(x/10);
	putchar(x%10+'0');
}
int n, s[N];
int p[N];
struct node{
	int u, v;
}e[N];
vector<int> G[N];
int dfs(int cur){
	int l=G[cur].size();
	if(l==0) return 0;
	int ans=0;
	while(s[cur]<=l){
		s[cur]*=2;
		ans++;
	}
	ans+=l;
	s[cur]-=l;
	for(int i=0;i<l;i++){
		int id=G[cur][i];
		s[id]++;
		ans+=dfs(id);
	}
	return ans;
}
signed main(){
	n = read();
	for(int i=1;i<=n;i++) p[i]=N;
	p[1]=0;
	for(int i=1;i<n;i++){
		e[i].u = read();
		e[i].v = read();
		if(e[i].u > e[i].v) swap(e[i].u,e[i].v);
	}
	sort(e+1,e+n,[&](node a, node b){
		return a.u < b.u;
	});
	for(int i=1;i<n;i++){
		int u=e[i].u;
		int v=e[i].v;
		if(p[v]==N){
			G[u].push_back(v);
			p[v] = p[u]+1;
		}else{
			G[v].push_back(u);
			p[u] = p[v]+1;
		}
	}
	s[1] = 1;
	int ans=dfs(1);
	write(ans);
	return 0;
}

24分,求助大佬,帮我看一下

2023/8/10 18:24
加载中...