Cod sursa(job #3319333)

Utilizator petru-robuRobu Petru petru-robu Data 31 octombrie 2025 18:41:47
Problema Arbore partial de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
// Naive kruskal
#include <bits/stdc++.h>
using namespace std;

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

class Edge
{
public:
    int x, y, c;

    Edge(int x, int y, int c): x(x), y(y), c(c){}

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

int n, m, cost;
vector<Edge> edges, mst;
vector<int> tree_id;


void read()
{
    fin>>n>>m;
    for(int i=0; i<m; i++)
    {
        int x, y, c;
        fin>>x>>y>>c;
        edges.push_back(Edge(x, y, c));
    }

    tree_id.assign(n+1, 0);
}

void solve()
{
    for(int i=1; i<=n; i++)
        tree_id[i] = i;

    sort(edges.begin(), edges.end());

    for(auto &e:edges)
    {
        if(tree_id[e.x] != tree_id[e.y]) //in different trees
        {
            cost += e.c;
            mst.push_back(e);

            int oldid = tree_id[e.x], newid = tree_id[e.y]; //merge in O(n)
            for(int i=1; i<=n; i++)
                if(tree_id[i] == oldid)
                    tree_id[i] = newid;
        }
    }
}

int main()
{
    read();
    solve();

    fout<<cost<<'\n'<<mst.size()<<'\n';
    for(auto &e:mst)
    {
        fout<<e.x<<' '<<e.y<<'\n';
    }

    return 0;
}