zoukankan      html  css  js  c++  java
  • Subsequence(二分)

    A sequence of N positive integers (10 < N < 100 000), each of them less than or equal 10000, and a positive integer S (S < 100 000 000) are given. Write a program to find the minimal length of the subsequence of consecutive elements of the sequence, the sum of which is greater than or equal to S.

    Input

    The first line is the number of test cases. For each test case the program has to read the numbers N and S, separated by an interval, from the first line. The numbers of the sequence are given in the second line of the test case, separated by intervals. The input will finish with the end of file.

    Output

    For each the case the program has to print the result on separate line of the output file.if no answer, print 0.

    Sample Input

    2
    10 15
    5 1 3 5 10 7 4 9 2 8
    5 11
    1 2 3 4 5

    Sample Output

    2
    3

    一开始c++交不过,g++过,原来是int 输入的时候是long long,wa了,g++交没这个问题

    代码:

    #include<cstdio>
    #include<iostream>
    #include<algorithm>
    #include<cstring>
    #include<map>
    #include<set>
    #include<stack>
    #include<queue>
    #include<cmath>
    
    const int maxn=1e5+5;
    typedef long long ll;
    using namespace std;
    ll a[maxn];
    ll s[maxn];
    ll n,ss;
    bool check(int x)
    {
        if(x>=n)
        {
        	return true;
    	}
    	for(int t=x;t<=n;t++)
    	{
    //		cout<<s[t]<<" "<<s[t-x+1]<<endl;
    		if(s[t]-s[t-x+1]>=ss)
    		{
    			
    			return true;
    		}
    	}
    	return false;
    }
    int  main()
    {
    	int  T;
    	cin>>T;
    	while(T--)
    	{
    		scanf("%lld%lld",&n,&ss);
    		for(int t=1;t<=n;t++)
    		{
    			scanf("%lld",&a[t]);
    		}
    		memset(s,0,sizeof(s));
    		for(int t=1;t<=n;t++)
    		{
    			s[t]=s[t-1]+a[t];
    		}
    		if(s[n]<ss)
    		{
    			cout<<"0"<<endl;
    	    }
    	    else
    	    {
    		int l=0,r=100000;
    		int mid;
    		while(l<=r)
    		{
    			mid=(l+r)/2;
    			if(check(mid))
    			{
    		      r=mid-1;
    			}
    			else
    			{
    			  l=mid+1;
    			}
    		}
    		mid=(l+r)/2;
    		cout<<mid<<endl;
    	   }
    	}
    	
    	return 0;
    }
  • 相关阅读:
    【ansible】 笔记 (1)
    centos 把网卡名称修改为 eth0
    服务器从购买到交付使用流程
    (转载) Linux IO模式及 select、poll、epoll详解
    孤儿进程、僵尸进程和守护进程
    (转载)linux下各个文件夹的作用
    缓存穿透与缓存雪崩
    SpringCloud核心组件在微服务架构中的作用
    双十一电商Java开发聊聊秒杀限流的多种实现
    localhost 和 127.0.0.1 的区别
  • 原文地址:https://www.cnblogs.com/Staceyacm/p/10781772.html
Copyright © 2011-2022 走看看