Cod sursa(job #3373115)

Utilizator corneacarminaCornea Carmina-Stefania corneacarmina Data 6 noiembrie 2026 09:04:38
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 200005;
const int MMAX = 400005;

int p[NMAX+1]; 
int sz[NMAX+1];

int Find(int x){ 
     while(x != p[x]){
          x = p[x];
     }
     return x;
}

void Union(int x, int y)
{
     x = Find(x);
     y = Find(y);
     if(x != y)
     {
          if(sz[x] < sz[y]){
               p[x] = y;
               sz[y] += sz[x];
          } else {
               p[y] = x;
               sz[x] += sz[y];
          }
     }
}

struct muchie{
     int x, y, c;
};

muchie v[MMAX];
muchie sol[NMAX];

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

int main()
{
    ifstream cin("apm.in");
    ofstream cout("apm.out");
    int n, m;
    if (!(cin >> n >> m)) return 0;
    
    for(int i = 1; i <= n; i++)
    {
          p[i] = i;
          sz[i] = 1;
    }
    for(int i = 1; i <= m; i++)
    {
          cin >> v[i].x >> v[i].y >> v[i].c;
    }
    
    sort(v + 1, v + m + 1, cmp);    // ATENȚIE: Costul total poate fi mare (sau negativ), folosim long long!
    long long apm = 0;
    int nr = 0;

    for(int i = 1; i <= m; i++)
    {
          if(Find(v[i].x) != Find(v[i].y))
          {
               apm += v[i].c;
               Union(v[i].x, v[i].y);
               sol[++nr] = v[i];
          }
    }

    cout << apm << "\n";
    cout << nr << "\n";
    for(int i = 1; i <= nr; i++)
    {
          cout << sol[i].x << " " << sol[i].y << "\n";
    }
    
    return 0;
}