Пример #1
0
    def getSubtreeCount(self, start, end):
        edges = zip(start, end)
        from operator import mul
        from collections import defaultdict as ddic, deque
        graph = ddic(list)
        rgraph = ddic(list)
        degree = ddic(int)
        for u, v in edges:
            graph[u].append(v)
            rgraph[v].append(u)
            degree[u] += 1
            degree[v]

        dp = ddic(int)
        MOD = 10000007
        leaves = deque(k for k in degree if degree[k] == 0)
        while leaves:
            node = leaves.popleft()
            try:
                bns = 1
                for x in graph[node]:
                    bns *= 1 + dp[x]
                    bns %= MOD

                dp[node] = bns
            except:
                dp[node] = 1
            for par in rgraph[node]:
                degree[par] -= 1
                if degree[par] == 0:
                    leaves.append(par)
        return sum(dp.values()) % MOD
Пример #2
0
def solve(N, AA):

    A = [(j[0], j[1], i) for i, j in enumerate(AA)]
    A.sort()
    crossdic = ddic(int)
    for i in xrange(N):
        for j in xrange(N):
            for k in xrange(N):
                zz = cross(A[i], A[j], A[k])
                if zz > 0: crossdic[(i, j, k)] = 2
                elif zz < 0: crossdic[(i, j, k)] = 1
    ansdic = ddic(int)
    #answer for ith point
    for i in xrange(N):
        ansdic[i] = 99999
    if N == 1: return [0]
    for i in xrange(N - 1):
        for j in xrange(i + 1, N):
            #look at the line A[i],A[j].  If the least number of pts to the left/right of it is M,
            # then A[i][2] and A[j][2] admit solutions of M.
            type1, type2 = 0, 0
            for k in xrange(N):
                if k != i and k != j:
                    z = crossdic[(k, i, j)]
                    if z == 2: type2 += 1
                    elif z == 1: type1 += 1
                    else: pass  #on the line so doesnt count
            #print i,j,A[i],A[j],type1,type2
            least = min(type1, type2)
            ansdic[A[i][2]] = min(least, ansdic[A[i][2]])
            ansdic[A[j][2]] = min(least, ansdic[A[j][2]])
    #print ansdic
    return [ansdic[i] for i in xrange(N)]
Пример #3
0
    def getBarycentre(self, X, Y):
        N = len(X)
        from collections import defaultdict as ddic
        graph = ddic(list)
        for u, v in zip(X, Y):
            graph[u].append(v)
            graph[v].append(u)

        memo = {}

        def dfs(node, par):
            if (node, par) in memo: return memo[node, par]
            ans = 1
            for nei in graph[node]:
                if nei != par:
                    ans += dfs(nei, node)
            memo[node, par] = ans
            memo[par, node] = N - ans
            return ans

        ans = 1234432
        for root in sorted(graph):
            bns = 0
            for nei in graph[root]:
                bns = max(bns, dfs(nei, root))
            if bns < ans:
                ans = bns
                fans = root
        return fans
Пример #4
0
def solve(B, N, A):
    L = lcmargs(A)
    Adic = {i: j for i, j in enumerate(A)}
    Bans = ddic(set)
    ct = 0
    for i in xrange(L):
        for j in xrange(B):
            if i % Adic[j] == 0:
                Bans[j].add(ct)
                ct += 1
    N -= 1
    N = N % ct
    for i in xrange(B):
        if N in Bans[i]: return i + 1
    raise
Пример #5
0
def crosswordFormation(words):
    from itertools import permutations as perms
    from collections import defaultdict as ddic
    ans = 0
    for p in perms(words):
        M = ddic(int)
        a,b,c,d = p
        for i in range(2, min(len(a),len(b))):
            for p in range(len(a) - i):
                for q in range(len(b) - i):
                    M[a[p],a[p+i],b[q],b[q+i]] += 1
        for i in range(2, min(len(c),len(d))):
            for p in range(len(c) - i):
                for q in range(len(d) - i):
                    ans += M[c[p],d[q],c[p+i],d[q+i]]
    return ans
