Obtain forest out of tree with even number of nodes

后端 未结 8 499
别跟我提以往
别跟我提以往 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:15

    Solution - Traverse all the edges, and count the number of even edges

    If we remove an edge from the tree and it results in two tree with even number of vertices, let's call that edge - even edge

    If we remove an edge from the tree and it results in two trees with odd number of vertices, let's call that edge - odd edge

    Here is my solution in Ruby

    num_vertices, num_edges = gets.chomp.split(' ').map { |e| e.to_i }
    graph = Graph.new
    (1..num_vertices).to_a.each do |vertex|
      graph.add_node_by_val(vertex)
    end
    
    num_edges.times do |edge|
      first, second = gets.chomp.split(' ').map { |e| e.to_i }
      graph.add_edge_by_val(first, second, 0, false)
    end
    
    even_edges = 0
    graph.edges.each do |edge|
      dup = graph.deep_dup
      first_tree = nil
      second_tree = nil
      subject_edge = nil
      dup.edges.each do |e|
        if e.first.value == edge.first.value && e.second.value == edge.second.value
          subject_edge = e
          first_tree = e.first
          second_tree = e.second
        end
      end
      dup.remove_edge(subject_edge)
      if first_tree.size.even? && second_tree.size.even?
        even_edges += 1
      end
    end
    puts even_edges
    

    Note - Click Here to check out the code for Graph, Node and Edge classes

提交回复
热议问题