Pagini recente » Cod sursa (job #1371275) | Cod sursa (job #1874799)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int NMAX = 50000 + 5;
const int MMAX = 5 * NMAX;
const int INF = 1000000000 + 15;
int N, M;
vector <pair <int, int> > graph[NMAX];
bool vis[NMAX];
int dist[NMAX];
struct Elem {
int d;
int node;
Elem(int _d = 0, int _node = 0) {
d = _d;
node = _node;
}
bool operator<(const Elem &arg) const {
return d > arg.d;
}
};
priority_queue <Elem> q;
void dijkstra(int s) {
for (int i = 1; i <= N; ++ i)
dist[i] = INF;
dist[s] = 0;
q.push(Elem(0, s));
while (!q.empty()) {
int node = q.top().node;
q.pop();
if (vis[node]) //Lazy deletion
continue;
vis[node] = true;
for (int i = 0; i < graph[node].size(); ++ i)
if (dist[node] + graph[node][i].second < dist[graph[node][i].first]) {
dist[graph[node][i].first] = dist[node] + graph[node][i].second;
q.push(Elem(dist[graph[node][i].first], graph[node][i].first));
}
}
}
int main()
{
ifstream cin("djkstra.in");
ofstream cout("dijkstra.out");
cin >> N >> M;
for (int i = 1; i <= M; ++ i) {
int a, b, c;
cin >> a >> b >> c;
graph[a].push_back(make_pair(b, c));
graph[b].push_back(make_pair(a, c));
}
dijkstra(1);
for (int i = 1; i <= N; ++ i)
if (!vis[i])
dist[i] = 0; //Why not?
if (N > 1) {
cout << dist[2];
for (int i = 3; i <= N; ++ i)
cout << ' ' << dist[i];
}
cout << '\n';
return 0;
}