Cod sursa(job #3260255)

Utilizator TonyyAntonie Danoiu Tonyy Data 1 decembrie 2024 12:01:35
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin ("apm.in");
ofstream fout("apm.out");

const int Max = 2e5 + 1;
int n, m, cost, x, y, z;
vector<pair<int,int>> graph[Max];
vector<int> parent(Max), d(Max, INT_MAX);
bitset<Max> v;
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> q;

void prim(int node)
{
    q.push({0, node});
    d[node] = 0;
    while(!q.empty())
    {
        tie(z, node) = q.top();
        q.pop();
        if(v[node])
            continue;
        v[node] = 1;
        cost += z;
        for(auto i: graph[node])
        {
            int neighbour = i.first;
            int dist = i.second;
            if(!v[neighbour] && dist < d[neighbour])
            {
                d[neighbour] = dist;
                parent[neighbour] = node;
                q.push({d[neighbour], neighbour});
            }
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);
    fin.tie(NULL);

    fin >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        fin >> x >> y >> z;
        graph[x].push_back({y, z});
        graph[y].push_back({x, z});
    }
    prim(1);
    fout << cost << "\n" << n - 1 << "\n";
    for(int i = 2; i <= n; ++i)
        fout << i << " " << parent[i] << "\n";

    fin.close();
    fout.close();
    return 0;
}