Cod sursa(job #1437453)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 17 mai 2015 19:27:44
Problema Arbore partial de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;

ifstream is("apm.in");
ofstream os("apm.out");

typedef vector<int> VI;
typedef vector<VI> VVI;
typedef pair<int, int> II;
typedef vector<II> VII;
typedef pair<int, II> III;
typedef vector<III> VIII;
typedef vector<VII> VVII;

int n, m, answ;
VII a;
VVI g;

void Read();
void Write();

int main()
{
    Read();
    int cmin, x, y;
    VI ok(n + 1);
    vector<int> q;
    q.push_back(1);
    ok[1] = 1;
    while ( q.size() < n )
    {
        cmin = INF;
        for ( const auto &nod : q )
            for ( int i = 1; i <= n; ++i )
                if ( !ok[i] && g[nod][i] < cmin )
                {
                    cmin = g[nod][i];
                    x = nod;
                    y = i;
                }
        q.push_back(y);
        ok[y] = 1;
        answ += cmin;
        a.push_back(make_pair(x, y));
    }
    Write();
    is.close();
    os.close();
    return 0;
}

void Write()
{
    os << answ << "\n" << n - 1 << "\n";
    for ( const auto &i : a )
        os << i.first << " " << i.second << "\n";
}

void Read()
{
    is >> n >> m;
    g = VVI(n + 1, VI(n + 1, INF));
    int x, y, cost;
    for ( int i = 1; i <= m; ++i )
    {
        is >> x >> y >> cost;
        g[x][y] = g[y][x] = cost;
    }
    for ( int i = 1; i <= n; ++i )
        g[i][i] = 0;
}