[英]C code gives different output
I'm trying to solve a problem in Code Forces — http://codeforces.com/problemset/problem/680/B .我正在尝试解决 Code Forces 中的一个问题——http: //codeforces.com/problemset/problem/680/B 。 I've already solved it locally, but when I upload it to Code Forces it gives different output.我已经在本地解决了它,但是当我将它上传到 Code Forces 时,它给出了不同的输出。
Currently, this is my code:目前,这是我的代码:
#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;
}
In my console, I enter the following input:在我的控制台中,我输入以下输入:
6 3
1 1 1 0 1 0
and the output is:输出是:
3
However, in codeforces, the following happens:但是,在 codeforces 中,会发生以下情况:
Input输入
6 3
1 1 1 0 1 0
Output输出
1998776724
Answer回答
3
It is all the same code.都是一样的代码。 Why does this happen?为什么会发生这种情况?
Your algorithm isn't quite correct.你的算法不太正确。
At this line在这一行
l = pos - i;
l
becomes smaller than 1 at some point and therefore you access cities out of bounds which is undefined behaviour. l
在某些时候变得小于 1,因此您可以越界访问城市,这是未定义的行为。
Modify like this:修改成这样:
#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];
Run your program again and you'll see what happens.再次运行你的程序,你会看到会发生什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.