Cod sursa(job #392986)

Utilizator ErgoVicol Sergiu Constantin Ergo Data 8 februarie 2010 18:16:53
Problema Pitici Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.92 kb
#include <fstream>
#include <vector>
#include <algorithm>

#define NMAX 1024
#define KMAX 1024
#define pb push_back
#define INF 1000000000

using namespace std;

int drum[NMAX][KMAX], N, M, K, Sortate[NMAX], Viz[NMAX], nrSort, heapLen;

struct nod{ int next, cost; };

vector<nod> Gr[NMAX];
nod Heap[KMAX];


void Citire(void)
{
	ifstream fin("pitici.in");
	
	int i, x; 
	nod a;
	
	fin >>N >>M >>K;
	
	for (i = 1; i <= M; i++)
	{
		fin >>x >>a.next >>a.cost;
		
		Gr[x].pb(a);
	}
	
	fin.close();
}

void DFS(int x)
{
	int i;
	
	for (i = 0; i < Gr[x].size(); i++)
		if (!Viz[Gr[x][i].next])
			DFS(Gr[x][i].next), Viz[Gr[x][i].next] = 1;
	
	Sortate[++nrSort] = x;
}

void SortareTopologica(void)
{
	int i;
	
	for (i = 1; i <= N; i++)
		if (!Viz[i])
			DFS(i), Viz[i] = 1;
}

int Ordine(nod a, nod b)
{
	if (a.cost < b.cost) return 0;
	else return 1;
}

void Rezolva(void)
{
	SortareTopologica();
	
	int i, nodCur, ChNod, j;
	
	for (i = 1; i <= N; i++)
	{
		nodCur = Sortate[i];
		heapLen = 0;
		
		for (j = 0; j < Gr[nodCur].size(); j++)
			Heap[++heapLen].cost = drum[Gr[nodCur][j].next][1] + Gr[nodCur][j].cost,
			Heap[heapLen].next = j,
			Viz[Gr[nodCur][j].next] = 1;
		
		make_heap(Heap+1, Heap+heapLen+1, Ordine);
		
		for (j = 1; j <= K && !Gr[nodCur].empty(); j++)
		{
			drum[nodCur][j] = Heap[1].cost;
			ChNod = Heap[1].next;
			
			swap(Heap[1], Heap[heapLen]);
			
			Heap[heapLen].cost = drum[Gr[nodCur][ChNod].next][++Viz[Gr[nodCur][ChNod].next]] + Gr[nodCur][ChNod].cost;
			
			push_heap(Heap+1, Heap+heapLen+1, Ordine);			
		}
		for (j = 2; j <= K && Gr[nodCur].empty(); j++)
			drum[nodCur][j] = INF;
	}
}

void Afiseaza(void)
{
	ofstream fout("pitici.out");
	
	int i;
	
	for (i = 1; i <= K; i++)
		fout <<drum[Sortate[N]][i] <<' ';
	
	fout.close();
}

int main()
{
	Citire();
	
	Rezolva();
	
	Afiseaza();
	
	return 0;
	
}