gpt4 book ai didi

C 代码给出不同的输出

转载 作者:行者123 更新时间:2023-11-30 19:33:04 24 4
gpt4 key购买 nike

我正在尝试解决 Code Forces 中的问题 — http://codeforces.com/problemset/problem/680/B 。我已经在本地解决了这个问题,但是当我将其上传到 Code Forces 时,它给出了不同的输出。

目前,这是我的代码:

#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

但是,在 codeforces 中,会发生以下情况:

输入

6 3
1 1 1 0 1 0

输出

1998776724

回答

3

都是相同的代码。为什么会出现这种情况?

最佳答案

您的算法不太正确。

在这一行

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];

再次运行你的程序,你就会看到会发生什么。

关于C 代码给出不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46399094/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com