Cod sursa(job #1255351)

Utilizator angelaAngela Visuian angela Data 4 noiembrie 2014 18:55:05
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
// ok - infoarena
#include <stdio.h>
#include <queue>
#include <bitset>
using namespace std;

const int Nmax = 200001, Inf = 1 << 30;
#define x first
#define y second

struct Edge {
    int node, cost;
    const bool operator < (const Edge &e) const
    {
        return cost > e.cost;
    }
};

vector<Edge> G[Nmax + 1];
vector<pair<int, int>> apm;
priority_queue<Edge> Q;
vector<int> key, t; // cheile,  predecesorii
int n;
long long cost_apm;
bitset<Nmax + 1> v;

void Prim (int k)
{
    key = vector<int>(n + 1, Inf);
    t = vector<int>(n + 1);
    int x, w;  // vecinul lui k si costul muchiei
    key[k] = 0;
    Q.push({k, 0});

    while (!Q.empty() )
    {
        k = Q.top().node;
        v[k] = 1;    // cost minim final pentru k (nu tebuie sa mai intre in coada)
        for (const auto& e : G[k])
        {
			x = e.node;
			if ( v[x] ) continue;
			w = e.cost;

            if( key[x] > w )
            {
                key[x] = w;
                t[x] = k;
                Q.push({x, key[x]});
            }
		}
		apm.push_back({t[k], k}); // adaug in apm si sursa (k, cu t[k] = 0)
		cost_apm += key[k];       // adaug si costul sursei k: 0

        while (!Q.empty() && v[Q.top().node])
            Q.pop();
    }
}

int main()
{
    freopen("apm.in","r",stdin);
    freopen("apm.out","w",stdout);
    int a, b, c, m;
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= m; i++)  // sar peste muchie [t[k], k]
    {
        scanf("%d%d%d", &a, &b, &c);
        G[a].push_back({b, c});
        G[b].push_back({a, c});
    }

    Prim(1);
	printf("%lld\n", cost_apm);
	printf("%d\n", (int)apm.size() - 1);
	for (size_t i = 1; i < apm.size(); ++i)
		printf("%d %d\n",  apm[i].x, apm[i].y);


    return 0;
}