Cod sursa(job #2467154)

Utilizator blotucosmincosmin blotucosmin Data 3 octombrie 2019 19:39:52
Problema Arbore partial de cost minim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
struct nod
{
    int x, y, cost;
} v[400001];
bool cmp(nod i, nod j)
{
    return i.cost < j.cost;
}
int tata[200001], n, m, val1, val2, s, ct, i;
bool viz[200001];
int find(int x)
{
    int val, y = x;
    while(tata[x] != x)
        x = tata[x];
    return x;
}
void join(int x, int y)
{
    tata[tata[x]] = find(y);
}
int main()
{
    f >> n >> m;
    for(i = 1; i <= m; ++ i)
        f >> v[i].x >> v[i].y >> v[i].cost;
    for(i = 1; i <= n; ++ i)
        tata[i] = i;
    sort(v + 1, v + m + 1, cmp);
    for(i = 1; i <= m && ct < n - 1; ++ i)
        if(find(v[i].x) != find(v[i].y))
        {
            s += v[i].cost;
            join(v[i].x, v[i].y);
            tata[val1] = val2;
            viz[i] = true;
            ct ++;
        }
    g << s << "\n" << ct << "\n";
    for(i = 1; i <= m; ++ i)
        if(viz[i] == true)
        g << v[i].y << " " << v[i].x  << "\n";
    return 0;
}