1 solutions

  • 2
    @ 2025-10-4 8:25:53

    题解

    很容易发现答案具有单调性,由此想到二分答案,此题主要难点在于check。

    很多人第一反应为排序后,每栋楼贪心取最小的能放的积木。

    但这个贪心是错的,对于

    6 3  
    1 2 4 8 8 16 
    

    这组数据,这种贪心只能搭建一个高塔楼(1,2,4)(1,2,4),剩下的(8,8,16)(8,8,16)则无法搭第二个。

    但事实上,可以(1,4,8)(1,4,8)一组,(2,8,16)(2,8,16)一组就能搭两个高塔。

    因此考虑更换贪心策略。考虑二分高塔数的的情况下,一层一层贪心搭建,每次对于每个高塔的这一层找到能放的最小积木。

    标程

    #include<bits/stdc++.h>
    #define MAXN 200010
    using namespace std;
    int n, k;
    long long a[MAXN], b[MAXN];
    bool check(int cnt){
        for(int i = 1; i <= cnt; ++i){ 
            b[i] = 0;
        }
        for(int id = 0,i = 1; i <= k; ++i){
            for(int j = 1; j <= cnt; ++j){
                while(a[++id] < b[j] * 2){
                    if (id > n) {
                        return 0;
                    }
                }
                b[j] = a[id];
            }
        }
        return 1;
    }
    int main(){
        scanf("%d%d", &n, &k);
        for(int i = 1; i <= n; ++i){ 
            scanf("%d", &a[i]);
        }
        sort(a + 1, a + n + 1);
        a[n + 1] = 0;
        int l = 0, r = n, ans;
        while(l <= r){
            int mid = (l + r) >> 1;
            if (check(mid)){ 
                l = mid + 1;
                ans = mid;
            } else { 
                r = mid - 1;
            }
        }
        printf("%d\n", ans);
        return 0;
    }
    
    • 1

    Information

    ID
    49
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    9
    Tags
    (None)
    # Submissions
    13
    Accepted
    4
    Uploaded By