Cod sursa(job #3213894)

Utilizator leelcheeseCiovnicu Denis leelcheese Data 13 martie 2024 16:30:52
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <bits/stdc++.h>
#include <unordered_map>
#define nmax 200006
#define MOD 1999999973
#define INF 2012345678
#define ll long long
using namespace std;
//#define fin cin
//#define fout cout

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

struct Patru {
    int x, y, cost, viz;
    bool operator < (const Patru w) const {
        return cost < w.cost;
    }
} a[2 * nmax];

int n, m;
int t[nmax];

int FindRoot(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 Union(int x, int y)
{
    t[y] = x;
}

int Kruskal()
{
    int x, y, costTotal, nrc;
    nrc = n; costTotal = 0;
    sort(a + 1, a + m + 1);
    
    for (int i = 1; nrc > 1; i++)
    {
        x = FindRoot(a[i].x);
        y = FindRoot(a[i].y);
        if (x != y)
        {
            Union(x, y);
            nrc--;
            costTotal += a[i].cost;
            a[i].viz = 1;
        }
    }
    return costTotal;
}

int main()
{
    int i, cnt;
    fin >> n >> m;
    for (i = 1; i <= m; i++)
        fin >> a[i].x >> a[i].y >> a[i].cost;

    fout << Kruskal() << "\n";

    cnt = 0;
    for (i = 1; i <= m; i++)
        if (a[i].viz == 1)
            cnt++;
    fout << cnt << "\n";

    for (i = 1; i <= m; i++)
        if (a[i].viz == 1)
            fout << a[i].x << " " << a[i].y << "\n";
    fin.close();
    fout.close();
    return 0;
}