


In a directed weighted graph, find the shortest path containing exactly k edges.
In a coordinated weighted graph, the problem of finding the shortest path with exactly k edges involves determining the path with the smallest weight when navigating exactly k edges. This will be achieved by employing dynamic programming strategies, such as employing 3D frameworks to store minimal weights in all conceivable ways. The calculation is repeated at vertices and edges, adjusting the minimum weight at each step. By considering all possible ways of having exactly k edges, the calculation can distinguish the most limited way of having k edges in the graph.
usage instructions
Naive recursive method
Dijkstra’s algorithm with edge constraints
Naive recursive method
Naive recursive methods can be an important and clear strategy for problem solving, which involves decomposing complex problems into smaller sub-problems and solving them recursively. In this approach, the work calls itself multiple times to explore subproblems until the base case is reached. Nonetheless, it can be wasteful for larger problems due to double counting and covering subproblems. It requires optimization methods such as memory or energy programming. Gullible recursive methods are easy to obtain and implement, but may suffer from exponential time complexity. It is often used to solve small-scale problems or as a starting point for more optimal calculations.
algorithm
Represents the working shortest path (graph, u, v, k) that takes as input a graph, a source vertex u, a target vertex v, and the number of edges k.
Check the basic situation:
a. Return if k and u break even with v (since no edges are allowed in this case).
the second. If k is 1 and there is an edge between u and v in the graph, its weight is returned.
c. If k is less than or equal to 0, return unbounded (because negative or zero edges are not allowed).
Initialize an infinite variable res to store the shortest path distance.
The graph should iterate over all vertices as follows:
a. If u and i do not rise to u or v, then there is an edge from u to i:
Call shortestPath recursively, where i is the modern source vertex, v is the target vertex, and k−1 is the number of remaining edges.
If the returned result is not infinite, res will be upgraded to the minimum value of res and the weight of the current edge and the recursive result.
Return the value of res as the most limited way to accurately separate k edges.
Example
#include <iostream> #include <climits> #define V 4 #define INF INT_MAX int shortestPathWithKEdges(int graph[][V], int source, int destination, int k) { // Base cases if (k == 0 && source == destination) return 0; if (k == 1 && graph[source][destination] != INF) return graph[source][destination]; if (k <= 0) return INF; // Initialize result int shortestPathDistance = INF; // Explore all adjacent vertices of the source vertex for (int i = 0; i < V; i++) { if (graph[source][i] != INF && source != i && destination != i) { int recursiveDistance = shortestPathWithKEdges(graph, i, destination, k - 1); if (recursiveDistance != INF) shortestPathDistance = std::min(shortestPathDistance, graph[source][i] + recursiveDistance); } } return shortestPathDistance; } int main() { int graph[V][V] = { {0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0} }; int source = 0, destination = 3, k = 2; std::cout << "Weight of the shortest path is " << shortestPathWithKEdges(graph, source, destination, k) << std::endl; return 0; }
Output
Weight of the shortest path is 9
Dijkstra's algorithm with edge constraints
Dijkstra's algorithm with edge constraints is a graph traversal calculation that identifies the shortest path between a source vertex and all other vertices on the graph. It takes into account limits or constraints on the edges of the graph, such as the most or least extreme edge weights. This calculation retains the required vertex lines and iteratively selects the fewest vertices to remove. At this point, if a shorter path is found, it relaxes adjacent vertices by increasing the distance between them. This preparation continues until all vertices have been visited. Dijkstra's algorithm with edge commands guarantees that the chosen way satisfies the required edge constraints while finding the most limited way
algorithm
Create Dijkstra's artwork using the following parameters
Graph: Input graph with vertices and edges
Source: starting vertex of the most limited path
Constraints: Limitations or obstacles at the edge
Initialize a set of vanished vertices and a demand line to store the vertices and their distances.
Create a deletion cluster and set deletion to terminability for all vertices except the source vertex, which is set to 0.
Arrange the source vertices into the desired rows by their distance.
Although the demand pipeline is not purgeable, please do the following:
Dequeue the vertex with the least number of eliminations from the desired queue.
If the vertex is no longer visited now,
Mark it as visited.
For each adjacent vertex of the modern vertex:
Apply edge barriers to determine whether an edge can be considered.
Calculate the unused distance from the feeding vertex to the adjacent vertex taking into account edge weights and constraints.
Improve the delimiter array if the current delimiters are shorter than modern delimiters.
Queue adjacent vertices at their unused distance into the desired row.
After all vertices are reached, individual clusters will contain the maximum short distance from the supply vertex to each vertex that satisfies the edge constraints.
Return individual clusters as results.
示例
#include <iostream> #include <vector> #include <limits> struct Edge { int destination; int weight; }; void dijkstra(const std::vector<std::vector<Edge>>& graph, int source, std::vector<int>& distance) { int numVertices = graph.size(); std::vector<bool> visited(numVertices, false); distance.resize(numVertices, std::numeric_limits<int>::max()); distance[source] = 0; for (int i = 0; i < numVertices - 1; ++i) { int minDistance = std::numeric_limits<int>::max(); int minVertex = -1; for (int v = 0; v < numVertices; ++v) { if (!visited[v] && distance[v] < minDistance) { minDistance = distance[v]; minVertex = v; } } if (minVertex == -1) break; visited[minVertex] = true; for (const auto& edge : graph[minVertex]) { int destination = edge.destination; int weight = edge.weight; if (!visited[destination] && distance[minVertex] != std::numeric_limits<int>::max() && distance[minVertex] + weight < distance[destination]) { distance[destination] = distance[minVertex] + weight; } } } } int main() { int numVertices = 4; int source = 0; std::vector<std::vector<Edge>> graph(numVertices); // Add edges to the graph (destination, weight) graph[0] = {{1, 10}, {2, 3}}; graph[1] = {{2, 1}, {3, 7}}; graph[2] = {{3, 6}}; std::vector<int> distance; dijkstra(graph, source, distance); // Print the shortest distances from the source vertex std::cout << "Shortest distances from vertex " << source << ":\n"; for (int i = 0; i < numVertices; ++i) { std::cout << "Vertex " << i << ": " << distance[i] << '\n'; } return 0; }
输出
Shortest distances from vertex 0: Vertex 0: 0 Vertex 1: 10 Vertex 2: 3 Vertex 3: 9
结论
本文概述了两个重要的计算,以帮助理解协调和加权图表中的大多数问题。它阐明了易受骗的递归方法和带有边缘限制的 Dijkstra 计算。轻信递归方法包括递归地研究具有精确 k 个边的所有可能的方式,以发现最有限的方式。 Dijkstra 的边命令式计算采用了所需的线和面积规则,成功地找出了图表中从供给顶点到所有不同顶点的最大受限方式。本文包含了计算的具体说明,并给出了测试代码来说明其用法.
The above is the detailed content of In a directed weighted graph, find the shortest path containing exactly k edges.. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

