- 我
浙大数据结构编程作业PAT
-
错误原因
-
错误代码,Partially accepted
#include<stdio.h>
#include<stdlib.h>
int main(void){
int n;
int thisSum, maxSum;
int first, tempfirst, last;
//input data
scanf("%d\n", &n);
int *a = (int *)malloc(n*sizeof(int));
for(int i=0; i<n; i++){
scanf("%d", &a[i]);
getchar();
}
thisSum = maxSum = 0;
tempfirst = first = a[0];
last = a[n-1];
for(int i=0; i<n; i++){
thisSum += a[i];
if(thisSum > maxSum){
first = tempfirst;
last = a[i];
maxSum = thisSum;
}
if(thisSum < 0){
if(i+1<n)
tempfirst = a[i+1];
thisSum = 0;
}
}
printf("%d %d %d", maxSum, first, last);
return 0;
}
- Accepted
#include<stdio.h>
#include<stdlib.h>
int main(void){
int n;
int thisSum, maxSum;
int first, tempfirst, last;
//input data
scanf("%d\n", &n);
int *a = (int *)malloc(n*sizeof(int));
for(int i=0; i<n; i++){
scanf("%d", &a[i]);
getchar();
}
thisSum = 0;
maxSum = -1;
tempfirst = first = a[0];
last = a[n-1];
for(int i=0; i<n; i++){
thisSum += a[i];
if(thisSum > maxSum){
first = tempfirst;
last = a[i];
maxSum = thisSum;
}
if(thisSum < 0){
if(i+1<n)
tempfirst = a[i+1];
thisSum = 0;
}
}
if(maxSum<0)
printf("0 %d %d", first, last);
else
printf("%d %d %d", maxSum, first, last);
return 0;
}