Table of Contents
usage instructions
Improved Dijkstra algorithm for weighted products
algorithm
Example
Output
Modified Bellman-Ford algorithm with weighted product
in conclusion
Home Backend Development C++ Minimum product path with edges with weight greater than or equal to 1

Minimum product path with edges with weight greater than or equal to 1

Aug 30, 2023 am 11:37 AM
Weights path side

Minimum product path with edges with weight greater than or equal to 1

To find the path with the smallest edge with weight greater than or equal to 1, we can use Dijkstra's algorithm with a slight modification. First, we set the weight of the source node to 1 and the weight of other nodes to infinity. During the execution of the algorithm, we no longer update the distance, but the product of the weights. This ensures that the path with the smallest weight is selected. By selecting the node with the smallest weight at each step, we iteratively discover the shortest path until the target node is reached. Finally, the product of weights along this path will be minimal, satisfying the given condition.

usage instructions

  • Modified Dijkstra’s algorithm with weighted product

  • Modified Bellman-Ford algorithm with weighted product

Improved Dijkstra algorithm for weighted products

In the modified Dijkstra algorithm, we first set the weight of the source node to infinity and the weights of all other nodes to infinity. While performing the calculation, instead of updating the distances with all the weights, we update them with the product of the weights encountered so far. At each step, we select the node with the smallest weight and update the weights of its neighboring nodes in the same way. This process continues until reaching the target node. Ultimately, the product of weights along this path will represent the smallest possible value, satisfying the condition that the weight is greater than or equal to 1.

algorithm

  • Initialize all center weights to infinity, except the source center, whose weight is set to 0.

  • Create a cleanup collection to track deleted nodes.

  • When there are unvisited nodes,

    • Select the center with the smallest weight among unvisited nodes.

    • Mark the selected center as visited.

    • For each unvisited adjacent hub:

    • Calculate the weight of the current central node and the weight of the edges connected to it.

    • If the calculated term is less than the weight of the adjacent center, replace its weight with the calculated product.

  • Repeat step 3 until the target center disappears or all centers are visited.

  • The target center weight reflects the smallest item weight along the way from the source to the target point.

Example

#include <bits/stdc++.h>
using namespace std;

// Function to return the smallest product of edges
double modifiedDijkstra(int source, int destination, vector<vector<pair<int, double> > > graph)
{
    // If the source is equal to the destination
    if (source == destination)
        return 0;

    // Initialize the priority queue
    set<pair<double, int>> pq;
    pq.insert({1, source});

    // Visited array
    bool visited[graph.size()] = {0};

    // While the priority queue is not empty
    while (!pq.empty())
    {
        // Current node
        int current = pq.begin()->second;

        // Current product of weights
        double product = pq.begin()->first;

        // Pop the top-most element
        pq.erase(pq.begin());

        // If already visited, continue
        if (visited[current])
            continue;

        // Mark the node as visited
        visited[current] = true;

        // If it is a destination node
        if (current == destination)
            return product;

        // Traverse the neighbors of the current node
        for (auto neighbor : graph[current])
        {
            int neighborNode = neighbor.first;
            double weight = neighbor.second;

            // Calculate the product of weights
            double newProduct = product * weight;

            // Insert the new product and neighbor into the priority queue
            pq.insert({newProduct, neighborNode});
        }
    }

    // If no path exists
    return -1;
}

// Function to add an edge to the graph
void addEdge(vector<vector<pair<int, double>>>& graph, int u, int v, double weight)
{
    graph[u].push_back({v, weight});
}

// Function to print the graph
void printGraph(const vector<vector<pair<int, double>>>& graph)
{
    for (int i = 1; i < graph.size(); i++)
    {
        cout << "Node " << i << ": ";
        for (auto neighbor : graph[i])
        {
            cout << "(" << neighbor.first << ", " << neighbor.second << ") ";
        }
        cout << endl;
    }
}

// Driver code
int main()
{
    int numNodes = 3;

    // Graph as adjacency list
    vector<vector<pair<int, double>>> graph(numNodes + 1);

    // Input edges
    addEdge(graph, 1, 3, 9);
    addEdge(graph, 2, 3, 1);
    addEdge(graph, 1, 2, 5);

    // Source and destination
    int source = 1, destination = 3;

    // Modified Dijkstra
    double smallestProduct = modifiedDijkstra(source, destination, graph);

    // Print the result
    cout << "Smallest product of weights: " << smallestProduct << endl;

    // Print the graph
    cout << "Graph: " << endl;
    printGraph(graph);

    return 0;
}
Copy after login

