Gym 101194D Ice Cream Tower (二分查找 + 貪心)


 

用貪心判斷當前個數是否成立, 然后二分查找搜答案

 

#include<bits/stdc++.h>
using namespace std;
#define INF ox3f3f3f3f
#define LLU unsigned long long
#pragma GCC optimize(3,"Ofast","inline")
const LLU maxn = 3e5 + 10;
LLU a[maxn],b[maxn];
LLU n, k;
bool check(LLU mid)
{

    for(int i = 0; i < mid; i++)
        b[i] = a[i];

    LLU x = 1,j = 0;
    for(int i = mid; i < n; i++)
    {
        if(a[i] >= b[j] * 2)
        {
            b[j++] = a[i];
            if(j >= mid)
            {
                ++x;
                j = 0;
            }
        }
    }
    return x >= k;
}


int main()
{

#ifndef ONLINE_JUDGE
    freopen("in.txt", "r",stdin);
    freopen("out.txt", "w",stdout);
#endif // ONLINE_JUDGE
    int T;
    cin >> T;
    for(int t = 1; t <= T; t++)
    {
        LLU ans = 0;
        printf("Case #%d: ", t);
        cin >> n >> k;
        for(LLU i = 0; i < n; i++)
            scanf("%lld", &a[i]);
        sort(a, a + n);

        int l = 0, r = n + 1, mid;
        while(l < r - 1)
        {
            mid = (l + r) / 2;
            if(check(mid))
                l = mid;
            else
                r = mid;
        }
        printf("%d\n",l);
    }
}

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com