Cod sursa(job #1380151)

Utilizator viuscenkoViktor Iuscenko viuscenko Data 6 martie 2015 22:26:19
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include <bits/stdc++.h>

using namespace std;

#define     mp              make_pair
#define     fs              first
#define     sc              second
#define     pob             pop_back
#define     pub             push_back
#define     eps             1E-7
#define     sz(a)           a.size()
#define     count_one       __builtin_popcount;
#define     count_onell     __builtin_popcountll;
#define     fastIO          ios_base::sync_with_stdio(false)
#define     PI              (acos(-1.0))
#define     linf            (1LL<<62)//>4e18
#define     inf             (0x7f7f7f7f)//>2e9

#define MAXN 200010
#define MAXM 400010

#ifndef ONLINE_JUDGE
FILE *in = fopen("apm.in", "r");
FILE *out = fopen("apm.out", "w");
#endif

int n, m;
vector<pair<int, int> > edge;
vector<int> cost;
int IND[MAXM];  // indexes
int par[MAXN];  // parents

inline int cmp(const int &l, const int &r) {
    return cost[l] < cost[r];
}

int findP(int x) {
    if(par[x] == x)
        return x;

    par[x] = findP(par[x]);
    return par[x];
}

void unite(int x, int y) {
    par[findP(x)] = findP(y);
}

int main() {
    int x, y, c;

    fscanf(in, "%d%d", &n, &m);
    for(int i = 0; i < m; ++i) {
        fscanf(in, "%d%d%d", &x, &y, &c);
        edge.pub(mp(x, y));
        cost.pub(c);
        IND[i] = i;
    }

    for(int i = 1; i <= n; ++i)
        par[i] = i;

    sort(IND, IND + m, cmp);

    long long ct = 0;
    vector<pair<int, int> > sol;
    for(int i = 0; i < m; ++i) {
        if(findP(edge[IND[i]].fs) == findP(edge[IND[i]].sc))
            continue;

        unite(edge[IND[i]].fs, edge[IND[i]].sc);
        ct += cost[IND[i]];
        sol.pub(edge[IND[i]]);
    }
    fprintf(out, "%lld\n", ct);
    fprintf(out, "%d\n", sol.size());
    for(auto it: sol) {
        fprintf(out, "%d %d\n", it.fs, it.sc);
    }
    return 0;
}