题解:P10136 [USACO24JAN] Cowlendar S

· · 题解

题目思路

尝试分析数据范围,可以轻而易举的看出暴力方法。我们需要对暴力进行优化。

首先考虑将数组 a 去重,应为没有影响。判断此时还有几个数,如果只有 3 个,或者更少,那么就直接输出从 1 到 a 最小值的和即可(BS 学员提醒您:运算有风险,右移需谨慎;顺序不规范,代码两行泪)。

根据抽屉原理可得,对于一个合法的 L,在数组 a 的前 4 个元素中,至少有两个同余于 l。换句话说,就是 L 整除 |a_i - a_j|(i,j 表示 1 至 4 中的两个不同的数)。我们可以枚举 |a_i - a_j| 的因数,判断即可。

时间复杂度:O(n \times \sqrt{w})(w 表示值域)。

AC Code

#include <set>
#include <list>
#include <queue>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>

#define endl '\n'
#define int long long
#define inf 0x3f3f3f3f
#define lnf 0x3f3f3f3f3f3f3f3f

using namespace std;

const int N = 1e4;

void init ();

int n;
int a[N + 5];
int _Mn = lnf, _Sm;
set <int> _St;

bool _Chck (int x) {
    set <int> _St_;

    for (register int i = 1; i <= n; ++ i) {
        if ((x << 2) > a[i]) {
            return 0;
        }

        _St_.insert (a[i] % x);

        if (_St_.size () > 3) {
            return 0;
        }
    }

    return 1;
}

int x;

signed main () {
    init ();
    cin >> n;

    for (register int i = 1; i <= n; ++ i) {
        cin >> a[i];
        _Mn = min (_Mn, a[i]);
    }

    sort (a + 1, a + n + 1);
    n = unique (a + 1, a + n + 1) - a - 1;

    if (n <= 3) {
//      cout << ((((_Mn * _Mn) >> 2) + _Mn) >> 3) << endl;
        cout << ((_Mn / 4) * (_Mn / 4) + _Mn / 4) / 2;
        return 0;
    }

    for (register int _ = 1; _ < 4; ++ _) {
        for (register int __ = _ + 1; __ <= 4; ++ __) {
            x = abs (a[_] - a[__]);

            for (register int i = 1; i <= x / i; ++ i) {
                if (x % i == 0) {
                    _St.insert (i);
                    _St.insert (x / i);
                }
            }
        }
    }

    for (int it : _St) {
        if (_Chck (it)) {
            _Sm += it;
        }
    }

    cout << _Sm << endl;
    return 0;
}

void init () {
    ios::sync_with_stdio (false);
    cin.tie (0);
    cout.tie (0);
}