PAT 1007_部分正确_已解决

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

typedef struct{
	int s;
	int e;
	int sum;
}seq;

int main(){
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
	int n,i,num[10010];
	scanf("%d",&n);
	seq max;
	max.sum = 0;
	

	int curSum = 0;
	int start = 0,end;

	for(i=0;i<n;i++){
		int input;
		scanf("%d",&input);
		num[i] = input;

		

		if(input<0){			
			if(curSum > max.sum){
				 max.sum = curSum;
				 max.s = start;
				 max.e = end;
			}
			if(curSum + input>0){
				curSum += input;
				end = i;
			}else{
				curSum = 0;
				start = i+1;
			}
			continue;		
		}
		else{
			end = i;
			curSum += input;
		}		
	}
	//如果最后一个是正数,又得检查一次
	if(curSum > max.sum){
				max.sum = curSum;
				max.s = start;
				max.e = end;
	}
	if(max.sum == 0){
		max.s = 0;
		max.e = n-1;
	}

	printf("%d %d %d",max.sum,num[max.s],num[max.e]);
	return 0;
}

1,漏了这种情况: 3 4 0 应该输出 7 3 4, 那个0不能包含进最小序列

2,,题干中: If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

漏了只有负数和0的情况,如-1 0 0 -1应该输出0 0 0

正确代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

typedef struct{
	int s;
	int e;
	int sum;
}seq;

int main(){
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
	int n,i,num[10010];
	scanf("%d",&n);
	seq max;
	max.sum = 0;
	

	int curSum = 0;
	int start = 0,end;
	int firstZeroFlag = 0;

	for(i=0;i<n;i++){
		int input;
		scanf("%d",&input);
		num[i] = input;

		

		if(input<0){			
			if(curSum > max.sum){
				 max.sum = curSum;
				 max.s = start;
				 max.e = end;
			}
			if(curSum + input>0){
				curSum += input;
				end = i;
			}else{
				curSum = 0;
				start = i+1;
			}	
		}
		else if(input>0){
			end = i;
			curSum += input;
		}
		//input如果为0,什么都不用做,除非这种情况:-1 0 0 -1
		else if(input ==0 && !firstZeroFlag){
			firstZeroFlag = 1;
		}

	}
	//如果最后一个是正数,又得检查一次
	if(curSum > max.sum){
				max.sum = curSum;
				max.s = start;
				max.e = end;
	}
	

	if(max.sum > 0){
		printf("%d %d %d",max.sum,num[max.s],num[max.e]);
	}
	//全是负数
	else if(max.sum == 0 && firstZeroFlag == 0){
		printf("0 %d %d",num[0],num[n-1]);	
	}
	//有0存在,其余全是负数
	else if(max.sum == 0 && firstZeroFlag == 1){
		printf("0 0 0");
	}

	return 0;
}


转载于:https://my.oschina.net/kaneiqi/blog/201253

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值