当前位置: 代码迷 >> 综合 >> Codeforces Round #760 D. Array and Operations
  详细解决方案

Codeforces Round #760 D. Array and Operations

热度:13   发布时间:2023-12-05 01:51:45.0

贪心证明:首先,对n个数从小到大排序后,后k个数做分母肯定最优

其次,前n-2*k个数都作为剩下的数最优,这个需要证明一下我才舒服

假如当前方案前n-2*k个数中的某个数做了分子,与这个数有关的分数的贡献是0或1,我们在条件允许的情况下让一个比它大的数来代替它的位置,分数贡献最多增加1,但是,剩余的数的贡献至少减少了1,所以总的来看贡献不会变大,我们不如就让那个比它大的数做分子,反正贡献不会增加

所以前n-2*k个数都作为剩下的数最好

所以我们就要挑选次k大的数作为分子,剩下的问题就是怎么配对分子分母了

官方题解给出的做法是:It can be done by pairing the numbers into fractions in the following way: an?2k+1/an?k+1, an?2k+2/an?k+2, ..., an?k/an (assuming aa is sorted).

这样做也是可以证明是对的

假设现在(an?k/an) 这种东东有一个的值是1,我们贪心的想把它变成0,那就看看在能不能条件允许的情况下在前面找一个更小的数,让这个小数做分子。如果有这样的更小数,我们为达到目的就得交换这2个数,交换后我们发现与交换前相比,贡献没变。

代码实现一下

#include<iostream>
#include<cmath>
#include<map>
#include<cstring>
#include<queue>
#include<algorithm>
#include<string>
#include<vector>
#include<stack>
#include<sstream>
using namespace std;
typedef long long ll;
int a[110], b[110];
int main()
{ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);int t;cin >> t;while (t--){int n, k;cin >> n >> k;for (int i = 1;i <= n;i++) cin >> a[i];sort(a + 1, a + n + 1);int ans = 0;for (int i = 1;i <= n - 2 * k;i++) ans += a[i];for (int i = n - 2 * k + 1;i <= n - k;i++) if (a[i] == a[i + k]) ans++;cout << ans << endl;}
}

  相关解决方案