Cod sursa(job #2468909)

Utilizator Anakin1001George Giorgiu Gica Anakin1001 Data 6 octombrie 2019 11:07:01
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <algorithm>
#define DIM 200000
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
struct meme{
    int x, y, c;
}v[DIM + 1];
bool viz[2 * DIM + 1];
int k, i, n, m, S, tata[DIM + 1];
int cmp(meme a, meme b){
    if(a.c == b.c)
        return a.x < b.x;
    return a.c < b.c;
}
int father(int node){
    while(tata[node] > 0)
        node = tata[node];
    return node;
}
int main()
{   f >> n >> m;
    for( i = 1; i <= m; i++ ){
        f >> v[i].x >> v[i].y >> v[i].c;
    }
    sort(v + 1, v + m + 1, cmp);
    for( i = 1; i <= m; i++ )
        tata[i] = -1;
    k = 0;
    i = 1;
    while( k != n - 1 ){
        int x = v[i].x;
        int y = v[i].y;
        int father_x = father(x);
        int father_y = father(y);
        if(father_x != father_y){
            S += v[i].c;
            k++;
            viz[i] = 1;
            if(tata[father_x] >= tata[father_y]){
                tata[father_y] += tata[father_x];
                tata[father_x] = father_y;
            }
            else{
                tata[father_x] += tata[father_y];
                tata[father_y] = father_x;
            }
        }
        i++;
    }
    g << S << '\n';
    for( i = 1; i <= m; i++ )
        if(viz[i] == true)
            g << v[i].x << ' ' << v[i].y << '\n';
    return 0;
}