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.

Solution (Python):

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 all_group_members(self):
        return {r: self.members(r) for r in self.roots()}


    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

n,m=map(int,input().split())
a=list(map(int,input().split()))
if n-1==m:
    print(0)
    exit()
if n<2*(n-m-1):
    print("Impossible")
    exit()
uf=UnionFind(n)
for _ in range(m):
    x,y=map(int,input().split())
    uf.union(x,y)
v=[[] for _ in range(n)]
for i in range(n):
    v[uf.find(i)].append((a[i],i))
flag=set()
ans,cnt=0,0
for t in v:
    if t:
        t.sort()
        c,idx=t[0]
        flag.add(idx)
        cnt+=1
        ans+=c
for i in range(n):
    a[i]=(a[i],i)
a.sort()
for i in range(n):
    if cnt==2*(n-m-1):
        break
    c,idx=a[i]
    if idx not in flag:
        ans+=c
        cnt+=1
print(ans)

Solution (Python):
n,m=map(int,input().split())
a=list(map(int,input().split()))
ki=[[] for _ in range(n)]
for _ in range(m):
  x,y=map(int,input().split())
  ki[x].append(y)
  ki[y].append(x)
ans=0
cost=[]
mi=set(range(n))
cnt=0
from heapq import heappop,heappush,heapify
while mi:
  todo=[mi.pop()]
  g=[a[todo[0]]]
  while todo:
    v=todo.pop()
    for nv in ki[v]:
      if nv in mi:
        todo.append(nv)
        heappush(g,a[nv])
        mi.discard(nv)
  ans+=heappop(g)
  cost+=g
  cnt+=1
if cnt==1:
  print(0)
elif 2*(cnt-1)<=n:
  cost.sort()
  k=(cnt-1)*2-cnt
  ans+=sum(cost[:k])
  print(ans)
else:
  print('Impossible')

Solution (Python):
from collections import defaultdict
from heapq import nsmallest

class UnionFind():
    "Either 0-indexed or 1-indexed"

    __slots__ = ["parent"]

    def __init__(self, size):
        self.parent = [-1] * (size + 1)
    
    def find(self, a):
        path = []
        while self.parent[a] >= 0:
            path.append(a)
            a = self.parent[a]
        for child in path:
            self.parent[child] = a
        return a

    def union(self, a, b):
        a = self.find(a)
        b = self.find(b)

        if a == b:
            return
        else:
            if self.parent[a] == self.parent[b]:
                self.parent[a] = b
                self.parent[b] -= 1
            elif self.parent[a] < self.parent[b]: 
                self.parent[b] = a
            else:
                self.parent[a] = b 
        
    def same(self, a, b):
        return self.find(a) == self.find(b)


N, M = map(int, input().split())
As = list(map(int, input().split()))
uf = UnionFind(N)
for _ in range(M):
    x, y = map(int, input().split())
    uf.union(x, y)

anc_to_group = defaultdict(list)
for v in range(N):
    anc_to_group[uf.find(v)].append(v)

group_minima = []
remains = []
for group in anc_to_group.values():
    costs = [As[v] for v in group]
    minimum = min(costs)
    costs.remove(minimum)
    group_minima.append(minimum)
    remains += costs

if len(anc_to_group) == 1:
    print(0)
elif len(anc_to_group) - 2 > len(remains):
    print("Impossible")
else:
    ans = sum(group_minima)
    ans += sum(nsmallest((len(anc_to_group) - 2), remains))
    print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
N,M = map(int,input().split())
A = list(map(int,input().split()))
XY = [tuple(map(int,input().split())) for i in range(M)]

if (N-1-M)*2 > N:
    print('Impossible')
    exit()

class UnionFind:
    def __init__(self,N):
        self.parent = [i for i in range(N)]
        self._size = [1] * N
        self.count = 0
    def root(self,a):
        if self.parent[a] == a:
            return a
        else:
            self.parent[a] = self.root(self.parent[a])
            return self.parent[a]
    def is_same(self,a,b):
        return self.root(a) == self.root(b)
    def unite(self,a,b):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb: return
        if self._size[ra] < self._size[rb]: ra,rb = rb,ra
        self._size[ra] += self._size[rb]
        self.parent[rb] = ra
        self.count += 1
    def size(self,a):
        return self._size[self.root(a)]

uf = UnionFind(N)
for x,y in XY:
    if uf.is_same(x,y): continue
    uf.unite(x,y)
for i in range(N):
    uf.root(i)

