CF1337D Xenia and Colorful Gems(二分)

首先要知道,三个数离的越近越好,因此我们假设三个数a<=b<=c,之后我们固定b,查找a和c即可

有六种组合,就能遍历所有情况

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=4e5+10;
const int mod=1e9+7;
ll x;
vector<ll> a,b,c;
ll ans;
long long sq(ll x) { return 1ll * x * x; }
void solve(vector<ll> a, vector<ll> b, vector<ll> c) {
    for (auto x : a) {
        auto y = lower_bound(b.begin(), b.end(), x);
        auto z = upper_bound(c.begin(), c.end(), x);
        if (y == b.end() || z == c.begin()) { continue; }
        z--; ans = min(ans, sq(x - *y) + sq(*y - *z) + sq(*z - x));
    }
}
int main(){
    int t;
    cin>>t;
    while(t--){
        int n1,n2,n3;
        cin>>n1>>n2>>n3;
        int i;
        a.clear();
        b.clear();
        c.clear();
        for(i=1;i<=n1;i++){
            scanf("%lld",&x);
            a.push_back(x);
        }
        for(i=1;i<=n2;i++){
            scanf("%lld",&x);
            b.push_back(x);
        }
        for(i=1;i<=n3;i++){
            scanf("%lld",&x);
            c.push_back(x);
        }
        sort(a.begin(),a.end());
        sort(b.begin(),b.end());
        sort(c.begin(),c.end());
        ans=9e18;
        solve(a,b,c),solve(c,b,a);
        solve(a,c,b),solve(b,c,a);
        solve(c,a,b),solve(b,a,c);
        cout<<ans<<endl;
    }
}
View Code
原文地址:https://www.cnblogs.com/ctyakwf/p/12790124.html