Pagini recente » Cod sursa (job #2179991) | Cod sursa (job #85849) | Cod sursa (job #779891) | Cod sursa (job #2108071) | Cod sursa (job #2271120)
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <vector>
#define min(a, b) (a<b?a:b)
#define MaxN 50005
#define Inf 1<<30
using namespace std;
int MinD[MaxN], N, M, i;
bool Use[MaxN];
struct Pair{
int Node;
int Cost;
};
Pair *A[MaxN];
struct comp{
bool operator()(int x, int y){
return MinD[x]>MinD[y];
}
};
priority_queue<int, vector<int>, comp> Q;
void Read();
void Dijkstra();
void Write();
int main()
{
freopen("dijkstra.in", "r", stdin);
freopen("dijkstra.out", "w", stdout);
Read();
Dijkstra();
Write();
return 0;
}
void Dijkstra(){
size_t i;
for(i=1; i<=N; ++i)MinD[i]=Inf;
MinD[1]=0;
Q.push(1);
Use[1]=true;
while(!Q.empty()){
int a=Q.top();
Use[a]=false;
Q.pop();
for(i=1; i<=A[a][0].Node; ++i){
int b=A[a][i].Node;
int C=A[a][i].Cost;
if(MinD[a]+C<MinD[b]){
MinD[b]=MinD[a]+C;
if(Use[b]==false){
Use[b]=true;
Q.push(b);
}
}
}
}
return;
}
void Read(){
scanf("%d%d", &N, &M);
for(i=1; i<=N; ++i){
A[i]=(Pair *)realloc(A[i], sizeof(Pair));
A[i][0].Node=A[i][0].Cost=0;
}
for(i=1; i<=M; ++i){
int x, y, z;
scanf("%d%d%d", &x, &y, &z);
++A[x][0].Node; ++A[x][0].Cost;
A[x]=(Pair *)realloc(A[x], (A[x][0].Node+1)*sizeof(Pair));
A[x][A[x][0].Node].Node=y;
A[x][A[x][0].Cost].Cost=z;
}
return;
}
void Write(){
int i;
for(i=2; i<=N; ++i){
if(MinD[i]==Inf)printf("0 ");
else printf("%d ", MinD[i]);
}
return;
}