Exemple #1
0
from sys import stdin, setrecursionlimit as SRL
SRL(10**6)

input = stdin.readline


def solve():
    M, N = map(int, input().split())
    dp = [[-1] * N for _ in range(M)]
    d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    arr = []
    for _ in range(M):
        arr.append(list(map(int, input().split())))

    def dfs(nx, ny):

        if dp[nx][ny] != -1:
            return dp[nx][ny]

        elif nx == M - 1 and ny == N - 1:
            return 1

        ret_val = 0
        for dx, dy in d:
            x, y = nx + dx, ny + dy
            if 0 <= x < M and 0 <= y < N and arr[nx][ny] > arr[x][y]:
                ret_val += dfs(x, y)
        dp[nx][ny] = ret_val
        return ret_val

    print(dfs(0, 0))
# Josephus problem
# g is for small k and large n
# below iterative version is simpler
from sys import setrecursionlimit as SRL, stdin
SRL(242424)
def g(n, k):
    if k == 1: return n-1
    if n == 1: return 0
    if n < k: return (g(n-1,k) + k) % n
    np = n - n//k
    return k*((g(np,k)-n%k)%np) // (k-1)

n, k = map(int,input().split())
r = 0
for i in range(1, n+1): r = (r+k)%i
print(r)
Exemple #3
0
#UVa: 10327 - Flip sort
from sys import setrecursionlimit as SRL
from sys import stdin

SRL(10000)


def solve(num, low, hi):
    r = 0
    if (hi - low <= 1):
        return 0
    mid = low + ((hi - low) >> 1)
    aux, a, b = [], low, mid

    r = solve(num, low, mid)
    r += solve(num, mid, hi)

    while (a < mid and b < hi):
        if (num[a] <= num[b]):
            aux.append(num[a])
            a += 1
        elif (num[a] > num[b]):
            aux.append(num[b])
            b += 1
            r += mid - a

    while (a < mid):
        aux.append(num[a])
        a += 1

    while (b < hi):
# Tarjan algorithm for strongly connected component
# v = number of vertices
# adj = list of adjacent nodes
# This is 1-indexed; adj[0] should be []

from sys import setrecursionlimit as SRL, stdin

SRL(150000)


def SCC(adj):
    # given |V| and adj, compute SCC
    def SC(i):
        nonlocal ind
        vin[i] = ind
        vll[i] = ind
        ind += 1
        stack.append(i)
        stacked[i] = 1
        for j in adj[i]:
            if vin[j] == 0:
                SC(j)
                vll[i] = min(vll[i], vll[j])
            elif stacked[j]:
                vll[i] = min(vll[i], vin[j])
        if vll[i] == vin[i]:
            scc = []
            j = 0
            while j != i:
                j = stack.pop()
                stacked[j] = 0
Exemple #5
0
    for s in strs:
        n = root
        for c in s:
            i = ord(c) - ord('a')
            if n[i]:
                n = n[i]
                continue
            n[i] = Node(size)
            n.singular = i if n.singular == -1 else -2
            n = n[i]
        n.end = True
    return root


from sys import setrecursionlimit as SRL
SRL(23423)


def contract(trie):
    for i in range(len(trie.nxt)):
        if not trie[i]: continue
        while 1:
            if trie[i].singular < 0 or trie[i].end: break
            grandson = trie[i][trie[i].singular]
            trie[i].end |= grandson.end
            trie[i] = grandson
        contract(trie[i])


#### Dict trie
def makeTrie(words):
Exemple #6
0
from sys import stdin, setrecursionlimit as SRL
SRL(10**5)


def check(num):

    if len(num) == 0:
        return True

    elif num[0] == '1':
        if len(num) < 4:
            return False
        elif num[1] == '0' and num[2] == '0':
            offset = 3
            while offset < len(num) and num[offset] == '0':
                offset += 1
            if offset == len(num):
                return False
            else:
                while offset < len(num) and num[offset] == '1':
                    offset += 1
                if offset == len(num):
                    return True
                else:
                    if check(num[offset:]) or (num[offset - 2] == '1'
                                               and check(num[offset - 1:])):
                        return True
                    else:
                        return False
    else:
        if len(num) <= 1:
Exemple #7
0
from sys import setrecursionlimit as SRL
SRL(23232)


def start(ty):
    return (1, 1) if ty == 0 else (n, n)


def dist(i, j, ty):
    xi, yi = p[i] if i else start(ty)
    xj, yj = p[j] if j else start(ty)
    return abs(xi - xj) + abs(yi - yj)


def update(i, j):
    nx = max(i, j) + 1
    if nx == w + 1: return
    D = dp[i][j] + dist(i, nx, 1)
    if dp[nx][j] > D: dp[nx][j], prev[nx][j] = D, (i, j)
    D = dp[i][j] + dist(j, nx, 0)
    if dp[i][nx] > D: dp[i][nx], prev[i][nx] = D, (i, j)


n = int(input())
w = int(input())
p = [(-1, -1)] + [tuple(map(int, input().split())) for i in range(w)]
dp = [[float('inf')] * (w + 1) for i in range(w + 1)]
prev = [[(-1, -1)] * (w + 1) for i in range(w + 1)]
dp[0][0] = 0
for v in range(w + 1):
    # update [v+1][j]
Exemple #8
0
from sys import setrecursionlimit as SRL, stdin
SRL(55555)
input = stdin.readline
range = xrange

def update(i, j):
    nx = max(i, j) + 1
    if nx == n: return
    dp[nx][j] = min(dp[nx][j], dp[i][j]+dist(i,nx))
    dp[i][nx] = min(dp[i][nx], dp[i][j]+dist(j,nx))

def dist(i, j):
    xi, yi = p[i]
    xj, yj = p[j]
    return ((xi-xj)**2 + (yi-yj)**2) ** 0.5

for TEST in range(int(input())):
    n = int(input())
    p = [tuple(map(int,input().split())) for i in range(n)]
    dp = [[float('inf')]*n for i in range(n)]
    dp[0][0] = 0
    for v in range(n):
        # update [v+1][j]
        for i in range(v+1): update(i, v)
        for j in range(v): update(v, j)
    finish = [dp[i][n-1] + dist(i, n-1) for i in range(n)]\
        + [dp[n-1][j] + dist(n-1, j) for j in range(n)]
    print(min(finish))
Exemple #9
0
def makeTrie(words):
    root = {}
    for w in words:
        cd = root
        for l in w:
            cd = cd.setdefault(l, {})
        cd[''] = ''
    return root


from sys import setrecursionlimit as SRL

SRL(22222)


def contract(trie):
    for desc in trie:
        while 1:
            if len(trie[desc]) > 1: break
            if trie[desc] == '': break
            s = next(iter(trie[desc]))
            if s == '': break
            trie[desc] = trie[desc][s]
        contract(trie[desc])


def totdepth(trie, depth=0):
    if trie == '': return depth  # totdepth, numelements
    return sum(totdepth(trie[desc], depth + 1) for desc in trie)

from sys import setrecursionlimit as SRL, stdin
SRL(550000)
input = stdin.readline

def BellmanFord(n, adj, source):
    dist = [float('inf')]*(n+1)
    dist[source] = 0
    for i in range(n-1):
        for u in range(1, n+1):
            for v, c in adj[u]:
                dist[v] = min(dist[v], dist[u]+c)
    for u in range(1, n+1):
        for v, c in adj[u]:
            if dist[u]+c < dist[v]:
                return False
    return dist

n, m = map(int,input().split())
adj = [[] for i in range(n+1)]
for i in range(m):
    a, b, c = map(int,input().split())
    adj[a].append((b,c))
res = BellmanFord(n, adj, 1)
if not res:
    print(-1)
else:
    for i in range(2,n+1):
        print(res[i] if res[i] != float('inf') else -1)
Exemple #11
0
# DnC Optimization of DP can be used if
# dp[t][i] = min(k<i) dp[t-1][k]+c[k][i] and
# best[t][i] <= best[t][i+1]
# Especially, quadrangle inequality is nice:
# c[a][c]+c[b][d] <= c[a][d]+c[b][c] for a<=b<=c<=d

from sys import setrecursionlimit as SRL
SRL(232323)


def dnc(s, e, p, q):
    if s > e: return
    m = (s + e) // 2
    for i in range(p, min(q + 1, m)):
        v = dp[t - 1][i] + c[i][m]  # Change this line!
        if dp[m] < v:
            dp[m] = v
            best[m] = i  # Change this "<" if necessary
    dnc(s, m - 1, p, best[m])
    dnc(m + 1, e, best[m], q)


dp = [-float('inf')] * n
best = [0] * n
    n = len(adj)
    visited = [False] * n
    visited[source] = True
    Q = deque()
    Q.append(source)
    while len(Q):
        p = Q.popleft()
        for q in adj[p]:
            if visited[q]: continue
            visited[q] = True
            Q.append(q)
    return visited


from sys import setrecursionlimit as SRL, stdin
SRL(234234)
input = stdin.readline

n = int(input())
adj = [[] for i in range(n + 1)]
radj = [[] for i in range(n + 1)]
for i in range(1, n):
    room = int(input())
    for j in map(int, input().split()):
        adj[i].append(j)
        radj[j].append(i)

limited = "UNLIMITED" if cyclic(adj) else "LIMITED"
bfs1 = bfs(adj, 1)
bfs2 = bfs(radj, n)
pardon = "PRISON" if any(