超时解法 O()
通过:9/13个数据
设原数组中任取三个数:x,y,z
它们模k的余数为:a,b,c
有(a+b+c)%k == 0
即原数x+y+z的和是k的倍数
利用散列数组保存原数组中的项,mod[i]中保存原数组项%k的所有值遍历a的值和b的值,c的值能根据上式表达
证明:(a+b+c)%k == 0 时,c的取值是0或k-(a+b)%k
#include<iostream>
#include<queue>
using namespace std;
const int N = 1e5+5,K = 1e3+5;
int a[N],n,k;
priority_queue<int> mod[K];
int get(int idx){
int x = 0;
if(!mod[idx].empty()){
x = mod[idx].top();
mod[idx].pop();
}
return x;
}
int main(){
int res = 0;
cin >> n >> k;
for(int i = 0; i < n; ++i){
scanf("%d",&a[i]);
mod[a[i]%k].push(a[i]);
// cout << a[i] % k << ' ';
}
// cout << endl;
for(int a = 0; a < k; ++a){
for(int b = 0; b < k; ++b){
//a = 0 b = 0 c = 0
int c;
if((a+b)%k == 0) c = 0;
else c = k - (a+b)%k;
int x,y,z;
x = get(a),y = get(b),z = get(c);
// cout << a << ' ' << b << ' ' << c << endl;
// cout << x << ' ' << y << ' ' << z << endl;
res = max(x+y+z,res);
mod[a].push(x);
mod[b].push(y);
mod[c].push(z);
}
}
cout << res;
return 0;
}
dp解法待更新...