【问题标题】:Problems with Floyd-Warshall algorithm implementationFloyd-Warshall 算法实现的问题
【发布时间】:2015-01-22 20:06:35
【问题描述】:

我试图从INOI 2014 paper 中解决第二个问题,即。 FREETICKET 并使用 Floyd-Warshall 算法计算答案。我的代码在最后的子任务中似乎失败了,并且似乎为几个测试用例提供了 WA。代码如下:

#include <iostream>
#include <cstdio>
#include <climits>
#include <vector>
#include <algorithm>
using namespace std;

typedef vector<long long int> vl;
typedef vector<vl> vvl;

long long int maxelem(const vvl& arr)
{
     long long int max = 0, curmax;
     for(int i = 0, l = int(arr.size());i < l;i++)
     {
             curmax = *(max_element(arr[i].begin(), arr[i].end()));
             if(curmax > max)
             {
                  max = curmax;
             }
     }
     return max;
}

int main(void)
{
    long long int c, f, x, y, p;
    scanf("%lld%lld", &c, &f);
    vvl adj(c, vl(c, 26336));
    for(int i = 0;i < f;i++)
    {
         scanf("%lld%lld%lld", &x, &y, &p);
         adj[x-1][y-1] = p;
         adj[y-1][x-1] = p;           
    }
    long long int max = 0;
    for(int k = 0;k < c;k++)
    { 
            for(int i = 0;i < c;i++)
            {
                    for(int j = 0;j < i;j++)
                    {
                            adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]);        
                    }
                    for(int j = (i + 1);j < c;j++)
                    {
                           adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]);         
                    }      
            }
    }
    max = maxelem(adj);
    printf("%lld\n", max);
}

此代码仅使用邻接矩阵并确保该人不会尝试从同一个地方到同一个地方(在最内层循环中)。它未能解决子任务 3 中的一些子任务,并给我 50/100 分。谁能帮我找到我的代码中的错误?我什至尝试将数据类型更改为long long int's。(为了安全起见)。

【问题讨论】:

  • 第一个问题不是FREETICKET,你是说第二个问题吗?
  • @phamtrung 是的,我的错,这是第二个问题......

标签: c++ algorithm debugging


【解决方案1】:

您的算法的问题是:

for(int i = 0;i < f;i++)
{
      scanf("%lld%lld%lld", &x, &y, &p);
      adj[x-1][y-1] = p;
      adj[y-1][x-1] = p;           
}

应该是:

 for(int i = 0;i < f;i++)
 {
      scanf("%lld%lld%lld", &x, &y, &p);
      adj[x-1][y-1] = min(p, adj[x-1][y-1]);
      adj[y-1][x-1] = min(p, adj[y-1][x-1]);           
 }

因为如果a -> b城市之间有多条路线,我们只需要走最便宜的路线。

你还需要为所有0 &lt;= i &lt; c设置每个adj[i][i] = 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2016-01-18
    • 2018-11-11
    • 2011-02-10
    • 2014-06-28
    • 2014-07-18
    相关资源
    最近更新 更多