zoukankan      html  css  js  c++  java
  • HDU

    有n个数字,你需要把这n个数字合成一个数字,每次只能把k个数字合并成一个,花费为这k个数字的和。

    给一个最大花费,问不超过这个最大花费的情况下,k的最小值。

    Sample Input
    1
    5 25
    1 2 3 4 5
    
    Sample Output
    3
    

    这个题很容易想到二分答案+优先队列check

    然而这样复杂度是 O(n logn*logn ),会TLE(这特么都会TLE?加个读入优化就过了)

    可以先给所有数字排个序,然后用两个队列,一个存原来的数字,一个存新合成的数字。

    所以两个队列都是有序的。每次取的时候比较那个队列的第一个数小,就从哪一个里面取。这样复杂度是O(nlogn)的。

    然后有一个坑点。你是要把n个数合并成一个,那么说你要减少n-1个数。每次只能减少 k-1 个数。

    那么当 (n-1) % (k-1) != 0 时,就一定不能正好最优合并,所以要添加 k-1 - (n-1)%(k-1) 个0,来补齐。

    开long long。否则就WA。很真实。

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <queue>
    #include <iostream>
    
    using namespace std;
    typedef long long LL;
    const int maxn =100000 +100;
    
    int T;
    int a[maxn];
    int n, p;
    
    bool check(int mid)
    {
        LL cost = 0;
        queue<LL> q1, q2;
    
        int t = (n-1) % (mid-1);
        if (t != 0)
            for (int i = 1; i <= mid-1-t; i++) q1.push(0);
    
        for (int i = 1; i <= n; i++) q1.push(a[i]);
    
        while(q1.size() + q2.size() > 1)
        {
            LL pp = 0;
            for (int i = 1; i <= mid; i++)
            {
                if (!q1.empty() && !q2.empty())
                {
                    if (q1.front() < q2.front()) pp += q1.front(), q1.pop();
                        else pp += q2.front(), q2.pop();
                }
                else if (!q1.empty()) pp+= q1.front(), q1.pop();
                else if (!q2.empty()) pp+= q2.front(), q2.pop();
                else break;
            }
            cost += pp;
            q2.push(pp);
        }
        return cost <= p;
    }
    
    int main()
    {
        int T;
        scanf("%d", &T);
        for (int t = 1; t <= T; t++)
        {
            scanf("%d%d", &n, &p);
            for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
            sort(a+1, a+1+n);
    
            int l = 2, r = n, ans;
            while(l <= r)
            {
                int mid = (l+r)/2;
                if (check(mid)) ans = mid, r = mid-1;
                    else l = mid+1;
            }
            printf("%d
    ", ans);
        }
    
    return 0;
    }
  • 相关阅读:
    JavaScript.how-to-debug-javascript
    iOS.mach_absolute_time
    Startup.国外新锐公司及其技术Blog
    Android.FamousBlogs
    iOS.PrototypeTools
    Android.API.Context.getFilesDir()
    Android.Tools.Ant
    Tools.OnlineAPIs
    Java.Class
    Android.StructureOfAndroidSourceCodeRootTree
  • 原文地址:https://www.cnblogs.com/ruthank/p/9530608.html
Copyright © 2011-2022 走看看