LSU——1116 Necklace(尺取)

1116 Necklace

通过率:5/23 难度系数:0
时间限制:1000ms 内存限制:32000KB java 两倍。

介绍

Little King has a beautiful pearl necklace, one day, he find that there is a number in each pearl, so he want to know whether he can find a continuous sequence that the sum of them is the number he give to you.

输入格式描述

The first line contains one integer T(T<=50),indicating the number of test cases.

For each test case ,the first line contains two integer N(5<=N<=100000),K(1<=K<=109)(within int),indicating there are N pearls in necklace and the number he give to you .The second line contains N integer Ai(1<=Ai<=10000),indicating the number in each pearl, pearls are sort by clockwise.

输出格式描述

For each test case, if he can find out print YES, otherwise print NO.

样例输入
样例输出
 
3
5 15
1 2 3 4 5
5 16
1 2 3 4 5
6 18
1 2 3 4 5 7

YES
NO
YES

突然想起来同学学校的题目我还没写。刚开始纠结于第三个例子,后来问了同学才想起来这是个项链,这坑会造成数组越界,稍微处理一下。怎么把cin同步关掉快scanf这么多,奇怪

代码:

#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<sstream>
#include<cstring>
#include<cstdio>
#include<string>
#include<deque>
#include<cmath>
#include<queue>
#include<set>
#include<map>
using namespace std;
int list[300010];
int main (void)
{
	ios::sync_with_stdio(false);
	int t,i,j,n,s;
	cin>>t;
	while (t--)	
	{
		memset(list,0,sizeof(list));
		cin>>n>>s;
		for (i=1; i<=n; i++)
		{
			cin>>list[i];
			list[n+i]=list[i];
		}
		bool flag=false;
		int l=1,r=1,temp=0;
		while (1)
		{
			while (temp<s&&r<=2*n)
			{
				temp+=list[r++];
			}
			if(temp<s)
				break;			
			if(temp==s&&r-l<=n)
			{
				flag=true;
				break;
			}
			temp-=list[l++];
			if(temp==s&&r-l<=n)
			{
				flag=true;
				break;
			}			
		}
		if(flag)
			cout<<"YES"<<endl;
		else
			cout<<"NO"<<endl;
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/Blackops/p/5397080.html