結果
問題 | No.1365 [Cherry 1st Tune] Whose Fault? |
ユーザー |
![]() |
提出日時 | 2021-01-23 13:43:57 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 1,434 ms / 2,000 ms |
コード長 | 2,283 bytes |
コンパイル時間 | 446 ms |
コンパイル使用メモリ | 82,048 KB |
実行使用メモリ | 106,464 KB |
最終ジャッジ日時 | 2024-12-30 16:44:53 |
合計ジャッジ時間 | 39,861 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 46 |
ソースコード
#yuki-1365from collections import defaultdictN = int(input())A = list(map(int, input().split())) #初期エネルギーB = list(map(int, input().split())) #目標エネルギーP = list(map(int, input().split())) #重みづけP2 = [float('inf') if p == 0 else 1/p for p in P]class UnionFind():def __init__(self, n):self.n = nself.roots = [[-1, A[i], B[i], P2[i]] for i in range(n)]self.cost = sum((A[i]-B[i])**2/P2[i] for i in range(n))def find(self, x): #xの根を見つけるif self.roots[x][0] < 0:return xelse:self.roots[x][0] = self.find(self.roots[x][0]) #つなぎ直すreturn self.roots[x][0]def union(self, x, y): #x,yが入っている部分集合を合体させるx = self.find(x)y = self.find(y)if x == y:return self.costif self.roots[x][0] > self.roots[y][0]:x, y = y, xvx, vy = self.roots[x], self.roots[y]self.cost -= (vx[1]-vx[2])**2/vx[3]+(vy[1]-vy[2])**2/vy[3]for i in range(4):self.roots[x][i] += self.roots[y][i]self.roots[y][0] = xvx = self.roots[x]self.cost += (vx[1]-vx[2])**2/vx[3]return self.costdef size(self, x): #ある元が入っている部分集合の大きさを求めるreturn -self.roots[self.find(x)][0]def same(self, x, y):return self.find(x) == self.find(y)def members(self, x):root = self.find(x)return [i for i in range(self.n) if self.find(i) == root]def rootss(self):return [i for i, x in enumerate(self.roots) if x[0] < 0]def group_count(self):return len(self.rootss())def all_group_members(self): #defaultdictの形で各部分集合を返すgroup_members = defaultdict(list)for member in range(self.n):group_members[self.find(member)].append(member)return group_membersdef __str__(self):return '\n'.join(f'{r}: {m}' for r, m in self.all_group_members().items())u = UnionFind(N)Q = int(input())ans = sum(P[i]*(A[i]-B[i])**2 for i in range(N))for _ in range(Q):X, Y = map(int, input().split())print(u.union(X-1, Y-1))