【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 5Sample 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,两个队列代替优先队列)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【牛客 - 551E】CSL 的魔法(贪
- 下一篇: 退市新规要来了,一大批股票或面临退市,怎