Cod sursa(job #2305327)

Utilizator AndreiLunguLungu Andrei Sebastian AndreiLungu Data 19 decembrie 2018 21:44:25
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int n , m , t[400005];
struct Muchie
{
    int x , y , cost;
    bool check;
    bool operator <(const Muchie &A) const
    {
        return cost < A.cost;
    }
};
Muchie a[400005];
void Citire()
{
    int i;
    fin >> n >> m;
    for(i = 1; i <= m; i++)
        fin >> a[i].x >> a[i].y >> a[i].cost;
    fin.close();
}
void Union(int x , int y)
{
    t[y] = x;
}
int Find(int x)
{
    int rad , y;
    rad = x;
    while(t[rad] != 0)
        rad = t[rad];
    while(x != rad)
    {
        y = t[x];
        t[x] = rad;
        x = y;
    }
    return rad;
}
void Kruskal()
{
    int x , y , i , nrcc , costmin , nr;
    costmin = 0;
    nrcc = n;
    sort(a + 1 , a + m + 1);
    for(i = 1; i <= m && nrcc > 1; i++)
    {
        x = a[i].x;
        y = a[i].y;
        x = Find(x);
        y = Find(y);
        if(x != y)
        {
            Union(x , y);
            nrcc--;
            costmin += a[i].cost;
            a[i].check = true;
        }
    }
    fout << costmin << "\n";
    nr = 0;
    for(i = 1; i <= m; i++)
        if(a[i].check == true)nr++;
    fout << nr << "\n";
    for(i = 1; i <= m; i++)
        if(a[i].check == true)
        fout << a[i].x << " " << a[i].y << "\n";
    fout.close();
}
int main()
{
    Citire();
    Kruskal();
    return 0;
}