C language functions are the basis for code modularization and program building. They consist of declarations (function headers) and definitions (function bodies). C language uses values to pass parameters by default, but external variables can also be modified using address pass. Functions can have or have no return value, and the return value type must be consistent with the declaration. Function naming should be clear and easy to understand, using camel or underscore nomenclature. Follow the single responsibility principle and keep the function simplicity to improve maintainability and readability.

The calculation of C35 is essentially combinatorial mathematics, representing the number of combinations selected from 3 of 5 elements. The calculation formula is C53 = 5! / (3! * 2!), which can be directly calculated by loops to improve efficiency and avoid overflow. In addition, understanding the nature of combinations and mastering efficient calculation methods is crucial to solving many problems in the fields of probability statistics, cryptography, algorithm design, etc.

The C language function name definition includes: return value type, function name, parameter list and function body. Function names should be clear, concise and unified in style to avoid conflicts with keywords. Function names have scopes and can be used after declaration. Function pointers allow functions to be passed or assigned as arguments. Common errors include naming conflicts, mismatch of parameter types, and undeclared functions. Performance optimization focuses on function design and implementation, while clear and easy-to-read code is crucial.

C language functions are reusable code blocks. They receive input, perform operations, and return results, which modularly improves reusability and reduces complexity. The internal mechanism of the function includes parameter passing, function execution, and return values. The entire process involves optimization such as function inline. A good function is written following the principle of single responsibility, small number of parameters, naming specifications, and error handling. Pointers combined with functions can achieve more powerful functions, such as modifying external variable values. Function pointers pass functions as parameters or store addresses, and are used to implement dynamic calls to functions. Understanding function features and techniques is the key to writing efficient, maintainable, and easy to understand C programs.

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

Algorithms are the set of instructions to solve problems, and their execution speed and memory usage vary. In programming, many algorithms are based on data search and sorting. This article will introduce several data retrieval and sorting algorithms. Linear search assumes that there is an array [20,500,10,5,100,1,50] and needs to find the number 50. The linear search algorithm checks each element in the array one by one until the target value is found or the complete array is traversed. The algorithm flowchart is as follows: The pseudo-code for linear search is as follows: Check each element: If the target value is found: Return true Return false C language implementation: #include#includeintmain(void){i
