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:
from collections import defaultdict
from collections import deque
N,M = map(int,input().split())
src = list(map(int,input().split()))
es = [tuple(map(int,input().split())) for i in range(M)]

if N == 1:
    print(0)
    exit()
if M + N//2 < N-1:
    print('Impossible')
    exit()

parent = [i for i in range(N)]
rank = [0] * N
def root(a):
    if parent[a] == a:
        return a
    else:
        parent[a] = root(parent[a])
        return parent[a]
def same(a,b):
    return root(a) == root(b)
def unite(a,b):
    ra = root(a)
    rb = root(b)
    if ra == rb: return
    if rank[ra] < rank[rb]:
        parent[ra] = rb
    else:
        parent[rb] = ra
        if rank[ra] == rank[rb]: rank[ra] += 1

for a,b in es:
    unite(a,b)
for i in range(N):
    root(i)

costs = []
for i,c in enumerate(src):
    costs.append((c,i))
costs.sort()

ans = 0
i,j = 0,1
qs = defaultdict(lambda: deque())
while j < N:
    ci,vi = costs[i]
    cj,vj = costs[j]
    if same(vi,vj):
        j += 1
        qs[root(vj)].append(cj)
    else:
        cost = ci
        rj = root(vj)
        if qs[rj]:
            cost += qs[rj].popleft()
        else:
            cost += cj
        ans += cost
        unite(vi,vj)
        i = j+1
        j = i+1
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque
N,M = map(int,input().split())
src = list(map(int,input().split()))
es = [tuple(map(int,input().split())) for i in range(M)]

if N == 1:
    print(0)
    exit()
if M + N//2 < N-1:
    print('Impossible')
    exit()

parent = [i for i in range(N)]
rank = [0] * N
def root(a):
    if parent[a] == a:
        return a
    else:
        parent[a] = root(parent[a])
        return parent[a]
def same(a,b):
    return root(a) == root(b)
def unite(a,b):
    ra = root(a)
    rb = root(b)
    if ra == rb: return
    if rank[ra] < rank[rb]:
        parent[ra] = rb
    else:
        parent[rb] = ra
        if rank[ra] == rank[rb]: rank[ra] += 1

for a,b in es:
    unite(a,b)
for i in range(N):
    root(a)

costs = []
for i,c in enumerate(src):
    costs.append((c,i))
costs.sort()

ans = 0
i,j = 0,1
qs = defaultdict(lambda: deque())
while j < N:
    ci,vi = costs[i]
    cj,vj = costs[j]
    if same(vi,vj):
        j += 1
        qs[root(vj)].append(cj)
    else:
        cost = ci
        rj = root(vj)
        if qs[rj]:
            cost += qs[rj].popleft()
        else:
            cost += cj
        ans += cost
        unite(vi,vj)
        i = j+1
        j = i+1
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
from collections import deque
from heapq import heappush, heappop, heapify, merge
from collections import defaultdict
import sys
sys.setrecursionlimit(10**7)
def inpl(): return tuple(map(int, input().split()))
 
N, M = inpl()
A = inpl()
tree = [[-1, 1]  for _ in range(N)] # [next, rank]
 
def find(i):
    if tree[i][0] == -1:
        group = i
    else:
        group = find(tree[i][0]) 
        tree[i][0] = group
    return group
  
def unite(x, y):
    px = find(x)
    py = find(y)
      
    if tree[px][1] == tree[py][1]: # rank is same
        tree[py][0] = px
        tree[px][1] += 1
    else:
        if tree[px][1] < tree[py][1]:
            px, py = py, px
        tree[py][0] = px
  
for _ in range(M):
    x, y = tuple(map(int, input().split()))
    if not int(find(x) == find(y)):
        unite(x, y)
 
D = defaultdict(list)
for n in range(N):
    D[find(n)].append(A[n])
 
H = []
S = [] # single

for k, v in D.items():
    if len(v) == 1:
        S.append(v)
    else:
        H.append(sorted(v))
 
heapify(H)
heapify(S)
 
res = 0 
while True:
    if (len(H) == 0) or (len(S) + len(H) <= 1):
        break
    
    if len(S) > 0:
        A = heappop(S)
    else:
        A = heappop(H)
 
    B = heappop(H)
 
    res += A[0] + B[0]
    C = list(merge(A[1:], B[1:]))
 
    if len(C) == 1:
        heappush(S, C)
    else:
        heappush(H, C)
 
ok = True
if len(S) > 2:
    print("Impossible")
    ok = False
elif len(S) == 2:
    res += S[0][0]+S[1][0]
elif len(S) == 1:
    A = S[0]
    if len(H) == 1:
        B = heappop(H)
        res += A[0] + B[0]
else:
    pass
if ok:
    print(res)

Submission status: Wrong Answer

Solution code:
import copy
nm = list(map(int, input().split()))
a = list(map(int, input().split()))
b = []
for i in range(nm[1]):
    b.append(list(map(int, input().split())))
dot = {}
cost = {}
for i in range(nm[0]):
    dot.setdefault(i, [i])
    cost.setdefault(i, [a[i]])
def line(x, y):
    global dot, cost
    new_dot = copy.deepcopy(dot)
    new_cost = copy.deepcopy(cost)
    for i in dot.keys():
        for j in dot.keys():
            if x in dot[i] and y in dot[j]:
                new_dot.setdefault(max(dot.keys()) + 1, dot[i] + dot[j])
                del new_dot[i]
                del new_dot[j]
                new_cost.setdefault(max(cost.keys()) + 1, cost[i] + cost[j])
                del new_cost[i]
                del new_cost[j]
    dot = copy.deepcopy(new_dot)
    cost = copy.deepcopy(new_cost)
for i in range(nm[1]):
    line(b[i][0], b[i][1])

total_cost = 0
def new_line(x, y):
    global dot, cost, total_cost
    new_dot = copy.deepcopy(dot)
    new_cost = copy.deepcopy(cost)
    for i in dot.keys():
        for j in dot.keys():
            if x in dot[i] and y in dot[j]:
                dot[i].remove(min(dot[i]))
                dot[j].remove(min(dot[j]))
                new_dot.setdefault(max(dot.keys()) + 1, dot[i] + dot[j])
                del new_dot[i]
                del new_dot[j]
                total_cost = total_cost + min(cost[i]) + min(cost[j])
                cost[i].remove(min(cost[i]))
                cost[j].remove(min(cost[j]))
                new_cost.setdefault(max(cost.keys()) + 1, cost[i] + cost[j])
                del new_cost[i]
                del new_cost[j]
    dot = copy.deepcopy(new_dot)
    cost = copy.deepcopy(new_cost)

def link_island(a, b):
    new_line(min(dot[a]), min(dot[b]))

island = list(dot.keys())
try:
    for i in range(1, len(island)):
        link_island(island[0], island[i])
    print(total_cost)
except:
    print("Impossible")

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque
N,M = map(int,input().split())
src = list(map(int,input().split()))
es = [tuple(map(int,input().split())) for i in range(M)]

if N == 1:
    print(0)
    exit()
if M + N//2 < N-1:
    print('Impossible')
    exit()

parent = [i for i in range(N)]
rank = [0] * N
def root(a):
    if parent[a] == a:
        return a
    else:
        parent[a] = root(parent[a])
        return parent[a]
def same(a,b):
    return root(a) == root(b)
def unite(a,b):
    ra = root(a)
    rb = root(b)
    if ra == rb: return
    if rank[ra] < rank[rb]:
        parent[ra] = rb
    else:
        parent[rb] = ra
        if rank[ra] == rank[rb]: rank[ra] += 1

for a,b in es:
    unite(a,b)

costs = []
for i,c in enumerate(src):
    costs.append((c,i))
costs.sort()

ans = 0
i,j = 0,1
qs = defaultdict(lambda: deque())
while j < N:
    ci,vi = costs[i]
    cj,vj = costs[j]
    if same(vi,vj):
        j += 1
        qs[root(vj)].append(cj)
    else:
        cost = ci
        rj = root(vj)
        if qs[rj]:
            cost += qs[rj].popleft()
        else:
            cost += cj
        ans += cost
        unite(vi,vj)
        i = j+1
        j = i+1
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
from collections import deque
from heapq import heappush, heappop, heapify, merge
from collections import defaultdict
import sys
sys.setrecursionlimit(10**7)
def inpl(): return tuple(map(int, input().split()))
 
