2023.11.15 每日一题(AI自生成应用)【C++】【Python】【Java】【Go】 动态路径分析

目录

一、题目

二、解决方法

三、改进


一、题目

背景: 在一个城市中,有数个交通节点,每个节点间有双向道路相连。每条道路具有一个初始权重,代表通行该路段的成本(例如时间、费用等)。随着时间的变化,道路的权重可能会发生变化,比如由于交通堵塞或道路维修。

问题: 设计一个算法,以处理以下两种类型的查询:

  1. 更新查询:给定两个节点及新的权重值,更新这两个节点之间道路的权重。
  2. 最短路径查询:给定两个节点,找出这两个节点之间的最短路径及其权重。

输入格式

输出格式

  • 对于每个最短路径查询,输出一个整数,表示最短路径的权重。如果两个节点之间没有路径,则输出 -1

实际应用: 这个问题可以应用于交通管理系统,例如实时更新交通状况并为司机提供最优路线。也适用于网络数据流量管理,其中节点代表数据中心,道路代表连接它们的网络。

挑战

  • 设计一个高效的数据结构来存储和更新节点间的道路权重。
  • 实现一个算法来快速回答最短路径查询,考虑到道路权重可能频繁变化。

二、解决方法

解决:

为了解决这个动态路径分析问题,我们可以采用以下策略:

  1. 数据结构:使用邻接表来表示图,其中每个节点都有一个列表存储它与其他节点的连接及其权重。
  2. 路径更新:对于更新操作,我们只需要修改邻接表中对应的权重。
  3. 最短路径查询:使用 Dijkstra 算法来找到最短路径。由于权重可能会频繁变化,我们在每次查询时都从头开始执行 Dijkstra 算法。

C++实现:

#include <iostream>
#include <vector>
#include <queue>
#include <climits>using namespace std;typedef pair<int, int> pii; // pair of (weight, node)class Graph {int V; // Number of verticesvector<vector<pii>> adj; // Adjacency listpublic:Graph(int V) : V(V), adj(V) {}void addEdge(int u, int v, int w) {adj[u].push_back({w, v});adj[v].push_back({w, u}); // For undirected graph}void updateEdge(int u, int v, int w) {// Update weight for edge u-vfor (auto &p : adj[u]) {if (p.second == v) {p.first = w;break;}}for (auto &p : adj[v]) {if (p.second == u) {p.first = w;break;}}}int shortestPath(int source, int destination) {priority_queue<pii, vector<pii>, greater<pii>> pq;vector<int> dist(V, INT_MAX);pq.push({0, source});dist[source] = 0;while (!pq.empty()) {int u = pq.top().second;pq.pop();for (auto &[w, v] : adj[u]) {if (dist[v] > dist[u] + w) {dist[v] = dist[u] + w;pq.push({dist[v], v});}}}return (dist[destination] == INT_MAX) ? -1 : dist[destination];}
};int main() {int N, M, u, v, w;cin >> N >> M;Graph g(N);for (int i = 0; i < M; ++i) {cin >> u >> v >> w;g.addEdge(u, v, w);}// Querieschar queryType;while (cin >> queryType) {if (queryType == 'U') {cin >> u >> v >> w;g.updateEdge(u, v, w);} else if (queryType == 'Q') {cin >> u >> v;cout << g.shortestPath(u, v) << endl;}}return 0;
}

Python:

import heapqclass Graph:def __init__(self, V):self.V = Vself.graph = {i: {} for i in range(V)}def add_edge(self, u, v, w):self.graph[u][v] = wself.graph[v][u] = wdef update_edge(self, u, v, w):if v in self.graph[u]:self.graph[u][v] = wif u in self.graph[v]:self.graph[v][u] = wdef shortest_path(self, source, destination):dist = [float('inf')] * self.Vdist[source] = 0pq = [(0, source)]while pq:d, u = heapq.heappop(pq)if d > dist[u]:continuefor v, w in self.graph[u].items():if dist[u] + w < dist[v]:dist[v] = dist[u] + wheapq.heappush(pq, (dist[v], v))return dist[destination] if dist[destination] != float('inf') else -1# Example usage
g = Graph(N)  # N is the number of vertices
# Add edges and handle queries similarly to the C++ example

