题目:dijkstra(堆优化)
题目链接:
47. 参加科学大会(第六期模拟笔试) (kamacoder.com)
代码:
#include<bits/stdc++.h>
using namespace std;
class mycomparison {
public:
bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) {
return lhs.second > rhs.second;
}
};
struct Edge {
int to;
int val;
Edge(int t, int w) :to(t), val(w) {}
};
int main() {
int n, m, p1, p2, val;
cin >> n >> m;
vector<list<Edge>>grid(n + 1);
for (int i = 0; i < m; i++) {
cin >> p1 >> p2 >> val;
grid[p1].push_back(Edge(p2, val));
}
int start = 1;
int end = n;
vector<int>minDist(n + 1, INT_MAX);
vector<bool>visited(n + 1, false);
priority_queue<pair<int, int>, vector<pair<int, int>>, mycomparison>pq;
pq.push(pair<int, int>(start, 0));
minDist[start] = 0;
while (!pq.empty()) {
pair<int, int>cur = pq.top(); pq.pop();
if (visited[cur.first]) continue;
visited[cur.first] = true;
for (Edge edge : grid[cur.first]) {
if (!visited[edge.to] && minDist[cur.first] + edge.val < minDist[edge.to]) {
minDist[edge.to] = minDist[cur.first] + edge.val;
pq.push(pair<int, int>(edge.to, minDist[edge.to]));
}
}
}
if (minDist[end] == INT_MAX) cout << -1 << endl;
else cout << minDist[end] << endl;
}
题目:bellman_ford
题目链接:
代码:
#include<bits/stdc++.h>
using namespace std;
int main() {
int n, m, p1, p2, val;
cin >> n >> m;
vector<vector<int>>grid;
for (int i = 0; i < m; i++) {
cin >> p1 >> p2 >> val;
grid.push_back({ p1,p2,val });
}
int start = 1;
int end = n;
vector<int>minDist(n + 1, INT_MAX);
minDist[start] = 0;
for (int i = 1; i < n ; i++) {
for (vector<int> & vec : grid) {
int from = vec[0];
int to = vec[1];
int val = vec[2];
if (minDist[from] != INT_MAX && minDist[from] + val < minDist[to]) {
minDist[to] = minDist[from] + val;
}
}
}
if (minDist[n] == INT_MAX) cout << "unconnected" << endl;
else {
cout << minDist[end] << endl;
}
}