-
-
Save taksatou/f22569247e08b9a72a87 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
#!/usr/bin/env ruby | |
class Node | |
attr_accessor :size, :num, :left, :right | |
def initialize(n) | |
self.size = 1 | |
self.num = n | |
self.left = nil | |
self.right = nil | |
end | |
def insert(node) | |
self.size += 1 | |
if self.num < node.num | |
if self.right.nil? | |
self.right = node | |
return 0 | |
else | |
return self.right.insert(node) | |
end | |
else | |
if self.left.nil? | |
self.left = node | |
return self.size - 1 | |
else | |
return self.left.insert(node) + 1 + (self.right.nil? ? 0 : self.right.size) | |
end | |
end | |
end | |
end | |
def solve(lis) | |
sum = 0 | |
root = Node.new lis.shift | |
lis.each do |e| | |
sum += root.insert(Node.new(e)) | |
end | |
sum | |
end | |
if __FILE__ == $0 | |
lis = ARGF.read.split | |
puts solve(lis) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment