Saturday, 25 July 2015

Even Tree in c++ Hackerrank solution


You are given a tree (a simple connected graph with no cycles). You have to remove as many edges from the tree as possible to obtain a forest with the condition that : Each connected component of the forest  should contain an even number of vertices.
To accomplish this, you will remove some edges from the tree. Find out the number of removed edges.
Input Format
The first line of input contains two integers N and M. N is the number of vertices and M is the number of edges.
The next M lines contain two integers ui and vi which specifies an edge of the tree. (1-based index)
Output Format
Print the answer, a single integer.
Constraints
2 <= N <= 100.
Note: The tree in the input will be such that it can always be decomposed into components containing even number of nodes.

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int V,E;
    cin>>V>>E;
    int array[E][2];
    for(int i=0;i<E;i++)
    {
         cin>>array[i][0]>>array[i][1];
    }
    int count[V+1];
    for(int j=0;j<=V;j++)
    {
        count[j]=1;
    }
    for(int k=0;k<E;k++)
    {
        count[array[k][1]]=0;
    }

  int c=0,l;
    for(int i=V;i>=0;i--)
    {
        if(count[i]==0)
        {
            for(int k=0;k<E;k++)
            {
                if(array[k][1]== i)
                {   l=array[k][0];
                    if(count[l]%2 != 0)
                    {
                    c=c+count[l];
                    }
                 }
            }
            count[i]=c+1;
        }
        c=0;
    }
    int t=0;
    for(int i=0;i<=V;i++)
        {
            if(count[i]%2 == 0)
            {
                t=t+1;
            }
        }

        cout<<(t-1)<<endl;
    return 0;
}

2 comments:

  1. Can you please explain? Elaborate?

    ReplyDelete
    Replies
    1. http://stackoverflow.com/questions/12043252/obtain-forest-out-of-tree-with-even-number-of-nodes....use the same concept that mention in top of this page

      Delete