Cod sursa(job #338614)

Utilizator bacerandreiBacer Andrei bacerandrei Data 6 august 2009 12:23:42
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct muchie
{
  int x , y , c;
};
muchie e[400003], a[400003];
long n , m , t[400003] , cost , o = 1;



void reuneste(long i , long j)
{
  long k;
  i = t[i];
  j = t[j];
    if(i == j)
      return;
  for(k = 1 ; k <= n ; k++)
    if(t[k] == i)
      t[k] = j;
}



int comp_muchie(const void *i , const void *j)
{
  return ((int *) i)[2] - ((int *) j)[2];
}



void kruskal()
{
  long i , j , k , c;
   qsort(e , m , sizeof(e[0]) , comp_muchie);
  for(i = 1 ; i <= n ; i++)
    t[i] = i;
  for(k = 0 ; k < m ; k++)
    {
       i = e[k].x ; j = e[k].y;
       c = e[k].c;
	 if(t[i] == t[j])
	   continue;
      reuneste(i, j);
      cost += c;
       //printf("%d %d %d\n" , i , j);
       a[o].x = i;
       a[o].y = j;
       o++;
    }
  printf("%ld\n" , cost);
}



int main()
{
  freopen("kruskal.in" , "r" , stdin);
  freopen("kruskal.out" , "w" , stdout);
    scanf("%d %d" , &n , &m);
     for(long i = 1 ; i <= m ; i++)
       scanf("%d %d %d" , &e[i].x , &e[i].y , &e[i].c);
    kruskal();
  printf("%ld\n" , o-1);
   for(i = 1 ; i < o ; i++)
     printf("%ld %ld\n" , a[i].x , a[i].y);
return 0;
}