F:Honk's pool (The Preliminary Contest for ICPC Asia Shenyang 2019)


As we all know, Honk has nn pools, numbered as 11 ~ nn . There is a_iai liters water in the ii-th pool. Every day, Honk will perform the following operations in sequence.

  1. Find the pool with the most water (If there are more than one, choose one at random) and take one liter of water.

  2. Find the pool with the least water (If there are more than one, choose one at random) and pour one liter of water into the pool.

  3. Go home and rest (Waiting for the next day).

Please calculate the difference between the amount of water in the pool with the most water and the amount of water in the pool with the least water after the kk days.

Input

The input consists of multiple test cases. The input is terminated by the end of file.The number of data sets will not exceed 40

The first line of each test case contains two integers nn and kk, which indicate the number of pools and the number of days to operate the pool.

The second line of each test case contains nn integers, and the ii-th number represent a_iai indicating the initial amount of water in the ii-th pool.

1 \le n \le 5000001n500000, 1 \le k \le 10^91k109, 1 \le a_i \le 10^91ai109.

Output

For each test case, print one line containing the answer described above.

樣例輸入1

4 100
1 1 10 10

樣例輸出1

1

樣例輸入2

4 3
2 2 2 2

樣例輸出2

 

不得不承認隊友的天賦比我高多了,思維是真的強!
然后,一定要去魔改各種方法!!!



由於昨天的數據比較弱,所以這個代碼雖然能過,但是依然存在着很大的bug,所以呢,只推薦理解。

用二分來做的話,嗯~,就是先找二分達到穩定狀態(就是達到平均值average
)然后判斷所需的步數cnt,
如果cnt<=k(給定步數),判斷穩定狀態有幾個值
  一個的話為
average,兩個的話average和average+1一個的話為0,反之為1
如果cnt>k,嗯~,二分k步時的最大值最小值,二分在k步時,average左邊的最小值,以及average右邊的最大值,做差就可以了
  這一步類似於二分題“月度開銷”的過程



#include <iostream> #include <cmath> #include <map> #include <queue> #include <algorithm>

using namespace std; long long a[500010]; int main() { int n,k; std::ios::sync_with_stdio(false); priority_queue<long long,vector<long long>,less<long long> >q; priority_queue<long long,vector<long long>,greater<long long> >p; while(cin>>n>>k) { while(!q.empty()) q.pop(); while(!p.empty()) p.pop(); int flag=0; long long sum=0,arv,num=0; for(int i=0;i<n;i++) { cin>>a[i]; q.push(a[i]); p.push(a[i]); sum+=a[i]; } if(sum%n) flag=1; arv=sum/n; sort(a,a+n); for(int i=0;i<n;i++) { if(a[i]==arv||(flag&&a[i]==arv+1)) continue; num+=abs(arv-a[i]); } long long x,y; if(k>=num/2) { if(flag) cout<<1<<endl; else cout<<0<<endl; } else { while(k--) { x=q.top(); y=p.top(); q.pop();p.pop(); x--;y++; q.push(x); p.push(y); } cout<<q.top()-p.top()<<endl; } } return 0; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM