1044. Shopping in Mars

来源:互联网 发布:贵定浪人网络客服 编辑:程序博客网 时间:2024/04/28 21:55

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;elseselectChain();return 0;}


原创粉丝点击