zoukankan      html  css  js  c++  java
  • 【二分答案nlogn/标解O(n)】【UVA1121】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 

    Many test cases will be given. 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 there isn't such a subsequence, print 0 on a line by itself.

    Sample Input 

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

    Sample Output 

    2 
    3


    n个正整数组成一个序列。给定整数S,求长度最短的连续序列,使它们的和大于或等于S

    【输入格式】

    输入包含多组数据。每组数据的第一行为整数nS(10<n≤100 000,S<109);第二行为n个正整数,均不超过10 000。输入结束标志为文件结束符(EOF)。

    【输出格式】

    对于每组数据,输出满足条件的最短序列的长度。如果不存在,输出0。


    二分答案(即序列长度)+前缀和可以轻松搞定

    复杂度为O(n*logn)

    (这个方法可以解决数可能为负数的数据,所以也是一种值得记忆的方法)

    #include <cstdio>  
    #include <cstdlib>  
    #include <cmath>  
    #include <cstring>  
    #include <ctime>  
    #include <algorithm>  
    #include <iostream>
    #include <sstream>
    #include <string>
    #define oo 0x13131313   
    using namespace std;
    int n,S;
    int A[100010];
    int ans;
    int OK(int m)
    {
    	if(S==0) return 1;
    	int temp=0;
    	for(int i=1;i<=n-(m-1);i++)
    	{
    		temp=A[i+(m-1)]-A[i-1];
    		if(S<=temp) return 1;
    	}
    	return 0;
    }
    void solve()
    {
    	ans=0;
    	int l=1,r=n;
    	int m=(l+r)/2;
    	while(l<r)
    	{		
    		if(OK(m)) r=m;
    		else l=m+1;
    		m=(l+r)/2;
    	}
    	ans=m;
    }
    void input()
    {
    	for(int i=1;i<=n;i++)
    		{
    			scanf("%d",&A[i]);
    			A[i]=A[i-1]+A[i];
    		}
    }
    int main()
    {
    	while(scanf("%d%d",&n,&S)!=EOF)
    	{
    		input();
    		solve();
    		if(ans!=n)
    		printf("%d
    ",ans);
    		else if(A[n]<S)
    		{
    			printf("0
    ");
    		}
    		else printf("%d
    ",n);
    	}
    	return 0;
    }
      


  • 相关阅读:
    进程
    并发编程小结
    操作系统发展史
    基于socketsever实现并发的socket编程
    UDP套接字
    粘包问题及解决
    socket套接字编程
    TCP协议与三次握手四次挥手
    OSI七层协议
    互联网的组成
  • 原文地址:https://www.cnblogs.com/zy691357966/p/5480449.html
Copyright © 2011-2022 走看看