Problem p03440 (python)

Fixed submission:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
#import math
#import time
#import random  # randome is not available at Codeforces
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
#ts=time.time()
#sys.setrecursionlimit(10**6)
input=lambda: sys.stdin.readline().rstrip()
import sys
sys.setrecursionlimit(10**7)

show_flg=False
show_flg=True


n,m=LI()
a=LI()
g=[[] for _ in range(n)]
ans=0
cmp=0
for i in range(m):
    x,y=LI()
    g[x].append(y)
    g[y].append(x)

rest=[]
q=[]
v=[-1]*n

for i in range(n):
    if v[i]!=-1:
        continue
    p=[]
    cost=[]
    p.append(i)
    heappush(cost,a[i])
    while p:
        c=p.pop()
        v[c]=a[c]
        for nb in g[c]:
            if v[nb]==-1:
                p.append(nb)
                v[nb]=a[nb]
                heappush(cost,a[nb])
    ans+=heappop(cost)
    cmp+=1
    while cost:
        heappush(rest,heappop(cost))

if cmp==1:
    ans=0
elif len(rest)<cmp-2:
    ans="Impossible"
else:# cmp=n-m, n-m-1 edges needed, 2n-2m-2 vers, 2n-2m-2-cmp=n-m-2=cmp-2
    for i in range(cmp-2):
        ans+=heappop(rest)

print(ans)

Buggy submission (verdict: Runtime Error):
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<functional>
#include<assert.h>
#include<numeric>
using namespace std;
#define REP(i,m,n) for(int i=(int)(m) ; i < (int) (n) ; ++i )
#define rep(i,n) REP(i,0,n)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
using ll = long long;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;
const ll mod=1e9+7 ;
using namespace std;
struct Fast { Fast(){ std::cin.tie(0); ios::sync_with_stdio(false); } } fast;

template<typename ...Ts>
void show(Ts... ts){
  cout<<"#:";
  auto print=[](auto v){cout<<v<<" ";};
  initializer_list<int>{(void(print(ts)),0)...};
  cout<<endl;
}



int main(void){
    ll n,m,x,y,ans=0,cmp=0;
    cin>>n>>m;
    vector<ll> a(n,0);
    vector<ll> v(n,-1);
    vector<vector<ll>> g(n);
    rep(i,n)cin>>a[i];
    rep(i,m){
        cin>>x>>y;
        g[x].push_back(y);
        g[y].push_back(x);
    }

    priority_queue<ll,vector<ll>,greater<ll>> rest;
    
    rep(i,n){
        if(v[i]>0)continue;
        vector<ll> p;
        priority_queue<ll,vector<ll>,greater<ll>> cost;

        p.push_back(i);
        cost.push(a[i]);
        while(!p.empty()){
            ll c=p.back();
            p.pop_back();
            v[c]=a[c];
            for(ll nb:g[c]){
                if(v[nb]==-1){
                    p.push_back(nb);
                    v[nb]=a[nb];
                    cost.push(a[nb]);
                }
            }
        }
        ans+=cost.top();
        cmp+=1;
        cost.pop();
        while(!cost.empty()){
            rest.push(cost.top());
            cost.pop();
        }
    }
    
    if (cmp==1){
        cout<<0<<endl;
    }else if (rest.size()<cmp-2){
        cout<<"Impossible";
    }else{
        rep(i,2*(cmp-1)-cmp){
            ans+=rest.top();
            rest.pop();
        }
        cout<<ans;
    }
}

Buggy submission (verdict: Runtime Error):
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
#import math
#import time
#import random  # randome is not available at Codeforces
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
#ts=time.time()
#sys.setrecursionlimit(10**6)
input=lambda: sys.stdin.readline().rstrip()
import sys
sys.setrecursionlimit(10**7)

show_flg=False
show_flg=True


n,m=LI()
a=LI()
g=[[] for _ in range(n)]
ans=0
cmp=0
for i in range(m):
    x,y=LI()
    g[x].append(y)
    g[y].append(x)

rest=[]
q=[]
v=[-1]*n

for i in range(n):
    if v[i]!=-1:
        continue
    p=[]
    cost=[]
    p.append(i)
    heappush(cost,a[i])
    while p:
        c=p.pop()
        v[c]=a[c]
        for nb in g[c]:
            if v[nb]==-1:
                p.append(nb)
                v[nb]=a[nb]
                heappush(cost,a[nb])
    ans+=heappop(cost)
    cmp+=1
    while cost:
        heappush(rest,heappop(cost))

if cmp==1:
    ans=0
elif len(rest)<cmp-1:
    ans="Impossible"
    a[10**100]
else:# cmp=n-m, n-m-1 edges needed, 2n-2m-2 vers, 2n-2m-2-cmp=n-m-2=cmp-2
    for i in range(cmp-2):
        ans+=heappop(rest)

print(ans)

Buggy submission (verdict: Runtime Error):
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
#import math
#import time
#import random  # randome is not available at Codeforces
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
#ts=time.time()
#sys.setrecursionlimit(10**6)
input=lambda: sys.stdin.readline().rstrip()
import sys
sys.setrecursionlimit(10**7)

show_flg=False
show_flg=True

n,m=LI()
a=LI()
g=[[] for _ in range(n)]
ans=0
cmp=0
for i in range(m):
    x,y=LI()
    g[x].append(y)
    g[y].append(x)

rest=[]
q=[]
v=[-1]*n

for i in range(n):
    if v[i]>0:
        continue
    p=[]
    cost=[]
    p.append(i)
    heappush(cost,a[i])
    while p:
        c=p.pop()
        v[c]=a[c]
        for nb in g[c]:
            if v[nb]==-1:
                p.append(nb)
                v[nb]=a[nb]
                heappush(cost,a[nb])
    ans+=heappop(cost)
    cmp+=1
    while cost:
        heappush(rest,heappop(cost))
    
if len(rest)<cmp-1:
    ans="Impossible"
    a=[0]
    a[1]
elif cmp==1:
    ans=0
    a=[0]
    a[1]
else:
    for i in range(cmp-2):
        ans+=heappop(rest)

print(ans)