Pagini recente » Cod sursa (job #943120) | Cod sursa (job #332256) | Cod sursa (job #692513) | Cod sursa (job #2404329) | Cod sursa (job #1148921)
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int INF = 0x3f3f3f3f;
int N, M;
int Dmin[50002];
vector<pair<int, int> > V[50002];
queue<int> Q;
bool inqueue[50002];
void bellman_ford(int nod)
{
memset(Dmin, INF, sizeof(Dmin));
Dmin[1] = 0;
Q.push(nod);
inqueue[nod] = true;
while (!Q.empty())
{
int now = Q.front();
Q.pop();
inqueue[now] = false;
for (vector<pair<int, int> >::iterator it = V[now].begin(); it != V[now].end(); ++it)
{
if (Dmin[now] + it->second < Dmin[it->first])
{
Dmin[it->first] = Dmin[now] + it->second;
if (!inqueue[it->first])
{
Q.push(it->first);
inqueue[it->first] = true;
}
}
}
}
}
int main()
{
fin >> N >> M;
for (int i = 1, nod1, nod2, cost; i <= M; ++i)
{
fin >> nod1 >> nod2 >> cost;
V[nod1].push_back(make_pair(nod2, cost));
V[nod2].push_back(make_pair(nod1, cost));
}
bellman_ford(1);
for (int i = 2; i <= N; ++i)
{
if (Dmin[i] == INF)
fout << "0 ";
else
fout << Dmin[i] << ' ';
}
fout << '\n';
fin.close();
fout.close();
return 0;
}