Problem:


Score : 600 points

Problem Statement

You are given a forest with N vertices and M edges. The vertices are numbered 0 through N-1.
The edges are given in the format (x_i,y_i), which means that Vertex x_i and y_i are connected by an edge.

Each vertex i has a value a_i.
You want to add edges in the given forest so that the forest becomes connected.
To add an edge, you choose two different vertices i and j, then span an edge between i and j.
This operation costs a_i + a_j dollars, and afterward neither Vertex i nor j can be selected again.

Find the minimum total cost required to make the forest connected, or print Impossible if it is impossible.

Constraints

1 ≤ N ≤ 100,000

0 ≤ M ≤ N-1

1 ≤ a_i ≤ 10^9

0 ≤ x_i,y_i ≤ N-1

The given graph is a forest.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_0 a_1 .. a_{N-1}
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the minimum total cost required to make the forest connected, or print Impossible if it is impossible.

Sample Input 1

7 5
1 2 3 4 5 6 7
3 0
4 0
1 2
1 3
5 6

Sample Output 1

7

If we connect vertices 0 and 5, the graph becomes connected, for the cost of 1 + 6 = 7 dollars.

Sample Input 2

5 0
3 1 4 1 5

Sample Output 2

Impossible

We can't make the graph connected.

Sample Input 3

1 0
5

Sample Output 3

0

The graph is already connected, so we do not need to add any edges.



Sample input:
7 5
1 2 3 4 5 6 7
3 0
4 0
1 2
1 3
5 6


Sample output:
7

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys

NO = "Impossible"  # type: str

class Impossible(Exception):
    pass

def solve(N: int, M: int, a: "List[int]", x: "List[int]", y: "List[int]"):
    from heapq import merge
    uf = UnionFind(N)
    for xx, yy in zip(x, y):
        uf.union(xx, yy)

    def f():
        aa = {r:iter(sorted(map(lambda x: a[x], m))) for r, m in uf.all_group_members().items()}
        god = uf.find(0)
        return
        for r in uf.roots():
            if uf.same(god, r):
                continue
            uf.union(god, r)
            try:
                yield next(aa[god])
                yield next(aa[r])
            except StopIteration:
                raise Impossible
            tmp = merge(aa[god], aa[r])
            god = uf.find(god)
            aa[god] = tmp
    
    try:
        return sum(f())
    except Impossible:
        return NO


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    a = [int(next(tokens)) for _ in range(N - 1 - 0 + 1)]  # type: "List[int]"
    x = [int()] * (M)  # type: "List[int]"
    y = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        x[i] = int(next(tokens))
        y[i] = int(next(tokens))
    print(solve(N, M, a, x, y))

# https://note.nkmk.me/python-union-find/
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        
    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]
    
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        
        if x == y:
            return
        
        if self.parents[x] > self.parents[y]:
            x, y = y, x
        
        self.parents[x] += self.parents[y]
        self.parents[y] = x
    
    def size(self, x):
        return -self.parents[self.find(x)]
        
    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 roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]
 
    def group_count(self):
        return len(self.roots())

    def __iter__(self):
        return iter(range(self.n))
    
    def all_group_members(self):
        ret = {r:[] for r in self.roots()}
        for n in self:
            ret[self.find(n)].append(n)
        return ret
    
    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,m = map(int,input().split())
A = list(map(int,input().split()))
C = [list(map(int,input().split())) for i in range(m)]

V = [0] * (n)
# P = [-1] * (n+1)

M = [[] for i in range(n)]
for i in range(m):
    M[C[i][0]].append(C[i][1])
    M[C[i][1]].append(C[i][0])

# 1始まりの場合
BB = []
one = 0
for ii in range(n):
    B = []
    if V[ii] == 0:
        Q = [ii]
        s = 0
        V[ii] = 1
        onef = 1
        B.append([ii,A[ii]])
        while s < len(Q):
            i = Q[s]
            for x in M[i]:
                if V[x] == 0:
                    V[x] = 1
                    onef = 0
                    B.append([x,A[x]])
                    # P[x] = i
                    Q.append(x)
            s += 1
        if onef == 1:
            one += 1
        B.sort(key=lambda x:x[1])
        BB.append(B[0])

