Obtain forest out of tree with even number of nodes

后端 未结 8 627
别跟我提以往
别跟我提以往 2021-02-03 20:31

I\'m stuck on a code challenge, and I want a hint.

PROBLEM: You are given a tree data structure (without cycles) and are asked to remo

8条回答
  •  南旧
    南旧 (楼主)
    2021-02-03 21:18

    I know that this has already been answered here lots and lots of time. I still want to know reviews on my solution here. I tried to construct the child count as the edges were coming through the input and it passed all the test cases.

    namespace Hackerrank
    {
        using System;
        using System.Collections.Generic;
        using System.Linq;
    
        class Program
        {
            static void Main(string[] args)
            {
                var tempArray = Console.ReadLine().Split(' ').Select(x => Convert.ToInt32(x)).ToList();
                int verticeNumber = tempArray[0];
                int edgeNumber = tempArray[1];
    
                Dictionary childCount = new Dictionary();
    
                Dictionary parentDict = new Dictionary();
    
                for (int count = 0; count < edgeNumber; count++)
                {
                    var nodes = Console.ReadLine().Split(' ').Select(x => Convert.ToInt32(x)).ToList();
                    var node1 = nodes[0];
                    var node2 = nodes[1];
    
                    if (childCount.ContainsKey(node2))
                        childCount[node2]++;
                    else childCount.Add(node2, 1);
    
                    var parent = node2;
                    while (parentDict.ContainsKey(parent))
                    {
                        var par = parentDict[parent];
                        childCount[par]++;
                        parent = par;
                    }
    
                    parentDict[node1] = node2;
                }
    
                Console.WriteLine(childCount.Count(x => x.Value % 2 == 1) - 1);
            }
        }
    }
    

提交回复
热议问题