1029E - Tree with Small Distances - CodeForces Solution


dp graphs greedy *2100

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0);cin.tie(0)
#define endl "\n"  
#define fo(i,a,n) for (int i=a;i<=n;i++)
#define ro(i,a,n) for (int i=n;i>=a;i--)
#define yes cout<<"YES"<<endl
#define no  cout<<"NO"<<endl
#define fi first
#define se second
#define pb push_back 
#define int long long
//#pragma GCC optimize(2)
using namespace std;
typedef pair<int,int> PII;
typedef long long ll;
const int N=2e5+10,mod=1000000007;
int n,m;
int a[N],d[N],st[N],f[N];
int gcd(int a, int b) {  if (b == 0) {return a;}  return gcd(b, a % b);}
// gcd(a,b,c,d)=gcd(a,gcd(b,c,d))=gcd(a,gcd(b-a,c-a,d-a))
int lcm(int a, int b) {return a * b / gcd(a, b);}
int qmi(int a, int b){int res=1%mod;a%=mod;while(b){if(b&1)res=res*a%mod;a=a*a%mod;b>>=1;}return res;} 
vector<int> e[N];
void dfs(int u,int fa){
	if(u!=1)d[u]=d[fa]+1;
	for(auto v:e[u])
	if(v!=fa)f[v]=u,dfs(v,u);
	return ;
}
signed main()
{
	IOS;cin>>n;
	fo(i,1,n-1){
		int u,v;cin>>u>>v;
		e[u].pb(v),e[v].pb(u);
	}
	dfs(1,0);
	priority_queue<PII > s; int ans=0;
	fo(i,1,n)if(d[i]>2)s.push({d[i],i});
	while(s.size()){
		auto pos=s.top();s.pop();
		int idx=pos.se;
		if(st[idx])continue ;
		st[idx]=1;ans++;
		for(auto v:e[idx])st[v]=1;
		for(auto v:e[f[idx]])st[v]=1;
	}
	cout<<ans<<endl;
	return 0;
}


Comments

Submit
0 Comments
More Questions

1244E - Minimizing Difference
1688A - Cirno's Perfect Bitmasks Classroom
219A - k-String
952A - Quirky Quantifiers
451B - Sort the Array
1505H - L BREAK into program
171E - MYSTERIOUS LANGUAGE
630D - Hexagons
1690D - Black and White Stripe
1688D - The Enchanted Forest
1674C - Infinite Replacement
712A - Memory and Crow
1676C - Most Similar Words
1681A - Game with Cards
151C - Win or Freeze
1585A - Life of a Flower
1662A - Organizing SWERC
466C - Number of Ways
1146A - Love "A"
1618D - Array and Operations
1255A - Changing Volume
1710C - XOR Triangle
415C - Mashmokh and Numbers
8A - Train and Peter
591A - Wizards' Duel
1703G - Good Key Bad Key
1705A - Mark the Photographer
1707A - Doremy's IQ
1706B - Making Towers
1325B - CopyCopyCopyCopyCopy