JAVA:

import java.util.*;public class Graph {private int V;private Map<Integer, Map<Integer, Integer>> adj;public Graph(int V) {this.V = V;this.adj = new HashMap<>();for (int i = 0; i < V; i++) {adj.put(i, new HashMap<>());}}public void addEdge(int u, int v, int w) {adj.get(u).put(v, w);adj.get(v).put(u, w);}public void updateEdge(int u, int v, int w) {if (adj.get(u).containsKey(v)) {adj.get(u).put(v, w);}if (adj.get(v).containsKey(u)) {adj.get(v).put(u, w);}}public int shortestPath(int source, int destination) {int[] dist = new int[V];Arrays.fill(dist, Integer.MAX_VALUE);dist[source] = 0;PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));pq.add(new int[]{source, 0});while (!pq.isEmpty()) {int[] current = pq.poll();int u = current[0];if (u == destination) {break;}for (Map.Entry<Integer, Integer> entry : adj.get(u).entrySet()) {int v = entry.getKey();int weight = entry.getValue();if (dist[u] + weight < dist[v]) {dist[v] = dist[u] + weight;pq.add(new int[]{v, dist[v]});}}}return dist[destination] == Integer.MAX_VALUE ? -1 : dist[destination];}// Example usagepublic static void main(String[] args) {Graph g = new Graph(N); // N is the number of vertices// Add edges and handle queries similarly to the C++ example}
}

Go语言:

package mainimport ("container/heap""fmt""math"
)type Edge struct {node, weight int
}type Graph struct {V     intedges map[int]map[int]int
}func NewGraph(V int) *Graph {g := &Graph{V:     V,edges: make(map[int]map[int]int),}for i := 0; i < V; i++ {g.edges[i] = make(map[int]int)}return g
}
func (g *Graph) UpdateEdge(u, v, w int) {if _, ok := g.edges[u][v]; ok {g.edges[u][v] = w}if _, ok := g.edges[v][u]; ok {g.edges[v][u] = w}
}func (g *Graph) ShortestPath(source, destination int) int {dist := make([]int, g.V)for i := range dist {dist[i] = math.MaxInt32}dist[source] = 0pq := make(PriorityQueue, 0)heap.Init(&pq)heap.Push(&pq, &Item{value:    source,priority: 0,})for pq.Len() > 0 {item := heap.Pop(&pq).(*Item)u := item.valueif u == destination {break}for v, w := range g.edges[u] {if dist[u]+w < dist[v] {dist[v] = dist[u] + wheap.Push(&pq, &Item{value:    v,priority: dist[v],})}}}if dist[destination] == math.MaxInt32 {return -1}return dist[destination]
}// Define the priority queue used for Dijkstra's algorithm
type Item struct {value    int // The node indexpriority int // The node's priority (distance)index    int // The index of the item in the heap
}type PriorityQueue []*Itemfunc (pq PriorityQueue) Len() int { return len(pq) }func (pq PriorityQueue) Less(i, j int) bool {return pq[i].priority < pq[j].priority
}func (pq PriorityQueue) Swap(i, j int) {pq[i], pq[j] = pq[j], pq[i]pq[i].index = ipq[j].index = j
}func (pq *PriorityQueue) Push(x interface{}) {n := len(*pq)item := x.(*Item)item.index = n*pq = append(*pq, item)
}func (pq *PriorityQueue) Pop() interface{} {old := *pqn := len(old)item := old[n-1]old[n-1] = nilitem.index = -1*pq = old[0 : n-1]return item
}func main() {// Example usageg := NewGraph(N) // N is the number of vertices// Add edges and handle queries similarly to the C++ example
}

