题目是MT3055 交换排列
python大规模数据读取用这个sys.stdin.read。
import sys
input = sys.stdin.read
data = input().split()
这个是题解。
import heapqclass UnionFind:def __init__(self, size):self.parent = list(range(size))def find(self, x):if self.parent[x] == x:return xself.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] = rootYdef main():# python大规模数据读取用这个sys.stdin.read,具体读啥仿照这个示例import sysinput = sys.stdin.readdata = input().split()index = 0n = int(data[index])m = int(data[index + 1])index += 2num = [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 += 1for _ in range(m):x = int(data[index])y = int(data[index + 1])index += 2uf.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()