Cod sursa(job #2928664)

Utilizator BuzdiBuzdugan Rares Andrei Buzdi Data 23 octombrie 2022 17:07:51
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <cstring>
#include <bitset>

//#include <bits/stdc++.h>

#define ll long long
#define ull unsigned long long
#define MOD 1000000007
#define NMAX 200001
#define KMAX 105
#define LIM 1000
#define INF 1e9
#define LOG 17

using namespace std;

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

struct triplet
{
    int x, y, c;
    bool operator < (triplet other) const
    {
        return other.c < c;
    }
};

int n, m;
vector<pair<int, int>> G[NMAX];
vector<int> T(NMAX, 0), Value(NMAX, INF);
int TotalCost;
bool Visited[NMAX];

void Prim()
{
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    
    Value[1] = 0;
    pq.push({ 0, 1 });
    while (!pq.empty())
    {
        int NodeCur = pq.top().second;
        pq.pop();
        Visited[NodeCur] = 1;
        for (auto Edge : G[NodeCur])
        {
            int v = Edge.first, cost = Edge.second;
            if (!Visited[v] && cost < Value[v])
            {
                Value[v] = cost;
                T[v] = NodeCur;
                pq.push({ cost, v });
            }
        }
    }
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    cin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, c;
        cin >> x >> y >> c;
        G[x].push_back({ y, c });
        G[y].push_back({ x, c });
    }

    Prim();

    for (int i = 1; i <= n; i++)
        TotalCost += Value[i];

    cout << TotalCost << '\n';
    cout << n - 1 << '\n';
    for (int i = 2; i <= n; i++)
        cout << T[i] << ' ' << i << '\n';
    

    return 0;
}