Cod sursa(job #3030110)

Utilizator rapidu36Victor Manz rapidu36 Data 17 martie 2023 15:22:20
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>

using namespace std;

const int N = 2e5;
const int INF = 1e9;

struct muchie
{
    int vf, cost;
};

/*
struct pereche
{
    int vf, cost;
    bool operator < (const pereche &altul) const
    {
        return (this->cost < altul.cost);
    }
};
*/

vector <muchie> a[N+1];
int n, m, d[N+1], pred[N+1];

int prim()
{
    priority_queue <pair<int, int>, vector <pair<int, int>>, greater<pair<int, int>>> h;
    bitset <N+1> in_t;
    int cost_total = 0;
    for (int i = 2; i <= n; i++)
    {
        d[i] = INF;
    }
    //priority_queue <pereche> h;
    d[1] = 0;
    h.push({0, 1});
    while (!h.empty())
    {
        int x = h.top().second;
        h.pop();
        if (in_t[x])
        {
            continue;
        }
        cost_total += d[x];
        in_t[x] = 1;
        for (auto e: a[x])
        {
            int c = e.cost;
            int y = e.vf;
            if (!in_t[y] && c < d[y])
            {
                d[y] = c;
                h.push({c, y});
                pred[y] = x;
            }
        }
    }
    return cost_total;
}

int main()
{
    ifstream in("apm.in");
    ofstream out("apm.out");
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;
        a[x].push_back((muchie){y, c});
        a[y].push_back((muchie){x, c});
    }
    out << prim() << "\n" << n - 1 << "\n";
    for (int i = 2; i <= n; i++)
    {
        out << pred[i] << " " << i << "\n";
    }
    in.close();
    out.close();
    return 0;
}