Pagini recente » Cod sursa (job #2876555) | Cod sursa (job #3126702) | Cod sursa (job #2363258) | Cod sursa (job #1167159) | Cod sursa (job #2858826)
#include <algorithm>
#include <cstring>
#include <fstream>
#include <cassert>
#include <vector>
#include <set>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int MAX_SIZE = 50005;
const int MAX_SUM = 1000005;
vector<pair<int, int>> graph[MAX_SIZE];
int costs[MAX_SIZE];
int main() {
int peaks, arches;
fin >> peaks >> arches;
for (int i = 1; i <= arches; ++i) {
int start, end, cost;
fin >> start >> end >> cost;
graph[start].push_back(make_pair(end, cost));
}
memset(costs, MAX_SUM, sizeof costs);
set<pair<int, int>> positions;
positions.insert(0, 1);
while (!positions.empty()) {
int currentPeak = positions.begin()->second;
positions.erase(positions.begin());
for (pair<int,int> element : graph[currentPeak]) {
int nextPeak = element.first;
int nextCost = element.second;
if (costs[nextPeak] > costs[currentPeak] + nextCost) {
if (costs[nextPeak] != MAX_SUM) {
positions.erase(positions.find(make_pair(costs[nextPeak], nextPeak)));
}
costs[nextPeak] = costs[currentPeak] + nextCost;
positions.insert(make_pair(costs[nextPeak], nextPeak));
}
}
}
for (int i = 2; i <= peaks; ++i) {
if (costs[i] == MAX_SUM) {
costs[i] = 0;
}
fout << costs[i] << " ";
}
}
/*
#include <algorithm>
#include <iostream>
#include <cstring>
#include <fstream>
#include <cassert>
#include <vector>
#include <set>
using namespace std;
const int NMAX = 50005;
const int INF = 0x3f3f3f3f;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
vector<pair<int, int>> graph[NMAX];
int dist[NMAX];
int main() {
int n, m;
fin >> n >> m;
for (int i = 0; i < m; ++i) {
int start, end, cost;
fin >> start >> end >> cost;
graph[start].push_back(make_pair(end, cost));
}
memset(dist, INF, sizeof dist);
dist[1] = 0;
set<pair<int, int>> h;
h.insert(make_pair(0, 1));
while (!h.empty()) {
int node = h.begin()->second;
h.erase(h.begin());
for (pair<int, int> next : graph[node]) {
int to = next.first;
int cost = next.second;
if (dist[to] > dist[node] + cost) {
if (dist[to] != INF) {
h.erase(h.find(make_pair(dist[to], to)));
}
dist[to] = dist[node] + cost;
h.insert(make_pair(dist[to], to));
}
}
}
for (int i = 2; i <= n; ++i) {
if (dist[i] == INF) {
dist[i] = 0;
}
fout << dist[i] << ' ';
}
*/