1. 程式人生 > >Hihocoder-1514 偶像的條件

Hihocoder-1514 偶像的條件

解題思路:

其實就是隨意搞下就行。

求|a - b| + |b - c| + |c - a|的最小值

顯然列舉a,然後二分整個{b}找到離a最近的b,再二分整個{c}找到離a最近的c和離b最近的c

比較一下誰最近,就可以O(nlogn)搞出來了。

程式碼:

#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <vector>
#include <string>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;

const int maxn = 1e5 + 5;
int a[maxn], b[maxn], c[maxn];

inline long long Abs(long long x) {
    return (x >= 0 ? x : -x);
}
int main() {
    ios::sync_with_stdio(false); cin.tie(0);
    int n, m, l; cin >> n >> m >> l;
    for ( int i = 0; i < n; ++i ) cin >> a[i];
    for ( int i = 0; i < m; ++i ) cin >> b[i];
    for ( int i = 0; i < l; ++i ) cin >> c[i];
    sort(a, a + n); sort(b, b + m); sort(c, c + l);

    long long ans = 1e18 + 5;
    for ( int i = 0; i < n; ++i ) {
        int pos_b = lower_bound(b, b + m, a[i]) - b;

        int pos_c = lower_bound(c, c + l, a[i]) - c;
        ans = min(ans, Abs(a[i] - b[pos_b]) + Abs(b[pos_b] - c[pos_c]) + Abs(c[pos_c] - a[i]));
        if ( pos_c > 0 ) ans = min(ans, Abs(a[i] - b[pos_b]) + Abs(b[pos_b] - c[pos_c-1]) + Abs(c[pos_c-1] - a[i]));

        pos_c = lower_bound(c, c + l, b[pos_b]) - c;
        ans = min(ans, Abs(a[i] - b[pos_b]) + Abs(b[pos_b] - c[pos_c]) + Abs(c[pos_c] - a[i]));
        if ( pos_c > 0 ) ans = min(ans, Abs(a[i] - b[pos_b]) + Abs(b[pos_b] - c[pos_c-1]) + Abs(c[pos_c-1] - a[i]));

        if ( pos_b > 0 ) {
            pos_c = lower_bound(c, c + l, b[pos_b-1]) - c;
            ans = min(ans, Abs(a[i] - b[pos_b-1]) + Abs(b[pos_b-1] - c[pos_c]) + Abs(c[pos_c] - a[i]));
            if ( pos_c > 0 ) ans = min(ans, Abs(a[i] - b[pos_b-1]) + Abs(b[pos_b-1] - c[pos_c-1]) + Abs(c[pos_c-1] - a[i]));
        }
    }
    cout << ans << endl;
    return 0;
}