Cod sursa(job #1255275)

Utilizator angelaAngela Visuian angela Data 4 noiembrie 2014 16:57:30
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#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; // apartine deja apm-ului
			w = e.cost;
			
            if( key[x] > w ) 
            {
                key[x] = w;
                t[x] = k;
                Q.push({x, key[x]});
            }
		}
		if ( k != source) 
		{
			apm.push_back({t[k], k});
			cost_apm += key[k];
		}
        while (!Q.empty() && v[Q.top().node])
            Q.pop();
    }
}
 
int main() 
{
    freopen("prim.in","r",stdin);
    freopen("prim.out","w",stdout);
    int a, b, c, m;
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= m; i++) 
    {
        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());
	for (const auto& e : apm)
		printf("%d %d\n",  e.x, e.y);
   
   
    return 0;
}