簡體   English   中英

Floyd-Warshall算法實現存在的問題

[英]Problems with Floyd-Warshall algorithm implementation

我試圖解決INOI 2014論文中的第二個問題,即。 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 。(為了安全起見)。

您的算法問題是:

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 <= i < c設置每個adj[i][i] = 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM