Created
April 24, 2016 00:33
-
-
Save jianminchen/5c6b6cb4de9c4a2faf6237b7ac331a41 to your computer and use it in GitHub Desktop.
Even Tree - study code - very readable code - https://www.hackerrank.com/rest/contests/master/challenges/even-tree/hackers/Misha2Kota/download_solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.IO; | |
using System.Text; | |
namespace EvenTree | |
{ | |
class Solution | |
{ | |
static List<Tuple<int, int>> edges = new List<Tuple<int, int>>(); | |
static int numVert; | |
static Dictionary<int, List<int>> vertIndex = new Dictionary<int, List<int>>(); | |
static void Main(string[] args) | |
{ | |
//Console.SetIn(File.OpenText(@"C:\Users\Misha2Kota\Documents\eventree.input")); | |
numVert = Int32.Parse(Console.ReadLine().Split(' ')[0]); | |
for (int i = 0; i < numVert; i++) | |
vertIndex[i] = new List<int>(); | |
for (int i = 0; i < numVert - 1; ++i) | |
{ | |
var vals = Console.ReadLine().Split(' '); | |
int v1 = int.Parse(vals[0]) - 1; | |
int v2 = int.Parse(vals[1]) - 1; | |
edges.Add(Tuple.Create(v1, v2)); | |
vertIndex[v1].Add(v2); | |
vertIndex[v2].Add(v1); | |
} | |
Console.WriteLine(Enumerable.Range(0, numVert - 1).Where(vert => canRemove(vert)).Count()); | |
} | |
static bool canRemove(int edgeInd) | |
{ | |
HashSet<int> touched = new HashSet<int>(); | |
Queue<int> verQ = new Queue<int>(); | |
var edgeUnderTest = edges[edgeInd]; | |
touched.Add(edgeUnderTest.Item1); | |
touched.Add(edgeUnderTest.Item2); | |
verQ.Enqueue(edgeUnderTest.Item2); | |
while (verQ.Count > 0) | |
{ | |
int vert = verQ.Dequeue(); | |
foreach (int connect in vertIndex[vert]) | |
{ | |
if (!touched.Contains(connect)) | |
{ | |
touched.Add(connect); | |
verQ.Enqueue(connect); | |
} | |
} | |
} | |
return touched.Count % 2 == 1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment