Example #1
0
def calculateAntiClockwiseRecords():
    res = defaultdict(
        list)  # consulateRecords {consulate: [guestId1, guestId2]最后经过的那些人}
    guestStopAt = {}
    group = defaultdict(list)  # {stopAt: [guestId1, guestId2]}
    for gId, gSt, _ in GuestsAntiClockwise:
        delta = M % N
        stopAt = gSt - delta
        stopAt = stopAt + N if stopAt < 0 else stopAt

        guestStopAt[gId] = stopAt
        group[stopAt].append(gId)

    debug('group:', group)

    arr = sorted(group.keys(), reverse=True)  # ⭐ 注意是reverse了的
    # 对于使馆cid,找到它记住的那个group (第一个>=cid的stopAt)
    # choices = [0, 3, 7]  cid = 3
    for cid in range(N):
        groupId = getLastVisitGroupId(arr, cid, N, 'A')

        if groupId != -1:
            visitAt = M - getDistOnLoop(cid, groupId, N, 'A')
            if visitAt > 0:
                res[cid] += list(
                    map(
                        lambda gId: namedtuple(
                            'Record', ['guestId', 'visitAt'])(gId, visitAt),
                        group[groupId]))
    return res
Example #2
0
def calculateClockwiseRecords():
    res = defaultdict(
        list)  # consulateRecords {consulate: [guestId1, guestId2]最后经过的那些人}
    guestStopAt = {}
    group = defaultdict(list)  # {stopAt: [guestId1, guestId2]}
    for gId, gSt, _ in GuestsClockwise:
        stopAt = (gSt + M) % N
        guestStopAt[gId] = stopAt
        group[stopAt].append(gId)

    debug('group:', group)

    arr = sorted(group.keys())
    # 对于使馆cid,找到它记住的那个group (第一个>=cid的stopAt)
    # choices = [0, 3, 7]  cid = 3
    for cid in range(N):
        bsRes = bisect_left(arr, cid)
        visitAt = None
        if bsRes == len(arr):  # 找不到 >= cid 的数, arr里所有元素都 < cid
            if hasLoop:  # 多圈的情况
                groupId = arr[0]
                visitAt = (M + (cid - groupId)) - N  # M + 如果能再走几步就能走到 - 一圈
            else:
                groupId = -1
        else:
            groupId = arr[bsRes]
            visitAt = M - (groupId - cid)  # 这步比较直观

        if groupId != -1:
            res[cid] += list(
                map(
                    lambda gId: namedtuple('Record', ['guestId', 'visitAt'])
                    (gId, visitAt), group[groupId]))
    return res
Example #3
0
def solve(i, j, k):
    if i == 0:
        return 1

    debug('i, j, k:', i, j, k)

    choices = [solve(i - 1, j, k)]  # 操作1 append char
    choices += [solve(i, a, b) for a in range(i + 1)
                for b in range(a, i + 1)]  # 操作2 复制

    # 操作3 整段黏贴
    if j != -1 and k != -1:  # 剪贴板为空时,上一次操作不可能是黏贴
        clipboardLen = k - j + 1
        if S[j:k + 1] == S[i - clipboardLen + 1:i + 1]:
            choices.append(solve(i - clipboardLen, j, k))

    return min(choices)
Example #4
0
def cmp(a, b):
    na, nb = sorted([a, b])
    lenA, lenB = na.r - na.l + 1, nb.r - nb.l + 1
    if na.r < nb.l:  # 两个区间不相交
        left = min(lenA, lenB)
        right = min(lenA, lenB)
    elif na.l <= nb.l <= nb.r <= na.r:  # na包含nb
        left = 0  # na 在前
        right = min(lenB, lenA - lenB)  # nb在前
    else:  # 相交
        left = min(lenA, lenB - (na.r - nb.l + 1))
        right = min(lenB, lenA - (na.r - nb.l + 1))

    if left < right:
        res = 1  # a negative number for less-than
    elif left > right:
        res = -1  # a positive number for greater-than
    else:
        res = 0  # zero for equality
    debug('na, nb, left, right:', na, nb, left, right)
    res = res if na == a else -res
    # debug('a, b, res:', a, b, res)
    return res
