POJ3061Subsequence

题目链接:POJ3061


其实按道理来说这个题算是简单题了,为了好好总结这类思想,写个题解给自己留着


题意:给定n个数,一个数M

求连续的x个数的和不小于M的,最小的x


拿head和tail来扫描一遍就好

head往前走,走到当前区间的sum值大于等于M,然后记录下答案

tail再往前走,将区间缩小,直到当前区间的sum小于M,每走一格,都记录下答案

这样循环下去,直到遍历完整个数组


这个题有个坑,是要注意无解的情况!

所有的数加起来,都不够M的话,输出0


int t,n,m,ans;
int x[maxn];

void calc(){
	int head=1,tail=0;
	int sum=0;
	while(tail<=n){
		while(tail<=n){
			tail++;
			sum+=x[tail];
			if (sum>=m) break;
		}
		if (sum>=m) ans=min(ans,tail-head+1);
		while(sum>=m){
			sum-=x[head];
			head++;
			if (sum>=m) ans=min(ans,tail-head+1);
		}
	}
}

int main(){
	//input;
	scanf("%d",&t);
	while(t--){
		memset(x,0,sizeof(x));
		scanf("%d%d",&n,&m);
		ans=n+1;
		for(int i=1;i<=n;i++) scanf("%d",&x[i]);
		calc();
		if (ans==n+1) cout<<0<<endl;
		else cout<<ans<<endl;
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值