Output

Smallest product of weights: 5
Graph: 
Node 1: (3, 9) (2, 5) 
Node 2: (3, 1) 
Node 3: 
Copy after login

Modified Bellman-Ford algorithm with weighted product

In the adjusted Bellman-Ford algorithm with weighted objects, we start by setting the loading of the source center to 1 and the loading of all other centers to infinity. In each loop, all edges are unraveled by comparing the weight of the current node with the load of the edge connecting them to the target center. If the calculated weight is smaller than the load of the target center, we increase its weight by the calculated weight. Repeat this process V-1 times, where V is the total number of centers to ensure that all possible paths are considered. The weight of the target center represents the smallest weight on the path from the source to the target.

algorithm

  • Except the source center, the weight of all other centers should be infinite.

  • Repeat the above steps V−1 times, where V is the total number of nodes:

    • For each edge in the graph, calculate the weight of the item at the current center and the weights of the edges connected to them.

    • If the calculated item is less than the weight at the target center, its weight is upgraded with the calculated product.

  • After V-1 periods, the weights of all central nodes will be determined.

  • During the calculation, if there is a negative weight cycle in the graph, an additional cycle will be distinguished. If any weights are corrected during this process, this indicates the existence of a negative weight cycle.

  • The target center weight reflects the smallest item weight along the way from the source to the target point.

  • The greedy shading algorithm assigns colors to vertices in a greedy manner based on the available colors and the colors used by neighbor vertices. While it may not always use the minimum number of colors to accomplish graph shading, it provides a fast and efficient method of vertex shading.

Example

#include <iostream>
#include <vector>
#include <limits>

struct Edge {
    int source, destination;
    double weight;
};

// Function to find the smallest product of weights using the modified Bellman-Ford algorithm
double findSmallestProduct(int numNodes, int source, int destination, std::vector<Edge>& edges) {
    std::vector<double> weights(numNodes, std::numeric_limits<double>::infinity());
    weights[source] = 1;

    for (int i = 1; i < numNodes; i++) {
        for (const auto& edge : edges) {
            double newWeight = weights[edge.source] * edge.weight;
            if (newWeight < weights[edge.destination]) {
                weights[edge.destination] = newWeight;
            }
        }
    }

    for (const auto& edge : edges) {
        double newWeight = weights[edge.source] * edge.weight;
        if (newWeight < weights[edge.destination]) {
            return -1.0; // Negative-weight cycle detected
        }
    }

    return weights[destination];
}

int main() {
    int numNodes = 4;

    std::vector<Edge> edges = {
        {0, 1, 2.0},
        {1, 2, 0.5},
        {2, 3, 1.5},
        {0, 3, 1.2},
        {1, 3, 0.8}
    };

    int source = 0, destination = 3;

    double smallestProduct = findSmallestProduct(numNodes, source, destination, edges);

    if (smallestProduct < std::numeric_limits<double>::infinity()) {
        std::cout << "The smallest product of weights along the path from node " << source
                  << " to node " << destination << " is: " << smallestProduct << std::endl;
    } else {
        std::cout << "A negative-weight cycle is detected. No valid path exists." << std::endl;
    }

    return 0;
}
Copy after login

Output

The smallest product of weights along the path from node 0 to node 3 is: 1.2
Copy after login

in conclusion

This article illustrates how to find the path with the smallest edge with weight greater than or equal to 1. It introduces two algorithms, the improved Dijkstra algorithm and the improved Bellman-Ford algorithm, for solving this problem. The modified Dijkstra algorithm selects the node with the minimum weight at each step, while the modified Bellman-Ford algorithm iteratively unwraps edges to update weights. The article provides the implementation of these two algorithms in C language and illustrates their use with test inputs. The output is the minimum weight on the path from the source node to the destination node.

The above is the detailed content of Minimum product path with edges with weight greater than or equal to 1. 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 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)

Where are themes located in Windows 11? Where are themes located in Windows 11? Aug 01, 2023 am 09:29 AM