if len(BB) == 1:
    print(0)
elif len(BB)*2 > n:
    print("Impossible")
else:
    ans = sum([i[1] for i in BB])
    # print(ans)
    anoBind = [0] * n
    anoB = []
    for i in range(len(BB)):
        anoBind[BB[i][0]] = 1
    for i in range(n):
        if anoBind[i] == 0:
            anoB.append(A[i])
    anoB.sort()
    # print(anoB)
    ans += sum(anoB[:len(BB)-2])
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,m = map(int,input().split())
A = list(map(int,input().split()))
C = [list(map(int,input().split())) for i in range(m)]

V = [0] * (n)
# P = [-1] * (n+1)

M = [[] for i in range(n)]
for i in range(m):
    M[C[i][0]].append(C[i][1])
    M[C[i][1]].append(C[i][0])

# 1始まりの場合
BB = []
one = 0
for ii in range(n):
    B = []
    if V[ii] == 0:
        Q = [ii]
        s = 0
        V[ii] = 1
        onef = 1
        B.append([ii,A[ii]])
        while s < len(Q):
            i = Q[s]
            for x in M[i]:
                if V[x] == 0:
                    V[x] = 1
                    onef = 0
                    B.append([x,A[x]])
                    # P[x] = i
                    Q.append(x)
            s += 1
        if onef == 1:
            one += 1
        B.sort(key=lambda x:x[1])
        BB.append(B[0])

if len(BB) == 1:
    print(0)
elif one >= 3:
    print("Impossible")
else:
    ans = sum([i[1] for i in BB])
    # print(ans)
    anoBind = [0] * n
    anoB = []
    for i in range(len(BB)):
        anoBind[BB[i][0]] = 1
    for i in range(n):
        if anoBind[i] == 0:
            anoB.append(A[i])
    anoB.sort()
    # print(anoB)
    ans += sum(anoB[:len(BB)-2])
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,m = map(int,input().split())
A = list(map(int,input().split()))
C = [list(map(int,input().split())) for i in range(m)]

V = [0] * (n)
# P = [-1] * (n+1)

M = [[] for i in range(n)]
for i in range(m):
    M[C[i][0]].append(C[i][1])
    M[C[i][1]].append(C[i][0])

# 1始まりの場合
BB = []
for ii in range(n):
    B = []
    if V[ii] == 0:
        Q = [ii]
        s = 0
        V[ii] = 1
        B.append(A[ii])
        while s < len(Q):
            i = Q[s]
            for x in M[i]:
                if V[x] == 0:
                    V[x] = 1
                    B.append(A[x])
                    # P[x] = i
                    Q.append(x)
            s += 1
        if len(B) == 1:
            B.append(10**16)
        B.sort()
        BB.append([B[0], B[1]])

if len(BB) == 1:
    print(0)
else:
    B1 = [i[1] for i in BB]
    B1.sort()
    ans = sum([i[0]+i[1] for i in BB]) - B1[-1] - B1[-2]
    if ans >= 10**16:
        print("Impossible")
    else:
        print(ans)

Submission status: Wrong Answer

Solution code:
n,m,*L=map(int,open(0).read().split())
a=L[:n];b=L[n:]
if n//2+m<n-1:
	print('Impossible')
	exit()
con=[[] for _ in range(n)]
vis=[0]*n
for x,y in zip(*[iter(b)]*2):
	con[x].append(y)
	con[y].append(x)
least=[]
rest=[]
cnt=0
for i in range(n):
	if not vis[i]:
		cnt+=1
		q=[i]
		es=[a[i]]
		vis[i]=1
		while q:
			cur=q.pop()
			for nxt in con[cur]:
				if not vis[nxt]:
					q.append(nxt)
					es.append(a[nxt])
					vis[nxt]=1
		mi=min(es)
		es.remove(mi)
		least.append(mi)
		rest+=es
# print(least,rest)
if cnt==1:
	least=[]