Example #5
0
def calculateAntiClockwiseRecords():
    res = defaultdict(
        list)  # consulateRecords {consulate: [guestId1, guestId2]最后经过的那些人}
    guestStopAt = {}
    group = defaultdict(list)  # {stopAt: [guestId1, guestId2]}
    for gId, gSt, _ in GuestsAntiClockwise:
        delta = M % N
        stopAt = gSt - delta
        stopAt = stopAt + N if stopAt < 0 else stopAt

        guestStopAt[gId] = stopAt
        group[stopAt].append(gId)

    debug('group:', group)

    arr = sorted(group.keys())
    # 对于使馆cid,找到它记住的那个group (第一个>=cid的stopAt)
    # choices = [0, 3, 7]  cid = 3
    for cid in range(N):
        bsRes = bisect_right(arr, cid)
        visitAt = None
        if bsRes == 0:  # 找不到 <= cid 的数, arr里所有元素都 > cid
            if hasLoop:  # 多圈的情况
                groupId = arr[-1]
                visitAt = (M + (groupId - cid)) - N
            else:
                groupId = -1
        else:
            groupId = arr[bsRes - 1]
            visitAt = M - (cid - groupId)

        if groupId != -1:
            res[cid] += list(
                map(
                    lambda gId: namedtuple('Record', ['guestId', 'visitAt'])
                    (gId, visitAt), group[groupId]))
    return res
Example #6
0
def solve(codeGoal, eatGoal):
    if S == 1:
        c, e = slots[0]
        return (1 - codeGoal / c) * e >= eatGoal

    if S == 2:
        c1, e1 = slots[0]
        c2, e2 = slots[1]

        row1 = [c1, c2, codeGoal]
        row2 = [-e1, -e2, eatGoal - (e1 + e2)]
        row3 = [-e1, -e2, eatGoal - (e1 + e2)]

        debug('codeGoal, eatGoal:', codeGoal, eatGoal)
        debug('row1, row2:', row1, row2)

        fac = row2[0] / row1[0]
        for i in range(3):
            row2[i] -= fac * row1[i]  # 消去f1 剩下f2

        fac = row3[1] / row1[1]
        for i in range(3):
            row3[i] -= fac * row1[i]  # 消去f2 剩下f1

        if row2[0] == row2[1] == 0:
            if row2[2] != 0:
                return row2[2] <= 0
            else:
                return True

        res1, res2 = True, True
        f1 = row2[2] / row2[1]
        if row2[1] < 0:  # <=
            res1 = f1 >= 0
        else:
            res1 = f1 <= 1
        debug('row1, row2, f1:', row1, row2, f1)

        f2 = row3[2] / row3[0]
        if row3[0] < 0:  # <=
            res2 = f2 >= 0
        else:  # >=
            res2 = f2 <= 1
        debug('row1, row3, f2:', row1, row3, f2)

        return res1 and res2
Example #7
0
if __name__ == '__main__':
    T = int(input())
    for caseIndex in range(T):
        N = int(input())
        # S: 吃掉要花多少时间 E: 吃掉可获得多少能量 L: 每秒流失多少能量
        A = [
            namedtuple('stone', ['S', 'E', 'L'])(*map(int,
                                                      input().split()))
            for i in range(N)
        ]

        A.sort(key=cmp_to_key(cmp))
        maxTime = sum(map(itemgetter(0), A))

        debug('A, maxTime:', A, maxTime)

        dp = defaultdict(int)
        length = len(A)
        ans = -inf

        # dp[i][t] 总共用t秒, 从前i个石头里选, 可以得到的最大收益
        # 这里的t并不是容量限制  而是必须要维护的辅助变量 不然无法获知损耗量是多少
        for i in range(length):
            for t in range(maxTime + 1):
                if i == 0:
                    dp[i, t] = A[0].E if A[0].S <= t else 0
                    ans = max(ans, dp[i, t])
                    continue

                if A[i].S <= t:
Example #8
0
    debug('i, j, k:', i, j, k)

    choices = [solve(i - 1, j, k)]  # 操作1 append char
    choices += [solve(i, a, b) for a in range(i + 1)
                for b in range(a, i + 1)]  # 操作2 复制

    # 操作3 整段黏贴
    if j != -1 and k != -1:  # 剪贴板为空时,上一次操作不可能是黏贴
        clipboardLen = k - j + 1
        if S[j:k + 1] == S[i - clipboardLen + 1:i + 1]:
            choices.append(solve(i - clipboardLen, j, k))

    return min(choices)