N, M = inpl()
A = inpl()
tree = [[-1, 1]  for _ in range(N)] # [next, rank]
 
def find(i):
    if tree[i][0] == -1:
        group = i
    else:
        group = find(tree[i][0]) 
        tree[i][0] = group
    return group
  
def unite(x, y):
    px = find(x)
    py = find(y)
      
    if tree[px][1] == tree[py][1]: # rank is same
        tree[py][0] = px
        tree[px][1] += 1
    else:
        if tree[px][1] < tree[py][1]:
            px, py = py, px
        tree[py][0] = px
  
for _ in range(M):
    x, y = tuple(map(int, input().split()))
    if not int(find(x) == find(y)):
        unite(x, y)
 
D = defaultdict(list)
for n in range(N):
    D[find(n)].append(A[n])
 
H = []
S = [] # single

for k, v in D.items():
    if len(v) == 1:
        S.append(v)
    else:
        H.append(sorted(v))
 
heapify(H)
heapify(S)
 
res = 0 
while True:
    if (len(H) == 0) or (len(S) + len(H) <= 1):
        break
    
    if len(S) > 0:
        A = heappop(S)
    else:
        A = heappop(H)
 
    B = heappop(H)
 
    res += A[0] + B[0]
    C = list(merge(A[1:], B[1:]))[:len(H)+len(S)+2]
 
    if len(C) == 1:
        heappush(S, C)
    else:
        heappush(H, C)
 
ok = True
if len(S) > 2:
    print("Impossible")
    ok = False
elif len(S) == 2:
    res += S[0][0]+S[1][0]
elif len(S) == 1:
    A = S[0]
    if len(H) == 1:
        B = heappop(H)
        res += A[0] + B[0]
else:
    pass
if ok:
    print(res)

Submission status: Wrong Answer

Solution code:
n, m = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
g = [[] for _ in range(n)]

if m == 0:
    print(0 if n == 1 else "Impossible")
    exit()

for _ in range(m):
    x, y = [int(x) for x in input().split()]
    g[x].append(y)
    g[y].append(x)
# print(g)
# print("=" * 50)

n_list = list(range(0, n - 1))
visited = []
f_group = []

while len(n_list) > 0:
    q = [n_list[0]]
    visited = []
    while len(q) > 0:
        pos_c = q.pop(0)
        for pos_n in g[pos_c]:
            if pos_n not in visited:
                q.append(pos_n)
                visited.append(pos_n)
    f_group.append(visited)
    n_list = list(set(n_list) - set(visited))

if len(f_group) == 1:
    print(0)
    exit()
# print(f_group)

f_node = []
for l in f_group:
    score = float("inf")
    for idx in l:
        if a[idx] < score:
            score = a[idx]
    f_node.append(score)

# print(f_node)
f_node.sort()
print(sum(f_node) + (len(f_node) - 2)*f_node[0])
#print(len(f_node))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
from collections import deque
from heapq import heappush, heappop, heapify, merge
from collections import defaultdict
import sys
sys.setrecursionlimit(10**7)
def inpl(): return tuple(map(int, input().split()))
 
N, M = inpl()
A = inpl()
tree = [[-1, 1]  for _ in range(N)] # [next, rank]
 
def find(i):
    if tree[i][0] == -1:
        group = i
    else:
        group = find(tree[i][0]) 
        tree[i][0] = group
    return group
  
def unite(x, y):
    px = find(x)
    py = find(y)
      
    if tree[px][1] == tree[py][1]: # rank is same
        tree[py][0] = px
        tree[px][1] += 1
    else:
        if tree[px][1] < tree[py][1]:
            px, py = py, px
        tree[py][0] = px
  
for _ in range(M):
    x, y = tuple(map(int, input().split()))
    if not int(find(x) == find(y)):
        unite(x, y)
 
D = defaultdict(list)
for n in range(N):
    D[find(n)].append(A[n])
 
H = []
S = deque([]) # single

for k, v in D.items():
    if len(v) == 1:
        S.append(v)
    else:
        H.append(sorted(v))
 
