Pagini recente » Cod sursa (job #1858975) | Cod sursa (job #252814) | Cod sursa (job #3290692) | Cod sursa (job #715430) | Cod sursa (job #1134253)
#include <iostream>
#include <fstream>
#include <list>
#include <sstream>
#include <string>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int n,i,k,j;
struct edge
{
int node,val;
};
struct t
{
int parent,dist;
t():dist(99999){}
}dist[50005];
typedef list<int>::iterator iter;
typedef list<int> LST;
list<edge> a[50005];
LST active;
iter find_min(LST &active,t *b)
{
int minn=9999999;
int mini=0;
int i=0;
iter res;
for(iter it = active.begin();it!=active.end();it++)
{
i++;
int node = (*it);
if (b[node].dist<minn)
{
minn = node;
mini = i;
}
}
res = active.begin();
advance(res,mini-1);
return res;
}
void dijkstra(int s)
{
//cout<<active.back()<<endl;
while(!active.empty())
{
iter node = find_min(active,dist);
int curr_node = (*node);
//cout<<curr_node<<endl;
//print_list(curr_node);
for(list<edge>::iterator it=a[curr_node].begin();it!=a[curr_node].end();it++)
{
int val = (*it).val;
int node = (*it).node;
//cout<<val<<endl;
if(dist[node].dist > dist[curr_node].dist + val)
{
dist[node].dist = dist[curr_node].dist + val;
dist[node].parent = curr_node;
active.push_front(node);
}
}
active.erase(node);
}
}
void read_edge()
{
int m,z,x,c;
fin>>n>>m;
for(int i=1;i<=m;i++)
{
fin>>z>>x>>c;
edge curr = {x,c};
a[z].push_back(curr);
}
}
int main()
{
read_edge();
/// INIT
dist[1].dist = 0;
active.push_front(1);
dijkstra(1);
for(int i=2;i<=n;i++)
{
if(dist[i].dist == 99999)
fout<<"0 ";
else
fout<<dist[i].dist<<" ";
}
}