三、改进

  1. 效率问题:每次查询最短路径时都需要从头执行 Dijkstra 算法。在频繁更新边权重的场景中,这可能导致效率低下。
  2. 数据结构选择:现有实现使用邻接表来存储图,这对于稀疏图是合适的。但对于密集图,这种表示方式可能导致内存使用不经济。

改进:

  1. 增量更新算法:对于频繁更新的场景,可以考虑使用更高级的图算法,如“动态最短路径算法”。这类算法可以在不重新计算整个图的情况下,有效更新最短路径。
  2. 数据结构优化:针对不同类型的图(稀疏或密集),选择合适的数据结构。例如,对于密集图,可以使用邻接矩阵来代替邻接表。
#include <iostream>
#include <vector>
#include <queue>
#include <climits>using namespace std;const int MAX_V = 1000; // 假设图中最多有1000个节点class Graph {int V; // 顶点数vector<vector<int>> adjMatrix; // 邻接矩阵public:Graph(int V) : V(V), adjMatrix(V, vector<int>(V, INT_MAX)) {}void addEdge(int u, int v, int w) {adjMatrix[u][v] = w;adjMatrix[v][u] = w;}void updateEdge(int u, int v, int w) {adjMatrix[u][v] = w;adjMatrix[v][u] = w;}int shortestPath(int source, int destination) {vector<int> dist(V, INT_MAX);vector<bool> sptSet(V, false);dist[source] = 0;for (int count = 0; count < V - 1; count++) {int u = minDistance(dist, sptSet);sptSet[u] = true;for (int v = 0; v < V; v++) {if (!sptSet[v] && adjMatrix[u][v] != INT_MAX && dist[u] != INT_MAX &&dist[u] + adjMatrix[u][v] < dist[v]) {dist[v] = dist[u] + adjMatrix[u][v];}}}return (dist[destination] == INT_MAX) ? -1 : dist[destination];}private:int minDistance(const vector<int> &dist, const vector<bool> &sptSet) {int min = INT_MAX, min_index;for (int v = 0; v < V; v++) {if (!sptSet[v] && dist[v] <= min) {min = dist[v];min_index = v;}}return min_index;}
};int main() {// 示例用法int N, M, u, v, w;cin >> N >> M;Graph g(N);for (int i = 0; i < M; ++i) {cin >> u >> v >> w;g.addEdge(u, v, w);}// 处理查询// ...
}

        这个实现针对密集图进行了优化,但它不包括动态最短路径算法的实现。动态最短路径算法通常更复杂,可能需要使用更高级的数据结构和算法技巧。这种算法的实现和优化通常是图算法研究的前沿话题。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/180152.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

LeetCode(18)整数转罗马数字【数组/字符串】【中等】

目录 1.题目2.答案3.提交结果截图 链接&#xff1a; 12. 整数转罗马数字 1.题目 罗马数字包含以下七种字符&#xff1a; I&#xff0c; V&#xff0c; X&#xff0c; L&#xff0c;C&#xff0c;D 和 M。 字符 数值 I 1 V 5 X …

flutter开发web应用支持浏览器跨域设置

开发web应用难免会遇到跨域问题&#xff0c;所以flutter设置允许web跨域的设置是要在你的flutter安装路径下面 flutter\bin\cache 找到flutter_tools.stamp文件&#xff0c;然后删除掉&#xff1a;这个文件是临时缓存文件 然后找到 flutter\packages\flutter_tools\lib\src\web…

基于PHP的化妆品销售网站,MySQL数据库,PHPstudy,前台用户+后台管理,完美运行,有一万多字论文

目录 演示视频 基本介绍 论文截图 系统截图 演示视频 基本介绍 基于PHP的化妆品销售网站&#xff0c;MySQL数据库&#xff0c;PHPstudy&#xff0c;原生PHP&#xff0c;前台用户后台管理&#xff0c;完美运行&#xff0c;有一万多字论文。 前台功能&#xff1a;用户的注册…

