【发布时间】:2014-06-27 08:33:51
【问题描述】:
我的编程老师给了我这个问题,用 c 编写代码:
给定由 N 个整数 A 和一个数字 K 组成的数组。在一个回合中,选择所有 Ai 的最大值,我们称之为 MAX。那么艾=
MAX - Ai 是为每个 1 <= i <= N 完成的。帮助 Roman 找出 K 转后数组的样子。
输入
数字 N 和 K 在输入的第一行给出。然后在第二行给出 N 个整数,表示数组 A。
输出
在一行上输出 N 个数字。应该是K转后的数组A。
约束
* 1 <= N <= 10^5
* 0 <= K <= 10^9
* Ai does not exceed 2 * 10^9 by it's absolute value.
例子
Input:
4 1
5 -1 7 0
Output:
2 8 0 7
我解决这个问题的代码是:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
long int Max(long int *arr, int low, int high)
{
long int max,i;
max = arr[low];
for(i=0;i<=high;i++)
{
if(max<=arr[i])
max = arr[i];
}
return max;
}
/* Driver program to test above function */
int main()
{
long int max,*arr;
long int n,k,c1,c2,c3,i,j;
c1 = (long int)pow(10,5);
c2 = (long int)pow(10,9);
c3 = 2*c2;
scanf("%ld %ld",&n,&k);
if(n<1||n>c1)
exit(1);
else if(k<0||k>c2)
exit(1);
else
{
arr = (long int *)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
{
scanf("%ld",&arr[i]);
if(abs(arr[i])>c3)
exit(1);
}
if(k%2 == 0)
{
for(i=0;i<2;i++)
{
max = Max(arr, 0, n-1);
for(j=0;j<n;j++)
{
arr[j] = max-arr[j];
if(abs(arr[j])>c3)
exit(1);
}
}
}
else if(k%2 != 0)
{
max = Max(arr, 0, n-1);
for(j=0;j<n;j++)
{
arr[j] = max-arr[j];
/*if(abs(arr[j])>c3)
exit(1);*/
}
}
/* for(m=0;m<n;m++)
printf("%ld ",arr[m]);
printf("\n");*/
for(i=0;i<n;i++)
printf("%ld ",arr[i]);
printf("\n");
}
return 0;
}
我在ubuntu 的gcc 编译器上执行了这段代码,它在满足所有约束的情况下完美运行,但是当我将这段代码上传到有编译器并执行代码的老师门户上时,它说Runtime错误 -
nzec which means a non-zero exception which is used to signify that main() does not have "return 0;" statement or exception thrown by c++ compiler.
拜托,任何人都可以帮助我的代码有什么问题,因为有一个返回 0;我的代码中的声明。请帮忙。
每个人都指出了 exits 的多次使用...我可以使用任何其他方式代替 exit() 来减少它们吗?
【问题讨论】:
-
long int和int的大小不一定相同。 -
@Marco:但是如果我想退出代码,如果这些条件中的任何一个不满足,我该怎么办?我尝试使用不同的退出非零值,因为非零值的退出是异常终止,但仍然没有发生任何事情。是不是我们不能多次使用相同的值退出。
-
@JoachimIsaksson :我不明白你的评论。我知道 long int 和 int 的大小不同,所以这就是为什么我将所有变量声明为 long int 因为我必须检查问题中给出的约束值,这些值不能容纳在 int 中
-
是的,但您已将
arr设置为指向为n整数 分配的内存,而不是n长整数。这很可能会破坏内存并给出您遇到的错误。sizeof(int)sizeof(long int),也就是说,您分配的内存可能比您正在使用的要少。 -
这是来自codechef的问题。希望codechef不是你的老师codechef.com/MAY14/problems/CHEFBM
标签: c++ c arrays error-handling runtime