heapify(H)
 
res = 0 
while True:
    if (len(H) == 0) or (len(S) + len(H) <= 1):
        break
    
    if len(S) > 0:
        A = S.popleft()
    else:
        if len(H) <= 1:
            break
        A = heappop(H)
 
    B = heappop(H)
 
    res += A[0] + B[0]
    C = list(merge(A[1:], B[1:]))[:len(H)+len(S)+2]
 
    if len(C) == 1:
        S.append(C)
    elif len(C) == 0: # ありえないはず
        pass
    else:
        heappush(H, C)
 
ok = True
if len(S) > 2:
    print("Impossible")
    ok = False
elif len(S) == 2:
    res += S[0][0]+S[1][0]
elif len(S) == 1:
    A = S[0]
    if len(H) == 1:
        B = heappop(H)
        res += A[0] + B[0]
else:
    pass
if ok:
    print(res)

Submission status: Wrong Answer

Solution code:
n, m = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
g = [[] for _ in range(n)]

if m == 0:
    print(0 if n == 1 else "Impossible")
    exit()

for _ in range(m):
    x, y = [int(x) for x in input().split()]
    g[x].append(y)
    g[y].append(x)
# print(g)
# print("=" * 50)

n_list = list(range(0, n - 1))
visited = []
f_group = []

while len(n_list) > 0:
    q = [n_list[0]]
    visited = []
    while len(q) > 0:
        pos_c = q.pop(0)
        for pos_n in g[pos_c]:
            if pos_n not in visited:
                q.append(pos_n)
                visited.append(pos_n)
    f_group.append(visited)
    n_list = list(set(n_list) - set(visited))
# print(f_group)

ans = 0
for l in f_group:
    score = float("inf")
    for idx in l:
        if a[idx] < score:
            score = a[idx]
    ans += score

print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
from collections import deque
from heapq import heappush, heappop, heapify, merge
from collections import defaultdict
import sys
sys.setrecursionlimit(10**7)
def inpl(): return tuple(map(int, input().split()))
 
N, M = inpl()
A = inpl()
tree = [[-1, 1]  for _ in range(N)] # [next, rank]
 
def find(i):
    if tree[i][0] == -1:
        group = i
    else:
        group = find(tree[i][0]) 
        tree[i][0] = group
    return group
  
def unite(x, y):
    px = find(x)
    py = find(y)
      
    if tree[px][1] == tree[py][1]: # rank is same
        tree[py][0] = px
        tree[px][1] += 1
    else:
        if tree[px][1] < tree[py][1]:
            px, py = py, px
        tree[py][0] = px
  
for _ in range(M):
    x, y = tuple(map(int, input().split()))
    if not int(find(x) == find(y)):
        unite(x, y)
 
D = defaultdict(list)
for n in range(N):
    D[find(n)].append(A[n])
 
H = []
S = deque([]) # single
for k, v in D.items():
    if len(v) == 1:
        S.append(v)
    else:
        H.append(sorted(v))
 
heapify(H)
 
res = 0 
while True:
    if (len(H) == 0) or (len(S) + len(H) <= 1):
        break
    
    if len(S) > 1:
        A = S.popleft()
    else:
        if len(H) <= 1:
            break
        A = heappop(H)
 
    B = heappop(H)
 
    res += A[0] + B[0]
    C = list(merge(A[1:], B[1:]))
 
    if len(C) == 1:
        S.append(C)
    elif len(C) == 0: # ありえないはず
        pass
    else:
        heappush(H, C)
 
ok = True
if len(S) > 2:
    print("Impossible")
    ok = False
elif len(S) == 2:
    res += S[0][0]+S[1][0]
elif len(S) == 1:
    A = S[0]
    if len(H) == 1:
        B = heappop(H)
        res += A[0] + B[0]
else:
    pass
if ok:
    print(res)

Submission status: Wrong Answer

Solution code:
import heapq
N,M = map(int,input().split())
src = list(map(int,input().split()))
es = [tuple(map(int,input().split())) for i in range(M)]

if N == 1:
    print(0)
    exit()
if M + N//2 < N-1:
    print('Impossible')
    exit()

