Minimum cost (multiplication shortest path)

Minimum cost

Title

Given an undirected graph, the edge weight is wi (0 ≤ wi ≤ 1) w_i(0\leq w_i\leq1)wi(0wi1 ) . Define the distance between two points as the product of all the values ​​on the path. Find the longest way between two points.

Ideas

Suppose the distance is w 1 w 2… wk w_1w_2\dots w_kw1w2wk, It can be processed by logarithm, that is, log ⁡ w 1 w 2… wk = log ⁡ w 1 + log ⁡ w 2 +… log ⁡ wk \log w_1w_2\dots w_k = \log w_1 + \log w_2 + \dots \log w_klogw1w2wk=logw1+logw2+logwk. In this way, the multiplication is transformed into adding points. In order to find the longest path, the opposite number can be processed. Because wi (0 ≤ wi ≤ 1) w_i(0\leq w_i\leq1)wi(0wi1),所以 log ⁡ w i ≤ 0 \log w_i \leq 0 logwi0 , all non-negative numbers after taking the opposite number, so Dijkstra algorithm can be used.

Code

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 2010;

int n,m,S,T;
double g[N][N];
double dist[N];
bool st[N];

void dijkstra()
{
    
    
    dist[S] = 1;
    for(int i=1;i<=n;i++){
    
    
        int t = -1;
        for(int j=1;j<=n;j++){
    
    
            if(!st[j]&&(t==-1||dist[t]<dist[j])){
    
    
                t = j;
            }
        }
        st[t] = true;
        for(int j=1;j<=n;j++){
    
    
            dist[j] = max(dist[j],dist[t]*g[t][j]);
        }
    }
}

int main()
{
    
    
    scanf("%d%d",&n,&m);
    while(m--){
    
    
        int a,b,c;
        scanf("%d%d%d",&a,&b,&c);
        double z = (100.0 - c) / 100;
        g[a][b] = g[b][a] = max(g[a][b], z);
    }
    scanf("%d%d",&S,&T);
    dijkstra();
    printf("%.8f\n",100.0/dist[T]);
    return 0;
}

reward

  • To find the longest path, you can reverse the side weight and make the shortest path. In fact, in the process of writing the code, it is not necessary to actually reverse it, just reverse the inequality sign of the triangle inequality, min minm i n changed tomax maxm A X can.
  • For multiplication, if the weight is less than or equal to 1 11 , then it is equivalent to the negative side weight of addition; if it is greater than1 1In the case of 1 , it means the right to the front.

Guess you like

Origin blog.csdn.net/weixin_43634220/article/details/108589155