日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

【HDU - 5884】Sort(k叉哈夫曼树,优化tricks,两个队列代替优先队列)

發布時間:2023/12/10 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【HDU - 5884】Sort(k叉哈夫曼树,优化tricks,两个队列代替优先队列) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題干:

Recently, Bob has just learnt a naive sorting algorithm: merge sort. Now, Bob receives a task from Alice.?
Alice will give Bob?NN?sorted sequences, and the?ii-th sequence includes?aiai?elements. Bob need to merge all of these sequences. He can write a program, which can merge no more than?kk?sequences in one time. The cost of a merging operation is the sum of the length of these sequences. Unfortunately, Alice allows this program to use no more than?TT?cost. So Bob wants to know the smallest?kk?to make the program complete in time.

Input

The first line of input contains an integer?t0t0, the number of test cases.?t0t0?test cases follow.?
For each test case, the first line consists two integers?N?(2≤N≤100000)N?(2≤N≤100000)?and?T?(∑Ni=1ai<T<231)T?(∑i=1Nai<T<231).?
In the next line there are?NN?integers?a1,a2,a3,...,aN(?i,0≤ai≤1000)a1,a2,a3,...,aN(?i,0≤ai≤1000).

Output

For each test cases, output the smallest?kk.

Sample Input

1 5 25 1 2 3 4 5

Sample Output

3

題目大意:

有n個數,每個數有個值,現在你可以選擇每次K個數合并,合并的消耗為這K個數的權值和,問在合并為只有1個數的時候,總消耗不超過T的情況下,最小的K是多少

解題報告:

首先能想到的做法,二分一個K,然后check的時候按照標準k叉哈夫曼樹的做法,搞個優先隊列,別忘補0(通過n%(k-1)==1這個判斷條件不斷n++),但是這個做法是nlognlogn的。現在考慮優化:

首先如果是2叉哈夫曼樹:

可以設兩個數組,一個存放排序后的原數據,一個存放每次相加后的值。對于取之也有幾種分析:

1.全部來源于a,此時q為空或者q的隊頭的元素比a的前兩個元素都小.

2.全部來源于b,此時a為空或者a的隊頭的元素比b的前兩個元素都小.

3.a和b中各取一個.

對于k叉:

就一個一個的取,一共取k次,每次取的時候就在兩個數組中選一個小的就行了

AC代碼:

#include<iostream> #include<cstdio> #include<algorithm> #include<cmath> #include<cstring> #include<queue> #include<stack> #include<map> #include<set> #include<string> #include<vector> #define mod (1000000007) using namespace std; typedef long long ll; int a[200010]; int c[200010]; int b[200010]; int T; int cal(int n,int k) {int i=1;int b1=0,cnt=0;int x=0;int ans=0;int add=0,y=k;if(k!=2) {while((n+add)%(k-1)!=1) add++;}for(int j=n; j>=1; j--) c[j+add]=a[j];for(int j=add; j>=1; j--) c[j]=0;n+=add;while(true) {int x=0;int ad=0;while((i<=n||b1<cnt)&&x<k) {if(i>n) {ad+=b[b1];ans+=b[b1];b1++;} else if(b1>=cnt) {ad+=c[i];ans+=c[i];i++;} else {if(c[i]<b[b1]) {ad+=c[i];ans+=c[i];i++;} else {ad+=b[b1];ans+=b[b1];b1++;}}x++;}if(i>n&&b1>=cnt) {break;}b[cnt++]=ad;}return ans; } int main() {int t;cin>>t;while(t--) {int n;scanf("%d%d",&n,&T);for(int i=1; i<=n; i++) scanf("%d",&a[i]);sort(a+1,a+1+n);int l=2,r=n;int ans;while(l<=r) {int mid=(l+r)/2;if(cal(n,mid)<=T) r=mid-1, ans=mid;else l=mid+1;}printf("%d\n",ans);}return 0; }

?

總結

以上是生活随笔為你收集整理的【HDU - 5884】Sort(k叉哈夫曼树,优化tricks,两个队列代替优先队列)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。