Skip to content

Instantly share code, notes, and snippets.

@jakab922
jakab922 / centroid.py
Created April 28, 2018 21:22
Centroid tree of a tree in O(n * log_{2}(n)) time.
from collections import defaultdict as dd
def _calc_size(tree, root, found, sizes):
"""Practically a dfs on the remaining nodes
where the size of the parent node is the sum of
sizes of the child nodes."""
stack = [(root, 0)]
on_route = set([root])
@jakab922
jakab922 / sol.py
Created April 29, 2018 20:09
Code Jam 18 / 1B / Rounding Error
from heapq import heappop as pop, heappush as push
from math import floor, ceil
t = int(raw_input().strip())
def show(i, sol):
print "Case #%s: %s" % (i, sol)
@jakab922
jakab922 / dynamic_line_intersection.py
Last active April 30, 2018 06:49
Dynamic line intersection
from math import sqrt, ceil
LIMIT = 10 ** 5
n = int(raw_input().strip())
SLIMIT = int(ceil(sqrt(LIMIT)))
small = [[0] * (SLIMIT + 1) for _ in xrange(SLIMIT + 1)]
big = [0 for _ in xrange(LIMIT + 1)]
@jakab922
jakab922 / sol.py
Created April 30, 2018 10:20
Mysterious road signs
from collections import defaultdict as dd
def show(i, key, count):
print "Case #%s: %s %s" % (i, key, count)
t = int(raw_input().strip())
for ct in xrange(1, t + 1):
s = int(raw_input().strip())
@jakab922
jakab922 / bit_part.py
Created May 5, 2018 07:25
Google Code Jam 2018 / 1A / Bit Party
t = int(raw_input().strip())
M, S, P = range(3)
def show(case, sol):
print "Case #%s: %s" % (case, sol)
def transform(m, s, p, limit):
@jakab922
jakab922 / lollipop.py
Created May 5, 2018 11:39
Google Code Jam 18 / 1C / Lollipop shop
from random import choice
import sys
t = int(raw_input().strip())
LOW, HIGH = 0.005, 0.1
def calc(p, count, curr, left):
return pow(p, count) * pow(1.0 - p, curr - count) * pow(1.0 - p, left)
for case in xrange(1, t + 1):
from collections import defaultdict as dd
def fill(distances, was, backlinks, top, curr, dist):
distances[curr] = dist
was[curr] = True
while dist > 0:
distances[curr] = dist
was[curr] = True
curr = backlinks[curr][0]
from collections import defaultdict as dd
# 2SAT linear solver START
def strongly_connected(graph):
""" From Cormen: Strongly connected components chapter. """
l = len(graph)
normal = [list(graph[i]) for i in xrange(l)]
reverse = [[] for _ in xrange(l)]
for fr, tos in enumerate(normal):
@jakab922
jakab922 / beaming_with_joy.py
Created May 14, 2018 16:15
Code Jam 17/2/3
from collections import defaultdict as dd
from itertools import product
# 2SAT linear solver START
def strongly_connected(graph):
""" From Cormen: Strongly connected components chapter. """
l = len(graph)
normal = [list(graph[i]) for i in xrange(l)]
reverse = [[] for _ in xrange(l)]
@jakab922
jakab922 / palindromic_subsets.py
Created June 13, 2018 21:03
Palindromic subsets
MOD = 10 ** 9 + 7
LEFT, RIGHT = range(2)
def modpow(x, y, mod):
elems = []
while y:
elems.append(y % 2)
y >>= 1
el = len(elems)