Cod sursa(job #2806866)

Utilizator cyg_Alex_codegicianBarbu Alexandru cyg_Alex_codegician Data 23 noiembrie 2021 09:20:34
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define inf INT32_MAX
#define nr_max_vf 200005
using namespace std;
int n,m,viz[nr_max_vf], d[nr_max_vf], tata[nr_max_vf];
vector <pair<int,int>> la[nr_max_vf];
priority_queue<pair<int,int>> pq;
ofstream fout("apm.out");
void citire(const char* nume_fisier)
{
    ifstream fin(nume_fisier);
    fin >> n >> m;
    int x,y,c;
    for (int i=1; i<=m; i++)
    {
        fin >> x >> y >> c;
        la[x].push_back({y,c});
        la[y].push_back({x,c});
    }
    fin.close();
}
void prim(int s)
{
    for (int i=1; i<=n; i++)
    {
        d[i]=inf;
        tata[i]=viz[i]=0;
    }
    d[s]=0;
    pq.push({-d[s],s});
    int u, v, w;
    for (int i=1; i<=n-1; i++)
    {
        pair<int, int> minn = pq.top();
        u = minn.second;
        pq.pop();

        while(viz[u] == 1)
        {
            minn = pq.top();
            u = minn.second;
            pq.pop();
        }

        viz[u]=1;
        for (auto vecin : la[u])
        {
            v = vecin.first;
            w = vecin.second;
            if (viz[v] == 0)
            {
                if (w < d[v])
                {
                    d[v] = w;
                    tata[v] = u;
                    pq.push({-d[v], v});
                }
            }
        }
    }
}
int main()
{
    citire("apm.in");
    prim(1);
    int cost = 0;
    for (int i=1; i<=n; i++)
    {
        if (tata[i]!=0)
            cost += d[i];
    }
    fout << cost << '\n';
    fout << n-1 << '\n';
    for (int i=1; i<=n; i++)
    {
        if (tata[i]!=0)
        {
            fout << i << " " << tata[i] << '\n';
        }
    }
}