Pagini recente » Cod sursa (job #2517834) | Cod sursa (job #2460010) | Cod sursa (job #1970936) | Cod sursa (job #1140097) | Cod sursa (job #2111395)
#include<fstream>
#include<list>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
struct graph{
int nod, cost;
};
const int Nmax = 50005;
const int inf = (1<<31) - 1;
list<graph>l[Nmax];
list<graph>::iterator it;
int n, m, v[Nmax], t[Nmax], mini, nod_curent;
bool viz[Nmax];
void read(){
f >> n >> m;
int from, to, cost;
while(f >> from >> to >> cost)
l[from].push_back({to, cost});
}
void dijkstra(){
viz[1] = true;
t[1] = 0;
for(it = l[1].begin(); it != l[1].end(); it++)
v[it->nod] = it->cost;
for(int k = 1; k <= n; k++)
if(v[k] == 0)
v[k] = inf;
for(int i = 2; i <= n - 2; i++){
mini = inf;
for(int k = 1; k <= n; k++)
if(v[k] < mini and !viz[k]){
mini = v[k];
nod_curent = k;
}
viz[nod_curent] = true;
for(it = l[nod_curent].begin(); it != l[nod_curent].end(); it++)
if(!viz[it->nod])
if(v[it->nod] > v[nod_curent] + it->cost){
v[it->nod] = v[nod_curent] + it->cost;
t[it->nod] = nod_curent;
}
}
}
void write(){
for(int i = 2; i <= n ; i++)
if(v[i] == inf)
g << 0 << ' ';
else
g << v[i] << ' ';
}
int main(){
read();
dijkstra();
write();
}