Cod sursa(job #3030459)

Utilizator raulboancaBoanca Raul Alin raulboanca Data 17 martie 2023 18:00:16
Problema Arbore partial de cost minim Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("apm.in");
ofstream fout("apm.out");

set <pair <int,int> > st;
vector <pair <int,int> > v[50005];
int viz[50005],tata[50005],dist[50005];
int n,m,disttot;
const int oo=2000000001;

void citire()
{
    fin>>n>>m;
    int x,y,c;
    for(int i=1; i<=m; i++)
    {
        fin>>x>>y>>c;
        v[x].push_back({y,c});
        v[y].push_back({x,c});
    }
}



void init()
{
    for(int i=1; i<=n; i++)
        dist[i]=oo;
    dist[1]=0;
    st.insert({0,1});
}

void apm()
{
    while(!st.empty())
    {
        int nod=st.begin()->second;
        int di=st.begin()->first;
        st.erase(st.begin());
        if(viz[nod]==0)
        {
            viz[nod]=1;
            disttot+=di;
            for(auto k:v[nod])
            {
                if(dist[k.first]>k.second && viz[k.first]==0)
                {
                    dist[k.first]=k.second;
                    st.insert({dist[k.first],k.first});
                    tata[k.first]=nod;
                }
            }
        }
    }
}

int main()
{
    citire();
    init();
    apm();
    fout << disttot << '\n';
    fout << n-1 << '\n';
    for (int i=2; i<=n; i++)
    {
        fout << i << " " << tata[i] << '\n';
    }
    return 0;
}