1044. Shopping in Mars

Two points (proposed to be low and high )both start to point the begining of the array,

If current subsequence sum is more than the need sum,low++;

If current subsequence sum is less than the need sum,high++;

If current subsequence sum is equal to  the need sum,print the current subsequence;

At the end,if we can't find the corresponding result is equal to the need sum,just find the minimum sum(minimumMax) of the subsequence which is more than the need sum.

Then,search the subsequence which is equal to minimumMax as previously described.

// 1044. Shopping in Mars.cpp: 主项目文件。

#include "stdafx.h"
#include <cstdio>

const int INF=0x7fffffff;
const int N=100003;
int diamond[N];
int arrNum,needSum;

bool selectChain(){
	bool tag=false;
	int low=0,high=0,minimumMax=INF,curSum=diamond[low];
	while(low<arrNum&&high<arrNum&&low<=high){
		if(curSum>needSum){
			if(curSum<minimumMax)
				minimumMax=curSum;
		}
		if(low==high&&curSum>needSum){
			low++,high++;
			curSum=diamond[low];
			continue;
		}
		if(curSum==needSum){
			tag=true;
			printf("%d-%d\n",low+1,high+1);
			curSum=curSum-diamond[low++]+diamond[++high];
		}
		else if(curSum<needSum){
			high++;
			curSum+=diamond[high];
		}
		else{
			curSum-=diamond[low];
			low++;
		}
	}
	needSum=minimumMax;
	return tag;
}

int main()
{
	scanf("%d%d",&arrNum,&needSum);
	for(int i=0;i<arrNum;i++)
		scanf("%d",diamond+i);
	bool tag=selectChain();
	if(tag)
		return 0;
	else
		selectChain();
	return 0;
}


转载于:https://www.cnblogs.com/cjweffort/archive/2013/03/13/3374847.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值