From 2697a4567e78b372ea1615990acd02901c1fd1fc Mon Sep 17 00:00:00 2001 From: Adarsh <46349391+4d4r5h@users.noreply.github.com> Date: Mon, 10 Oct 2022 20:51:57 +0530 Subject: [PATCH] Create Finding a Centroid.cpp --- cses/Finding a Centroid.cpp | 85 +++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 cses/Finding a Centroid.cpp diff --git a/cses/Finding a Centroid.cpp b/cses/Finding a Centroid.cpp new file mode 100644 index 0000000..ce29adf --- /dev/null +++ b/cses/Finding a Centroid.cpp @@ -0,0 +1,85 @@ +// Centroid of a tree is a node such that when it is appointed the root of the tree, each subtree has at most floor(n/2) nodes (n = number of nodes in the graph). +// A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), +// the size of the largest connected component of the remaining graph is the smallest possible (which is at most floor(n/2)) +// A tree may have one centroid or may have two centroids. If it has two centroids, they are always connected. + +#include +#define pb(x) push_back(x) +#define all(x) (x).begin(), (x).end() +#define rall(x) (x).rbegin(), (x).rend() +#define F(w,x,y) for(ll w=x; w adj[200001]; +ll subtreeSize[200001]; +int vis[200001]; + +void dfs(ll node) +{ + subtreeSize[node]=1; + + for(auto x:adj[node]) + { + if(subtreeSize[x]==-1) + { + dfs(x); + subtreeSize[node]+=subtreeSize[x]; + } + } +} + +ll centroid(ll node) +{ + vis[node]=1; + + for(auto x:adj[node]) + { + if(!vis[x]) + { + if(subtreeSize[x]>(n/2)) + return centroid(x); + } + } + + return node; +} + +void play() +{ + memset(subtreeSize,-1,sizeof(subtreeSize)); + ll a,b; + cin>>n; + F(i,1,n) + { + cin>>a>>b; + adj[a].pb(b); + adj[b].pb(a); + } + + dfs(1); + + cout<>t; + F(i,1,t+1) + { + //cout<<"Case #"<