parent = [i for i in range(N)]
rank = [0] * N
def root(a):
    if parent[a] == a:
        return a
    else:
        parent[a] = root(parent[a])
        return parent[a]
def same(a,b):
    return root(a) == root(b)
def unite(a,b):
    ra = root(a)
    rb = root(b)
    if ra == rb: return
    if rank[ra] < rank[rb]:
        parent[ra] = rb
    else:
        parent[rb] = ra
        if rank[ra] == rank[rb]: rank[ra] += 1

for a,b in es:
    unite(a,b)

costs = []
for i,c in enumerate(src):
    costs.append((c,i))
costs.sort()

ans = 0
i,j = 0,1
while j < N:
    ci,vi = costs[i]
    cj,vj = costs[j]
    if same(vi,vj):
        j += 1
    else:
        ans += ci+cj
        unite(vi,vj)
        i = j+1
        j = i+1
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import heapq

n, m = map(int, input().split())
a = list(map(int, input().split()))

qs = {}
graph = [[] for x in range(n)]
for i in range(m):
    _from, _to = map(int, input().split())
    graph[_from].append(_to)
    graph[_to].append(_from)

visited = [False for x in range(n)]
# print(graph)

for i in range(n):
    first = i
    if visited[i]:
        continue
    que = [[first]]
    q_target = qs.get(first) or []
    while que:
        targets = que.pop()
        for next_target in targets:
            if not visited[next_target]:
                q_target.append(a[next_target])
                visited[next_target] = True
                que.append(graph[next_target])

    q_target.sort()
    qs[first] = q_target
    # print(i)
    # print(visited)
    # print(qs[first])

# print("====")
# print(qs)
# print("====")
cost = 0
first = 0
def impossible():
    print("Impossible")
    sys.exit()


while True:
    qsf = qs[first]
    if not qsf:
        impossible()

    min_v = float("inf")
    result = None
    for key, value in qs.items():
        if key == first:
            continue
        v = value[0]
        if min_v > v:
            result = key, v
            min_v = v

    if result is None:
        print(0)
        sys.exit()

    cost += result[1] + qsf[0]
    qs[first] = list(heapq.merge(qs[first][1:], qs[result[0]][1:]))
    del qs[result[0]]
    if len(qs.keys()) == 1:
        print(cost)
        sys.exit()
    # print(qs)
    # print(cost)

Submission status: Wrong Answer

Solution code:
import math
min_v = float("inf")

Submission status: Wrong Answer

Solution code:
import math
import sys
import heapq

n, m = map(int, input().split())
a = list(map(int, input().split()))

qs = {}
graph = [[] for x in range(n)]
for i in range(m):
    _from, _to = map(int, input().split())
    graph[_from].append(_to)
    graph[_to].append(_from)

visited = [False for x in range(n)]
# print(graph)

for i in range(n):
    first = i
    if visited[i]:
        continue
    que = [[first]]
    q_target = qs.get(first) or []
    while que:
        targets = que.pop()
        for next_target in targets:
            if not visited[next_target]:
                q_target.append(a[next_target])
                visited[next_target] = True
                que.append(graph[next_target])

    q_target.sort()
    qs[first] = q_target
    # print(i)
    # print(visited)
    # print(qs[first])

# print("====")
# print(qs)
# print("====")
cost = 0
first = 0
def impossible():
    print("Impossible")
    sys.exit()


qsf = qs[first]
if not qsf:
    impossible()

Submission status: Wrong Answer

Solution code:
import math
import sys
import heapq

n, m = map(int, input().split())
a = list(map(int, input().split()))

qs = {}
graph = [[] for x in range(n)]
for i in range(m):
    _from, _to = map(int, input().split())
    graph[_from].append(_to)
    graph[_to].append(_from)

visited = [False for x in range(n)]
# print(graph)

for i in range(n):
    first = i
    if visited[i]:
        continue
    que = [[first]]
    q_target = qs.get(first) or []
    while que:
        targets = que.pop()
        for next_target in targets:
            if not visited[next_target]:
                q_target.append(a[next_target])
                visited[next_target] = True
                que.append(graph[next_target])

    q_target.sort()
    qs[first] = q_target
    # print(i)
    # print(visited)
    # print(qs[first])

