Cod sursa(job #3123541)

Utilizator RalucaioneteRalucaIonete Ralucaionete Data 24 aprilie 2023 15:26:26
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include<fstream>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;

ifstream cin("apm.in");
ofstream cout("apm.out");

const int N=2e5;

struct edges
{
    int x;
    int y;
    int c;
    bool operator<(const edges &other) const
    {
        return c > other.c;
    }
};

priority_queue<edges> pq;

vector<pair<int, int>> v[N+1];
pair<int, int> result[N+1];

bool viz[N+1];

int main()
{
    int n, m;
    long long costuri =0;
    cin >> n >> m;
    for(int i=1; i<=m; i++)
    {
        int from, to, cost;
        cin >> from >> to >> cost;
        v[from].push_back(make_pair(to, cost));
        v[to].push_back(make_pair(from, cost));
    }
    viz[1]=true;
    for(auto x: v[1])
        pq.push({1, x.first, x.second});

    int parcurgem=1;
    while(parcurgem < n)
    {
        edges e = pq.top();
        pq.pop();
        if(!viz[e.y])
        {
            viz[e.y]=true;
            result[parcurgem]=make_pair(e.x, e.y);
            parcurgem++;
            costuri+=e.c;
            for(auto x: v[e.y])
            {
                if(!viz[x.first])
                    pq.push({e.y, x.first, x.second});
            }

        }
    }

    cout << costuri << '\n';
    cout << parcurgem-1 << '\n';
    for(int i=1; i<=parcurgem-1; i++)
    {
        cout << result[i].first << " " << result[i].second << '\n';
    }
    return 0;
}