Cod sursa(job #3030461)

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

using namespace std;

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

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

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

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

void apm()
{
    while(st.empty()==0)
    {
        int nod=st.begin()->second;
        int di=st.begin()->first;
        st.erase(st.begin());
        if(viz[nod]==0)
        {
            viz[nod]=1;
            totdist+=di;
        for(auto k:v[nod])
        {
            if(dist[k.first]>k.second && viz[k.first]==0)
            {
                //st.erase({dist[k.first],k.first});
                dist[k.first]=k.second;
                st.insert({dist[k.first],k.first});
                tata[k.first]=nod;
            }
        }
    }
}
}
void afisare()
{
    fout<<totdist<<'\n';
    fout<<n-1<<'\n';
    for(int i=2; i<=n; i++)
    {
        fout<<i<<" "<<tata[i]<<'\n';
    }
}

int main()
{
    citire();
    init();
    apm();
    afisare();
    return 0;
}