print(sum(least+sorted(rest)[:2*(n-1-m)-cnt]))

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
k = n - m
we = list(map(int,input().split()))
pre = [i for i in range(n)]
for _ in range(m):
  a,b = map(int,input().split())
  while a != pre[a]:
    a = pre[a]
  while b != pre[b]:
    b = pre[b]
  if a != b:
    pre[b] = a
#print(pre)
root = []
for i in range(n):
  I = int(i)
  while I != pre[I]:
    I = pre[I]
  root.append(I)
#print(root)
rel = [10**6 for _ in range(n)]
cnt = 0
for i in range(n):
  if root[i] == i:
    rel[i] = cnt
    cnt += 1
#print(rel)
trees = [[] for _ in range(k)]
for i in range(n):
  trees[rel[root[i]]].append(we[i])
#print(trees)
import heapq
now = trees[0]
heapq.heapify(now)
ans = 0
for j in range(1,k):
  if not now:
    print('Impossible')
    exit()
  w0 = heapq.heappop(now)
  w1 = min(trees[j])
  ans += w0 + w1
  att = 0
  for x in trees[j]:
    if att == 1 or x != w1:
      heapq.heappush(now,x)
    else:
      att = 1
print(ans)

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
k = n - m
we = list(map(int,input().split()))
pre = [i for i in range(n)]
for _ in range(m):
  a,b = map(int,input().split())
  while a != pre[a]:
    a = pre[a]
  while b != pre[b]:
    b = pre[b]
  if a != b:
    pre[b] = a
#print(pre)
root = []
for i in range(n):
  I = int(i)
  while I != pre[I]:
    I = pre[I]
  root.append(I)
#print(root)
rel = [-1 for _ in range(n)]
cnt = 0
for i in range(n):
  if root[i] == i:
    rel[i] = cnt
    cnt += 1
#print(rel)
trees = [[] for _ in range(k)]
for i in range(n):
  trees[rel[root[i]]].append([we[i],i])
#print(trees)
import heapq
now = trees[0]
heapq.heapify(now)
ans = 0
for j in range(1,k):
  if not now:
    print('Impossible')
    exit()
  w0,i0 = heapq.heappop(now)
  w1,i1 = min(trees[j])
  ans += w0 + w1
  for x in trees[j]:
    if x[1] != i1:
      heapq.heappush(now,x)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque, defaultdict
import heapq

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M = lr()
A = lr()

# Aでxの根を求める
def find(A,x):
    p = A[x]
    if p == x:
        return x
    a = find(A,p)
    A[x] = a
    return a

# Aでxとyの属する集合の併合
def union(A, x, y):
    if find(A,x) > find(A,y):
        bx, by = find(A,y), find(A,x)
    else:
        bx, by = find(A,x), find(A,y)
    # 根をbxに統一
    A[by] = bx

edges = [[] for _ in range(N)]
V = [i for i in range(N)]
for _ in range(M):
    x, y = lr()
    if find(V, x) != find(V, y):
        union(V, x, y)
    edges[x].append(y)
    edges[y].append(x)

for i in range(N):
    V[i] = find(V, i)

if M == N - 1:
    print(0); exit()
elif N < 2 * (N-M-1):
    print('Impossible'); exit()

# 孤立していない頂点の根
roots = [V[i] for i in range(N)]
root_point = defaultdict(list)
for i in range(N):
    r = V[i]
    heapq.heappush(root_point[r], A[i])

#各グループの最小値以外で使うコストの数
answer = 0
candidates = []
for p_list in root_point:
    answer += heapq.heappop(root_point[p_list])
    candidates.extend(root_point[p_list])

remain = 2 * (N-M-1) - len(root_point)
candidates.sort(reverse=True)
answer += sum(candidates[:remain])
print(answer)

Submission status: Wrong Answer

Solution code:
import heapq
from collections import defaultdict
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)


