一.题目链接:
HDU-5884
二.题目大意:
给出 n 个数 和 一个数 t.
求最小的 k 值,使得这 n 个数对应的 k 叉哈弗曼树的 wpl 不大于 t.
三.分析:
二分 k 即可.
如果直接用优先队列模拟会 T.
这里用数组模拟.
详见代码.
四.代码实现:
#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define eps 1e-8
#define lc k * 2
#define rc k * 2 + 1
#define pi acos(-1.0)
#define ll long long
#define ull unsigned long long
using namespace std;
const int M = (int)1e6;
const int mod = 99991;
const int inf = 0x3f3f3f3f;
int n, t;
int a[M + 5];
int b[M + 5];
int cnt, sum, w, aidx, bidx, blen;
bool check(int k)
{
cnt = n, sum = aidx = bidx = blen = 0;
while((cnt - 1) % (k - 1)) ++cnt, b[blen++] = 0;
while(aidx != n || blen - bidx != 1)
{
w = 0;
for(int i = 0; i < k; ++i)
{
if(aidx == n) w += b[bidx++];
else if(bidx == blen) w += a[aidx++];
else if(b[bidx] < a[aidx]) w += b[bidx++];
else w += a[aidx++];
}
sum += w;
if(sum > t)
return 0;
b[blen++] = w;
}
return 1;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
scanf("%d %d", &n, &t);
for(int i = 0; i < n; ++i)
scanf("%d", &a[i]);
sort(a, a + n);
int l = 2, r = n, mid;
while(l < r)
{
mid = (l + r) >> 1;
if(check(mid))
r = mid;
else
l = mid + 1;
}
printf("%d\n", r);
}
return 0;
}