代码随想录算法训练营第五十九天 | 图论part09

47. 参加科学大会

使用邻接表和堆来优化dijkstra算法。原来的时间复杂度是 O ( n 2 ) O(n^2) O(n2),n是节点数量。

使用堆优化,从宏观角度来说就是将每条边都加入堆,一共是E条边,每次操作的时间复杂度是 l o g ( E ) log(E) log(E),所以时间复杂度是 E l o g ( E ) Elog(E) Elog(E)。

cpp 复制代码
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
#include <list>
#include <fstream>
#include <climits>


using namespace std;

struct Edge {
	int end, val;
	Edge(int end, int val):end(end), val(val) {}
};

class myCompare {
public:
	bool operator()(const pair<int, int>& a, const pair<int, int>& b) {
		return a.second > b.second;
	}
};


int main() {
	int n, m;
	int s, e, v;
	ifstream infile("input.txt");
	cin >> n >> m;
	vector<list<Edge>> graph(n + 1);
	
	while (m--) {
		cin >> s >> e >> v;
		graph[s].emplace_back(Edge(e, v));
	}
	// 记录访问的一维数组
	vector<bool> visited(n + 1, false);
	// 记录到源点的距离的一维数组  
	vector<int> minDist(n + 1, INT_MAX);
	// 记录目前已知到源点距离最短的点和距离
	priority_queue <pair<int, int>, vector<pair<int, int>>, myCompare> pq;

	minDist[1] = 0;
	pq.push({ 1, 0 });

	while (!pq.empty()) {
		// 找到距离源点最近的节点
		pair<int, int> cur = pq.top(); pq.pop();
		if (visited[cur.first]) continue;

		// 将节点标记为已访问
		visited[cur.first] = true;

		// 更新非访问节点的minDist
		for (Edge edge : graph[cur.first]) {
			if (!visited[edge.end] && edge.val + cur.second < minDist[edge.end]) {
				minDist[edge.end] = edge.val + cur.second;
				pq.push({ edge.end, minDist[edge.end] });
			}
		}
		
	}
	if (minDist[n] == INT_MAX) cout << -1 << endl;
	else cout << minDist[n] << endl;
	return 0;
}

94. 城市间货物运输 I

Bellman_ford算法就是松弛n-1次。每一次会将所有点到源点的距离更新。

使用Bellman_ford算法,需要以下数据结构:

  • 邻接表
  • 记录到源点的距离的一维数组
cpp 复制代码
#include <iostream>
#include <vector>
#include <list>
#include <fstream>
#include <climits>

using namespace std;

struct Edge {
	int from, end, val;
	Edge(int from, int end, int val):from(from), end(end), val(val) {}
};


int main() {
	int n, m;
	int s, e, v;
	ifstream infile("input.txt");
	cin >> n >> m;
	vector<Edge> graph;
	
	while (m--) {
		cin >> s >> e >> v;
		graph.emplace_back(Edge(s, e, v));
	}
	
	// 记录到源点的距离的一维数组  
	vector<int> minDist(n + 1, INT_MAX);
	

	minDist[1] = 0;
	
	for (int i = 1; i < n; ++i) { // 重复n-1次

		for (Edge& e : graph) {
			if (minDist[e.from] != INT_MAX && minDist[e.end] > minDist[e.from] + e.val) {
				minDist[e.end] = minDist[e.from] + e.val;
			}
		}
		
	}
	
	if (minDist[n] == INT_MAX) cout << "unconnected" << endl;
	else cout << minDist[n] << endl;
	return 0;
}
相关推荐
yzx99101339 分钟前
基于 Q-Learning 算法和 CNN 的强化学习实现方案
人工智能·算法·cnn
亮亮爱刷题42 分钟前
算法练习-回溯
算法
眼镜哥(with glasses)2 小时前
蓝桥杯 国赛2024python(b组)题目(1-3)
数据结构·算法·蓝桥杯
int型码农6 小时前
数据结构第八章(一) 插入排序
c语言·数据结构·算法·排序算法·希尔排序
UFIT6 小时前
NoSQL之redis哨兵
java·前端·算法
喜欢吃燃面7 小时前
C++刷题:日期模拟(1)
c++·学习·算法
SHERlocked937 小时前
CPP 从 0 到 1 完成一个支持 future/promise 的 Windows 异步串口通信库
c++·算法·promise
怀旧,7 小时前
【数据结构】6. 时间与空间复杂度
java·数据结构·算法
积极向上的向日葵7 小时前
有效的括号题解
数据结构·算法·
GIS小天7 小时前
AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年6月7日第101弹
人工智能·算法·机器学习·彩票