Cod sursa(job #2373847)

Utilizator AngelEclipseGarleanu Alexandru Stefan AngelEclipse Data 7 martie 2019 15:29:43
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <bits/stdc++.h>

struct Edge
{
    int32_t NodeA, NodeB, Length;

    Edge(int32_t construct_NodeA = 0, int32_t construct_NodeB = 0, int32_t construct_Lungime = 0)
        : NodeA(construct_NodeA), NodeB(construct_NodeB), Length(construct_Lungime) {}

    bool operator<(const Edge &other) const
    {
        return Length < other.Length;
    }
};

std::ifstream f("apm.in");
std::ofstream g("apm.out");
int32_t NumberOfNodes, NumberOfEdges;
std::vector<Edge> Edges;
Edge InitialEdges[200005];
int32_t NodeParent[200005];

void Read()
{
    f >> NumberOfNodes >> NumberOfEdges;
    for (int32_t i = 0, x, y, l; i < NumberOfEdges; i++)
    {
        f >> x >> y >> l;
        InitialEdges[i] = Edge(x, y, l);
    }
}

int32_t Root(int32_t Vertex)
{
    if (NodeParent[Vertex] != Vertex)
        NodeParent[Vertex] = Root(NodeParent[Vertex]);
    return NodeParent[Vertex];
}

int main()
{
    Read();

    for (int i = 1; i < NumberOfNodes; i++)
        NodeParent[i] = i;

    std::sort(InitialEdges, InitialEdges + NumberOfEdges);

    for (int i = 0; i < NumberOfEdges; i++)
    {
        int RootA = Root(InitialEdges[i].NodeA);
        int RootB = Root(InitialEdges[i].NodeB);
        if (RootA != RootB)
        {
            NodeParent[RootB] = RootA;
            Edges.push_back(InitialEdges[i]);
        }
    }
    int32_t Sum = 0;
    for (auto i : Edges)
    {
        Sum += i.Length;
    }
    g << Sum << '\n';
    g << Edges.size() << '\n';
    for (auto i : Edges)
    {
        g << i.NodeA << ' ' << i.NodeB << '\n';
    }
}