Created
November 7, 2014 22:37
-
-
Save ktusznio/60cd8c3d3369c5cee8ea to your computer and use it in GitHub Desktop.
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
def solution(strengths, weights, connections) | |
# simulate the order by going through the conections and building the graph | |
# at each step, evaluate the graph to detect breaks | |
# at each step, attach the weight, then travel up the graph and check for breaks O(n * log(n)) | |
# data structure: | |
# node(parent_node, strength, weight (incl. children), children) | |
# map(i: node) | |
# create root node | |
map = {} | |
count = 0 | |
# at each step: | |
# get parent node | |
# create new node and attach | |
# start with new node weight, travel up parent, check whether strength < weight + added_weight | |
connections.each_with_index do |parent_index, i| | |
parent = map[parent_index] | |
node = Node.new(weights[i], strengths[i], parent) | |
map[i] = node | |
if parent | |
parent.add_weight(node.weight) | |
end | |
if node.valid? | |
count += 1 | |
else | |
return count | |
end | |
end | |
count | |
end | |
class Node | |
attr_reader :parent, :strength, :weight | |
def initialize(weight, strength, parent) | |
@weight = weight | |
@strength = strength | |
@parent = parent | |
@children = [] | |
end | |
def add_weight(weight) | |
@weight += weight | |
if parent | |
parent.add_weight(weight) | |
end | |
end | |
def valid? | |
weight <= strength && (parent.nil? || parent.valid?) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment