Cod sursa(job #2183026)

Utilizator miguelMihail Lavric miguel Data 22 martie 2018 19:13:24
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#pragma GCC optimize("O3")
#include<bits/stdc++.h>
using namespace std;
#define rc(x) return cout<<x<<endl,0
#define pb push_back
#define dbg(x) cout << #x << '=' << x << '\n';
#define ll long long
#define inf 1e18
#define sz size()
#define x first
#define y second
#define pi pair <int, int>
#define pii pair <pi, pi>
#define vi vector <int>
const ll mod = 1e9 + 7;
int n, m;
vector <int> g[200001];
vector <pair<int, pi>> e;
int p[100001];
int w[100001];
int viz[400001];
ll ans, x, y, c, ans1;

int root(int a){
    while(p[a]!=a){
        p[a]=p[p[a]];
        a=p[a];
    }
    return a;
}

void u1918(int a, int b){
    int a1=root(a);
    int b1=root(b);
    if(w[a1]>w[b1]){
        w[b1]+=w[a1];
        p[a1]=b1;
    }
    else{
        w[a1]+=w[b1];
        p[b1]=a1;
    }
}

int check(int a, int b){
    if(root(a)==root(b)) return 1;
    else return 0;
}

int32_t main(){
    ios_base :: sync_with_stdio(0); cin.tie(); cout.tie();
    ifstream cin("apm.in");
    ofstream cout("apm.out");
    cin>>n>>m;
    for(int i=0; i<=1e5; i++){p[i]=i; w[i]++;}
    for(int i=0; i<=m-1; i++){
        cin>>x>>y>>c;
        e.pb({c, {x, y}});

    }
    sort(e.begin(), e.end());
    for(int i=0; i<m; i++){
        if(!check(e[i].y.x, e[i].y.y)){
            viz[i]=1;
            ans+=e[i].x;
            ans1++;
            u1918(e[i].y.x, e[i].y.y);
        }
    }
    cout<<ans<<'\n'<<ans1<<'\n';
    for(int i=0; i<=m-1; i++){
        if(viz[i]) cout<<e[i].y.x<<" "<<e[i].y.y<<'\n';
    }
}