Pagini recente » Cod sursa (job #1593045) | Cod sursa (job #1265621) | Cod sursa (job #1821174) | Cod sursa (job #2448680) | Cod sursa (job #2858809)
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <set>
#include <queue>
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];
void findMinimumCosts(int peaks) {
for (int i = 2; i <= peaks; ++i) {
costs[i] = MAX_SUM;
}
set<pair<int, int>> positions; // peak / cost
positions.insert(make_pair(1, 0));
while (!positions.empty()) {
int currentPeak = positions.begin()->first;
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(nextPeak, costs[nextPeak])));
}
costs[nextPeak] = costs[currentPeak] + nextCost;
positions.insert(make_pair(nextPeak, costs[nextPeak]));
}
}
}
for (int i = 2; i <= peaks; ++i) {
if (costs[i] == MAX_SUM) {
costs[i] = 0;
}
fout << costs[i] << " ";
}
}
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)); // peak / cost
}
findMinimumCosts(peaks);
return 0;
}
/*
1 ≤ N ≤ 50 000
1 ≤ M ≤ 250 000
Lungimile arcelor sunt numere naturale cel mult egale cu 20 000.
Pot exista arce de lungime 0
Nu exista un arc de la un nod la acelasi nod.
Daca nu exista drum de la nodul 1 la un nod i, se considera ca lungimea minima este 0.
Arcele date in fisierul de intrare nu se repeta.
50000 7
1 2 1
2 3 2
3 4 3
4 5 1
1 5 700
2 5 100
3 5 30 -> 1 3 5 7 + multe 0-uri
5 7
1 2 1
2 3 2
3 4 3
4 5 1
1 5 700
2 5 100
3 5 30 -> 1 3 6 7
5 3
1 5 2
1 4 5
5 4 1 -> 0 0 3 2
5 3
1 5 2
1 4 3
5 4 1 -> 0 0 3 2
3 1
1 2 1 -> 1 0
4 4
1 2 1
1 3 2
3 4 1
2 4 1 -> 1 2 2
5 6
1 2 1
1 4 2
4 3 4
2 3 2
4 5 3
3 5 6 -> 1 3 2 5
*/