Cod sursa(job #449261)

Utilizator Bogdan_CCebere Bogdan Bogdan_C Data 6 mai 2010 00:38:07
Problema Arbore partial de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.31 kb
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<queue>
#define MMAX 400000
#define NMAX 200000

using namespace std;

int N,M,x,y,c,*tata,*rang,card,cost,nod;
struct Vect
{
	int x,y,c;
} *Edge;
vector<int> *V,APM;
queue<int> Q;


int get_father(int i)
{
	int x,z;;
	for(x = i ; x!=tata[x]; x=tata[x]);
	for( ; i != tata[i] ; ) 
	{		
		z = tata[i];
		tata[i] = x;
		i = z;
	}
	return x;
}

void unite(int x,int y)
{
	if(rang[x]>rang[y]) tata[y] = x;
	else tata[x] = y;
	if(rang[x] == rang[y]) rang[y]++;
}

int comp(int a , int b)
{
	return Edge[a].c > Edge[b].c;
}


int main()
{
	freopen("apm.in","r",stdin);
	freopen("apm.out","w",stdout);
	scanf("%d %d",&N,&M);
	tata = new int[N+2];
	rang = new int[N+2];
	Edge = new Vect[M+2];
	V = new vector<int>[N+2];
	for(int i = 1 ;i <= M ;i++)
	{
		
		scanf("%d %d %d",&x,&y,&c);
		V[x].push_back(i);
		V[y].push_back(i);
		Edge[i].x = x;
		Edge[i].y = y;
		Edge[i].c = c;
	}

	for(int i = 1 ; i <= N ; i++)
	{
		rang[i] = 1 ;
		tata[i] = i;
		Q.push(i);
		make_heap(V[i].begin(),V[i].end(),comp);
	
	}
    card = 0;
	while(card < N-1 )
	{
		if(Q.empty()) break;
		nod = Q.front();
		Q.pop();
		if(V[nod].empty()) continue; 
		int e,tx,ty;
		e = V[nod].front();
		pop_heap(V[nod].begin(),V[nod].end(),comp);
		V[nod].pop_back(); 
		tx = get_father(Edge[e].x);
		ty = get_father(Edge[e].y);
		if(tx!=ty)
		{
			cost+=Edge[e].c;
			APM.push_back(e);
			card++;
			int setNum = rang[tx] + rang[ty];
            if (rang[tx] > rang[ty]) {
                    tata[tx] = ty;
					while(!V[tx].empty())
					{
						V[ty].push_back(V[tx].back());
						V[tx].pop_back();
						push_heap(V[ty].begin(),V[ty].end(),comp);
					}
                    
                    Q.push(ty);
            } else {
                    tata[ty] = tx;
					if(rang[tx] == rang[ty] ) rang[ty]++; 
                    while(!V[ty].empty())
					{
						V[tx].push_back(V[ty].back());
						V[ty].pop_back();
						push_heap(V[tx].begin(),V[tx].end(),comp);
					}
                    
                    Q.push(tx);
			}
		}
		else Q.push(tx);
	}
	printf("%d\n%d\n",cost,N-1);
	vector<int>::iterator it;
	for(it=APM.begin();it!=APM.end();it++)
		printf("%d %d\n",Edge[*it].x,Edge[*it].y);
	return 0;

}