思路
搞了一个暴力的做法,就是把所有数按模K的结果分组,暴力枚举前两个数模K的结果,然后就可以推出第三个数模K的结果,在这三组里面都取个最大值即可。
对于每一组,只需要维护3个最值即可
时间复杂度O(K2logn)
代码
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N = 1e3 + 10;
int heap[N][3];
void add(int idx, int x) {
if (x > heap[idx][0]) {
heap[idx][2] = heap[idx][1];
heap[idx][1] = heap[idx][0];
heap[idx][0] = x;
}
else if (x > heap[idx][1]) {
heap[idx][2] = heap[idx][1];
heap[idx][1] = x;
}
else if (x > heap[idx][2]) {
heap[idx][2] = x;
}
}
int pop(int i) {
int ans = heap[i][0];
heap[i][0] = heap[i][1];
heap[i][1] = heap[i][2];
heap[i][2] = -1;
return ans;
}
void solve() {
memset(heap, -1, sizeof heap);
int n, K;
cin >> n >> K;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
add(x % K, x);
}
int maxv = 0;
for (int i = 0; i < K; i++) {
if (heap[i][0] == -1) continue;
int a = pop(i);
for (int j = i; j < K; j++) {
if (heap[j][0] == -1) continue;
int b = pop(j);
if (heap[(K - (i + j) % K) % K][0] != -1) {
int c = heap[(K - (i + j) % K) % K][0];
maxv = max(maxv, a + b + c);
}
add(j, b);
}
add(i, a);
}
cout << maxv;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
solve();
return 0;
}