from collections import defaultdict
dic = defaultdict(lambda: [])
for i in range(N):
    r = uf.root(i)
    dic[r].append(A[i])
if len(dic)==1:
    print(0)
    exit()

ans = 0
arr = []
c = 0
for k in dic.keys():
    dic[k].sort(reverse=True)
    ans += dic[k].pop()
    c += 1
    for a in dic[k]:
        arr.append(a)
rem = (N-1-M)*2 - c
if rem > len(arr):
    print('Impossible')
else:
    arr.sort()
    ans += sum(arr[:rem])
print(ans)

Solution (Python):
N,M=map(int, input().split())
A=list(map(int, input().split()))
if N-1==M:
  print(0)
  exit()

a,b=N-M,N-M-1
if N<2*(N-M-1):
  print('Impossible')
  exit()

par=[i for i in range(N)]
rank=[0]*(N)
size=[1]*N

def find(x):
  if par[x]==x:
    return x
  else:
    par[x]=find(par[x])
    return par[x]
def same(x,y):
  return find(x)==find(y)
def union(x,y):
  x=find(x)
  y=find(y)
  if x==y:
    return 
  if rank[x]>rank[y]:
    par[y]=x
    size[x]+=size[y]
  else:
    par[x]=y
    size[y]+=size[x]
    if rank[x]==rank[y]:
      rank[y]+=1
      
for i in range(M):
  a,b=map(int,input().split())
  union(a,b)
D=[[10**9+1,-1] for i in range(N)]
C=[]
for i in range(N):
  a=find(i)
  if D[a][0]>A[i]:
    C.append([D[a][0],D[a][1]])
    D[a][0]=A[i]
    D[a][1]=i
  else:
    C.append([A[i],i])
ans=0
cnt=0
for a,b in D:
  if b!=-1:
    ans+=a
    cnt+=1
C=sorted(C)
for a,b in C:
  if cnt==2*(N-M-1):
    break
  ans+=a
  cnt+=1
print(ans)

Solution (Python):
n,m = map(int, input().split())
a = list(map(int, input().split()))
xy=[list(map(int,input().split())) for i in range(m)]

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())

uf = UnionFind(n)
for x,y in xy:
    uf.union(x,y)

g=uf.group_count()

if g==1:
    print(0)
    exit()

if n<(g-1)*2:
    print("Impossible")
    exit()

ans=0
all_costs=[]

from collections import defaultdict
costs=defaultdict(list)
for i in range(n):
    costs[uf.find(i)].append(a[i])

for k,v in costs.items():
    v.sort()
    ans+=v[0]
    all_costs.extend(v[1:])

all_costs.sort()
ans+=sum(all_costs[:(g-2)])

print(ans)

Solution (Python):
import heapq

class UnionFind():
  def __init__(self,n):
    self.n=n
    self.root=[-1]*(n+1)
    self.rank=[0]*(n+1)
  def FindRoot(self,x):
    if self.root[x]<0:
      return x
    else:
      self.root[x]=self.FindRoot(self.root[x])
      return self.root[x]
  def Unite(self,x,y):
    x=self.FindRoot(x)
    y=self.FindRoot(y)
    if x==y:
      return
    else:
      if self.rank[x]>self.rank[y]:
        self.root[x]+=self.root[y]
        self.root[y]=x
      elif self.rank[x]<=self.rank[y]:
        self.root[y]+=self.root[x]
        self.root[x]=y
        if self.rank[x]==self.rank[y]:
          self.rank[y]+=1
  def isSameGroup(self,x,y):
    return self.FindRoot(x)==self.FindRoot(y)
  def Count(self,x):
    return -self.root[self.FindRoot(x)]

n,m=map(int,input().split())
costs=list(map(int,input().split()))
if m==n-1:
  print(0)
  exit()
edges=[list(map(int,input().split())) for _ in range(m)]
uf=UnionFind(n)
for a,b in edges:
  uf.Unite(a,b)
qs=[[] for _ in range(n)]
roots=set()
for i in range(n):
  root=uf.FindRoot(i)
  roots.add(root)
  heapq.heappush(qs[root],costs[i])
remains=[]
ans=0
cnt=0
for root in roots:
  cost=heapq.heappop(qs[root])
  ans+=cost
  cnt+=1
  while len(qs[root])!=0:
    cost=heapq.heappop(qs[root])
    heapq.heappush(remains,cost)
while len(remains)!=0 and cnt<2*(n-m-1):
  cost=heapq.heappop(remains)
  ans+=cost
  cnt+=1
if cnt==2*(n-m-1):
  print(ans)
else:
  print('Impossible')

Solution (Python):
import heapq

class UnionFind():
  def __init__(self,n):
    self.n=n
    self.root=[-1]*(n+1)
    self.rank=[0]*(n+1)
  def FindRoot(self,x):
    if self.root[x]<0:
      return x
    else:
      self.root[x]=self.FindRoot(self.root[x])
      return self.root[x]
  def Unite(self,x,y):
    x=self.FindRoot(x)
    y=self.FindRoot(y)
    if x==y:
      return
    else:
      if self.rank[x]>self.rank[y]:
        self.root[x]+=self.root[y]
        self.root[y]=x
      elif self.rank[x]<=self.rank[y]:
        self.root[y]+=self.root[x]
        self.root[x]=y
        if self.rank[x]==self.rank[y]:
          self.rank[y]+=1
  def isSameGroup(self,x,y):
    return self.FindRoot(x)==self.FindRoot(y)
  def Count(self,x):
    return -self.root[self.FindRoot(x)]

n,m=map(int,input().split())
cost=list(map(int,input().split()))
if n==1:
  print(0)
  exit()
if n==2:
  if m==0:
    print(cost[0]+cost[1])
    exit()
  if m==1:
    print(0)
    exit()
edges=[list(map(int,input().split())) for _ in range(m)]
uf=UnionFind(n)
for a,b in edges:
  uf.Unite(a,b)
isolates=set()
isolates_cnt=0
groups=set()
groups_cnt=2
roots=[]
qs=[[] for _ in range(n)]
for i in range(n):
  root=uf.FindRoot(i)
  cnt=uf.Count(i)
  if cnt==1:
    isolates_cnt+=1
    isolates.add(root)
    heapq.heappush(qs[root],(cost[i],i))
  else:
    if root not in groups:
      groups_cnt+=cnt-2
      roots.append((root,cnt))
    groups.add(root)
    heapq.heappush(qs[root],(cost[i],i))
if groups_cnt<isolates_cnt:
  print('Impossible')
else:
  ans=0
  roots=sorted(roots,reverse=True,key=lambda x:x[1])
  root=roots[0][0]
  for tmp_root,_ in roots[1:]:
    cv,v=heapq.heappop(qs[root])
    cu,u=heapq.heappop(qs[tmp_root])
    ans+=(cv+cu)
    while len(qs[tmp_root])!=0:
      tc,tv=heapq.heappop(qs[tmp_root])
      heapq.heappush(qs[root],(tc,tv))
  for tmp_root in isolates:
    cv,v=heapq.heappop(qs[root])
    cu,u=heapq.heappop(qs[tmp_root])
    ans+=(cv+cu)
  print(ans)

Solution (Python):
from collections import defaultdict

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 all_group_members(self):  
        ret = defaultdict(list)
        for i in range(self.n):
            ret[self.find(i)].append(i)
        return ret



n, m = (int(x) for x in input().split())
A = list(int(x) for x in input().split())
XY = [tuple(int(x) for x in input().split()) for _ in range(m)]
B = [(a, i) for i, a in enumerate(A)]

uf = UnionFind(n)
for x, y in XY:
    uf.union(x, y)

k = n - m
if k == 1:
    print(0)
    exit()
if n < 2 * k - 2:
    print("Impossible")
    exit()

ans = 0
used = set()
for root, members in uf.all_group_members().items():
    tmp, i = min((A[x], x) for x in members)
    used.add(i)
    ans += tmp

B.sort(reverse=True)
count = 0
while count < k - 2:
    a, i = B.pop()
    if i in used:
        continue
    else:
        ans += a
        count += 1

print(ans)

Solution (Python):
s=sorted
(n,m,*b),a,*q=[map(int,t.split())for t in open(0)]
t=[-1]*n
r=lambda x:r(t[x])if-1<t[x]else x
def u(x):
 x,y=map(r,x)
 if x-y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
*map(u,q),
i=c=0
k=j=n+~m<<1
*d,=eval('[],'*n)
for v in a:d[r(i)]+=v,;i+=1
for p in d:
 if p:x,*y=s(p);c+=x;b+=y;j-=1
print((c+sum(s(b)[:j]),'Impossible')[k>n]*(k>0))

Solution (Python):
s=sorted
(n,m,*b),a,*q=[map(int,t.split())for t in open(0)]
t=[-1]*n
def r(x):
 while-1<t[x]:x=t[x]
 return x
def u(x):
 x,y=map(r,x)
 if x-y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
*map(u,q),
i=c=0
k=j=n+~m<<1
*d,=eval('[],'*n)
for v in a:d[r(i)]+=v,;i+=1
for p in d:
 if p:x,*y=s(p);c+=x;b+=y;j-=1
print((c+sum(s(b)[:j]),'Impossible')[k>n]*(k>0))

Solution (Python):
s=sorted
(n,m,*b),a,*q=[map(int,t.split())for t in open(0)]
t=[-1]*n
def r(x):
 while-1<t[x]:x=t[x]
 return x
def u(x):
 x,y=map(r,x)
 if x-y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
[*map(u,q)]
i=c=0
k=j=n+~m<<1
*d,=eval('[],'*n)
for v in a:d[r(i)]+=v,;i+=1
for p in d:
 if p:x,*y=s(p);c+=x;b+=y;j-=1
print((c+sum(s(b)[:j]),'Impossible')[k>n]*(k>0))

Solution (Python):
(n,m,*b),a,*q=[map(int,t.split())for t in open(0)]
t=[-1]*n
def r(x):
 while-1<t[x]:x=t[x]
 return x
def u(x):
 x,y=map(r,x)
 if x-y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
[*map(u,q)]
i=c=0
k=j=n+~m<<1
*d,=eval('[],'*n)
for v in a:d[r(i)]+=v,;i+=1
for p in d:
 if p:x,*y=sorted(p);c+=x;b+=y;j-=1
print((c+sum(sorted(b)[:j]),'Impossible')[k>n]*(k>0))

Solution (Python):
(n,m,*b),a,*q=[map(int,t.split())for t in open(0)]
t=[-1]*n
def r(x):
 while-1<t[x]:x=t[x]
 return x
def u(x):
 x,y=map(r,x)
 if x-y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
[*map(u,q)]
i=c=0
k=j=n+~m<<1
*d,=eval('[],'*n)
for v in a:d[r(i)]+=v,;i+=1
for p in d:x,*y=sorted(p)+[0];c+=x;b+=y[:-1];j-=p>[]
print((c+sum(sorted(b)[:j]),'Impossible')[k>n]*(k>0))

Solution (Python):
(n,m,*b),a,*q=[map(int,t.split())for t in open(0)]
t=[-1]*n
def r(x):
 while-1<t[x]:x=t[x]
 return x
def u(x):
 x,y=map(r,x)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
[*map(u,q)]
i=c=0
k=j=n+~m<<1
*d,=eval('[],'*n)
for v in a:d[r(i)]+=v,;i+=1
for p in d:x,*y=sorted(p)+[0];c+=x;b+=y[:-1];j-=p>[]
print((c+sum(sorted(b)[:j]),'Impossible')[k>n]*(k>0))

Solution (Python):
(n,m,*b),a,*q=[map(int,t.split())for t in open(0)]
t=[-1]*n
def r(x):
 while-1<t[x]:x=t[x]
 return x
def u(x):
 x,y=map(r,x)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
[*map(u,q)]
i=c=0
k=j=n+~m<<1
*d,=eval('[],'*n)
for v in a:d[r(i)]+=v,;i+=1
for p in d:x,*y=sorted(p)+[0];c+=x;b+=y[:-1];j-=p>[]
print(k<1and'0'or(k>n)*'Impossible'or c+sum(sorted(b)[:j]))

Solution (Python):
(n,m),a,*q=[map(int,t.split())for t in open(0)]
t=[-1]*n
def r(x):
 while-1<t[x]:x=t[x]
 return x
def u(x):
 x,y=map(r,x)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
