Cod sursa(job #2990743)

Utilizator StefanL2005Stefan Leustean StefanL2005 Data 8 martie 2023 14:13:58
Problema Arbore partial de cost minim Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#include <cmath>
using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");

struct muchie
{
    int x, y, cost;
};

bool rule(muchie A, muchie B)
{
    if (A.cost == B.cost)
    {
        if (A.x == B.x)
            return A.y < B.y;
        return A.x < B.x;
    }
    return A.cost < B.cost;
}

bool Kruskal(muchie A, int &CompNr, vector<int> &Component)
{
    if (Component[A.x] == Component[A.y])
    {
        if (Component[A.x] == -1)
        {
            Component[A.x] = CompNr;
            Component[A.y] = CompNr;
            CompNr++;
            return true;
        }
        return false;
    }

    if (Component[A.x] == -1 || Component[A.y] == -1)
    {
        if (Component[A.y] == -1)
            swap(A.x, A.y);
        Component[A.x] = Component[A.y];
        return true;
    }

    int C = Component[A.y];
    for (int i = 0; i < Component.size(); i++)
        if (Component[i] == C)
            Component[i] = Component[A.x];
    return true;
}
int main()
{
    int n, m, S = 0, CompNr = 0;
    in>> n >> m;

    vector<int> Component(n, -1);
    vector<muchie> M(m);
    vector<pair<int, int>> Apm;

    for (int i = 0; i < m; i++)
    {
        muchie A;
        in>> A.x >> A.y >> A.cost;
        A.x--; A.y--;
        M[i] = A;
    }

    sort(M.begin(), M.end(), rule);

    for (int i = 0; i < m; i++)
        if (Kruskal(M[i], CompNr, Component))
        {
            S+= M[i].cost;
            Apm.push_back(make_pair(M[i].x, M[i].y));
        }

    out<< S << "\n";
    out<< Apm.size() << "\n";
    for (int i = 0; i < Apm.size(); i++)
        out<< Apm[i].first + 1 << " " << Apm[i].second + 1<< "\n";

    return 0;
}