# print("====")
# print(qs)
# print("====")
cost = 0
first = 0
def impossible():
    print("Impossible")
    sys.exit()


qsf = qs[first]

Submission status: Wrong Answer

Solution code:

import heapq

n, m = map(int, input().split())
a = list(map(int, input().split()))

qs = {}
graph = [[] for x in range(n)]
for i in range(m):
    _from, _to = map(int, input().split())
    graph[_from].append(_to)
    graph[_to].append(_from)

visited = [False for x in range(n)]
# print(graph)

for i in range(n):
    first = i
    if visited[i]:
        continue
    que = [[first]]
    q_target = qs.get(first) or []
    while que:
        targets = que.pop()
        for next_target in targets:
            if not visited[next_target]:
                q_target.append(a[next_target])
                visited[next_target] = True
                que.append(graph[next_target])

    q_target.sort()
    qs[first] = q_target
    # print(i)
    # print(visited)
    # print(qs[first])

# print("====")
# print(qs)
# print("====")
cost = 0
first = 0
def impossible():
    print("Impossible")
    __import__("sys").exit()

Submission status: Wrong Answer

Solution code:
import heapq

n, m = map(int, input().split())
a = list(map(int, input().split()))

qs = {}
graph = [[] for x in range(n)]
for i in range(m):
    _from, _to = map(int, input().split())
    graph[_from].append(_to)
    graph[_to].append(_from)

Submission status: Wrong Answer

Solution code:
def a():
    x, y = map(int, input().split())


def b():
    import numpy as np
    n = int(input())
    a = np.asarray(list(map(int, input().split())))
    b = np.asarray(list(map(int, input().split())))
    x = b.sum() - a.sum()
    d = b - a
    a_req = 0
    b_req = 0
    for i in d:
        if i <= 0:
            b_req += i // -1
        else:
            a_req += i // 2 + i % 2
            b_req += i % 2
    # total require
    if (a_req >= b_req and (0 < a_req + (a_req - b_req) == x)) or (a_req == 0 and b_req == 0):
        print('Yes')
    else:
        print('No')


def d():
    n, m = map(int, input().split())
    a = list(map(int, input().split()))
    G = []
    for _ in range(m):
        s = set(map(int, input().split()))
        for S in G:
            if s & S:
                s |= S
        G = [i for i in G if not s >= i]
        G.append(s)
    G = [sorted([a[i] for i in S], reverse=True) for S in G]
    # 見なしのv, e
    _v = len(G)
    _e = _v - 1
    e = _e * 2
    cost = 0
    tmp = []
    for D in G:
        cost += D.pop()
        tmp += D
    tbd = e - _v
    cost += sum(sorted(tmp[:tbd]))
    print(cost)


if __name__ == '__main__':
    d()

Submission status: Wrong Answer

Solution code:
def findRoot(group, x):
	old_x = x
	while(group[x] != x):
		new_x = group[x]
		group[old_x] = new_x
		old_x = x
		x = new_x
	group[old_x] = x
	return x
def isSameGroup(group, x, y):
	return findRoot(group, x) == findRoot(group, y)

N,M = map(int,input().split())
a = list(map(int,input().split()))
group = [i for i in range(N)]
unused = [(True,i) for i in range(N)]
for i in range(M):
	x,y = map(int,input().split())
	unused[x] = (False, x)
	unused[y] = (False, y)
	if group[x] != x:
		group[y] = x
	elif group[y] != y:
		group[x] = y
	else:
		group[max(x,y)] = min(x,y)
if N == 1:
	print(0)
	exit()
unused = [i for b,i in unused if b]
ans = sum([a[i] for i in unused])
for i in unused:
	group[i] = 0
a_sorted = sorted([(a[i], i) for i in range(N) if not i in unused])
unusedNum = len(unused)

while len(a_sorted) > 0:
	cost, node = a_sorted.pop(0)
	root = findRoot(group, node)
	l = len(a_sorted)
	i = 0
	for i in range(l):
		c,n = a_sorted[i]
		if not root == findRoot(group, n):
			group[max(root,n)] = min(root,n)
			ans += cost + c
			a_sorted.pop(i)
			break
	if i == l - 1:
		break

