【随手记】python大规模数据读取

题目是MT3055 交换排列
python大规模数据读取用这个sys.stdin.read。

import sys
input = sys.stdin.read
data = input().split()

这个是题解。

import heapq

class UnionFind:
    def __init__(self, size):
        self.parent = list(range(size))

    def find(self, x):
        if self.parent[x] == x:
            return x
        self.parent[x] = self.find(self.parent[x])
        return self.parent[x]

    def union(self, x, y):
        rootX = self.find(x)
        rootY = self.find(y)
        if rootX != rootY:
            self.parent[rootX] = rootY

def main():
    # python大规模数据读取用这个sys.stdin.read,具体读啥仿照这个示例
    import sys
    input = sys.stdin.read
    data = input().split()
    
    index = 0
    n = int(data[index])
    m = int(data[index + 1])
    index += 2

    num = [0] * (n + 1)
    fa = list(range(n + 1))
    q = [[] for _ in range(n + 1)]

    uf = UnionFind(n + 1)

    for i in range(1, n + 1):
        num[i] = int(data[index])
        index += 1

    for _ in range(m):
        x = int(data[index])
        y = int(data[index + 1])
        index += 2
        uf.union(x, y)

    for i in range(1, n + 1):
        root = uf.find(i)
        heapq.heappush(q[root], -num[i])

    result = []
    for i in range(1, n + 1):
        root = uf.find(i)
        result.append(-heapq.heappop(q[root]))

    print(" ".join(map(str, result)))

if __name__ == "__main__":
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zcongfly

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值