Cod sursa(job #2928594)

Utilizator BuzdiBuzdugan Rares Andrei Buzdi Data 23 octombrie 2022 14:20:51
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 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;
    
}a[NMAX];

int n, m;
vector<int> T(NMAX, -1);
int TotalCost;
vector<pair<int, int>> APM;

bool cmp(triplet x, triplet y)
{
    return x.c < y.c;
}

int GetRoot(int Node)
{
    int aux = Node;
    while (T[Node] > 0)
        Node = T[Node];

    int Root = Node;
    Node = aux;

    while (Node != Root)
    {
        aux = T[Node];
        T[Node] = Root;
        Node = aux;
    }

    return Root;
}

bool Joined(int x, int y)
{
    int xRoot = GetRoot(x);
    int yRoot = GetRoot(y);

    if (xRoot == yRoot)
        return false;

    if (T[xRoot] <= T[yRoot])
    {
        T[yRoot] += T[xRoot];
        T[xRoot] = yRoot;
    }
    else
    {
        T[xRoot] += T[yRoot];
        T[yRoot] = xRoot;
    }

    return true;
}

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;
        a[i] = { x, y, c };
    }

    sort(a + 1, a + m + 1, cmp);
    for (int i = 1; i <= m && APM.size() != n; i++)
    {
        int x, y, c;
        x = a[i].x;
        y = a[i].y;
        c = a[i].c;

        if (Joined(x, y))
        {
            TotalCost += c;
            APM.push_back({ x, y });
        }
    }

    cout << TotalCost << '\n';
    cout << APM.size() << '\n';
    for (auto x : APM)
        cout << x.first << ' ' << x.second << '\n';



    return 0;
}