Cod sursa(job #3237080)

Utilizator Sasha_12454Eric Paturan Sasha_12454 Data 4 iulie 2024 16:43:46
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
//O(m log(n))
#include <bits/stdc++.h>

std :: ifstream in ("apm.in");

std :: ofstream out ("apm.out");

const int NMAX = 2e5 + 5;

const int INF = 2e9;

int n;

int m;

int x;

int y;

int d;

long long sum;

int dist[NMAX];

int parent[NMAX];

std :: vector <std :: pair <int, int>> v[NMAX];

std :: stack <std :: pair <int, int>> s;

std :: priority_queue <std :: pair <int, int>> pq;

std :: bitset <NMAX> visited;

void prim()
{
    while(s.size() < n && !pq.empty())
    {
        int nod = pq.top().second;

        d = -pq.top().first;

        pq.pop();

        if(visited[nod] == false)
        {
            visited[nod] = true;

            sum += d;

            if(parent[nod])
            {
                s.push(std :: make_pair(nod, parent[nod]));
            }

            for(auto i : v[nod])
            {
                if(visited[i.first] == false && i.second < dist[i.first])
                {
                    dist[i.first] = i.second;

                    parent[i.first] = nod;

                    pq.push(std :: make_pair(-dist[i.first], i.first));
                }
            }
        }
    }
}

int main()
{

    in >> n >> m;

    for(int i = 1; i <= m; i ++)
    {
        in >> x >> y >> d;

        v[x].push_back(std :: make_pair(y, d));

        v[y].push_back(std :: make_pair(x, d));
    }

    for(int i = 1; i <= n; i ++)
    {
        dist[i] = INF;
    }

    dist[1] = 0;

    pq.push(std :: make_pair(0, 1));

    n --;

    prim();

    out << sum << '\n';

    out << n << '\n';

    while(!s.empty())
    {
        out << s.top().first << " " << s.top().second << '\n';

        s.pop();
    }

    return 0;
}