Cod sursa(job #1351)

Utilizator pantaniMarco Pantani pantani Data 13 decembrie 2006 13:31:42
Problema PScNv Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.14 kb
#include <cstdio>
#include <algorithm>
#include <string.h>
#include <stdlib.h>

using namespace std;

#define sz(a) a.size()
#define sch(x, y) x ^= y ^= x ^= y
#define Max(x, y) x > y ? x : y

#define Nmax 250005
#define Mmax 500005

int n, start, stop, heap[Nmax], poz[Nmax], el[Nmax], viz[Nmax], lung, last[Nmax];
int m2[Mmax], m3[Mmax], par[Mmax];

void readdata()
{
	freopen("pscnv.in", "r", stdin);
	freopen("pscnv.out", "w", stdout);
	
	int m, i, a, b, cost, poz;
	char s[15];
	
	scanf("%d %d %d %d\n", &n, &m, &start, &stop);
	
	for (i = 1; i <= m; ++i)
	{
		gets(s);
		lung = strlen(s);
		scanf("\n");
		a = 0; b = 0; cost = 0;
		poz = 0;
		while (s[poz] != ' ')
			a = a*10+s[poz++]-'0';
		++poz;
		while (s[poz] != ' ')
			b = b*10+s[poz++]-'0';
		poz++;
		while (poz < lung)
			cost = cost*10+s[poz++]-'0';
			
		m2[i] = b; m3[i] = cost;
		par[i] = last[a];
		last[a] = i;
	}
}

void recon(int k)
{
	int max = k, p = 2*k;
	
	if (p <= lung)
	if (heap[p] < heap[max]) max = p;
	
	++p;
	if (p <= lung)
	if (heap[p] < heap[max]) max = p;	
	
	if (max > k)
	{
		sch(heap[max], heap[k]);
		sch(el[max], el[k]);
		poz[el[max]] = max; poz[el[k]] = k;
		recon(max);
	}
}

void scoate()
{
	heap[1] = heap[lung];
	el[1] = el[lung];
	poz[el[1]] = 1;
	--lung;
	recon(1);
}

void recon2(int k)
{
	if (k < 2) return;
	
	int max = k/2;
	if (heap[max] > heap[k])
	{
		sch(heap[max], heap[k]);
		sch(el[max], el[k]);
		poz[el[k]] = k; poz[el[max]] = max;
		recon2(max);
	}
}

void solve()
{
	int i, nod, lim, d;
	
	lung = 1;
	heap[lung] = 0;
	el[lung] = start;
	poz[start] = 1;
	while (!viz[stop])
	{
		nod = el[1];
		d = heap[1];
		scoate();
		viz[nod] = 1;
		
		for (i = last[nod]; i; i = par[i])
		if (!viz[m2[i]])
			if (poz[m2[i]] == 0)
			{
				heap[++lung] = max(d, m3[i]);
				el[lung] = m2[i];
				poz[el[lung]] = lung;
				recon2(lung);
			}
			else
			{
				if (Max(d, m3[i]) < heap[poz[m2[i]]])
				{
					heap[poz[m2[i]]] = Max(d, m3[i]);
					recon2(poz[m2[i]]);
				}
			}
	}
	printf("%d\n", d);
}

int main()
{
	readdata();
	solve();
	return 0;
}