Pagini recente » Cod sursa (job #1383318) | Cod sursa (job #22091) | Cod sursa (job #2071727) | Cod sursa (job #972330) | Cod sursa (job #1134229)
#include <iostream>
#include <fstream>
#include <list>
#include <stdio.h>
#include <queue>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
struct item
{
int val,to;
};
typedef list<item> INT_LIST;
typedef list<int> NODES_LIST;
typedef list<item>::iterator iter;
void print(NODES_LIST &nodes)
{
for(list<int>::iterator it=nodes.begin();it!=nodes.end();it++)
cout<<(*it)<<" ";
cout<<endl;
}
void dijkstra(INT_LIST *a, int *b, int n, NODES_LIST &nodes)
{
while(!nodes.empty())
{
NODES_LIST tmp;
int curr = nodes.back();
//print(nodes);
//cout<<"-> "<<curr<<endl;
for(iter it=a[curr].begin();it!=a[curr].end();it++)
{
int to = (*it).to;
int val = (*it).val;
//cout<<from<<" -> "<<to<<" : "<<val<<endl;
if(b[curr]+val < b[to])
{
b[to] = b[curr]+val;
nodes.push_front(to);
}
}
nodes.pop_back();
}
}
int main()
{
// Initialization
int n,m;
fin>>n>>m;
INT_LIST *a = new INT_LIST[n+2];
int *b = new int[n+2];
fill(b,b+n+2,99999);
NODES_LIST nodes;
for(int i=1;i<=m;i++)
{
int from,to,val;
fin>>from>>to>>val;
item curr;
curr.to = to;
curr.val = val;
a[from].push_front(curr);
curr.to = from;
a[to].push_front(curr);
}
nodes.push_back(1);
b[1] = 0;
dijkstra(a,b,n,nodes);
for(int i=2;i<=n;i++) fout<<b[i]<<" ";
}