Cod sursa(job #1629821)

Utilizator papinubPapa Victor papinub Data 4 martie 2016 18:55:04
Problema Arbore partial de cost minim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.76 kb
# include <cstdio>
# include <vector>
# include <algorithm>
using namespace std;

const int N_MAX = 200001;
const int buffer_dim = 10000;

FILE *f = freopen("apm.in", "r" ,stdin);
FILE *g = freopen("apm.out", "w", stdout);


class inputReader{

    int pos;
    char buffer[buffer_dim];

public:
    void get_buffer()
    {
        pos = 0;
        fread(buffer,1,buffer_dim,stdin);
    }

    bool cif(char c)
    {
        return (c >= '0' && c <= '9');
    }

    void get_INT(int &num)
    {
        num = 0;
        char semn;
        while (!cif(buffer[pos]))
        {
            semn = buffer[pos];

            if (++pos == buffer_dim)
                get_buffer();
        }
        while (cif(buffer[pos]))
        {
            num = num * 10 + buffer[pos] - '0';

            if (++pos == buffer_dim)
                get_buffer();
        }
        if (semn == '-')
            num = -num;
    }

}cin;

struct vecin{
    int capat;
    int cost;

    vecin (int &a, int &b)
    {
        this -> capat = a;
        this -> cost = b;
    }
};

struct muchie{
    int capat1;
    int capat2;
    int cost;

    muchie (int &a, int &b, int &c)
    {
        this -> capat1 = a;
        this -> capat2 = b;
        this -> cost = c;
    }

   bool operator < (const muchie &other) const
    {
        return (this -> cost < other.cost);
    }
};

int n, m;
vector <vecin> G[N_MAX];
vector <muchie> candidati;
vector <vecin> solutie;
int father[N_MAX];
int sol, needed;

int group(int x)
{
    if (x != father[x])
        x = group(father[x]);
    return father[x];
}

int main()
{
    cin.get_buffer();
    cin.get_INT(n);
    cin.get_INT(m);

    for (int i=1; i<=m; i++)
    {
        int x, y, c;
        cin.get_INT(x);
        cin.get_INT(y);
        cin.get_INT(c);

        G[x].push_back(vecin(y, c));
        G[y].push_back(vecin(x, c));
        candidati.push_back(muchie(x, y, c));
    }

    sort(candidati.begin(), candidati.end());
    //for (muchie i : candidati) printf("%d %d %d\n", i.capat1, i.capat2, i.cost);

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

    needed = n-1;

    for (int i=0; i<candidati.size() && needed; i++)
    {
        muchie nod = candidati[i];

        int g1 = group(nod.capat1);
        int g2 = group(nod.capat2);

        if (g1 != g2)
        {
            needed --;
            sol += nod.cost;
            father[g1] = g2;
            solutie.push_back(vecin(nod.capat1, nod.capat2));
        }
    }

    printf("%d\n", sol);
    printf("%u\n", solutie.size());

    for (unsigned int i = 0; i<solutie.size(); i++)
    {
        printf("%d %d\n", solutie[i].capat, solutie[i].cost);
    }
    return 0;
}