Pagini recente » Cod sursa (job #1798733) | Cod sursa (job #2160345) | Cod sursa (job #659152) | Cod sursa (job #2448307) | Cod sursa (job #807334)
Cod sursa(job #807334)
#include <fstream>
#include <vector>
#include <set>
#define INF 2000000000
using namespace std;
int n, m;
struct NOD
{
int x, cost;
};
bool operator<(const NOD& A, const NOD& B)
{
return A.cost < B.cost ;
}
set <NOD> S;
vector <NOD> a[50005];
int d[50005];
bool v[50005];
inline void Read()
{
ifstream f("dijkstra.in");
f>>n>>m;
int i, x, y, cost;
NOD aux;
for(i=1; i<=m; i++)
{
f>>x>>y>>cost;
aux.x = y;
aux.cost = cost;
a[x].push_back(aux);
}
f.close();
}
inline void Dijkstra()
{
int i;
for(i=1; i<=n; i++)
{
d[i] = INF;
}
d[1] = 0;
int minim, x, y, cost, k;
bool stop = false;
vector <NOD>::iterator it, final;
NOD aux;
aux.x = 1;
aux.cost = 0;
S.insert(aux);
set<NOD>::iterator gica;
for (int pas = 1; pas<n && !stop; pas++)
{
if (S.empty())
{
stop = true;
}
else
{
gica = S.begin();
aux = *gica;
k = aux.x;
cost = aux.cost;
S.erase(aux);
//v[k] = true;
it = a[k].begin();
final = a[k].end();
for(; it!=final; it++)
{
// parcurg toti adiacentii lui k, pentru care am gasit distanta minima, si ii actualizez si pe ei
aux = *it;
x = aux.x;
cost = aux.cost;
if (d[x] > d[k] + cost)
{
d[x] = d[k] + cost;
//S.erase(aux);
aux.x = x;
aux.cost = d[x];
S.insert(aux);
}
}
}
}
}
inline void Write()
{
int i;
ofstream g("dijkstra.out");
for(i = 2; i<=n; i++)
{
if (d[i] < INF)
{
g<<d[i]<<" ";
}
else
{
g<<"0 ";
}
}
g<<"\n";
g.close();
}
int main()
{
Read();
Dijkstra();
Write();
return 0;
}