Cod sursa(job #1321667)

Utilizator dianaa21Diana Pislaru dianaa21 Data 19 ianuarie 2015 14:11:52
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream is ("apm.in");
ofstream os ("apm.out");

vector<int> ANS;
int N, M, ANSW;
int GR[400003], IND[400003];
int X[400003], Y[400003], C[400003];

bool Comp(const int i, const int j)
{
    return C[i] < C[j];
}

void Read();
void Solve();
void Union(int i, int j);
int Grupa(int x);

int main()
{
    Read();
    Solve();
    os << ANSW << "\n" << ANS.size() << "\n";
    vector<int>::iterator it;
    for(it = ANS.begin(); it != ANS.end(); ++it)
        os << X[*it] << " " << Y[*it] << "\n";
    is.close();
    os.close();
    return 0;
}
void Read()
{
    int x, y, c;
    is >> N >> M;

    for(int i = 1; i <= M; ++i)
    {
        is >> x >> y >> c;
        X[i] = x;
        Y[i] = y;
        C[i] = c;
        IND[i] = i;
    }
    for(int i = 1; i <= N; ++i)
        GR[i] = i;
    sort(IND+1, IND+M+1, Comp);
}
void Solve()
{
    int x;
    for(int i = 1; i <= M; ++i)
    {
        x = IND[i];
        if(Grupa(X[x]) != Grupa(Y[x]))
        {
            ANSW += C[x];
            Union(X[x], Y[x]);
            ANS.push_back(x);
        }
    }
}
void Union(int i, int j)
{
    GR[Grupa(i)] = Grupa(j);
}

int Grupa(int x)
{
    if(GR[x] == x) return x;
    GR[x] = Grupa(GR[x]);
    return GR[x];
}