Cod sursa(job #2131628)

Utilizator FrequeAlex Iordachescu Freque Data 14 februarie 2018 20:12:18
Problema Arbore partial de cost minim Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int NMAX = 200000 + 5;
const int MMAX = 400000 + 5;

struct edge
{
    int x;
    int y;
    int cost;

    edge()
    {
        x = 0;
        y = 0;
        cost = 0;
    }

    edge(int _x, int _y)
    {
        x = _x;
        y = _y;
        cost = 0;
    }

    edge(int _x, int _y, int _cost)
    {
        x = _x;
        y = _y;
        cost = _cost;
    }

    bool operator < (const edge &arg) const
    {
        return cost > arg.cost;
    }
};

priority_queue <edge> pq;
vector <edge> graph[NMAX];
vector <edge> ans;
int n, m, sum;
bool vis[NMAX];

void write()
{
    fout << sum << '\n' << ans.size() << '\n';
    for (auto i: ans)
        fout << i.x << " " << i.y << '\n';
}

void read()
{
    int x, y, c;

    fin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        fin >> x >> y >> c;
        graph[x].push_back(edge(x, y, c));
        graph[y].push_back(edge(y, x, c));
    }
}

int main()
{
    read();

    vis[1] = true;
    for (auto i: graph[1])
        pq.push(i);

    while (!pq.empty())
    {
        edge e = pq.top();
        pq.pop();

        int nod;
        if (!vis[e.x]) nod = e.x;
        else if (!vis[e.y]) nod = e.y;
        else continue;

        vis[nod] = true;
        sum += e.cost;
        ans.push_back(e);
        for (auto i: graph[nod])
        {
            pq.push(i);

        }
    }

    write();

    return 0;
}