Cod sursa(job #2870199)

Utilizator RTG123Razvan Diaconescu RTG123 Data 12 martie 2022 10:43:02
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define MAXN 200001
#define MINM -1001
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
struct queueval
{
    int a,b,cost;
};
int n,m,x,y,z,viz[MAXN],d[MAXN],s,from[MAXN],nr;
vector <vector <int>>  v(MAXN),cost(MAXN);
auto cmp=[](queueval a,queueval b)
{
    if (a.cost>b.cost)
        return 1;
    else return 0;
};
priority_queue <queueval,std:: vector<queueval>,decltype(cmp)> st(cmp);
int main()
{
    f>>n>>m;
    for (int i=1; i<=m; i++)
    {
        f>>x>>y>>z;
        v[x].push_back(y);
        v[y].push_back(x);
        cost[x].push_back(z);
        cost[y].push_back(z);
    }
    for (int i=1; i<=n; i++)
    {
        d[i]=MINM;
    }
    queueval start;
    start.a=1;
    start.b=0;
    start.cost=0;
    st.push(start);
    d[1]=0;
    while (!st.empty())
    {
        int cur=st.top().a,ok=0;
        st.pop();
        viz[cur]=1;
        //cout<<cur<<'\n';
        for (int i=0; i<v[cur].size(); i++)
        {
            int next=v[cur][i];
            if (!viz[next] && (d[next]>cost[cur][i] || d[next]==MINM))
            {
                queueval ins;
                ins.a=next;
                ins.b=cur;
                ins.cost=cost[cur][i];
                ok=1;
                from[next]=cur;
                d[next]=cost[cur][i];
                //if (!viz[next]
                st.push(ins);
            }
        }
         //viz[cur]=0;
         //st.pop();

    }
    for (int i=1; i<=n; i++)
    {
        //cout<<from[i]<<' ';
        s+=d[i];
        if (from[i]>0)
            nr++;
    }
    //cout<<'\n';
    g<<s<<'\n'<<nr<<'\n';
    for (int i=2; i<=n; i++)
    {
        g<<i<<' '<<from[i]<<'\n';
    }
    return 0;
}