if __name__ == '__main__':
    T = int(input())
    for caseIndex in range(T):
        S = input()
        debug('S:', S)
        # 枚举所有可能的剪贴板内容
        choices = [
            solve(len(S) - 1, i, j) for i in range(len(S))
            for j in range(i, len(S))
        ]
        choices.append(solve(len(S) - 1, '?', '?'))
        ans = min(choices)

        print('Case #{}: {}'.format(caseIndex + 1,
                                    ans if ans != inf else 'IMPOSSIBLE'))
Example #9
0
            break

    return 1


@dump_args
@lru_cache(None)
def dpEven(n):
    # debug('dpEven, n:', n)
    if n == 1:
        return 0

    for i in range(2, n + 1):
        if n % i == 0 and i % 2 == 0:
            return dpEven(n // i) + 1

    return 0


if __name__ == '__main__':
    T = int(input())
    for caseIndex in range(T):
        L, R = list(map(int, input().split()))

        ans = 0
        for i in range(L, R + 1):
            debug('i:', i)
            if abs(dpOdd(i) - dpEven(i)) <= 2:
                ans += 1
        print('Case #{}: {}'.format(caseIndex + 1, ans))
Example #10
0
    sys.stdin = open(os.path.expanduser('./in.txt'))
    # sys.stdout = open(os.path.expanduser('./out.txt'), 'w')
    from icpc_util import debug
else:
    debug = lambda *args, **kwargs: None
    dump_args = lambda func: func

if __name__ == '__main__':
    T = int(input())
    for caseIndex in range(T):
        N, P = list(map(int, input().split()))
        forbiddenPrefixes = sorted([input() for i in range(P)],
                                   key=len,
                                   reverse=True)

        filteredForbiddenPrefixes = []
        for i in range(len(forbiddenPrefixes)):
            for j in range(i + 1, len(forbiddenPrefixes)):
                if forbiddenPrefixes[i].startswith(forbiddenPrefixes[j]):
                    break
            else:
                filteredForbiddenPrefixes.append(forbiddenPrefixes[i])

        debug('filteredForbiddenPrefixes:', filteredForbiddenPrefixes)

        ans = 2**N
        for px in filteredForbiddenPrefixes:
            ans -= 2**(N - len(px))

        print('Case #{}: {}'.format(caseIndex + 1, ans))
Example #11
0

if __name__ == '__main__':
    T = int(input())
    for caseIndex in range(T):
        N, M = list(map(int, input().split()))
        graph = defaultdict(list)
        nodes = set()
        for i in range(M):
            u, v = list(map(lambda s: int(s) - 1, input().split()))
            graph[u].append(v)
            graph[v].append(u)
            nodes.add(u)
            nodes.add(v)
        # /* 求各个黑连通集的数目 */

        connectSets = getConnectSets(graph, nodes)
        debug('connectSets:', connectSets)

        ans = 0
        blackCnt = 0
        for cs in connectSets.values():
            ans += len(cs) - 1  # 各个黑连通集内部的
            blackCnt += len(cs)

        redCnt = N - blackCnt
        blackSetCnt = len(connectSets.values())
        ans += (blackSetCnt + redCnt - 1) * 2

        print('Case #{}: {}'.format(caseIndex + 1, ans))
Example #12
0
                map(
                    lambda gId: namedtuple('Record', ['guestId', 'visitAt'])
                    (gId, visitAt), group[groupId]))
    return res


if __name__ == '__main__':
    import doctest

    doctest.testmod()
    assert 0

    T = int(input())
    for caseIndex in range(T):
        N, G, M = list(map(int, input().split()))
        debug('N, M:', N, M)
        GuestsClockwise, GuestsAntiClockwise = [], []
        for i in range(G):
            H, Direction = input().split()
            guest = namedtuple('Guest',
                               ['id', 'st', 'direction'])(i, int(H) - 1,
                                                          Direction)
            if guest.direction == 'C':
                GuestsClockwise.append(guest)
            else:
                GuestsAntiClockwise.append(guest)

        GuestsClockwise.sort(key=itemgetter(1))  # 按出发点从小往大排
        GuestsAntiClockwise.sort(key=itemgetter(1))
        hasLoop = M > N
