Codeforces 279B books

来源:互联网 发布:淘宝新开店铺旺旺采集 编辑:程序博客网 时间:2024/05/17 06:54


题目链接

题意:求数组中某一区间数值和不大于t的区间最大长度。

思路1 模拟 起始先固定左端点,找右边端点,然后移动左端点

#include <iostream>#include <stdio.h>#include <algorithm>#include <string.h>using namespace std;const int maxn = 100005;int a[maxn] ;int main(){    int t , Max , Left , n , Sum ;    while(scanf("%d%d" , &n , &t) != EOF)    {        Left = 1 , Max = 0 , Sum = 0;        for(int i = 1 ; i <= n ; i ++)        {            scanf("%d" , &a[i]) ;            Sum += a[i] ;            while(Sum > t)            {                Sum -= a[Left] ;                Left ++ ;            }            Max = max(Max , i - Left + 1) ;        }        printf("%d\n" , Max) ;    }    return 0;}

思路2 移动左端点二分查找右端点

#include <iostream>#include <stdio.h>#include <algorithm>#include <string.h>using namespace std;const int maxn = 100005;int a[maxn] ;int main(){    int t , Max , Left , n ,Right , Mid , Max1 ;    while(scanf("%d%d" , &n , &t) != EOF)    {        a[0] = 0 ;        for (int i = 1 ; i <= n ; i ++)        {            scanf("%d" , &a[i]) ;            a[i] += a[i-1] ;        }        Max = 0 , Max1 = 0 ;        for(int i = 0 ; i < n ; i ++)        {            Left = i+1 , Right = n ;            while(Left <= Right)            {                 Mid = (Left + Right)/2 ;                if(a[Mid] - a[i] <= t)                    Left = Mid + 1 ;                else Right = Mid - 1 ;            }           Max = max(Left - i  , Max) ;          // Max1 = max(Mid - i , Max1) ;           //printf("i=%d L=%d M=%d , Mid=%d MAX1=%d\n" ,i , Left , Max , Mid , Max1) ;        }        printf("%d\n" , Max - 1) ;    }    return 0;}



0 0
原创粉丝点击