Cod sursa(job #1290623)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 11 decembrie 2014 16:39:05
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include<cstdio>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<algorithm>
#include<vector>
#include<bitset>
#include<deque>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<unordered_map>

#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>

using namespace std;

const int nmax = 200005;
const int inf = (1LL << 31) - 1;

int n, m, i, x, y, c, cost, cnt, d[nmax], f[nmax], a[nmax], b[nmax];

vector<pii> v[nmax];
bitset<nmax> viz;
priority_queue<pii, vector<pii>, greater<pii>> q;

int main()
{
    freopen("apm.in", "r", stdin);
    freopen("apm.out", "w", stdout);

    scanf("%d%d", &n, &m);

    for(; m; m--)
    {
        scanf("%d%d%d", &x, &y, &c);
        v[x].pb(mp(y, c));
        v[y].pb(mp(x, c));
    }

    for(i = 1; i <= n; i++)
        d[i] = inf;

    viz[1] = 1;
    for(auto it : v[1])
    {
        d[it.first] = it.second;
        f[it.first] = 1;
        q.push(mp(d[it.first], it.first));
    }

    while(!q.empty())
    {
        c = q.top().first;
        x = q.top().second;
        q.pop();

        if(viz[x]) continue;
        viz[x] = 1;

        cost += c;
        cnt++;
        a[cnt] = x;
        b[cnt] = f[x];

        for(auto it : v[x])
            if(!viz[it.first] && it.second < d[it.first])
            {
                d[it.first] = it.second;
                f[it.first] = x;
                q.push(mp(d[it.first], it.first));
            }
    }

    printf("%d\n%d\n", cost, cnt);
    for(i = 1; i <= cnt; i++)
        printf("%d %d\n", a[i], b[i]);

    return 0;
}