if len(a_sorted) < unusedNum:
	print("Impossible")
	exit()
for i in range(1,N):
	if group[i] != 0 and findRoot(group, i) != 0:
		print("Impossible")
		exit()
for i in range(unusedNum):
	ans += a_sorted[i]
print(ans)
exit()

Submission status: Wrong Answer

Solution code:
def findRoot(group, x):
	old_x = x
	while(group[x] != x):
		new_x = group[x]
		group[old_x] = new_x
		old_x = x
		x = new_x
	group[old_x] = x
	return x
def isSameGroup(group, x, y):
	return findRoot(group, x) == findRoot(group, y)

N,M = map(int,input().split())
a = list(map(int,input().split()))
group = [i for i in range(N)]
unused = [(True,i) for i in range(N)]
for i in range(M):
	x,y = map(int,input().split())
	unused[x] = (False, x)
	unused[y] = (False, y)
	if group[x] != x:
		group[y] = x
	elif group[y] != y:
		group[x] = y
	else:
		group[max(x,y)] = min(x,y)
if N == 1:
	print(0)
	exit()
unused = [i for b,i in unused if b]
ans = sum([a[i] for i in unused])
for i in unused:
	group[i] = 0
a_sorted = sorted([(a[i], i) for i in range(N) if not i in unused])
unusedNum = len(unused)

while len(a_sorted) > 0:
	cost, node = a_sorted.pop(0)
	root = findRoot(group, node)
	l = len(a_sorted)
	i = 0
	for i in range(l):
		c,n = a_sorted[i]
		if not root == findRoot(group, n):
			group[n] = root
			ans += cost + c
			a_sorted.pop(i)
			break
	if i == l - 1:
		break

if len(a_sorted) < unusedNum:
	print("Impossible")
	exit()
for i in range(1,N):
	if group[i] != 0 and findRoot(group, i) != 0:
		print("Impossible")
		exit()
for i in range(unusedNum):
	ans += a_sorted[i]
print(ans)
exit()

Submission status: Wrong Answer

Solution code:
def findRoot(group, x):
	old_x = x
	while(group[x] != x):
		new_x = group[x]
		group[old_x] = new_x
		old_x = x
		x = new_x
	group[old_x] = x
	return x
def isSameGroup(group, x, y):
	return findRoot(group, x) == findRoot(group, y)

N,M = map(int,input().split())
a = list(map(int,input().split()))
group = [i for i in range(N)]
unused = [(True,i) for i in range(N)]
for i in range(M):
	x,y = map(int,input().split())
	unused[x] = (False, x)
	unused[y] = (False, y)
	if group[x] != x:
		group[y] = x
	elif group[y] != y:
		group[x] = y
	else:
		group[max(x,y)] = min(x,y)
if N == 1:
	print(0)
	exit()
unused = [i for b,i in unused if b]
ans = sum([a[i] for i in unused])
for i in unused:
	group[i] = 0
a_sorted = sorted([(a[i], i) for i in range(N) if not i in unused])
unusedNum = len(unused)

while len(a_sorted) > 0:
	cost, node = a_sorted.pop(0)
	root = findRoot(group, node)
	l = len(a_sorted)
	i = 0
	for i in range(l):
		c,n = a_sorted[i]
		if not root == findRoot(group, n):
			group[n] = root
			ans += cost + c
			a_sorted.pop(i)
			break
	if i == l - 1:
		break

if len(a_sorted) < unusedNum:
	print("Impossible")
	exit()
for i in range(1,N):
	if group[i] != 0 and findRoot(group, i) != 0:
		print("Impossible")
		exit()
print(ans)
exit()

Submission status: Wrong Answer

Solution code:
class DisjointSet:
  def __init__(self, size):
    self.parent = list(range(size))
    self.rank = [0]*size
  
  def find(self, x):
    if self.parent[x] == x:
      return x
    else:
      self.parent[x] = self.find(self.parent[x])
      return self.parent[x]

  def union(self, x, y):
    xr, yr = self.find(x), self.find(y)
    
    if self.rank[xr] > self.rank[yr]:
      self.parent[yr] = xr
    elif self.rank[xr] < self.rank[yr]:
      self.parent[xr] = yr
    elif xr != yr:
      self.parent[yr] = xr
      self.rank[xr] += 1


from sys import stdin
import heapq as hq

N,M = map(int,stdin.readline().split())


A = tuple(map(int,stdin.readline().split()))

ds = DisjointSet(N)
lines = stdin.readlines()
for line in lines:
  x,y = map(int,line.split())
  ds.union(x,y)

Q = [[] for _ in range(N)]

for i,a in enumerate(A):
  Q[ds.find(i)].append(a)

del ds

Q = [tuple(sorted(t)) for t in Q if t]

hq.heapify(Q)

cost = 0

while len(Q) > 1:
  a = iter(hq.heappop(Q))
  b = iter(hq.heappop(Q))
  cost += next(a)+next(b)
  a = tuple(hq.merge(a,b))
  if not a:
    print('Impossible')
    exit()
  hq.heappush(Q,a)

print(cost)

Submission status: Wrong Answer

Solution code:
from collections import deque, defaultdict
from heapq import heapify, heappop, merge, heapreplace


class UnionFind:
    def __init__(self, n):
        self.table = [-1] * n

    def _root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self._root(self.table[x])
            return self.table[x]

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

    def union(self, x, y):
        r1 = self._root(x)
        r2 = self._root(y)
        if r1 == r2:
            return
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2


def solve(aa, uft):
    roots = defaultdict(list)
    for x, a in enumerate(aa):
        roots[uft._root(x)].append(a)
    if n < (len(roots) - 1) * 2:
        return 'Impossible'
    queue = []
    for l in roots.values():
        l.sort()
        queue.append(deque(l))
    heapify(queue)
    ans = 0
    while len(queue) > 1:
        # print(queue)
        dq1 = heappop(queue)
        dq2 = queue[0]
        if len(dq1) == 1:
            buf = deque([dq1])
            while buf:
                while len(dq2) == 1 and len(queue) > 1:
                    buf.append(heappop(queue))
                    dq2 = queue[0]
                for _ in range(min(len(buf), len(dq2) - 1)):
                    ans += buf.popleft()[0] + dq2.popleft()
                if len(queue) == 1:
                    ans += buf[0][0] + dq2[0]
                    break
                if len(dq2) == 1:
                    buf.append(dq2)
            heapreplace(queue, dq2)
        else:
            ans += dq1.popleft() + dq2.popleft()
            heapreplace(queue, deque(merge(dq1, dq2)))
    return ans


n, m = map(int, input().split())
aa = list(map(int, input().split()))
uft = UnionFind(n)
for _ in range(m):
    uft.union(*map(int, input().split()))
print(solve(aa, uft))

Submission status: Wrong Answer

Solution code:
def findRoot(group, x):
	old_x = x
	while(group[x] != x):
		new_x = group[x]
		group[old_x] = new_x
		old_x = x
		x = new_x
	group[old_x] = x
	return x
def isSameGroup(group, x, y):
	return findRoot(group, x) == findRoot(group, y)

N,M = map(int,input().split())
a = list(map(int,input().split()))
a_sorted = sorted([(a[i], i) for i in range(N)])
group = [i for i in range(N)]
for i in range(M):
	x,y = map(int,input().split())
	if group[x] != x:
		group[y] = x
	elif group[y] != y:
		group[x] = y
	else:
		group[max(x,y)] = min(x,y)
ans = 0
while len(a_sorted) > 0:
	cost, node = a_sorted.pop(0)
	root = findRoot(group, node)
	l = len(a_sorted)
	i = 0
	for i in range(l):
		c,n = a_sorted[i]
		if not root == findRoot(group, n):
			group[n] = root
			ans += cost + c
			a_sorted.pop(i)
			break
	if i == l - 1:
		for i in range(1,N):
			if group[i] != 0 and findRoot(group, i) != 0:
				print("Impossible")
				exit()
		print(ans)
		exit()
for i in range(1,N):
	if group[i] != 0 and findRoot(group, i) != 0:
		print("Impossible")
		exit()
print(ans)
exit()