Skip to content

Instantly share code, notes, and snippets.

View juanplopes's full-sized avatar
🌲
Is that a Segment Tree problem?

Juan Lopes juanplopes

🌲
Is that a Segment Tree problem?
View GitHub Profile
#include <iostream>
#include <cmath>
#define ull long long
using namespace std;
ull a(ull n) {
if (n<=2) return n-1;
ull k = floor(log(n-1)/log(2));
ull p, q, m;
@juanplopes
juanplopes / avl.py
Created November 3, 2014 17:45
AVL Tree example
#to see the tree, use:
#python avl.py | dot -Tsvg | display
#requires: graphviz, imagemagick and librsvg2-bin
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.left_height = 0
M = (57, 71, 87, 97, 99, 101, 103, 113, 114, 115, 128, 129, 131, 137, 147, 156, 163, 186)
T = [1] + [0]*1024
for i in xrange(len(T)):
for m in M:
if i-m >= 0:
T[i] += T[i-m]
print T[1024]
@juanplopes
juanplopes / qsort.py
Created November 24, 2014 21:08
In-place quick sort
def partition(data, begin, end):
value = data[end-1]
pivot = begin
for i in xrange(begin, end-1):
if data[i] < value:
data[pivot], data[i] = data[i], data[pivot]
pivot += 1
data[pivot], data[end-1] = data[end-1], data[pivot]
@juanplopes
juanplopes / fib.py
Created December 19, 2014 13:34
Fibonacci in O(log n)
def mul(A, B):
return (A[0]*B[0] + A[1]*B[2], A[0]*B[1] + A[1]*B[3],
A[2]*B[0] + A[3]*B[2], A[2]*B[1] + A[3]*B[3])
def fib(n):
if n==1: return (1, 1, 1, 0)
A = fib(n>>1)
A = mul(A, A)
if n&1: A = mul(A, fib(1))
return A
@juanplopes
juanplopes / fib.py
Created December 19, 2014 14:26
Benchmark Fibonacci
from timeit import timeit
class MatrixFibonacci:
Q = [[1, 1],
[1, 0]]
def __init__(self):
self.__memo = {}
def __multiply_matrices(self, M1, M2):
import unittest, numbers
class AlmostNumber:
def __init__(self, number, delta):
self.number = number
self.delta = delta
def __eq__(self, other):
return abs(self.number-other) < self.delta
import math
def f(i, n):
if i==0: return 0
if i==1: return n/2
if i%2==0:
return f(i/2, n)-f(int(math.log(i)/math.log(2)), n)/2
else:
return f(i/2, n)+f(int(math.log(i)/math.log(2)), n)/2
def solve(number, k):
n = len(number)
stack = []
for i, digit in enumerate(str(number)):
while stack and digit < stack[-1] and n-i+len(stack) > k:
stack.pop()
if len(stack) < n - k:
stack.append(digit)
return int(''.join(stack[:k]))
@juanplopes
juanplopes / IntComparator.java
Created March 26, 2015 13:48
QConSP 2015: QuickSelect and stuff
public interface IntComparator {
public static final IntComparator DEFAULT = new IntComparator() {
@Override
public boolean lesser(int a, int b) {
return a < b;
}
};
public static final IntComparator REVERSE = new IntComparator() {
@Override