算法训练营|图论第9天 dijkstra(堆优化),bellman_ford

题目:dijkstra(堆优化)

题目链接:

47. 参加科学大会(第六期模拟笔试) (kamacoder.com)

代码:

#include
using namespace std;
class mycomparison {
public:
	bool operator()(const pair& lhs, const pair& 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>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;
	vectorminDist(n + 1, INT_MAX);
	vectorvisited(n + 1, false);
	priority_queue, vector>, mycomparison>pq;
	pq.push(pair(start, 0));
	minDist[start] = 0;
	while (!pq.empty()) {
		paircur = 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(edge.to, minDist[edge.to]));
			}
		}
	}
	if (minDist[end] == INT_MAX) cout << -1 << endl;
	else cout << minDist[end] << endl;
}

题目:bellman_ford

题目链接:

94. 城市间货物运输 I (kamacoder.com)

代码:

#include
using namespace std;
int main() {
	int n, m, p1, p2, val;
	cin >> n >> m;
	vector>grid;
	for (int i = 0; i < m; i++) {
		cin >> p1 >> p2 >> val;
		grid.push_back({ p1,p2,val });
	}
	int start = 1;
	int end = n;
	vectorminDist(n + 1, INT_MAX);
	minDist[start] = 0;
	for (int i = 1; i < n ; i++) {
		for (vector & 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;
	}
}

你可能感兴趣的:(算法,图论)