class UF_tree:
    def __init__(self, n):
        self.root = [-1] * (n + 1)  # -1ならそのノードが根,で絶対値が木の要素数
        self.rank = [0] * (n + 1)

    def find(self, x):  # xの根となる要素番号を返す
        if self.root[x] < 0:
            return x
        else:
            self.root[x] = self.find(self.root[x])
            return self.root[x]

    def isSame(self, x, y):
        return self.find(x) == self.find(y)

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        elif self.rank[x] < self.rank[y]:
            self.root[y] += self.root[x]
            self.root[x] = y
        else:
            self.root[x] += self.root[y]
            self.root[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def getNodeLen(self, x):
        return -self.root[self.find(x)]


if __name__ == "__main__":
    N, M = map(int, input().split())
    if M == N - 1:
        print(0)
        exit()
    elif N < 2 * (N - M - 1):
        print("Impossible")
        exit()

    A = list(map(int, input().split()))

    uf = UF_tree(N)
    for _ in range(M):
        x, y = map(int, input().split())
        uf.unite(x, y)

    d = defaultdict(list)
    for i in range(N):
        heapq.heappush(d[uf.find(i)], A[i])
        d[uf.find(i)].append(A[i])

    nodes = 2 * (N - M - 1)
    ans = 0
    tmp = []
    for k, v in d.items():
        ans += heapq.heappop(v)
        tmp.extend(v)
        nodes -= 1

    tmp.sort()
    ans += sum(tmp[:nodes])
    print(ans)

Submission status: Wrong Answer

Solution code:
import heapq
from collections import defaultdict
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)


