SPOJ Petya and the Road Repairs Solution

 #include <bits/stdc++.h>
using namespace std;
int main(){
    ios::sync_with_stdio(0);
    cin.tie(NULL);
    cout.tie(NULL);
    int t;
    cin>>t;
    while(t--){
        int n,m;
        cin>>n>>m;
        vector<int> a(n+1),vis(n+1);
        for(int i=1;i<=n;i++){
            cin>>a[i];
        }
        vector<vector<pair<int,int> > > g(n+1,vector<pair<int,int> >());
        for(int i=0;i<m;i++){
            int u,v,cost;
            cin>>u>>v>>cost;
            g[u].push_back({cost,v});
            g[v].push_back({cost,u});
        }
        priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;
        long long cost=0;
        for(int i=1;i<=n;i++){
            if(a[i]){
                for(auto x:g[i]){
                    pq.push(x);
                }
                vis[i]=1;
            }
        }
        int i;
        while(!pq.empty()){
            pair<int,int> p=pq.top();
            pq.pop();
            int cst=p.first,i=p.second;
            if(vis[i])continue;
            for(auto x:g[i]){
                    pq.push(x);
                }
            vis[i]=1;
            cost+=cst;
        }
        int tot=0;
        for(int i=1;i<=n;i++)
            tot+=vis[i];
        if(tot<n)
            cout<<"impossible"<<endl;
        else cout<<cost<<endl;
    }
    return 0;
}

Comments