Problem:


Score: 500 points

Problem Statement

We have caught N sardines. The deliciousness and fragrantness of the i-th sardine is A_i and B_i, respectively.

We will choose one or more of these sardines and put them into a cooler. However, two sardines on bad terms cannot be chosen at the same time.

The i-th and j-th sardines (i \neq j) are on bad terms if and only if A_i \cdot A_j + B_i \cdot B_j = 0.

In how many ways can we choose the set of sardines to put into the cooler? Since the count can be enormous, print it modulo 1000000007.

Constraints

All values in input are integers.

1 \leq N \leq 2 \times 10^5

-10^{18} \leq A_i, B_i \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the count modulo 1000000007.

Sample Input 1

3
1 2
-1 1
2 -1

Sample Output 1

5

There are five ways to choose the set of sardines, as follows:

The 1-st

The 1-st and 2-nd

The 2-nd

The 2-nd and 3-rd

The 3-rd

Sample Input 2

10
3 2
3 2
-1 1
2 -1
-3 -9
-8 12
7 7
8 1
8 2
8 4

Sample Output 2

479



Sample input:
3
1 2
-1 1
2 -1


Sample output:
5

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

import sys
# import time
import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n = ii()
    theta = []
    zero_zero_cnt = 0
    for i in range(n):
        a, b = mi()
        if a == 0 and b == 0:
            zero_zero_cnt += 1
        elif a == 0:
            tmp = 90.0 if b > 0 else -90.0
            theta.append(tmp)
        elif b == 0:
            tmp = 0.0 if b > 0 else -180.0
            theta.append(tmp)
        else:
            tmp = math.degrees(math.atan(b / a))
            theta.append(tmp)
    theta.sort()
    # print(theta)

    eps = 10 ** (-6)
    compressed_theta = []
    cnt_theta = []
    prev = inf
    for i in range(len(theta)):
        if prev - eps <= theta[i] <= prev + eps:
            cnt_theta[-1] += 1
            prev = theta[i]
        else:
            compressed_theta.append(theta[i])
            cnt_theta.append(1)
            prev = theta[i]

    pairs = []
    no_pair_ind = set(range(len(compressed_theta)))
    for i, dg in enumerate(compressed_theta):
        l_ind = bisect_left(theta, dg - 90 - eps)
        r_ind = bisect_right(theta, dg - 90 + eps)
        if l_ind != r_ind:
            assert(l_ind + 1 == r_ind)
            pairs.append((cnt_theta[l_ind], cnt_theta[i]))
            if l_ind in no_pair_ind:
                no_pair_ind.remove(l_ind)
            if i in no_pair_ind:
                no_pair_ind.remove(i)
    
    num_of_no_pairs = sum([cnt_theta[ind] for ind in no_pair_ind])

    ans = pow(2, num_of_no_pairs, mod)
    for k, l in pairs:
        ans = (ans * (1 + pow(2, k, mod) - 1 + pow(2, l, mod) - 1)) % mod
    ans -= 1

    ans += zero_zero_cnt
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from collections import defaultdict
import sys
from fractions import Fraction

count = defaultdict(int)
N = int(sys.stdin.readline())

edges = defaultdict(list)
for i in range(N):
    A, B = [int(x) for x in sys.stdin.readline().split()]
    if B == 0:
        angle = "I"
    else:
        angle = Fraction(A, B)
    count[angle] += 1

ZERO = Fraction(0, 1)
pairs = {}
solos = []
for k1 in count:
    if k1 in pairs:
        continue
    if k1 == "I":
        if ZERO in count:
            pairs[ZERO] = k1
        continue

    k2 = -1 / k1
    if k2 in count:
        pairs[k2] = k1
    else:
        solos.append(k1)
# print(pairs, solos)

P = 1000000007


