Pagini recente » Monitorul de evaluare | Cod sursa (job #1700640) | Cod sursa (job #1293613) | Cod sursa (job #3224775) | Cod sursa (job #807387)
Cod sursa(job #807387)
#include <fstream>
#include <vector>
#include <set>
#define INF 2000000000
using namespace std;
int n, m;
struct NOD
{
int x, cost;
};
vector <NOD> a[50005];
set<pair<int, int> > S;
int d[50005];
bool v[50005];
inline void Read()
{
ifstream f("dijkstra.in");
f>>n>>m;
int i, x, y, cost, j;
char c[100];
NOD aux;
f.get();
for(i=1; i<=m; i++)
{
f.getline(c, 100);
x = y = cost = 0;
j = 0;
while (c[j]!=' ')
{
x = x*10 + (c[j] - '0');
j++;
}
j++;
while (c[j]!=' ')
{
y = y*10 + (c[j] - '0');
j++;
}
j++;
while (c[j])
{
cost = cost*10 + (c[j] - '0');
j++;
}
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;
pair <int, int> pereche;
pereche.first = 0;
pereche.second = 1;
S.insert(pereche);
set<pair<int, int> >::iterator itp;
vector <NOD>::iterator it, final;
NOD aux;
for (int pas = 1; pas<n && !stop; pas++)
{
itp = S.begin();
pereche = *itp;
k = pereche.second;
if (S.empty())
{
stop = true;
}
else
{
S.erase(pereche);
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)
{
pereche.first = d[x];
pereche.second = x;
S.erase(pereche);
d[x] = d[k] + cost;
pereche.first = d[x];
pereche.second = x;
S.insert(pereche);
}
}
}
}
}
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;
}