Cod sursa(job #541737)

Utilizator robigiirimias robert robigi Data 25 februarie 2011 13:47:07
Problema Lazy Scor 10
Compilator cpp Status done
Runda Romanian Master in Mathematics and Sciences 2011, Ziua 1 Marime 2.4 kb
#include "stdio.h"

FILE *f=fopen("lazy.in", "r");
FILE *g=fopen("lazy.out", "w");


typedef struct nod
{
	int x, pozi;
	long long c;
	struct nod*adr;
};

nod *l[200001];

int n, m, nr, nnr;
long long heap[200001];
int poz[200001], vpoz[200001], viz[200001];
int muchii[200001], dl[200001];
int md;
long long sum;


void add(int x, int y, int c, int pozi)
{
	nod *p=new nod;
	p->x=y;
	p->pozi=pozi;
	p->c=c;
	p->adr=l[x];
	l[x]=p;
}


void read()
{
	fscanf(f, "%d%d", &n, &m);
	for (int i=1; i<=m; ++i)
	{
		int x, y;
		long long c, c2;
		fscanf(f, "%d%d%lld%lld", &x, &y, &c, &c2);
		add(x, y, c, i);
		add(y, x, c, i);
	}
}



void upheap(int x)
{
	int fiu=x;
	int tata=x/2;
	while (fiu>1 && heap[tata]>heap[fiu])
	{
		int h=heap[tata]; heap[tata]=heap[fiu]; heap[fiu]=h;
		h=poz[tata]; poz[tata]=poz[fiu]; poz[fiu]=h;
		h=muchii[tata]; muchii[tata]=muchii[fiu]; muchii[fiu]=h;
		vpoz[poz[tata]]=tata;
		vpoz[poz[fiu]]=fiu;
		fiu=tata;
		tata=fiu/2;
	}
}


void inheap(int c, int x, int mm)
{
	++nnr;
	heap[nnr]=c;
	poz[nnr]=x;
	muchii[nnr]=mm;
	vpoz[x]=nnr;
	upheap(nnr);
}


void inapm(int x)
{
	viz[x]=1;
	nod *p=l[x];
	while (p!=NULL)
	{
		if (!viz[p->x])
		{
			if (heap[vpoz[p->x]]>p->c)
			{
				heap[vpoz[p->x]]=p->c;
				muchii[vpoz[p->x]]=p->pozi;
				upheap(vpoz[p->x]);
			}
		}
		p=p->adr;
	}	
}



void initial()
{
	for (int i=2; i<=n; ++i)
		inheap(10000000, i, 1);
	inapm(1);
}


void downheap(int x)
{
	int tata=x;
	int fiu=tata*2;
	if (fiu+1<n-nr && heap[fiu]>heap[fiu+1])
		++fiu;
	while (heap[tata]>heap[fiu] && fiu<n-nr)
	{
		int h=heap[tata]; heap[tata]=heap[fiu]; heap[fiu]=h;
		h=poz[tata]; poz[tata]=poz[fiu]; poz[fiu]=h;
		h=muchii[tata]; muchii[tata]=muchii[fiu]; muchii[fiu]=h;
		vpoz[poz[tata]]=tata;
		vpoz[poz[fiu]]=fiu;
		tata=fiu;
		fiu=tata*2;
		if (fiu+1<n-nr && heap[fiu]>heap[fiu+1])
			++fiu;
	}
}


int extragemin(int &aux)
{
	dl[++md]=muchii[1];
	muchii[1]=muchii[n-nr];
	aux=poz[1];
	int cv=heap[1];
	heap[1]=heap[n-nr];
	poz[1]=poz[n-nr];
	vpoz[poz[1]]=1;
	poz[n-nr]=0;
	heap[n-nr]=0;
	downheap(1);
	return cv;
}



void program()
{
	for (int i=1; i<n; ++i)
	{
		int aux;
		++nr;
		sum+=extragemin(aux);
		inapm(aux);
	}
	for (int j=1; j<=md; ++j)
	{
		fprintf(g, "%d\n", dl[j]);
	}
}


int main()
{
	read();
	initial();
	program();
	return 0;
}