【题解】计蒜客 Honk's pool⭐⭐⭐ 【思维】

计蒜客 Honk’s pool

As we all know, Honk has nn pools, numbered as 11 ~ nn . There is a_ia i liters water in the ii-th pool. Every day, Honk will perform the following operations in sequence.
Find the pool with the most water (If there are more than one, choose one at random) and take one liter of water.
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.
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_ia i indicating the initial amount of water in the ii-th pool.

Output

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

Examples

样例输入1复制
4 100
1 1 10 10
样例输出1复制
1
样例输入2复制
4 3
2 2 2 2
样例输出2复制
0

Hint




题意:

给出n个数, 每次操作使得最大的-1, 最小的+1, 问k次操作后最大最小值之差

题解:

官方给出的题解是二分来写的, 说实话不太好想, 但这题似乎数据比较弱, 所以贪心+排序的简单写法也可以过
思路很简单, 就是模拟, 每次取最大的–, 然后处理排序, 再让最小的++, 处理排序, 反复k次

经验小结:

暴力出奇迹


#include
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const int inf = 1 << 30;
const int maxn = 5e5+10;

int n, k, a[maxn];
int main() {
    while(scanf("%d%d",&n,&k)!=EOF){
        for(int i = 1; i <= n; ++i)
            scanf("%d",&a[i]);
        sort(a+1, a+1+n);
        while(k--){
            --a[n];
            for(int i = n-1; i >= 1; --i){
                if(a[i] > a[i+1])
                    swap(a[i], a[i+1]);
                else break;
            }
            ++a[1];
            for(int i = 2; i <= n; ++i){
                if(a[i] < a[i-1])
                    swap(a[i], a[i-1]);
                else break;
            }
        }
        printf("%d\n",a[n]-a[1]);
    }
    return 0;
}

你可能感兴趣的:(贪心)