Cod sursa(job #672795)

Utilizator mateiuliIulian mateiuli Data 3 februarie 2012 09:44:05
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 kb
#include <iostream.h>
#include <fstream.h>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int m,a[100][100],n,c[100],s[100],cost;
const float Pinfinit=1.e20;
struct nod
	{
		int x,y,c;
	};
	nod g[100];
void cit()
{
	int i,j,o;
	fin>>n>>m;
	for(i=1;i<=m;i++)
		fin>>g[i].x>>g[i].y>>g[i].c;
	for(i=1;i<=n;i++)
		c[i]=i;
}
void sortareMuchii(int st, int dr)
{
	int i,j;
	nod e;
	if(st<dr)
	{
		e=g[st];
		i=st;
		j=dr;
		while(i<j)
		{
			while(i<j && g[j].c>=e.c)
				j--;
			g[i]=g[j];
			while(i<j && g[i].c<=e.c)
				i++;
			g[j]=g[i];
		}
		g[i]=e;
		sortareMuchii(st,i-1);
		sortareMuchii(i+1,dr);
	}
}
void afisare()
{
	int i;
	fout<<cost<<'\n';
	fout<<n-1<<'\n';
	for(i=1;i<n;i++)
		fout<<a[i][1]<<" "<<a[i][2]<<" "<<a[i][3]<<'\n';
}
void kruskal2()
{
	int i,j,k=0;
/*	s[g[1].x]=1;
	s[g[1].y]=1;
	a[1][1]=g[1].x;
	a[1][2]=g[1].y;
	a[1][3]=g[1].c;
	cost=g[1].c;
	*/for(i=1;i<=m;i++)
		if(s[g[i].x]==0 && s[g[i].y]==1)
		{
			s[g[i].x]=1;
			cost=cost+g[i].c;
			k++;
			a[k][1]=g[i].x;
			a[k][2]=g[i].y;
			a[k][3]=g[i].c;
		}
		else
			if(s[g[i].x]==1 && s[g[i].y]==0)
			{
				s[g[i].y]=1;
				cost=cost+g[i].c;
				k++;
				a[k][1]=g[i].y;
				a[k][2]=g[i].x;
				a[k][3]=g[i].c;
			}
			else
				if(s[g[i].x]==0 && s[g[i].y]==0)
				{
					s[g[i].x]=1;
					s[g[i].y]=1;
					cost=cost+g[i].c;
					k++;
					a[k][1]=g[i].x;
					a[k][2]=g[i].y;
					a[k][3]=g[i].c;
				}
}
	
int main()
{
	cit();
	sortareMuchii(1,m);
	kruskal2();
	afisare();
	return 0;
}

/*
void kruskal()
{
	int i,nrmsel=0,min,max,j;
	for(i=1;nrmsel<n-1;i++)
		if(c[g[i].x]!=c[g[i].y])//muchia i nu formeaza cicluri deja selectate
		{
		//	nrmsel++;
		//	a[++nrmsel]=i;//selectez muchia i
			if(c[g[i].x]<c[g[i].y])//unfic componentele conexe ale extremitatilor
			{
				min=c[g[i].x];
				max=c[g[i].y];
			}
			else
			{
				min=c[g[i].y];
				max=c[g[i].x];
			}
			for(j=1;j=n;j++)
				if(c[j]==max)
					c[j]=min;
		}
}*/