Пример #6
0
def solve(R, C, A):
    G = ddic(list)
    # Rows
    for i in xrange(R):
        tmp = []
        for j in xrange(C):
            if A[i][j] != '.': tmp.append((i, j))
        tmplen = len(tmp)
        if tmplen > 1:
            G[tmp[0]].append('>')
            G[tmp[tmplen - 1]].append('<')
            for i in xrange(1, tmplen - 1):
                G[tmp[i]].append('>')
                G[tmp[i]].append('<')
        else:
            pass

    #Columns
    for j in xrange(C):
        tmp = []

        for i in xrange(R):
            if A[i][j] != '.': tmp.append((i, j))
        tmplen = len(tmp)
        if tmplen > 1:
            G[tmp[0]].append('v')
            G[tmp[tmplen - 1]].append('^')
            for i in xrange(1, tmplen - 1):
                G[tmp[i]].append('v')
                G[tmp[i]].append('^')
        else:
            pass
    #Now G is a list of valid
    ans = 0

    for i in xrange(R):
        for j in xrange(C):
            if A[i][j] != '.':
                if G[(i, j)]:
                    if (A[i][j] not in G[(i, j)]): ans += 1
                else:
                    return "IMPOSSIBLE"
    return ans
Пример #7
0
n = int(input())
mod = 10**9 + 7
from collections import defaultdict as ddic
from math import factorial as fac
d = ddic(int)
l = list()
for _ in range(n):
    a = int(input())
    d[a] += 1
    l.append(a)
l.sort()
s = 0
p = 1
for i in range(n):
    s += l[i] * (n - i)
for i in d:
    p *= fac(d[i])
print(s)
print(p % mod)
def _trie():
    return ddic(_trie)
Пример #9
0
def buildSmall(x, ls):
    rec = ddic(list)
    for i, v in enumerate(ls):
        rec[v % x].append(i)
    return rec
Пример #10
0
    ix = bisect.bisect_left(arr, left)
    return jx - ix


def buildSmall(x, ls):
    rec = ddic(list)
    for i, v in enumerate(ls):
        rec[v % x].append(i)
    return rec


k, q = map(int, ins[0].strip().split())
ls = map(int, ins[1].strip().split())
index = 2

V = ddic(list)

M = max(ls)
for i, v in enumerate(ls):
    V[v].append(i)

smallRec = {}

MAGIC = 100

for i in range(q):
    l, r, x, y = map(int, ins[index + i].strip().split())
    if x <= MAGIC:
        if x not in smallRec:
            smallRec[x] = buildSmall(x, ls)
        print query(smallRec[x][y], l, r)
