Cod sursa(job #3251273)

Utilizator Torna3oVirtopeanu Andrei Torna3o Data 25 octombrie 2024 16:13:48
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");
void unire(int x, int y);
int sef(int x);

struct ura
{
    int x, y, c;
}v[400001];
int tata[200001], sol[400001];

bool cmp(ura a, ura b)
{
    return a.c < b.c;
}



int main()
{
    int n, m, i, luate = 0, cost = 0, cnt = 0;
    in >> n >> m;
    for(i = 1; i <= m; i++)
    {
        in >> v[i].x >> v[i].y >> v[i].c;
    }
    for(i = 1; i <= n; i++)
    {
        tata[i] = i;
    }
    sort(v + 1, v + m + 1, cmp);
    i = 1;
    while(luate < n - 1)
    {
        if(sef(v[i].x) != sef(v[i].y))
        {
            unire(v[i].x, v[i].y);
            cost += v[i].c;
            sol[++luate] = i;
        }
        i++;
    }
    out << cost << '\n';
    out << luate << '\n';
    for(i = 1; i <= luate; i++)
    {
        out << v[sol[i]].x << " " << v[sol[i]].y << '\n';
    }
    return 0;
}

void unire(int x, int y)
{
    int sefx = sef(x);
    int sefy = sef(y);
    tata[sefx] = sefy;
}

int sef(int x)
{
    if(tata[x] == x)
    {
        return x;
    }
    else
    {
        return tata[x] = sef(tata[x]);
    }
}