Pagini recente » Cod sursa (job #2586076) | Cod sursa (job #3179764) | Cod sursa (job #3126114) | Cod sursa (job #2317548) | Cod sursa (job #2750197)
#include <bits/stdc++.h>
using namespace std;
const int kNmax = 100005;
class Task {
public:
void solve() {
read_input();
print_output(get_result());
}
private:
int n;
int m;
vector<pair<int, int>> adj[kNmax];
int source;
void read_input() {
ifstream fin("dijkstra.in");
fin >> n >> m;
for (int i = 1, x, y, c; i <= m; i++) {
fin >> x >> y >> c;
adj[x].push_back(make_pair(y, c));
}
//fin >> source;
fin.close();
}
vector<int> get_result() {
vector<int> distances(n + 1, INT_MAX);
source = 1;
distances[source] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
// punand greater<pair..>, priority queue va fi ca un min heap
// am pus costul si apoi nodul in pereche pentru ca, de exemplu (0, 100) < (1, 0)
pq.push(make_pair(0, source));
while (!pq.empty()) {
pair<int, int> top = pq.top();
pq.pop();
int node = top.second;
int cost = top.first;
for (auto &neigh_pair : adj[node]) {
int neigh = neigh_pair.first;
int edgeCost = neigh_pair.second;
if (distances[neigh] > cost + edgeCost) {
distances[neigh] = cost + edgeCost;
pq.push(make_pair(distances[neigh], neigh));
}
}
}
return distances;
}
void print_output(vector<int> distances) {
ofstream fout("dijkstra.out");
for (int i = 2; i <= n; i++) {
int d = distances[i];
if (d == INT_MAX) {
fout << "0 ";
} else {
fout << d << " ";
}
}
fout.close();
}
};
int main() {
Task *task = new Task();
task->solve();
delete task;
return 0;
}