Cod sursa(job #2713064)

Utilizator petrisorvmyVamanu Petru Gabriel petrisorvmy Data 27 februarie 2021 10:33:22
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <bits/stdc++.h>
#define fast ios_base :: sync_with_stdio(0); cin.tie(0);
#pragma GCC optimize("O3")
#define FILE_NAME "apm"
#define NMAX 200000 + 100
#define MMAX 400000 + 100
#define vs nod<<1
#define vd nod<<1|1
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pi;
typedef pair<ll,ll> llp;
typedef pair<ld,ld> pct;

const ll inf = 1LL << 60;
const ll mod = 1e9 + 7;
const ld eps = 1e-9;

ifstream f(FILE_NAME".in");
ofstream g(FILE_NAME".out");

inline void add(ll &a , ll b)
{
    a += b;
    a %= mod;
}

inline void sub(ll &a, ll b)
{
    a = (a - b + mod) % mod;
}

int n, m, h[NMAX], t[NMAX],cat;
pair <int, pi> mch[MMAX];
vector <pi> apm;

int inters(int x, int y)
{
    if(h[x] > h[y])
        t[y] = x;
    else
    {
        t[x] = y;
        if(h[x] == h[y]) h[y]++;
    }
}

int unde(int nod)
{
    int r = nod;
    while(t[r] != r)
        r = t[r];
    while(t[nod] != r)
    {
        int nxt = t[nod];
        t[nod] = r;
        nod = nxt;
    }
    return r;
}

int main()
{
    f >> n >> m;
    for(int i = 1; i <= n; ++i)
        t[i] = i;
    for(int i = 1; i <= m; ++i)
        f >>  mch[i].second.first >> mch[i].second.second >> mch[i].first;
    sort(mch + 1, mch + m + 1);

    for(int i = 1; i <= m; ++i)
    {
        int a = mch[i].second.first;
        int b = mch[i].second.second;
        if(unde(a) != unde(b))
        {
            cat += mch[i].first;
            inters(unde(a), unde(b));
            apm.push_back(mch[i].second);
        }
    }
    g << cat << '\n' << apm.size() << '\n';
    for(auto it : apm)
        g << it.first << ' ' << it.second << '\n';
    f.close();
    g.close();
    return 0;
}