class UF_tree:
    def __init__(self, n):
        self.root = [-1] * (n + 1)  # -1ならそのノードが根,で絶対値が木の要素数
        self.rank = [0] * (n + 1)

    def find(self, x):  # xの根となる要素番号を返す
        if self.root[x] < 0:
            return x
        else:
            self.root[x] = self.find(self.root[x])
            return self.root[x]

    def isSame(self, x, y):
        return self.find(x) == self.find(y)

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        elif self.rank[x] < self.rank[y]:
            self.root[y] += self.root[x]
            self.root[x] = y
        else:
            self.root[x] += self.root[y]
            self.root[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def getNodeLen(self, x):
        return -self.root[self.find(x)]


if __name__ == "__main__":
    N, M = map(int, input().split())
    A = list(map(int, input().split()))

    uf = UF_tree(N)
    for _ in range(M):
        x, y = map(int, input().split())
        uf.unite(x, y)

    d = defaultdict(list)
    for i in range(N):
        heapq.heappush(d[uf.find(i)], A[i])
        d[uf.find(i)].append(A[i])

    Ncomp = len(d)
    loss = 2 * (Ncomp - 1)
    if N < loss:
        print("Impossible")
        exit()
    elif Ncomp == 1:
        print(0)
        exit()

    ans = 0
    tmp = []
    for k, v in d.items():
        ans += heapq.heappop(v)
        while v:
            heapq.heappush(tmp, v.pop())
    for _ in range(loss - Ncomp):
        ans += heapq.heappop(tmp)

    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict
import heapq

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M = lr()
A = lr()

# Aでxの根を求める
def find(A,x):
    p = A[x]
    if p == x:
        return x
    a = find(A,p)
    A[x] = a
    return a

# Aでxとyの属する集合の併合
def union(A, x, y):
    if find(A,x) > find(A,y):
        bx, by = find(A,y), find(A,x)
    else:
        bx, by = find(A,x), find(A,y)
    # 根をbxに統一
    A[by] = bx

edges = [[] for _ in range(N)]
V = [i for i in range(N)]
for _ in range(M):
    x, y = lr()
    if find(V, x) != find(V, y):
        union(V, x, y)
    edges[x].append(y)
    edges[y].append(x)

for i in range(N):
    V[i] = find(V, i)

dig_0 = [i for i in range(N) if len(edges[i]) == 0]
l0 = len(dig_0)
if N == 1:
    print(0); exit()
elif l0 > N//2:
    print('Impossible'); exit()

# 孤立していない頂点の根
roots = [V[i] for i in range(N) if i not in dig_0]
root_point = defaultdict(list)
for i in range(N):
    if i in dig_0:
        continue
    r = V[i]
    heapq.heappush(root_point[r], A[i])

#各グループの最小値以外で使うコストの数
remain = (l0 + len(set(roots)) - 1) * 2 - (l0 + len(set(roots)))
answer = 0
for i in dig_0:
    answer += A[i]

candidates = []
for po in root_point:
    answer += heapq.heappop(root_point[po])
    for i in range(min(remain, len(root_point[po]))):
        heapq.heappush(candidates, heapq.heappop(root_point[po]))

for i in range(remain):
    answer += heapq.heappop(candidates)
print(answer)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque, defaultdict
import heapq

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M = lr()
A = lr()

# Aでxの根を求める
def find(A,x):
    p = A[x]
    if p == x:
        return x
    a = find(A,p)
    A[x] = a
    return a

# Aでxとyの属する集合の併合
def union(A, x, y):
    if find(A,x) > find(A,y):
        bx, by = find(A,y), find(A,x)
    else:
        bx, by = find(A,x), find(A,y)
    # 根をbxに統一
    A[by] = bx

edges = [[] for _ in range(N)]
V = [i for i in range(N)]
for _ in range(M):
    x, y = lr()
    if find(V, x) != find(V, y):
        union(V, x, y)
    edges[x].append(y)
    edges[y].append(x)

for i in range(N):
    V[i] = find(V, i)

dig_0 = [i for i in range(N) if len(edges[i]) == 0]
l0 = len(dig_0)
if N == 1:
    print(0); exit()
elif l0 > N//2:
    print('Impossible'); exit()

# 孤立していない頂点の根
roots = [V[i] for i in range(N) if i not in dig_0]
root_point = defaultdict(list)
for i in range(N):
    if i in dig_0:
        continue
    r = V[i]
    heapq.heappush(root_point[r], A[i])

#各グループの最小値以外で使うコストの数
remain = (l0 + len(set(roots)) - 1) * 2 - (l0 + len(set(roots)))
answer = 0
for i in dig_0:
    answer += A[i]

candidates = []
for po in root_point:
    answer += heapq.heappop(root_point[po])
    for i in range(min(remain, len(root_point[po]))):
        heapq.heappush(candidates, heapq.heappop(root_point[po]))

for i in range(remain):
    answer += heapq.heappop(candidates)
print(answer)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque, defaultdict

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M = lr()
A = lr()

# Aでxの根を求める
def find(A,x):
    p = A[x]
    if p == x:
        return x
    a = find(A,p)
    A[x] = a
    return a

# Aでxとyの属する集合の併合
def union(A, x, y):
    if find(A,x) > find(A,y):
        bx, by = find(A,y), find(A,x)
    else:
        bx, by = find(A,x), find(A,y)
    # 根をbxに統一
    A[by] = bx

edges = [[] for _ in range(N)]
V = [i for i in range(N)]
for _ in range(M):
    x, y = lr()
    if find(V, x) != find(V, y):
        union(V, x, y)
    edges[x].append(y)
    edges[y].append(x)

for i in range(N):
    V[i] = find(V, i)

dig_0 = [i for i in range(N) if len(edges[i]) == 0]
l0 = len(dig_0)
if N == 1:
    print(0); exit()
elif l0 > N//2:
    print('Impossible'); exit()

# 孤立していない頂点の根
roots = [V[i] for i in range(N) if i not in dig_0]
root_point = defaultdict(deque)
for i in range(N):
    if i in dig_0:
        continue
    r = V[i]
    root_point[r].append(A[i])

#各グループの最小値以外で使うコストの数
remain = (l0 + len(set(roots)) - 1) * 2 - (l0 + len(set(roots)))
answer = 0
for i in dig_0:
    answer += A[i]

candidates = deque()
for po in root_point:
    answer += root_point[po].popleft()
    for i in range(min(remain, len(root_point[po]))):
        candidates.append(root_point[po].popleft())

for i in range(remain):
    answer += candidates.popleft()
print(answer)
# 43

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heapify, heappop, heappush

class UFT(): #Union-find tree class
    def __init__(self, N): 
        self.tree = [int(i) for i in range(N)] 
        self.rank = [0 for i in range(N)]

    def find(self, a):
        if self.tree[a] == a: return a
        else:
            self.tree[a] = self.find(self.tree[a])
            return self.tree[a]

    def unite(self, a, b):
        a = self.find(a)
        b = self.find(b)
        if a == b: return
        if self.rank[a] < self.rank[b]: self.tree[a] = b
        else:
            self.tree[b] = a
            if self.rank[a] == self.rank[b]: self.rank[a] += 1
def solve():
    N, M = map(int, input().split())
    A = [int(a) for a in input().split()]
    parent = UFT(N)
    for i in range(M):
        x, y = map(int, input().split())
        parent.unite(x, y)
    for i in range(N):
        a = parent.find(i)

    minCost = 0
    minF = dict()
    for i in range(N):
        a = parent.find(i)
        if a in minF: heappush(minF[a], A[i])
        else: 
            minF[a] = []
            heapify(minF[a])
            heappush(minF[a], A[i])

    par = parent.find(0)
    f = []
    heapify(f)
    for key in minF: heappush(f, (heappop(minF[key]), key))
    parNode = []
    heapify(parNode)
    startCost, startNode = heappop(f)
    heappush(parNode, startCost)
    while minF[startNode]: heappush(parNode, heappop(minF[startNode]))

    while f:
        if not parNode: 
            print("Impossible")
            break
        nextPar = heappop(parNode)
        addCost, nextSon = heappop(f)
        minCost += nextPar + addCost
        while minF[nextSon]: heappush(parNode, heappop(minF[nextSon]))
    else: print(minCost)



    return 0

if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heapify, heappop, heappush

class UFT(): #Union-find tree class
    def __init__(self, N): 
        self.tree = [int(i) for i in range(N)] 
        self.rank = [0 for i in range(N)]

    def find(self, a):
        if self.tree[a] == a: return a
        else:
            self.tree[a] = self.find(self.tree[a])
            return self.tree[a]

    def unite(self, a, b):
        a = self.find(a)
        b = self.find(b)
        if a == b: return
        if self.rank[a] < self.rank[b]: self.tree[a] = b
        else:
            self.tree[b] = a
            if self.rank[a] == self.rank[b]: self.rank[a] += 1
def solve():
    N, M = map(int, input().split())
    A = [int(a) for a in input().split()]
    parent = UFT(N)
    for i in range(M):
        x, y = map(int, input().split())
        parent.unite(x, y)
    for i in range(N):
        a = parent.find(i)

    minCost = 0
    minF = dict()
    for i in range(N):
        a = parent.find(i)
        if a in minF: heappush(minF[a], A[i])
        else: 
            minF[a] = []
            heapify(minF[a])
            heappush(minF[a], A[i])

    par = parent.find(0)
    f = []
    heapify(f)
    for key in minF: 
        if key != par: 
            heappush(f, (heappop(minF[key]), key))

    while f:
        if not minF[par]: 
            print("Impossible")
            break
        nextPar = heappop(minF[par])
        addCost, nextSon = heappop(f)
        minCost += nextPar + addCost
        while minF[nextSon]: heappush(minF[par], heappop(minF[nextSon]))
    else: print(minCost)



    return 0

if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
import collections
import heapq
N, M = map(int, input().split())
a = list(map(int, input().split()))


class unionFind:
    parent = []
    count = []

    def __init__(self, N):
        self.parent = [i for i in range(N)]
        self.count = [1 for i in range(N)]

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

    def same(self, x, y):
        x, y = x-1, y-1
        return(self.root(x) == self.root(y))

    def unite(self, x, y):
        x, y = x-1, y-1
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return
        else:
            self.parent[x] = y
            self.count[y] += self.count[x]
            self.count[x] = self.count[y]
            return


G = unionFind(N)
for i in range(M):
    x, y = map(int, input().split())
    G.unite(x+1, y+1)
A = [(a[i], i) for i in range(N)]
A.sort(key=lambda x: (-G.count[x[1]], x[0]))
a1 = 0
x = 0
ans = 0
t = []
for a, x in A:
    x = G.root(x)
    if len(t) > 0:
        if G.root(t[0][1]) == x:
            heapq.heappush(t, (a, x))
        else:
            a1, y = heapq.heappop(t)
            y = G.root(y)
            ans += (a + a1)
            G.unite(x+1, y+1)
    else:
        heapq.heappush(t, (a, x))


s = set()
for i in range(N):
    s.add(G.root(i))
if len(s) == 1:
    print(ans)
else:
    print("Impossible")

Submission status: Wrong Answer

Solution code:
import collections
import heapq
N, M = map(int, input().split())
a = list(map(int, input().split()))


class unionFind:
    parent = []

    def __init__(self, N):
        self.parent = [i for i in range(N)]

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

    def same(self, x, y):
        x, y = x-1, y-1
        return(self.root(x) == self.root(y))

    def unite(self, x, y):
        x, y = x-1, y-1
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return
        else:
            self.parent[x] = y
            return


G = unionFind(N)
for i in range(M):
    x, y = map(int, input().split())
    G.unite(x+1, y+1)
A = [(a[i], i) for i in range(N)]
A.sort(key=lambda x: (x[1], x[0]))
a1 = 0
x = 0
ans = 0
t = []
for a, x in A:
    x = G.root(x)
    if len(t) > 0:
        if G.root(t[0][1]) == x:
            heapq.heappush(t, (a, x))
        else:
            a1, y = heapq.heappop(t)
            y = G.root(y)
            ans += (a + a1)
            G.unite(x+1, y+1)
    else:
        heapq.heappush(t, (a, G.root(x)))


s = set()
for i in range(N):
    s.add(G.root(i))
if len(s) == 1:
    print(ans)
else:
    print("Impossible")
    # print(ans)
    # print(s)

Submission status: Wrong Answer

Solution code:
import collections
import heapq
N, M = map(int, input().split())
a = list(map(int, input().split()))


class unionFind:
    parent = []

    def __init__(self, N):
        self.parent = [i for i in range(N)]

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

    def same(self, x, y):
        x, y = x-1, y-1
        return(self.root(x) == self.root(y))

    def unite(self, x, y):
        x, y = x-1, y-1
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return
        else:
            self.parent[x] = y
            return


G = unionFind(N)
for i in range(M):
    x, y = map(int, input().split())
    G.unite(x+1, y+1)
A = [(a[i], i) for i in range(N)]
A.sort(reverse=True)
a1 = 0
x = 0
ans = 0
t = [(A.pop())]

while(A):
    if t:
        a1, x = heapq.heappop(t)
    else:
        a1, x = A.pop()
    x = G.root(x)
    if A:
        a2, y = A.pop()
        while(G.root(y) == x and A):
            heapq.heappush(t, (a2, y))
            a2, y = A.pop()
        if G.root(x) != G.root(y):
            ans += a1+a2
            y = G.root(y)
            G.unite(y+1, x+1)
        else:
            heapq.heappush(t, (a2, y))

s = set()
for i in range(N):
    s.add(G.root(i))
if len(s) == 1:
    print(ans)
else:
    print("Impossible")

Submission status: Wrong Answer

Solution code:
import collections
import heapq
N, M = map(int, input().split())
a = list(map(int, input().split()))


class unionFind:
    parent = []

    def __init__(self, N):
        self.parent = [i for i in range(N)]

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

    def same(self, x, y):
        x, y = x-1, y-1
        return(self.root(x) == self.root(y))

    def unite(self, x, y):
        x, y = x-1, y-1
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return
        else:
            self.parent[x] = y
            return


G = unionFind(N)
for i in range(M):
    x, y = map(int, input().split())
    G.unite(x, y)
A = [(a[i], i) for i in range(N)]
A.sort(reverse=True)
z = -1
a3 = 0
a1 = 0
x = 0
ans = 0
while(A):
    if z < 0:
        a1, x = A.pop()
    else:
        a1 = a3
        x = z
        z = -1
    x = G.root(x)
    if A:
        a2, y = A.pop()
        while(G.root(y) == x and A):
            if z < 0:
                a3 = a2
                z = y
            a2, y = A.pop()
        if x != G.root(y):
            ans += a2 + a3
            G.unite(x, y)
s = set()
for i in range(N):
    s.add(G.root(i))
if len(s) == 1:
    print(ans)
else:
    print("Impossible")