Cod sursa(job #556957)

Utilizator alexandru93moraru alexandru sebastian alexandru93 Data 16 martie 2011 13:23:40
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include<fstream>
#include<algorithm>
#include<queue>
#include<vector>
#define maxn 50010
using namespace std;
const int nmax=1000000;
vector< pair<int,int> > e[maxn];
bool test[maxn];
queue<int> Q;
int N,M;
long d[maxn];
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

void bellman(int S){
	for(int i=1;i<=N;i++)
		d[i]=nmax;
	memset(test,false,nmax);
	d[S]=0;
	test[S]=true;
	Q.push(S);
	while(!Q.empty()){
		int nod=Q.front();
		Q.pop();
		test[nod]=false;
		for(vector< pair<int,int> >::iterator it=e[nod].begin();it!=e[nod].end();++it){
			if(d[it->first]>d[nod]+it->second){
				d[it->first]=d[nod]+it->second;
				if(!test[it->first])
					Q.push(it->first),test[it->first]=true;
			}
			if(d[nod]>d[it->first]+it->second){
				d[nod]=d[it->first]+it->second;
				if(!test[nod])
					Q.push(nod),test[nod]=true;
			}
		}
	}
}
			
void citire(){
	int x,y,c;
	f>>N>>M;
	for(int i=1;i<=M;i++){
		f>>x>>y>>c;
		e[x].push_back(make_pair(y,c)),e[y].push_back(make_pair(x,c));
	}
}

int main(){
	citire();
	bellman(1);
	for(int i=2;i<=N;i++)
		g<<d[i]<<' ';
	g<<'\n';
	g.close();
	return 0;
}