蓝桥杯真题(第九届蓝桥杯省赛C++A组)

1234. 倍数问题 - AcWing题库

超时解法 O({\color{Red} n^2logn})

通过: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

if (a+b) == mk, m \in N\ then \ (a+b+0) == mk\\\\ else \ if (a+b)%k != 0, and \ (a+b+c)%k == 0 \\\\ then \ a+b == (m-1)k + r ,m,r \in N \ and \ r + c == k \\\\ c == k - r == k - (a+b - (m-1)k) == mk - (a+b) == k - (a+b)%k

#include
#include
using namespace std;
const int N = 1e5+5,K = 1e3+5;
int a[N],n,k;
priority_queue 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解法待更新...

你可能感兴趣的:(算法,错误,蓝桥杯,c++,算法)