簡體   English   中英

無法弄清楚我的程序在spoj上給出運行時錯誤但在ideone上給出運行時錯誤的原因

[英]Can't figure out the reason why my program is giving runtime error on spoj but not on ideone

我正在解決spoj上的老鼠和迷宮的問題http://www.spoj.com/problems/MICEMAZE/我正在使用一種簡單的遞歸方法,因為約束很小。

我的代碼在ideone上運行沒有任何錯誤,但在spoj上卻給出了運行時錯誤(分段錯誤)。 我無法在我的代碼中找出問題。

這是我的C ++程序,我使用鄰接表來表示圖形。

#include<iostream>
#include<vector>
#include<climits>
using namespace std;
vector<pair<int,int> > graph[100];  //adjacency list , pair stores the destination node of an edge and its weight
int e,t,n,count=0,cost,visited[105];

void maze(int v,int c) //recurssive routine which checks the cost of travelling to each node until it finds the exit node.
{
    if(c>t)
        return;
    if(v==e)
    {
        if(c<=cost)
            cost=c;
        return;
    }
    for(int i=0;i<graph[v].size();i++)
    {
        if(!visited[graph[v][i].first])
        {
            visited[graph[v][i].first]=1;
            maze(graph[v][i].first,graph[v][i].second+c);
            visited[graph[v][i].first]=0;
        }
    }

}

int main()
{
    int a,b,w,m;
    cin>>n;
    cin>>e;
    cin>>t;
    cin>>m;
    for(int i=0;i<m;i++)
    {
        cin>>a;
        cin>>b;
        cin>>w;
        graph[a].push_back(make_pair(b,w));
    }
    for(int i=1;i<=n;i++)
    {
        cost=INT_MAX;
        if(!visited[i])
        {
            visited[i]=1;
            maze(i,0);
            visited[i]=0;
        }
        if(cost<=t)
            count++;
    }
    cout<<count;
    return 0;
}

您將在第二個循環中從1轉到n。 如果n為105,則您的程序將出現分段錯誤。

您需要從0到104(i = 0; i <n)。

您運行maze(i,0); i1n包括1n變化,但是如果n等於100 ,則在訪問graph[v]時將超出graph范圍。

但是即使您解決了這個問題,也會遇到時間限制錯誤,因為盡管約束很小,但是您可以有效地檢查圖中給定長度的所有可能路徑,這大約是O(n!)復雜性。

很難說清楚為什么在一個系統上可以運行,而在另一個系統上卻沒有更多信息。 我的猜測是:內存超出。 請注意,在您的情況下,SPOJ之類的練習頁面通常也會提供內存限制。 他們寫道N <= 100,所以您可以使數組固定,因為100不是很大,但是他們沒有給您M的限制! 我敢打賭,他們為M准備了數量龐大的棘手輸入。在這種情況下,由於重新分配(矢量,Google的管理是殺手(谷歌提供更多信息,或在此處查看), std :: vector是否*在容量增加時可以移動對象?分配器可以“重新分配”嗎? )。

暫無
暫無

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

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