Counting removing edges to make it forest of even nodes. (dfs applin)



https://www.hackerrank.com/challenges/even-tree

Even Tree (dfs application )

In this question we have to count what is the maximum number of forests (of even nodes)
 that can be made by removal of minimum edges.


Here child returns its parent the no. of nodes ,if the number of nodes(including parent itself ) is even
then ans=ans+1;


#include<bits/stdc++.h>

using namespace std;

int ans=0,visited[100000];

vector<int> v[100000];

int dfs(int nod)
{
    visited[nod]=1;


   int  total=1;                  ///self count

   if(v[nod].size()==1 && nod!=1)
    return 1;                /// the leaf child gives 1 to parent

  for(int i=0;i<v[nod].size();i++)
  {
     if(visited[v[nod][i]]==0)
      total+=dfs(v[nod][i]);
  }

  if(total%2==0)
        ans++;


  visited[nod]=0;

  return total;
}



int main()
{
 int n,e,i,j,k,a,b,l;
 cin>>n>>e;


 for(i=1;i<=e;i++)
 {
  cin>>a>>b;
  v[a].push_back(b);
  v[b].push_back(a);
 }

 int kk=dfs(1);

 cout<<ans-1<<endl;

return 0;
}

Comments

Popular posts from this blog

Getting Started With MEAN App Development with AngularJs , ExpressJs , NodeJs and MongoDB.

B. Dreamoon and WiFi :calculate no. of ways : recursive solution (branch and bound )

A. Dreamoon and Stairs : minimum steps to reach : recursion solution.