Table of Contents
usage instructions
Naive recursive method
algorithm
Example
Output
Dijkstra's algorithm with edge constraints
示例
输出
结论
Home Backend Development C++ In a directed weighted graph, find the shortest path containing exactly k edges.

In a directed weighted graph, find the shortest path containing exactly k edges.

Sep 11, 2023 pm 07:17 PM
shortest path directed graph weighted graph

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;
}

Copy after login

Output

Weight of the shortest path is 9
Copy after login

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;
}
Copy after login

输出

Shortest distances from vertex 0:
Vertex 0: 0
Vertex 1: 10
Vertex 2: 3
Vertex 3: 9
Copy after login

结论

本文概述了两个重要的计算,以帮助理解协调和加权图表中的大多数问题。它阐明了易受骗的递归方法和带有边缘限制的 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the types of values ​​returned by c language functions? What determines the return value? What are the types of values ​​returned by c language functions? What determines the return value? Mar 03, 2025 pm 05:52 PM

This article details C function return types, encompassing basic (int, float, char, etc.), derived (arrays, pointers, structs), and void types. The compiler determines the return type via the function declaration and the return statement, enforcing

Gulc: C library built from scratch Gulc: C library built from scratch Mar 03, 2025 pm 05:46 PM

Gulc is a high-performance C library prioritizing minimal overhead, aggressive inlining, and compiler optimization. Ideal for performance-critical applications like high-frequency trading and embedded systems, its design emphasizes simplicity, modul

What are the definitions and calling rules of c language functions and what are the What are the definitions and calling rules of c language functions and what are the Mar 03, 2025 pm 05:53 PM

This article explains C function declaration vs. definition, argument passing (by value and by pointer), return values, and common pitfalls like memory leaks and type mismatches. It emphasizes the importance of declarations for modularity and provi

C language function format letter case conversion steps C language function format letter case conversion steps Mar 03, 2025 pm 05:53 PM

This article details C functions for string case conversion. It explains using toupper() and tolower() from ctype.h, iterating through strings, and handling null terminators. Common pitfalls like forgetting ctype.h and modifying string literals are

Where is the return value of the c language function stored in memory? Where is the return value of the c language function stored in memory? Mar 03, 2025 pm 05:51 PM

This article examines C function return value storage. Small return values are typically stored in registers for speed; larger values may use pointers to memory (stack or heap), impacting lifetime and requiring manual memory management. Directly acc

distinct usage and phrase sharing distinct usage and phrase sharing Mar 03, 2025 pm 05:51 PM

This article analyzes the multifaceted uses of the adjective "distinct," exploring its grammatical functions, common phrases (e.g., "distinct from," "distinctly different"), and nuanced application in formal vs. informal

How does the C   Standard Template Library (STL) work? How does the C Standard Template Library (STL) work? Mar 12, 2025 pm 04:50 PM

This article explains the C Standard Template Library (STL), focusing on its core components: containers, iterators, algorithms, and functors. It details how these interact to enable generic programming, improving code efficiency and readability t

How do I use algorithms from the STL (sort, find, transform, etc.) efficiently? How do I use algorithms from the STL (sort, find, transform, etc.) efficiently? Mar 12, 2025 pm 04:52 PM

This article details efficient STL algorithm usage in C . It emphasizes data structure choice (vectors vs. lists), algorithm complexity analysis (e.g., std::sort vs. std::partial_sort), iterator usage, and parallel execution. Common pitfalls like

See all articles