Xenia and Colorful Gems

时间:2020-04-17
本文章向大家介绍Xenia and Colorful Gems,主要包括Xenia and Colorful Gems使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

D - Xenia and Colorful Gems

参考:Codeforces Round #635 Editorial

暴力解法为\(O(n^3)\),但是此题数据范围为1e5,不可行。于是开始思考降低复杂度的方法。

可以知道如果最终结果为\(x,y,z\)三个数,且\(x\le y\le z\)。如果此时能找到一个比 y 小比 x 大的数,那么前面的假设就不成立了,即不是最优解。

所以只需要找到比 y 小于等于的最大数,和比 y 大于等于的最小数,然后贪心即可。

已知\(y\)\(\le y\)的最大值\(x\),和\(\ge y\)的最小值\(z\)

auto x=upper_bound(a.begin(), a.end(), y);
auto z=lower_bound(c.begin(), c.end(), y);
if(x==a.begin() || z==c.end()) continue;
x--;
//*x ≤ y ≤ *z
// Created by CAD on 2020/4/17.
#include <bits/stdc++.h>

#define INF 0x7fffffffffffffff
#define ll long long
using namespace std;

ll ans;
inline ll sq(ll r){
    return r*r;
}
void solve(vector<ll> a, vector<ll> b, vector<ll> c){
    for(auto y:b){
        auto z=lower_bound(c.begin(), c.end(), y);
        auto x=upper_bound(a.begin(), a.end(), y);
        if(x==a.begin() || z==c.end()) continue;
        x--;
        ans=min(ans, sq(y-*z)+sq(*x-y)+sq(*z-*x));
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;cin>>t;
    while(t--){
        int nr,ng,nb;cin >> nr >> ng >> nb;
        vector<ll> r(nr),g(ng),b(nb);
        for(auto &i:r) cin >> i;
        for(auto &i:g) cin >> i;
        for(auto &i:b) cin >> i;
        sort(r.begin(),r.end());
        sort(g.begin(),g.end());
        sort(b.begin(),b.end());
        ans=INF;
        solve(r, g, b),solve(r, b, g);
        solve(g, r, b),solve(g, b, r);
        solve(b, g, r),solve(b, r, g);

        cout<<ans<<"\n";
    }
    return 0;
}

原文地址:https://www.cnblogs.com/CADCADCAD/p/12720992.html