Cod sursa(job #1361322)

Utilizator mirceadinoMircea Popoveniuc mirceadino Data 25 februarie 2015 20:41:59
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include<cstdio>
#include<string>
#include<algorithm>

using namespace std;

#ifdef HOME
const string inputFile = "input.txt";
const string outputFile = "output.txt";
#else
const string problemName = "apm";
const string inputFile = problemName + ".in";
const string outputFile = problemName + ".out";
#endif

typedef pair<int, int> PII;
const int NMAX = 200000 + 5;
const int MMAX = 400000 + 5;

int N, M, cost;
pair<int, PII> P[MMAX];
PII sol[NMAX];
int root[NMAX];

int find(int x) {
    if(x != root[x])
        root[x] = find(root[x]);
    return root[x];
}

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

void krushkal() {
    int i, j, x, y, z;

    sort(P + 1, P + M + 1);

    for(i = 1; i <= N; i++)
        root[i] = i;

    for(i = 1, j = 0; i <= M && j < N - 1; i++) {
        x = P[i].second.first;
        y = P[i].second.second;
        z = P[i].first;

        if(find(x) == find(y))
            continue;

        unite(find(x), find(y));

        sol[++j] = make_pair(x, y);

        cost += z;
    }
}

int main() {
    int i, x, y, z;

    freopen(inputFile.c_str(), "r", stdin);
    freopen(outputFile.c_str(), "w", stdout);

    scanf("%d%d", &N, &M);

    for(i = 1; i <= M; i++) {
        scanf("%d%d%d", &x, &y, &z);
        P[i] = make_pair(z, make_pair(x, y));
    }

    krushkal();

    printf("%d\n%d\n", cost, N - 1);

    for(i = 1; i <= N - 1; i++)
        printf("%d %d\n", sol[i].first, sol[i].second);

    return 0;
}