Cod sursa(job #3320449)

Utilizator ionicaion ionica Data 5 noiembrie 2025 20:38:59
Problema Arbore partial de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>
#define NM 200001
#define INF 1000000000
using namespace std;
ifstream fin ("apm.in");
ofstream fout ("apm.out");
int n, m, t[NM], ct,viz[NM],d[NM];
struct pereche
{
    int y,c;
};

struct muchie
{
    int x, y, c;
    int operator<(muchie u)const
    {
        return c > u.c;
    }
};

priority_queue<muchie> q;


vector<pereche> G[105];

int main()
{
    int i,nr,x,y,c;
    muchie e;
    pereche p;

    fin >> n >> m;
    for(i=1; i<=m; i++)
    {
        fin >> x >> y >> c;
        G[x].push_back({y,c});
        G[y].push_back({x,c});
    }
    for(i=2;i<=n;i++)
        d[i]=INF;
    for(i=0;i<G[1].size();i++)
    {
       p=G[1][i];
       q.push({1, p.y, p.c});
       t[p.y]=1;
       d[p.y]=p.c;
    }
    viz[1]=1;
    nr=0;
    while(nr<n-1)
    {
        e= q.top();
        q.pop();

        if(viz[e.y]==0)
        {
            nr++;
            viz[e.y]=1;
            t[e.y]=e.x;
            ct=ct+e.c;

            for(i=0;i<G[e.y].size();i++)
            {
                p=G[e.y][i];
                if(viz[p.y]==0 && p.c<d[p.y])
                    {
                        q.push({e.y, p.y,p.c});
                        d[p.y]=p.c;
                    }
            }
        }
    }
    fout << ct << '\n';
    fout<<n-1<<'\n';
    for(i=2; i<=n; i++)
        fout <<i<<' '<< t[i] << '\n';
    return 0;
}