Windows 11 has so many customization options, including a range of themes and wallpapers. While these themes are aesthetic in their own way, some users still wonder where they stand in the background on Windows 11. This guide will show you the different ways to access the location of your Windows 11 theme. What is the Windows 11 default theme? The default theme background of Windows 11 is an abstract royal blue flower blooming with a sky blue background. This background is one of the most popular, thanks to the anticipation before the release of the operating system. However, the operating system also comes with a range of other backgrounds. Therefore, you can change the Windows 11 desktop theme background at any time. Themes are stored in Windo

Different uses of slashes and backslashes in file paths Different uses of slashes and backslashes in file paths Feb 26, 2024 pm 04:36 PM

A file path is a string used by the operating system to identify and locate a file or folder. In file paths, there are two common symbols separating paths, namely forward slash (/) and backslash (). These two symbols have different uses and meanings in different operating systems. The forward slash (/) is a commonly used path separator in Unix and Linux systems. On these systems, file paths start from the root directory (/) and are separated by forward slashes between each directory. For example, the path /home/user/Docume

How to fix error: Main class not found or loaded in Java How to fix error: Main class not found or loaded in Java Oct 26, 2023 pm 11:17 PM

This video cannot be played due to a technical error. (Error Code: 102006) This guide provides simple fixes for this common problem and continue your coding journey. We will also discuss the causes of Java errors and how to prevent it in the future. What is "Error: Main class not found or loaded" in Java? Java is a powerful programming language that enables developers to create a wide range of applications. However, its versatility and efficiency come with a host of common mistakes that can occur during development. One of the interrupts is Error: Main class user_jvm_args.txt not found or loaded, which occurs when the Java Virtual Machine (JVM) cannot find the main class to execute a program. This error acts as a roadblock even in

What is the difference in the 'My Computer' path in Win11? Quick way to find it! What is the difference in the 'My Computer' path in Win11? Quick way to find it! Mar 29, 2024 pm 12:33 PM

What is the difference in the "My Computer" path in Win11? Quick way to find it! As the Windows system is constantly updated, the latest Windows 11 system also brings some new changes and functions. One of the common problems is that users cannot find the path to "My Computer" in Win11 system. This was usually a simple operation in previous Windows systems. This article will introduce how the paths of "My Computer" are different in Win11 system, and how to quickly find them. In Windows1

Get the directory portion of a file path using the path/filepath.Dir function Get the directory portion of a file path using the path/filepath.Dir function Jul 27, 2023 am 09:06 AM

Use the path/filepath.Dir function to obtain the directory part of the file path. In our daily development process, file path processing is often involved. Sometimes, we need to get the directory part of the file path, that is, the path to the folder where the file is located. In the Go language, you can use the Dir function provided by the path/filepath package to implement this function. The signature of the Dir function is as follows: funcDir(pathstring)string The Dir function receives a word

Linux kernel source code storage path analysis Linux kernel source code storage path analysis Mar 14, 2024 am 11:45 AM

The Linux kernel is an open source operating system kernel whose source code is stored in a dedicated code repository. In this article, we will analyze the storage path of the Linux kernel source code in detail, and use specific code examples to help readers better understand. 1. Linux kernel source code storage path The Linux kernel source code is stored in a Git repository called linux, which is hosted at [https://github.com/torvalds/linux](http

How to use the os.path module to obtain various parts of the file path in Python 3.x How to use the os.path module to obtain various parts of the file path in Python 3.x Jul 30, 2023 pm 02:57 PM

How to use the os.path module in Python3.x to obtain various parts of the file path. In daily Python programming, we often need to operate on the file path, such as obtaining the file name, file directory, extension, etc. of the path. In Python, you can use the os.path module to perform these operations. This article will introduce how to use the os.path module to obtain various parts of the file path for better file manipulation. The os.path module provides a series of

How to find the storage path of RPM files in Linux system? How to find the storage path of RPM files in Linux system? Mar 14, 2024 pm 04:42 PM

In Linux systems, RPM (RedHatPackageManager) is a common software package management tool used to install, upgrade and delete software packages. Sometimes we need to find the storage path of an installed RPM file for search or other operations. The following will introduce how to find the storage path of the RPM file in the Linux system, and provide specific code examples. First, we can use the rpm command to find the installed RPM package and its storage path. Open

See all articles