Cod sursa(job #1502014)

Utilizator tain1234andrei laur tain1234 Data 14 octombrie 2015 02:42:03
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <vector>
#include <bitset>
using namespace std;
int H[50001], c[50001], P[50001], N, cnt = 0, M, par[50001], cost = 0;
bitset<50001> v;
const int inf = (1 << 30);
struct nod
{
	nod * next;
	int first;
	int second;
};
nod* No[50001];
void per(int k){
	if (k > 1){
		int f = k >> 1;
		if (c[H[f]] > c[H[k]]){
			swap(H[k], H[f]);
			swap(P[H[k]], P[H[f]]);
			per(f);
		}
	}
}
void sift(int poz)
{
	int f;
	if (poz <= cnt / 2){
		if (poz * 2 + 1 <= cnt)
		if (c[H[poz * 2]] < c[H[poz * 2 + 1]])
			f = 2 * poz;
		else f = 2 * poz + 1;
		else f = 2 * poz;
		if (c[H[poz]]>c[H[f]]){
			swap(H[poz], H[f]);
			swap(P[H[poz]], P[H[f]]);
			sift(f);
		}
	}
}

void add(int x){
	H[++cnt] = x;
	P[x] = cnt;
	per(cnt);
}
int rad(){
	int x = H[1];
	swap(H[1], H[cnt]);
	swap(P[H[1]], P[H[cnt]]);
	--cnt;
	sift(1);
	return x;
}
int main(){
	freopen("dijkstra.in", "r", stdin);
	freopen("dijkstra.out", "w", stdout);
	scanf("%d%d", &N, &M);
	for (int i = 2; i <= N; ++i){
		c[i] = inf;
	}
	c[1] = 0;
	for (int i = 1; i <= M; ++i){
		int a, b, d;
		scanf("%d%d%d", &a, &b, &d);
		nod* n = new nod;
		n->first = b;
		n->second = d;
		n->next = No[a];
		No[a] = n;;
	}
	add(1);
	while (cnt != 0){
		int x = rad();
		for (nod*i = No[x]; i != 0; i = i->next){
			if (!v[i->first] || i->second+c[x] < c[i->first]){
				c[i->first] =c[x]+ i->second;
				v[i->first] = 1;
				if (!P[i->first])add(i->first);
				else per(P[i->first]);
			}
		}
	}
	for (int i = 2; i <= N; ++i){
		if (c[i] == inf)printf("%d ", 0);
		else
		printf("%d ", c[i]);
	}
}