Cod sursa(job #2333641)

Utilizator mihailescu_eduardMihailescu Eduard-Florin mihailescu_eduard Data 1 februarie 2019 17:33:42
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
// APM Kruskal's Algorithm
 
#include <fstream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
ifstream fin("apm.in");
ofstream fout("apm.out");
 
static const int NMAX = 400100;
 
int n, m;
int x[NMAX], y[NMAX], weight[NMAX], ind[NMAX];
int TT[NMAX], RG[NMAX];
vector<int> sol;
 
bool cmp(int a,int b)
{
    return weight[a] < weight[b];
}
 
int find(int x)
{
    int R, y;
    
    for(R = x; TT[R] != R; R = TT[R]);
 
    while(TT[x] != x)
    {
        y = TT[x];
        TT[x] = R;
        x = y;
    }
    return R;
}
 
void unite(int xx, int yy)
{
    int x = find(xx);
    int y = find(yy);
    if(x == y)
        return;
    if(RG[x] > RG[y])
        TT[y] = x;
    else
        TT[x] = y;
 
    if(RG[x] == RG[y])
        RG[y]++;
    
}
int main()
{
    int total = 0;
    fin >> n >> m;
    for(int i = 1; i<=m ; ++i)
    {
        fin >> x[i] >> y[i] >> weight[i];
        ind[i] = i;
    }
    for(int i =1 ;i <= n; ++i)
    {
        TT[i] = i;
        RG[i] = 0;
    }
    sort(ind+1, ind+m+1, cmp);
    for(int i = 1; i<= m; ++i)
    {
        int parent1 = find(x[ind[i]]);
        int parent2 = find(y[ind[i]]);
 
        if(parent1 != parent2)
        {
            unite(x[ind[i]],y[ind[i]]);
            total+= weight[ind[i]];
            sol.push_back(ind[i]);
        }
    }
    fout << total << '\n' << sol.size() << '\n';
    for(auto it : sol)
        fout << y[it] << " " << x[it] << '\n';
 
    return 0;
 
}