Cod sursa(job #760413)

Utilizator scipianusFMI Ciprian Olariu scipianus Data 21 iunie 2012 11:49:38
Problema Lazy Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.54 kb
#include<fstream>
#include<cmath>
#include<algorithm>
#include<vector>
#include<cstring>
using namespace std;
int n,m;
int c[200100],h[200100];
int X[200100],Y[200100],Ind[200100];
long long Cost[200100],Profit[200100];

void Citire()
{
	int i,poz,ns,aux;
	long long aux2;
	char s[50];
	ifstream fin("lazy.in");
	fin>>n>>m;
	fin.getline(s,2);
	for(i=1;i<=m;i++)
	{
		//fin>>X[i]>>Y[i]>>Cost[i]>>Profit[i];
		fin.getline(s,50);
		ns=strlen(s);
		poz=0;
		aux=0;
		while(s[poz]!=' ')
			aux=aux*10+s[poz++]-'0';
		X[i]=aux;
		aux=0;
		poz++;
		while(s[poz]!=' ')
			aux=aux*10+s[poz++]-'0';
		Y[i]=aux;
		aux2=0;
		poz++;
		while(s[poz]!=' ')
			aux2=aux2*10+s[poz++]-'0';
		Cost[i]=aux2;
		aux2=0;
		poz++;
		while(s[poz]!=' ')
			aux2=aux2*10+s[poz++]-'0';
		Profit[i]=aux2;
		Ind[i]=i;
	}
	fin.close();
}

inline bool Sortare(int A,int B)
{
	if(Cost[A]==Cost[B])
		return Profit[A]>Profit[B];
	return Cost[A]<Cost[B];
}

inline int Find(int x)
{
	int r=x;
	while(c[r])
		r=c[r];
	int y=x,aux;
	while(y!=r)
	{
		aux=c[y];
		c[y]=r;
		y=aux;
	}
	return r;
}

inline void Union(int x,int y)
{
	if(h[x]>h[y])
		c[y]=x;
	else
	{
		c[x]=y;
		if(h[x]==h[y])
			h[y]++;
	}
}

void Kruskal()
{
	int i=1,A,B,nr=1;
	ofstream fout("lazy.out");
	sort(Ind+1,Ind+m+1,Sortare);
	while(nr<n)
	{
		A=Find(X[Ind[i]]);
		B=Find(Y[Ind[i]]);
		
		if(A!=B)
		{
			Union(A,B);
			fout<<Ind[i]<<"\n";
			nr++;
		}
		i++;
	}
	fout.close();
}

int main()
{
	Citire();
	Kruskal();
	return 0;
}