【问题标题】:Floyd/Warshall Algorithm mod to find cheapest path at max length kFloyd/Warshall Algorithm mod 在最大长度 k 处找到最便宜的路径
【发布时间】:2012-05-20 23:49:05
【问题描述】:

我正在编辑弗洛伊德的算法,所以不是每个 Dk,其中 k 是最高中间顶点,k 是最大路径长度。最终它将具有与 Floyd 相同的输出,但每次迭代都可能不同。例如,如果有 4 个顶点:0,1,2,3,我想找到从 0 到 3 的最大长度为 K 的最便宜的路径。假设该图是有向的。

所以如果 k=2,那么我只能检查 0->3...0->1->3...0->2->3,其中每个箭头都表示一条边/路径。如果 k=3,那么我只能检查 0->3...0->1->3...0->1->2->3...0->2->3... 0->2->1->3等等……

    0   1   2   3
0   0   4   9   12
1   9   0   3   11   // the adj matrix I'm referencing for 1 example
2   9   10  0   2
3   1   99  6   0

我需要帮助理解其中的实现,但不知道从哪里开始,除了弗洛伊德的算法。

【问题讨论】:

    标签: matrix shortest-path floyd-warshall


    【解决方案1】:

    这里是您的问题的示例 C++ 代码:

    #define INF 100000005
    
    using namespace std;
    
    int main()
    {
       int i,j,k,n,m,ver,edg,len,from,to;
       int mat[10][10][10],next[10][10][10];
       cin>>ver;
       for(i=0;i<ver;i++)
       {
           for(j=0;j<ver;j++)
           {
               for(k=0;k<ver;k++)
                {
                    mat[i][j][k]=INF;
                    next[i][j][k]=j;
                }
           }
       }
       for(i=0;i<ver;i++)
       {
    
           for(j=0;j<ver;j++)
           {
               cin>>mat[i][j][1];
           }
       }
       for(len=2;len<ver;len++)
       {
           for(k=0;k<ver;k++)
           {
               for(i=0;i<ver;i++)
               {
                   for(j=0;j<ver;j++)
                   {
                       if(mat[i][k][len-1]+mat[k][j][1]<mat[i][j][len])
                       {
                           mat[i][j][len]=mat[i][k][len-1]+mat[k][j][1];
                           next[i][j][len]=next[i][k][len-1];
                       }
                   }
               }
           }
       }
       if(mat[0][3][3]!=INF)
       {
           cout<<"Minimum Cost from 0 to 3,using exactly 3 pathlen is: "<<mat[0][3][3]<<endl;
           from=0;
           to=3;
           len=3;
           cout<<from;
           while(from!=to)
           {
               from=next[from][to][len--];
               cout<<"-->"<<from;
           }
       }
       else
           cout<<"No path"<<endl;
    }

    【讨论】:

      猜你喜欢
      • 2012-07-07
      • 2014-10-16
      • 2017-09-12
      • 2021-12-14
      • 2015-09-11
      • 2011-04-30
      • 1970-01-01
      • 2011-05-11
      • 2011-05-30
      相关资源
      最近更新 更多