2017-09-25 5 views
-1

コードフォースの問題を解決しようとしています - http://codeforces.com/problemset/problem/680/B。私はすでにローカルで解決していますが、コードフォースにアップロードすると、別の出力が得られます。Cコードの出力が異なります

は現在、これは私のコードです:私のコンソールで

#include <stdio.h> 

int main() 
{ 
    int q, pos; 
    scanf("%i %i", &q, &pos); 
    int cities[q]; 
    int criminal_count = 0; 
    //the greatest distance is naturally the number of cities 
    int criminals_by_dist[q]; 
    for (int i = 0; i < q; ++i) 
     criminals_by_dist[i] = 0; 

    for (int i = 0; i < q; ++i) 
     scanf("%i", &cities[i]); 

    //now we have the cites, lets count 
    //first the centre 
    if (cities[pos - 1] > 0) 
     criminals_by_dist[0]++; 
    int l = 0, r = 0; 
    for (int i = 1; i < q; ++i) 
    { 
     //count how many on the left of current position 
     //first check if it is not out of range 
     l = pos - i; 
     if (l >= 0) 
      criminals_by_dist[i] += cities[l - 1]; 
     //same with the right 
     //first check if it is not out of range 
     r = pos + i; 
     if (r < q) 
      criminals_by_dist[i] += cities[r - 1]; 
    } 

    //count how many criminals can be secured in a particular city 
    //the centre is always confirmed because there is only one centre 
    criminal_count += criminals_by_dist[0]; 
    int current = 0; 
    for (int i = 1; i < q; ++i) 
    { 
     current = criminals_by_dist[i]; 
     if ((current == 2 || (pos - i - 1 >= 0 != pos + i - 1 < q))) 
      criminal_count += current; 
    } 
    printf("%i", criminal_count); 
    return 0; 
} 

、私は次の入力に入力します。

6 3 
1 1 1 0 1 0 

をし、出力は次のようになります。

3 

しかし、中にコードフォースでは、次のようになります。

入力

6 3 
1 1 1 0 1 0 

出力

1998776724 

回答

3 

それはすべて同じコードです。なぜこれが起こるのですか?

+0

あなたのコードが何をすべきか説明してください。 – Yunnosch

+3

if(l> = 0)criminals_by_dist [i] + = cities [l-1];が間違っています。もし 'l == 0'ならば?それでは 'l - 1'は何ですか?後で同じループにある 'r'と同じこと。 –

+1

'if(1> = 0)criminals_by_dist [i] + = cities [l-1];'はアクセス不能に繋がります。 –

答えて

0

アルゴリズムが正しくありません。このライン

l = pos - i; 

l

は、いくつかの点で1よりも小さくなり、したがって、あなたは未定義の動作である範囲外の都市へのアクセス。

このような修正:

#include <assert.h> 
... 
//count how many on the left of current position 
//first check if it is not out of range 
l = pos - i; 
assert(l > 0);        // <<< add this line 
if (l >= 0) 
    criminals_by_dist[i] += cities[l - 1]; 

は、もう一度プログラムを実行し、あなたは何が起こるかわかります。

関連する問題