1039D - You Are Given a Tree - CodeForces Solution


data structures dp trees *2800

Please click on ads to support us..

C++ Code:

#include<iostream>
#include<stdio.h>
#include<math.h>
#define rg register
using namespace std;
const int N=1e5+5;
struct edge{
	int to,next;
}e[N*2];
int head[N],cnt,fa[N];
void add(int u,int v){
	e[++cnt].to=v;
	e[cnt].next=head[u];
	head[u]=cnt;
}
int f[N],ans[N],dfn[N],rev[N],idx;
void dfs(int u){
	dfn[u]=++idx;
	rev[idx]=u;
	for(rg int i=head[u];i;i=e[i].next){
		rg int v=e[i].to;
		if(v==fa[u]) continue;
		fa[v]=u;
		dfs(v);
	}
}
int read(){
	rg int x=0;
	char c=getchar();
	while(c<'0'||c>'9'){
	//	if(c=='-') flag=-1;
		c=getchar();
	}
	while(c>='0'&&c<='9'){
		x=x*10+c-'0';
		c=getchar();
	}
	return x;
}
void write(int x){
	if(x>9) write(x/10);
	putchar(x%10+'0');
}
int sol(int lim){
	int num=0,i,j,k,u,v,pos,mx1,mx2;
	for(i=idx;i>=1;--i){
		u=rev[i];
		mx1=mx2=0;
		f[u]=0;
		for(j=head[u];j;j=e[j].next){
			v=e[j].to;
			if(v==fa[u]) continue;
			if(f[v]>mx1){
				mx2=mx1,mx1=f[v];
			}
			else mx2=max(mx2,f[v]);
		}
		if(mx1+mx2+1>=lim) num++,f[u]=0;
		else f[u]=mx1+1;
	}
	return num;
}
int main(){
	int i,u,v,n,T,l,r,mid,ed,tmp;
	n=read();
	for(i=1;i<n;++i){
		u=read();v=read();
		add(u,v);add(v,u);
	}
	T=sqrt(n*log2(n));
	ans[1]=n;
	dfs(1);
	for(i=2;i<=T;++i){//对于每个点数,求最大条数
		ans[i]=sol(i);
	}
	for(i=T+1;i<=n;++i){
		tmp=sol(i);//对于每种条数,二分找最大点数
		l=i,r=n,ed=i;
		while(l<=r){
			mid=(l+r)/2;
			if(sol(mid)==tmp){
				l=mid+1;
				ed=mid;
			}
			else r=mid-1;
		}
		for(;i<=ed;++i) ans[i]=tmp;
		i--;//不然就跳了一个 
	}
	for(i=1;i<=n;++i){
		write(ans[i]);
		putchar('\n');
	} 
	return 0;
}
/*
10
4 7
5 1
8 10
3 9
6 2
1 6
6 8
2 4
8 3
*/
 	  		 						  	 	 		     			 	


Comments

Submit
0 Comments
More Questions

869. Reordered Power of 2
1593C - Save More Mice
1217. Minimum Cost to Move Chips to The Same Position
347. Top K Frequent Elements
1503. Last Moment Before All Ants Fall Out of a Plank
430. Flatten a Multilevel Doubly Linked List
1290. Convert Binary Number in a Linked List to Integer
1525. Number of Good Ways to Split a String
72. Edit Distance
563. Binary Tree Tilt
1306. Jump Game III
236. Lowest Common Ancestor of a Binary Tree
790. Domino and Tromino Tiling
878. Nth Magical Number
2099. Find Subsequence of Length K With the Largest Sum
1608A - Find Array
416. Partition Equal Subset Sum
1446. Consecutive Characters
1618A - Polycarp and Sums of Subsequences
1618B - Missing Bigram
938. Range Sum of BST
147. Insertion Sort List
310. Minimum Height Trees
2110. Number of Smooth Descent Periods of a Stock
2109. Adding Spaces to a String
2108. Find First Palindromic String in the Array
394. Decode String
902. Numbers At Most N Given Digit Set
221. Maximal Square
1200. Minimum Absolute Difference