Example #13
0
            Guests.append(
                namedtuple('Guest', ['id', 'st', 'direction'])(i, int(H) - 1,
                                                               Direction))

        consulateRecords = defaultdict(list)
        # M %= N

        for guest in Guests:
            for t in range(M + 1):
                if guest.direction == 'C':
                    consulateRecords[(guest.st + t) % N].append((t, guest.id))
                else:
                    consulateRecords[(guest.st - t + N) % N].append(
                        (t, guest.id))

        debug('consulateRecords:', consulateRecords)

        counter = {i: 0 for i in range(G)}
        for consulateId in consulateRecords:
            consulate = consulateRecords[consulateId]
            consulate.sort(reverse=True)
            if consulate:
                for record in consulate:
                    time, guestId = record
                    if time == consulate[0][0]:
                        counter[guestId] += 1

        debug('counter:', counter)

        print('Case #{}:'.format(caseIndex + 1), *counter.values())
Example #14
0
    else:
        res = 0  # zero for equality
    debug('na, nb, left, right:', na, nb, left, right)
    res = res if na == a else -res
    # debug('a, b, res:', a, b, res)
    return res


if __name__ == '__main__':
    T = int(input())
    for caseIndex in range(T):
        N, Q = list(map(int, input().split()))
        Books = [
            namedtuple('book', ['l', 'r'])(*map(lambda s: int(s) - 1,
                                                input().split()))
            for i in range(Q)
        ]
        debug('Books (Raw):', Books)
        Books.sort(key=cmp_to_key(cmp))
        debug('Books (Sorted):', Books)

        tr = SegmentTreeSumIntervalSet([0] * N)
        ans = inf
        for b in Books:
            before = tr.query(b.l, b.r)
            tr.intervalSet(b.l, b.r, 1)
            after = tr.query(b.l, b.r)
            ans = min(ans, after - before)

        print('Case #{}: {}'.format(caseIndex + 1, ans))
Example #15
0
    # print('graph', graph)
    def _dfs(u: int, footprint: list):
        # print('u, footprint:', u, footprint)
        footprint.append(u)
        # print('graph[u]:', graph[u])
        for v in graph[u]:
            if len(footprint) >= 2 and footprint[-2] == v:  # 防止走回头
                continue
            if v in footprint:
                return footprint[footprint.index(v):]
            else:
                return _dfs(v, footprint)

    if graph.keys():
        return _dfs(tuple(graph.keys())[0], [])
    else:
        return -1


if __name__ == '__main__':
    T = int(input())
    for caseIndex in range(T):
        edges = [tuple(map(int, input().split())) for i in range(int(input()))]
        graph = defaultdict(list)
        for u, v in edges:
            graph[u - 1].append(v - 1)
            graph[v - 1].append(u - 1)

        print('Case #{}:'.format(caseIndex + 1))
        debug(findCircle(graph))
Example #16
0
    counter = defaultdict(int)
    watershed = defaultdict(list)
    watershedBeginAt = defaultdict(int)

    for i, n in enumerate(A):
      counter[n] += 1
      if counter[n] <= S:
        effector[i] = 1
      elif counter[n] == S + 1:
        effector[i] = -S
        watershed[n].append(i)
      else:
        effector[i] = 0
        watershed[n].append(i)

    debug('effector:', effector)
    debug('watershed:', watershed)

    tr = SegmentTreeMaxSum(effector)
    ans = tr.query(0, len(effector) - 1)
    for k in range(N - 1):  # 从k之后开始选
      n = A[k]
      tr.update(k, 0)
      if len(watershed[n]) - 1 >= watershedBeginAt[n]:
        tr.update(watershed[n][watershedBeginAt[n]], 1)
        watershedBeginAt[n] += 1
      if len(watershed[n]) - 1 >= watershedBeginAt[n]:
        tr.update(watershed[n][watershedBeginAt[n]], -S)
      debug('k, tr.A:', k, tr.A)
      ans = max(ans, tr.query(0, len(effector) - 1))