问题陈述
给定长度为 的两个非负整数序列:
和一个正整数 。
在可以自由重新排列 中元素的情况下,求以下表达式的最小可能值:
题目分析
这题是个贪心。
我们注意到:当 时, 取得最小值为 。
所以,要使 取得最小,需要满足 为不小于 的最小值。即对于每个 ,计算 ,并在 中查找不小于 的最小元素 ,然后相加取模记录答案即可。
需要注意的是:当在 中找不到满足条件的 时,就返回 中还未使用过的最小元素,这样就能尽可能的使 最小。
我们可以用 STL 中的 multiset 来维护序列有序,lower_bound 实现二分查找,总时间复杂度为 。
CODE
#include <bits/stdc++.h>
using std::cin, std::cout, std::ios;
const int N = 3e5+349;
#define int long long
int T;
int a[N];
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> T;
while (T--){
int n= 0 ,m = 0,x,ans=0;
cin >> n >> m;
for (int i =1 ; i<= n;i++) cin >> a[i];
std::sort(a+1,a+1+n);
std::multiset<int> s;
for (int j = 1; j <= n;j++) cin >> x,s.insert(x);
for (int i = 1; i <= n;i++){
int k = m - a[i];
auto it = s.lower_bound(k);
if (it == s.end()) it = s.begin(); // 找不到就返回最小值
ans += (a[i] + *it) % m; // 累加答案
// cout << a[i] << ' ' << *it << '\n';
s.erase(it); // 用完即删
}
cout << ans << '\n';
}
return 0;
}
