Codeforces Round #577 (Div. 2) - C. Maximum Median(补题)

题意:输入 n , k;接下来a: n个数;题目要求:每个数字可增加1,同时k也是会减1的;要求你在 k 次以内将这个a的中位数变得最大;
思路:将a sort();然后用一个数组记录两个数之间的差值,从中间开始跑一直跑到n;k每次都减去 a[mid~x] (x - number)个一起升到 a[x+1] 的数值;如果升不了就将剩下的k值平均分到 a [mid~x]上去;
另外n == 1的时候需要特判一下;

C. Maximum Median

time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output

You are given an array a of n integers, where n is odd. You can make the following operation with it:

Choose one of the elements of the array (for example ai) and increase it by 1 (that is, replace it with ai+1).
You want to make the median of the array the largest possible using at most k operations.

The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1,5,2,3,5] is 3.

Input
The first line contains two integers n and k (1≤n≤2⋅105, n is odd, 1≤k≤109) — the number of elements in the array and the largest number of operations you can make.

The second line contains n integers a1,a2,…,an (1≤ai≤109).

Output
Print a single integer — the maximum possible median after the operations.

Examples
inputCopy
3 2
1 3 5
outputCopy
5
inputCopy
5 5
1 2 1 1 1
outputCopy
3
inputCopy
7 7
4 1 2 4 3 4 4
outputCopy
5
Note
In the first example, you can increase the second element twice. Than array will be [1,5,5] and it’s median is 5.

In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.

In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5,1,2,5,3,5,5] and the median will be 5.

AC_Code:

#include 
using namespace std;
typedef long long ll;

ll a[2*100000+10];
ll b[2*100000+10];

int main(){
	int n;
	ll k;
	while(cin >> n >> k){
		memset(b,0,sizeof(b));
		for(int i = 0;i < n;i++){
			cin >> a[i];
		}
		if(n == 1){
			cout << a[n/2] + k << endl;
			continue;
		}
		sort(a,a+n);
		for(int i = 0;i < n-1;i++){
			b[i] = a[i+1] - a[i];
		}
		int mid = n/2,num = 1;
		ll ans = 0;
//		for(int i = 0;i < n;i++){
//			cout << b[i] << " ";
//		}cout << endl;
		while(k > 0){	
			if(num*b[mid] <= k){
				ans += b[mid];
				k -= (num*b[mid]);
				mid++;
				num++;
			}else{
				break;
			}
			if(mid == n-1) break;
		}
		cout << (k/num + ans + a[n/2]) << endl;
	}
}

你可能感兴趣的:(codeforces)