PDF文件标题修改方法

目录 一、PDF文件的标题和名称 二、标题修改方法 1.浏览器打开PDF Editor Free网站 2.点击Free Oline 3.选择第三个从本地上传PDF附件 4.将附件上传&#xff0c;两种方法都可以​编辑 5.等待加载&#xff0c;附件大的情况下会有些慢&#xff0c;耐心等待即可 6. 导入文…

Python数据容器之(元组)

我们前面所了解的列表是可以修改的&#xff0c;但如果想要传递的信息&#xff0c;不被篡改&#xff0c;列表就不合适了。 元组同列表一样&#xff0c;都是可以封装多个、不同类型的元素在内。 但最大的不同点在于&#xff1a; 元组一旦定义完成&#xff0c;就不可修改 所以…

C#中.NET Framework4.8 Windows窗体应用通过EF访问新建数据库

目录 一、 操作步骤 二、编写EF模型和数据库上下文 三、 移植&#xff08;Migrations&#xff09;数据库 四、编写应用程序 五、生成效果 前文已经说过.NET Framework4.8 控制台应用通过EF访问已经建立的和新建的数据库。 本文想说的是&#xff0c;.NET Framework4.8 Win…

MR外包团队:MR、XR混合现实技术应用于游戏、培训,心理咨询、教育成为一种创新的各行业MR、XR形式!

随着VR、AR、XR、MR混合现实等技术逐渐应用于游戏开发、心理咨询、培训、教育各个领域&#xff0c;为教育、培训、心理咨询等行业带来了全新的可能性。MR、XR游戏开发、心理咨询是利用虚拟现实技术模拟真实场景&#xff0c;让学生身临其境地参与学习和体验&#xff0c;从而提高…

Synchronized面试题

一&#xff1a;轻量锁和偏向锁的区别&#xff1a; &#xff08;1&#xff09;争夺轻量锁失败时&#xff0c;自旋尝试抢占锁 &#xff08;2&#xff09;轻量级锁每次退出同步块都需要释放锁&#xff0c;而偏向锁是在竞争发生时才释放锁&#xff0c;线程不会主动释放偏向锁 二&…

【6】Spring Boot 3 集成组件:knift4j+springdoc+swagger3

目录 【6】Spring Boot 3 集成组件&#xff1a;knift4jspringdocswagger3OpenApi规范SpringFox Swagger3SpringFox工具&#xff08;不推荐&#xff09; Springdoc&#xff08;推荐&#xff09;从SpringFox迁移引入依赖配置jAVA Config 配置扩展配置&#xff1a;spring securit…

MAC地址_MAC地址格式_以太网的MAC帧_详解

MAC地址 全世界的每块网卡在出厂前都有一个唯一的代码,称为介质访问控制(MAC)地址 一.网络适配器(网卡) 要将计算机连接到以太网&#xff0c;需要使用相应的网络适配器(Adapter)&#xff0c;网络适配器一般简称为“网卡”。在计算机内部&#xff0c;网卡与CPU之间的通信&…

day26_css

今日内容 零、 复习昨日 一、CSS 零、 复习昨日 HTML - 页面基本骨架结构,内容展现 CSS - 美化页面,布局 JS - 动起来 一 、引言 1.1CSS概念 ​ 层叠样式表(英文全称&#xff1a;Cascading Style Sheets)是一种用来表现HTML&#xff08;标准通用标记语言的一个应用&#xff09;…

Windows 11 设置 wsl-ubuntu 使用桥接网络

Windows 11 设置 wsl-ubuntu 使用桥接网络 0. 背景1. Windows 11 下启用 Hyper-V2. 使用 Hyper-V 虚拟交换机管理器创建虚拟网络3. 创建 .wslconfig 文件4. 配置 wsl.conf 文件5. 配置 wsl-network.conf 文件6. 创建 00-wsl2.yaml7. 安装 net-tools 和 openssh-server 0. 背景 …