def pow2(n):
    if n < 30:
        return 2 ** n

    p = pow2(n // 2)
    pp = (p * p) % P
    if n % 2 == 1:
        return (2 * pp) % P
    else:
        return pp


result = 1
for p in pairs:
    # print("pair", p, count[p], pairs[p], count[pairs[p]])
    n = count[p]
    m = count[pairs[p]]
    result = result * ((pow2(n) - 1) + (pow2(m) - 1) + 1) % P
for k in solos:
    # print("solo", k, count[k])
    result = result * pow2(count[k]) % P

print(result - 1)

Submission status: Runtime Error

Solution code:
import math
MOD = 1e+9+7
N = int(input())

d_p = dict()
d_m = dict()
ans = 1
zz = 0

for n in range(N):
    a,b = map(int,input().split())

    if a==0 and b==0:
        zz += 1
        continue
    if a==0:
        n_sign = 0
        b = 0
    elif b==0:
        n_sign = 1
        a = 0

    else:    
        n_sign = ((a<0) + (b<0))%2
        a = abs(a)
        b = abs(b)
        gcd = math.gcd(a,b)
        a//=gcd
        b//=gcd

    if n_sign==1:
        s =str(b)+'/'+str(a)
        d_m[s] = d_m.get(s,0) + 1
    elif n_sign==0:
        s =str(a)+'/'+str(b)
        d_p[s] = d_p.get(s,0) + 1      

for k,v in d_m.items():
    if k in d_p:
        ans *= (2**v + 2**d_p[k] - 1)
        d_p.pop(k)
    else:
        ans *= 2**v
    ans %= MOD

for k,v in d_p.items():
    ans *= 2**v
    ans %= MOD
    
ans -= 1
ans += zz
ans %= MOD
print (ans)

Submission status: Runtime Error

Solution code:
from collections import Counter, defaultdict
import sys
input = sys.stdin.readline

n = int(input())
ab = [list(map(int, input().split())) for _ in range(n)]
mod = 1000000007

zero = sum([1 for a, b in ab if a ==  b == 0])
adivb = [(float('inf') if b == 0 else a / b)
         for a, b in ab if not(a == b == 0)]
bdiva = [(float('inf') if a == 0 else -b / a)
         for a, b in ab if not(a == b == 0)]

adb, bda = Counter(adivb), Counter(bdiva)
cntadb, cnt = defaultdict(int), 0
for i in adb:
    if (i in bda) and (i >= 0):
        cntadb[i] += 2 ** bda[i] + 2 ** adb[i] - 1
        cnt += bda[i] + adb[i]
ans = 1
for i in cntadb:
    ans *= cntadb[i]
print(int(ans * 2 ** (n - cnt - zero) + zero - 1) % mod)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

import sys
# import time
import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n = ii()
    theta = []
    zero_zero_cnt = 0
    for i in range(n):
        a, b = mi()
        if a == 0 and b == 0:
            zero_zero_cnt += 1
        elif a == 0:
            tmp = 90.0 if b > 0 else -90.0
            theta.append(tmp)
        elif b == 0:
            tmp = 0.0 if b > 0 else -180.0
            theta.append(tmp)
        else:
            tmp = math.degrees(math.atan(b / a))
            theta.append(tmp)
    theta.sort()
    # print(theta)

    eps = 10 ** (-4)
    compressed_theta = []
    cnt_theta = []
    prev = inf
    for i in range(len(theta)):
        if prev - eps <= theta[i] <= prev + eps:
            cnt_theta[-1] += 1
            prev = theta[i]
        else:
            compressed_theta.append(theta[i])
            cnt_theta.append(1)
            prev = theta[i]

    pairs = []
    no_pair_ind = set(range(len(compressed_theta)))
    for i, dg in enumerate(compressed_theta):
        l_ind = bisect_left(theta, dg - 90 - eps)
        r_ind = bisect_right(theta, dg - 90 + eps)
        if l_ind != r_ind:
            # assert(r_ind == l_ind + 1)
            print('moo')
            pairs.append((cnt_theta[l_ind], cnt_theta[i]))
            no_pair_ind.remove(l_ind)
            no_pair_ind.remove(i)
    
    num_of_no_pairs = sum([cnt_theta[ind] for ind in no_pair_ind])

    ans = pow(2, num_of_no_pairs, mod)
    for k, l in pairs:
        ans = (ans * (1 + pow(2, k, mod) - 1 + pow(2, l, mod) - 1)) % mod
    ans -= 1

    ans += zero_zero_cnt
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import math


def main():

    mod = 1000000007
    N = int(input())

    A = [0]
    B = [0]

    for n in range(N):
        a, b = map(int, input().split())
        A.append(a)
        B.append(b)

    calc = dict()

    for i in range(1, N + 1):
        r = math.gcd(A[i], B[i])
        m = 1
        if A[i] * B[i] < 0:
            m = -1

        k1 = (m * abs(A[i] // r), abs(B[i] // r))
        k2 = (-m * abs(B[i] // r), abs(A[i] // r))
        if calc.get(k1):
            calc[k1][0] += 1
        elif not calc.get(k2):
            calc[k1] = [1, 0]

    for i in range(1, N + 1):
        r = math.gcd(A[i], B[i])
        m = 1
        if A[i] * B[i] < 0:
            m = -1

        k2 = (-m * abs(B[i] // r), abs(A[i] // r))
        if calc.get(k2):
            calc[k2][1] += 1

    count = 0
    for k, v in calc.items():
        if not v[0] * v[1] == 0:
            count += v[0] + v[1]

    ans = pow(2, N - count, mod)
    for k, v in calc.items():
        if not v[0] * v[1] == 0:
            comb = (pow(2, v[0]) + pow(2, v[1]) - 1)
            ans = (ans * comb) % mod

    print(ans - 1)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

import sys
# import time
import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n = ii()
    theta = []
    zero_zero_cnt = 0
    for i in range(n):
        a, b = mi()
        if a == 0 and b == 0:
            zero_zero_cnt += 1
        elif a == 0:
            tmp = 90.0 if b > 0 else -90.0
            theta.append(tmp)
        elif b == 0:
            tmp = 0.0 if b > 0 else -180.0
            theta.append(tmp)
        else:
            tmp = math.degrees(math.atan(b / a))
            theta.append(tmp)
    theta.sort()
    # print(theta)

    eps = 10 ** (-4)
    compressed_theta = []
    cnt_theta = []
    prev = inf
    for i in range(len(theta)):
        if prev - eps <= theta[i] <= prev + eps:
            cnt_theta[-1] += 1
            prev = theta[i]
        else:
            compressed_theta.append(theta[i])
            cnt_theta.append(1)
            prev = theta[i]

    pairs = []
    no_pair_ind = set(range(len(compressed_theta)))
    for i, dg in enumerate(compressed_theta):
        l_ind = bisect_left(theta, dg - 90 - eps)
        r_ind = bisect_right(theta, dg - 90 + eps)
        if l_ind != r_ind:
            assert(r_ind == l_ind + 1)
            pairs.append((cnt_theta[l_ind], cnt_theta[i]))
            no_pair_ind.remove(l_ind)
            no_pair_ind.remove(i)
    
    num_of_no_pairs = sum([cnt_theta[ind] for ind in no_pair_ind])

    ans = pow(2, num_of_no_pairs, mod)
    for k, l in pairs:
        ans = (ans * (1 + pow(2, k, mod) - 1 + pow(2, l, mod) - 1)) % mod
    ans -= 1

    ans += zero_zero_cnt
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from collections import Counter, defaultdict
import sys
input = sys.stdin.readline

n = int(input())
ab = [list(map(int, input().split())) for _ in range(n)]
mod = 1000000007

zero = sum([1 for a, b in ab if a ==  b == 0])
adivb = [(float('inf') if b == 0 else a / b)
         for a, b in ab if not(a == b == 0)]
bdiva = [(float('inf') if a == 0 else -b / a)
         for a, b in ab if not(a == b == 0)]

adb, bda = Counter(adivb), Counter(bdiva)
cntadb, cnt = defaultdict(float), 0
for i in adb:
    if (i in bda) and (i >= 0):
        cntadb[i] += 2 ** bda[i] + 2 ** adb[i] - 1
        cnt += bda[i] + adb[i]
ans = 1
for i in cntadb:
    ans *= cntadb[i]
print(int(ans * 2 ** (n - cnt - zero) + zero - 1) % mod)

Submission status: Runtime Error

Solution code:
import math
import itertools

n = int(input())
mod = 1000000007

def Is_Positive(n):
    return n > 0

vectors = dict()
for i in range(n):
    a, b = map(int, input().split())
    gcd = math.gcd(a, b)

    key = (0, 0)
    if Is_Positive(a) and Is_Positive(b):
        key = (abs(a) // gcd, abs(b) // gcd)
        if key not in vectors:
            vectors[key] = (1, 0)
        else:
            vectors[key] = (vectors[key][0] + 1, vectors[key][1])
    else:
        key = (abs(b) // gcd, abs(a) // gcd)
        if key not in vectors:
            vectors[key] = (0, 1)
        else:
            vectors[key] = (vectors[key][0], vectors[key][1] + 1)



total = 1
for vec in vectors.values():

    total *= (1 + (2**(vec[0])-1)
              + (2**(vec[1])-1)) % mod

print(total- 1)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

import sys
# import time
import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n = ii()
    theta = [0] * n
    zero_zero_cnt = 0
    for i in range(n):
        a, b = mi()
        if a == 0 and b == 0:
            zero_zero_cnt += 1
        elif a == 0:
            theta[i] = 90.0 if b > 0 else -90.0
        elif b == 0:
            theta[i] = 0.0 if b > 0 else -180.0
        else:
            theta[i] = math.degrees(math.atan(b / a))
    theta.sort()
    # print(theta)

    eps = 10 ** (-4)
    compressed_theta = []
    cnt_theta = []
    prev = inf
    for i in range(n):
        if prev - eps <= theta[i] <= prev + eps:
            cnt_theta[-1] += 1
            prev = theta[i]
        else:
            compressed_theta.append(theta[i])
            cnt_theta.append(1)
            prev = theta[i]

    pairs = []
    no_pair_ind = set(range(len(compressed_theta)))
    for i, dg in enumerate(compressed_theta):
        l_ind = bisect_left(theta, dg - 90 - eps)
        r_ind = bisect_right(theta, dg - 90 + eps)
        if l_ind != r_ind:
            assert(r_ind == l_ind + 1)
            pairs.append((cnt_theta[l_ind], cnt_theta[i]))
            no_pair_ind.remove(l_ind)
            no_pair_ind.remove(i)
    
    num_of_no_pairs = sum([cnt_theta[ind] for ind in no_pair_ind])

    ans = pow(2, num_of_no_pairs, mod)
    for k, l in pairs:
        ans = (ans * (1 + pow(2, k, mod) - 1 + pow(2, l, mod) - 1)) % mod
    ans -= 1

    ans += zero_zero_cnt
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from collections import Counter, defaultdict
import sys
input = sys.stdin.readline

n = int(input())
ab = [list(map(int, input().split())) for _ in range(n)]
mod = 1000000007

zero = sum([1 for a, b in ab if (a == 0 and b == 0)])
adivb = [(float('inf') if b == 0 else a / b)
         for a, b in ab if not(a == b == 0)]
bdiva = [(float('inf') if a == 0 else -b / a)
         for a, b in ab if not(a == b == 0)]

adb, bda = Counter(adivb), Counter(bdiva)
cntadb, cnt = defaultdict(int), 0
for i in adb:
    if (i in bda) and (i >= 0):
        cntadb[i] += 2 ** bda[i] + 2 ** adb[i] - 1
        cnt += bda[i] + adb[i]
ans = 1
for i in cntadb:
    ans *= cntadb[i]
print((ans * 2 ** (n - cnt - zero) + zero - 1) % mod)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
import sys
from fractions import Fraction

count = defaultdict(int)
N = int(sys.stdin.readline())

edges = defaultdict(list)
for i in range(N):
    A, B = [int(x) for x in sys.stdin.readline().split()]
    if B == 0:
        angle = "I"
    else:
        angle = Fraction(A, B)
    count[angle] += 1

ZERO = Fraction(0, 1)
pairs = {}
solos = []
for k1 in count:
    if k1 in pairs:
        continue
    if k1 == "I":
        if ZERO in count:
            pairs[ZERO] = k1
        continue

    for k2 in count:
        if k2 == ZERO:
            continue
        if k1 * k2 == -1:
            pairs[k2] = k1
            break
    else:
        solos.append(k1)
# print(pairs, solos)

P = 1000000007


def pow2(n):
    if n < 30:
        return 2 ** n

    p = pow2(n // 2)
    pp = (p * p) % P
    if n % 2 == 1:
        return (2 * pp) % P
    else:
        return pp


result = 1
for p in pairs:
    # print("pair", p, count[p], pairs[p], count[pairs[p]])
    n = count[p]
    m = count[pairs[p]]
    result = result * ((pow2(n) - 1) + (pow2(m) - 1) + 1) % P
for k in solos:
    # print("solo", k, count[k])
    result = result * pow2(count[k]) % P

print(result - 1)

Submission status: Runtime Error

Solution code:
import collections
import fractions

n = int(input())
m = 0
mod = 10 ** 6 + 7
c = []
d = []
frac = {}
tmp = 0
for _ in range(n):
    a, b = map(int, input().split())
    if a == 0 and b == 0:
        tmp += 1
        m += 1
        continue
    try:
        if b == 0: frac[float('inf')] += 1
        else: frac[fractions.Fraction(a, b)] += 1
    except KeyError:
        if b == 0: frac[float('inf')] = 1
        else: frac[fractions.Fraction(a, b)] = 1
n -= tmp

for key, value in frac.items():
    if key > 0: continue
    try:
        if key == float('inf'):
            d.append(frac[fractions.Fraction(0)])
        else:
            d.append(frac[-1 / key])
        c.append(value)
    except KeyError:
        continue

ans = pow(2, n - sum(c) - sum(d), mod)
for i, j in zip(c, d):
    tmp = (pow(2, i, mod) + pow(2, j, mod) - 1)
    ans = (ans * (pow(2, i, mod) + pow(2, j, mod) - 1)) % mod
ans -= 1 + m

print(ans)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
from fractions import Fraction
import sys
input = sys.stdin.readline
N=int(input())
mod=10**9+7
dic=defaultdict(int)
c=0
d=0
e=0
for i in range(N):
 A,B = map(int,input().split())
 if A==0 and B==0:
  e+=1
 elif A==0:
  c+=1
 elif B==0:
  d+=1
 else:
   x=Fraction(A,B)
   dic[x]+=1
ans=1
for k in dic:
 if k>0:
  ans*=(pow(2,dic[k],mod)+pow(2,dic[-1/k],mod) -1)
 else:
  if -1/k in dic:
   continue
  else:
   ans*=pow(2,dic[k],mod)
 ans%=mod
ans*=(pow(2,c,mod)+pow(2,d,mod)-1)
print((ans-1+e)%mod)

Submission status: Runtime Error

Solution code:
from collections import deque
n,m = map(int,input().split())
g = [[] for i in range(n)]
for i in range(m):
    x,y = map(int,input().split())
    g[x-1].append(y-1)
    g[y-1].append(x-1)
a = [-1]*n
d = deque([0])
while d:
    f = d.popleft()
    for o in g[f]:
        if a[o] == -1:
            a[o] = f
            d.append(o)
print("Yes")
for i in a[1:]:print(i+1)