def pipesGame(state):
    sources = []  #contains the id of source and its coordinates
    for i in range(len(state)):
        for j in range(len(state[0])):
            if state[i][j] in string.ascii_lowercase:
                sources.append([state[i][j].upper(), i, j])
            state[i] = [j for j in state[i]]  #turning the map into a matrix
    if len(sources) == 0: return 0  #no source then

    D = ddic(int)  #this keeps track of seven-type pipes

    #this contains the no.of pipes after starting along a path where a pipe hits a leak or reaches wrong destination
    leak = []

    def play_game(i, j, pipe, source, last_move=None):
        #print(i,j,last_move,pipe)

        #if u reach the end
        if i < 0 or i >= len(state) or j < 0 or j >= len(state[0]):
            leak.append(pipe - 1)
            return (pipe - 1, source, "reached the end")
        #keeping track of seventype pipe -- put this statement below above - cost me 40k coins
        if state[i][j] == "7":
            D[(i, j, last_move)] += pipe

        #if u reach a sink
        if state[i][j] in string.ascii_uppercase:
            if state[i][j] == source:
                return (pipe - 1, source, "right destination")
            else:
                leak.append(pipe - 1)
                return (pipe - 1, source, "wrong destination")
        #if u reach an actual leak
        if state[i][j] == "0":
            leak.append(pipe - 1)
            return (pipe - 1, source, "leak")

        if pipe == 0:  #when u take a corner pipe on first move the count is decreased by 1
            if (last_move == "U" and i >= 1
                    and state[i - 1][j] in ["1", "4", "3", "7"]):
                if state[i - 1][j] == "1" or state[i - 1][j] == "7":
                    r = play_game(i - 1, j, pipe + 1, source, "U")
                elif state[i - 1][j] == "4":
                    r = play_game(i - 1, j - 1, pipe + 2, source, "L")
                elif state[i - 1][j] == "3":
                    r = play_game(i - 1, j + 1, pipe + 2, source, "R")
            elif (last_move == "D" and i + 1 < len(state)
                  and state[i + 1][j] in ["1", "5", "6", "7"]):
                if state[i + 1][j] == "1" or state[i + 1][j] == "7":
                    r = play_game(i + 1, j, pipe + 1, source, "D")
                elif state[i + 1][j] == "5":
                    r = play_game(i + 1, j - 1, pipe + 2, source, "L")
                elif state[i + 1][j] == "6":
                    r = play_game(i + 1, j + 1, pipe + 2, source, "R")
            elif (last_move == "R" and j + 1 < len(state[0])
                  and state[i][j + 1] in ["2", "4", "5", "7"]):
                if state[i][j + 1] == "2" or state[i][j + 1] == "7":
                    r = play_game(i, j + 1, pipe + 1, source, "R")
                elif state[i][j + 1] == "4":
                    r = play_game(i + 1, j + 1, pipe + 2, source, "D")
                elif state[i][j + 1] == "5":
                    r = play_game(i - 1, j + 1, pipe + 2, source, "U")
            elif (last_move == "L" and j >= 1
                  and state[i][j - 1] in ["2", "3", "6", "7"]):
                if state[i][j - 1] == "2" or state[i][j - 1] == "7":
                    r = play_game(i, j - 1, pipe + 1, source, "L")
                elif state[i][j - 1] == "3":
                    r = play_game(i + 1, j - 1, pipe + 2, source, "D")
                elif state[i][j - 1] == "6":
                    r = play_game(i - 1, j - 1, pipe + 2, source, "U")
            else:
                return 0
        else:
            if state[i][j] == "1":
                r = play_game(i + 1, j, pipe + 1, source,
                              "D") if last_move == "D" else play_game(
                                  i - 1, j, pipe + 1, source, "U")
            elif state[i][j] == "2":
                r = play_game(i, j + 1, pipe + 1, source,
                              "R") if last_move == "R" else play_game(
                                  i, j - 1, pipe + 1, source, "L")
            elif state[i][j] == "3":
                r = play_game(i, j + 1, pipe + 1, source,
                              "R") if last_move == "U" else play_game(
                                  i + 1, j, pipe + 1, source, "D")
            elif state[i][j] == "4":
                r = play_game(i + 1, j, pipe + 1, source,
                              "D") if last_move == "R" else play_game(
                                  i, j - 1, pipe + 1, source, "L")
            elif state[i][j] == "5":
                r = play_game(i - 1, j, pipe + 1, source,
                              "U") if last_move == "R" else play_game(
                                  i, j - 1, pipe + 1, source, "L")
            elif state[i][j] == "6":
                r = play_game(i, j + 1, pipe + 1, source,
                              "R") if last_move == "D" else play_game(
                                  i - 1, j, pipe + 1, source, "U")
            elif state[i][j] == "7":
                if last_move == "U":
                    r = play_game(i - 1, j, pipe + 1, source, "U")
                elif last_move == "D":
                    r = play_game(i + 1, j, pipe + 1, source, "D")
                elif last_move == "R":
                    r = play_game(i, j + 1, pipe + 1, source, "R")
                elif last_move == "L":
                    r = play_game(i, j - 1, pipe + 1, source, "L")
        return r

    pipes = [
    ]  #keeps track of pipe lengths of ALL PATHS, note: pipe 7 could be repeated
    initial_move = ["R", "L", "U", "D"]  #check all directions from the source
    for i in sources:
        for j in initial_move:
            a = play_game(i[1], i[2], 0, i[0], j)
            if a: pipes.append(a)

    counter = 0  #counts pipes with water, note: pipe 7 could be repeated
    for i in pipes:
        if leak:
            counter -= min(
                min(leak), i[0]
            )  #if leak choose the smallest b/w (leak constant,finished_path)
        else:
            counter += i[
                0]  #if no leak just add the lenght of path/no.of pipes. Note that seven-type pipe maybe be repeated

    E = ddic(int)
    seven = 0  #this will be number of extra "seven-type pipes"
    for i, j in D.items():
        if not E[i[:2]]: E[i[:2]] += j
        elif E[i[:2]]:
            if leak:  #only reduce if if passes through both "sevent-type" pipes before hitting leak somewhere
                if max(E[i[:2]], j) <= min(leak): seven += 1
            else: seven += 1
    print(counter)
    print(seven)
    if counter == 0: return 0
    return counter - seven if counter > 0 else counter + seven