Mai intai trebuie sa te autentifici.

Cod sursa(job #989828)

Utilizator gunner_292Mihai Manolescu gunner_292 Data 26 august 2013 16:04:54
Problema Arbore partial de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include<fstream>
#include<algorithm>
#include<vector>
#define nmax 200003
#define mmax 400003

using namespace std;

ifstream in("apm.in");
ofstream out("apm.out");

int n,m;

struct edge
{
    int vertex1;
    int vertex2;
    int weight;
};

edge e[mmax];

vector<int>mst;

int father[nmax];
int nRank[nmax];


int compF(edge e1, edge e2)
{
    return e1.weight <= e2.weight;
}

bool connected(int v1, int v2)
{
    while(father[v1] != -1)
        v1 = father[v1];

    while(father[v2] != -1)
        v2 = father[v2];

    return (v1 == v2);
}

void join(int v1, int v2)
{
    while(father[v1] != -1)
        v1 = father[v1];

    while(father[v2] != -1)
        v2 = father[v2];

    if(nRank[v1] > nRank[v2])
    {
        father[v2] = v1;
    }
    else if(nRank[v2] > nRank[v1])
    {
        father[v1] = v2;
    }
    else
    {
        father[v2] = v1;
        nRank[v1]++;
    }
}



void kruskal()
{
    sort(e, e+m, compF);

    for(int i=1; i<=n; i++)
    {
        father[i] = -1;
        nRank[i] = 1;
    }

    int edgesNr = 0;
    int totalW = 0;

    for(int i=0; i<m && edgesNr < n-1; i++)
    {
        if(!connected(e[i].vertex1, e[i].vertex2))
        {
            join(e[i].vertex1, e[i].vertex2);
            edgesNr++;
            totalW = totalW + e[i].weight;
            mst.push_back(i);
        }
    }

    out<<totalW<<'\n'<<n-1<<'\n';

    vector<int>::iterator it;

    for(it = mst.begin(); it < mst.end(); it++)
        out<<e[*it].vertex1<<" "<<e[*it].vertex2<<'\n';

}



int main()
{
    in>>n>>m;

    for(int i=0; i<m; i++)
    {
        in>>e[i].vertex1>>e[i].vertex2>>e[i].weight;
    }

    in.close();

    kruskal();

    out.close();

    return 0;

}