Cod sursa(job #3377133)

Utilizator Radu_GrigorieGrigorie Radu Stefan Radu_Grigorie Data 21 noiembrie 2026 19:42:02
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>
using namespace std;
const long long maxnode=200001;
priority_queue<pair<long long, long long>> q;
bool viz[200005];
vector<pair<long long, long long>> v[200005], apm;
long long n, m, a, b, c, costtot;
int main()
{
    cin >> n >> m;
    for(int i=1; i<=m; i++)
    {
        cin >> a >> b >> c;
        v[a].push_back({b, c});
        v[b].push_back({a, c});
    }
    viz[1]=1;
    for(auto t:v[1])
    {
        q.push({-t.second, t.first*maxnode+1});
    }
    while(!q.empty()&&apm.size()<n-1)
    {
        long long x=q.top().second/maxnode;
        long long y=q.top().second%maxnode;
        long long cost=-q.top().first;
        q.pop();
        if(viz[x]&&viz[y])
            continue;
        costtot+=cost;
        apm.push_back({x, y});
        int add;
        if(viz[x])
            add=y;
        else
            add=x;
        viz[add]=1;
        for(auto t:v[add])
        {
            if(!viz[t.first])
            {
                q.push({-t.second, t.first*maxnode+add});
            }
        }
    }
    cout << costtot << "\n" << n-1 << "\n";
    for(auto t:apm)
    {
        cout << t.first << " " << t.second << "\n";
    }
    return 0;
}