Pagini recente » Cod sursa (job #1978432) | Cod sursa (job #762260) | Cod sursa (job #3189631) | Cod sursa (job #2224616) | Cod sursa (job #3286050)
#include <fstream>
#include <vector>
#include <queue>
#define nmax 101
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
const int oo = (1 << 30);
int n, m, d[nmax];
bool inQueue[nmax];
vector<pair<int, int>> g[nmax];
struct cmp
{
bool operator() (int x, int y)
{
return d[x] > d[y];
}
};
priority_queue<int, vector<int>, cmp> q;
void citire()
{
in >> n >> m;
int x, y, c;
for (int i = 1; i <= m; i++)
{
in >> x >> y >> c;
g[x].push_back(make_pair(y, c));
}
in.close();
}
void afisare()
{
for (int i = 2; i <= n; i++)
if (d[i] != oo)
out << d[i] << ' ';
else
out << "0 ";
out.close();
}
void dijkstra(int nodStart)
{
for (int i = 1; i <= n; i++)
d[i] = oo;
d[nodStart] = 0;
q.push(nodStart);
inQueue[nodStart] = true;
while (!q.empty())
{
int nodCurent = q.top();
q.pop();
inQueue[nodCurent] = false;
for (size_t i = 0; i < g[nodCurent].size(); i++)
{
int vecin = g[nodCurent][i].first;
int cost = g[nodCurent][i].second;
if (d[nodCurent] + cost < d[vecin])
{
d[vecin] = d[nodCurent] + cost;
if (inQueue[vecin] == false)
{
q.push(vecin);
inQueue[vecin] = true;
}
}
}
}
}
int main()
{
citire();
dijkstra(1);
afisare();
return 0;
}