You have n barrels lined up in a row, numbered from left to right from one. Initially, the ii -th barrel contains a_iai liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels xx and yy (the xx -th barrel shouldn't be empty) and pour any possible amount of water from barrel xx to barrel yy (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most kk times.
Some examples:
- if you have four barrels, each containing 5 liters of water, and k=1 , you may pour 55 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10 ;
- if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0 .
输入格式
The first line contains one integer t( 1≤t≤1000 ) — the number of test cases.
The first line of each test case contains two integers nn and kk ( 1 <=k < n<=2⋅10^5 ) — the number of barrels and the number of pourings you can make.
The second line contains nn integers a1,a2,…,an ( 0≤ai≤109 ), where a_iai is the initial amount of water the ii -th barrel has.
It's guaranteed that the total sum of nn over test cases doesn't exceed 2⋅10^5 .
输出格式
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
题意翻译
T次询问,对于每一次询问:
有 n 个水桶,第 i 个水桶有 ai 单位的水,有 k 次机会把一个桶里的水倒在另一个桶里(任意单位,可以不执行完),询问最后最大水桶水量和最小水桶水量的差的最大值。
输入输出样例
输入 #1复制
1. 2 2. 4 1 3. 5 5 5 5 4. 3 2 5. 0 0 0
输出 #1复制
10 0
额,水题一道,直接上代码;写了2种,喜欢那一个就看那一个都可ac。
下面是ac代码,关建点都有注释。
有事你就q我;QQ2917366383
学习算法
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; typedef long long ll; const int maxn = 2e5 + 7; int a[maxn]; int main() { int T; scanf("%d",&T); while(T--) { int n,k; scanf("%d%d",&n,&k); for(int i = 1;i <= n;i++) {//几个桶 scanf("%d",&a[i]); } sort(a + 1,a + 1 + n);//默认小到大 ll num = a[n];//最后一个倒入 for(int i = n - 1;i >= 1;i--) {//由大到小倒 if(k) //!=0 { num += a[i]; k--;//倒几次水 } } printf("%lld\n",num); } }
#include<bits/stdc++.h> using namespace std; typedef long long ll; const ll maxn=1e6+8; ll p[maxn],sum; int main() { int t; cin>>t; while(t--) { int n,m; cin>>n>>m; for(int i=1;i<=n;i++) cin>>p[i]; sort(p+1,p+1+n); sum=p[n]; for(int i=n-1;i>=0;i--) { if(m) { sum+=p[i]; m--; } } cout<<sum<<endl; } }