[*map(u,q)]
i=c=0
k,*b=n+~m<<1,
*d,=eval('[],'*n)
for v in a:d[r(i)]+=v,;i+=1
print(k<1and'0'or(k>n)*'Impossible'or exec('for p in d:x,*y=sorted(p)+[0];c+=x;b+=y[:-1];k-=p>[]')or c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while-1<t[x]:x=t[x]
 return x
def u(L):
 x,y=map(r,L)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for l in q:u(l)
i=c=0;b=[];k=(n+~m)*2
for v in a:d[r(i)]+=v,;i+=1
print(k<1and'0'or(k>n)*'Impossible'or exec("for r,p in d.items():p.sort();c+=p.pop(0);b+=p;k-=1")or c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while-1<t[x]:x=t[x]
 return x
def u(L):
 x,y=map(r,L)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for l in q:u(l)
i=c=0;b=[];k=(n+~m)*2
for v in a:d[r(i)]+=v,;i+=1
print(k<1and'0'or k>n and'Impossible'or exec("for r,p in d.items():p.sort();c+=p.pop(0);b+=p;k-=1")or c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while t[x]>=0:x=t[x]
 return x
def u(L):
 x,y=map(r,L)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for l in q:u(l)
i=c=0;b=[];k=(n+~m)*2
for v in a:d[r(i)]+=v,;i+=1
print(k<1and'0'or k>n and'Impossible'or exec("for r,p in d.items():p.sort();c+=p.pop(0);b+=p;k-=1")or c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
from heapq import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while t[x]>=0:x=t[x]
 return x
def u(L):
 x,y=map(r,L)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for l in q:u(l)
i=c=0;b=[];k=(n+~m)*2
for v in a:d[r(i)]+=v,;i+=1
print(k<1and'0'or k>n and'Impossible'or exec("for r,p in d.items():p.sort();c+=p.pop(0);b+=p;k-=1")or c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
from heapq import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while t[x]>=0:x=t[x]
 return x
def u(x,y):
 x,y=r(x),r(y)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for x,y in q:u(x,y)
i=c=0;b=[];k=(n+~m)*2
for v in a:d[r(i)]+=v,;i+=1
print(k<1and'0'or k>n and'Impossible'or exec("for r,p in d.items():p.sort();c+=p.pop(0);b+=p;k-=1")or c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
from heapq import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while t[x]>=0:x=t[x]
 return x
def u(x,y):
 x,y=r(x),r(y)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for x,y in q:u(x,y)
i=c=0;b=[];k=(n+~m)*2;f=print
for v in a:d[r(i)]+=v,;i+=1
print(0if k<1else'Impossible'if k>n else exec("for r,p in d.items():p.sort();c+=p.pop(0);b+=p;k-=1")or c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
from heapq import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while t[x]>=0:x=t[x]
 return x
def u(x,y):
 x,y=r(x),r(y)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for x,y in q:u(x,y)
i=c=0;b=[];k=(n+~m)*2;f=print
for v in a:d[r(i)]+=v,;i+=1
if k<1:f(0)
elif k>n:f('Impossible')
else:
 for r,p in d.items():p.sort();c+=p.pop(0);b+=p;k-=1
 f(c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
from heapq import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while t[x]>=0:x=t[x]
 return x
def u(x,y):
 x,y=r(x),r(y)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for x,y in q:u(x,y)
i=c=0;b=[];k=(n+~m)*2
for v in a:d[r(i)]+=v,;i+=1
if k<1:print(0)
elif k>n:print('Impossible')
else:
 for r,p in d.items():p.sort();c+=p.pop(0);b+=p;k-=1
 print(c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
from heapq import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while t[x]>=0:x=t[x]
 return x
def u(x,y):
 x,y=r(x),r(y)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for x,y in q:u(x,y)
i=c=0;b=[]
for v in a:d[r(i)]+=v,;i+=1
if(k:=(n+~m)*2)<1:exit(print(0))
for r,p in d.items():p.sort();c+=p.pop(0);b+=p;k-=1
print(k>len(b)and'Impossible'or c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
from heapq import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while t[x]>=0:x=t[x]
 return x
def u(x,y):
 x,y=r(x),r(y)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for x,y in q:u(x,y)
i=c=0;b=[]
for v in a:d[r(i)]+=v,;i+=1
if(k:=n+~m)<1:exit(print(0))
k*=2
for r,p in d.items():p.sort();c+=p.pop(0);b+=p;k-=1
print(k>len(b)and'Impossible'or c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
from heapq import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while t[x]>=0:x=t[x]
 return x
def u(x,y):
 x,y=r(x),r(y)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for x,y in q:u(x,y)
i=c=0;b=[]
for v in a:d[r(i)]+=v,;i+=1
k=n+~m
if k<1:exit(print(0))
k*=2
for r,p in d.items():p.sort();c+=p.pop(0);b+=p;k-=1
print(k>len(b)and'Impossible'or c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
from heapq import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while t[x]>=0:x=t[x]
 return x
def u(x,y):
 x,y=r(x),r(y)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for x,y in q:u(x,y)
i=c=0;b=[];k=(n+~m)*2
for v in a:d[r(i)]+=v,;i+=1
if k<1:exit(print(0))
for r,p in d.items():p.sort();c+=p.pop(0);b+=p;k-=1
print(k>len(b)and'Impossible'or c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
from heapq import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while t[x]>=0:x=t[x]
 return x
def u(x,y):
 x,y=r(x),r(y)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for x,y in q:u(x,y)
i=0
for v in a:d[r(i)]+=v,;i+=1
if len(d)<2:exit(print(0))
c,b,k=0,[],(n-m-1)*2
for r,p in d.items():p.sort();c+=p.pop(0);b+=p;k-=1
print(k>len(b)and'Impossible'or c+sum(sorted(b)[:k]))

Solution (Python):
from collections import*
from heapq import*
(n,m),a,*q=[[*map(int,o.split())]for o in open(0)]
t=[-1]*n
def r(x):
 while t[x]>=0:x=t[x]
 return x
def u(x,y):
 x,y=r(x),r(y)
 if x!=y:
  if t[x]>t[y]:x,y=y,x
  t[x]+=t[y];t[y]=x
d=defaultdict(list)
for x,y in q:u(x,y)
i=0
for v in a:d[r(i)]+=v,;i+=1
if len(d)<2:exit(print(0))
*d,=map(sorted,d.values())
c=sum(heappop(t)for t in d)
l=[]
for t in d:l+=t
i=len(d)-2
print(i>len(l)and'Impossible'or c+sum(sorted(l)[:i]))

Solution (Python):
from heapq import heapify, heappop, heappush

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]
    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]
    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]
    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)
    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]

N,M = map(int,input().split())
A = list(map(int,input().split()))
if N == M +1:
  print(0)
  exit()
Cost = []
for i in range(N):
  heappush(Cost,[A[i],i]) 
uf = UnionFind(N)
for i in range(M):
  a,b = map(int,input().split())
  
  uf.union(a,b)
ans = 0
L = [[] for _ in range(N-M)]
dic = {}
num = 0
for i in range(N):
  par = uf.find(i)
  if par not in dic:
    dic[par] = num
    heappush(L[dic[par]],[A[i],i])
    num +=1
  else:
    heappush(L[dic[par]],[A[i],i])

Selected = set([])
for x in L:
  ans += x[0][0] 
  Selected.add(x[0][1]) 

ima = N-M
while ima < 2*(N-M-1) and Cost:
  cost, ID = heappop(Cost)
  if ID in Selected:
    continue
  else:
    ans += cost
    ima += 1
if ima < 2*(N-M-1):
  print("Impossible")
else:
  print(ans)

Solution (Python):
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 all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def get_all_members(self):
        pare_d = {}
        for i in range(self.n):
            parent = self.find(i)
            pare_d.setdefault(parent,[])
            pare_d[parent].append(i)
        return list(pare_d.values())

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())



def main():
    n,m = map(int, input().split())
    al = list(map(int, input().split()))    
    uf = UnionFind(n)
    for _ in range(m):
        x,y = map(int, input().split())
        uf.union(x,y)

    first_mins = []
    other_vals = []
    
    all_members = uf.get_all_members()
    
    if len(all_members) == 1:
        print(0)
        exit()

    for members in all_members:
        vs = []
        for m in members:
            vs.append(al[m])
        vs.sort()
        first_mins.append(vs[0])
        for i,v in enumerate(vs[1:]):
            
            other_vals.append(v)

    
    ans = 0
    ans += sum(first_mins)
    rem = len(all_members)-2
    if len(other_vals) < rem:
        print('Impossible')
        exit()
    other_vals.sort()
    ans += sum(other_vals[:rem])
    print(ans)



if __name__ == "__main__":
    main()

Solution (Python):
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 all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def get_all_members(self):
        pare_d = {}
        for i in range(self.n):
            parent = self.find(i)
            pare_d.setdefault(parent,[])
            pare_d[parent].append(i)
        return list(pare_d.values())

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())



def main():
    n,m = map(int, input().split())
    al = list(map(int, input().split()))    
    uf = UnionFind(n)
    for _ in range(m):
        x,y = map(int, input().split())
        uf.union(x,y)

    first_mins = []
    other_vals = []
    
    all_members = uf.get_all_members()
    if len(all_members) == 1:
        print(0)
        exit()

    for members in all_members:
        vs = []
        for m in members:
            vs.append(al[m])
        vs.sort()
        first_mins.append(vs[0])
        for i,v in enumerate(vs[1:]):
            
            other_vals.append(v)

    
    ans = 0
    ans += sum(first_mins)
    rem = len(all_members)-2
    if len(other_vals) < rem:
        print('Impossible')
        exit()
    other_vals.sort()
    ans += sum(other_vals[:rem])
    print(ans)



if __name__ == "__main__":
    main()