zoukankan      html  css  js  c++  java
  • 1124 咸鱼魔法记(“玲珑杯”线上赛 Round #15 河南专场)

    题目链接:http://ifrog.cc/acm/problem/1124

    这道题两种思路

    • 1.二分答案加O(n)判断
    • 2.直接O(n)尺取法,尺取出最大答案

    二分代码:

    #include<bits/stdc++.h>
    using namespace std;
    
    int arr[1000007];
    int n, k;
    
    bool judge(int x)
    {
        int res = 0;
        for(int i=0; i<x; ++ i)
            res += arr[i];
        if(res + k >= x)
            return true;
        for(int i=x; i<n; ++ i)
        {
            res += arr[i] - arr[i-x];
            if(res + k >= x)
                return true;
        }
        return false;
    }
    
    int main()
    {
        while(scanf("%d%d", &n, &k) != EOF)
        {
            for(int i=0; i<n; ++ i)
                scanf("%d", &arr[i]);
            int b = 0, e = n;
            while(b < e)
            {
                int mid = b + (e - b + 1) / 2;
                if(judge(mid))
                    b = mid;
                else
                    e = mid - 1;
            }
            printf("%d
    ", b);
        }
        return 0;
    }
    

    尺取代码如下:

    #include<bits/stdc++.h>
    using namespace std;
    
    
    int arr[300007];
    int main()
    {
        int n, k;
        while(scanf("%d%d", &n, &k)!=EOF)
        {
            for(int i=1; i<=n; ++ i)
                scanf("%d", &arr[i]);
    
            int mx = 0;
            if(k == 0)
            {
                int res = 0;
                for(int i=1; i<=n; ++ i)
                {
                    if(arr[i] == 1)
                        res ++;
                    else
                    {
                        mx = max(mx, res);
                        res = 0;
                    }
                }
                printf("%d
    ", res);
                continue;
            }
    
            for(int b = 1, e = 0, res = 0; b <= n;)
            {
                while(e+1 <= n && res + (arr[e + 1] == 0) <= k)
                    res += (arr[++ e] == 0);
    
                mx = max(mx, e - b + 1);
                if(e + 1 > n)
                    break;
                while(res == k && b <= e)
                {
                    res -= (arr[b ++] == 0);
                    if(res < k)
                        break;
                }
            }
            printf("%d
    ", mx);
        }
        return 0;
    }
    
    
  • 相关阅读:
    redis事务
    redis杂项
    redis的发布订阅
    redis持久化
    redis常用配置参考.txt
    python语法流程控制
    用户交互与数据类型
    编程语言与Python介绍
    计算机的五大组成部分
    jieba库的基本介绍及爬虫基本操作
  • 原文地址:https://www.cnblogs.com/aiterator/p/6924711.html
Copyright © 2011-2022 走看看