关于#算法#的问题,如何解决?(语言-c++)

用什么算法可以解决这个问题?需要详细步骤
语言:c++
题目来源:codeforce
详情如图所示。

img

img

img



#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
typedef long long ll;
ll mylog(ll x)
{
    ll ret = 0;
    ll now = 1;
    while (now<=x)
    {
        now <<= 1;
        ret++;
    }
    return ret;
}
ll a[N];
ll n;
bool check(ll x)
{
    int it1 = upper_bound(a + 1, a + n + 1, a[1] + 2 * x)-a;//掌管范围的右边界
    if (it1 > n)
    {//任意时刻右边界囊括n要立即返回
        return 1;
    }
    int it2 = upper_bound(a + it1, a + n + 1, a[it1] + 2 * x) - a;
    if (it2 > n)
        return 1;
    int it3 = upper_bound(a + it2, a + n + 1, a[it2] + 2 * x) - a;
    if (it3 > n)
        return 1;
    return 0;
}
int main()
{
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(false);
    int t;
    cin >> t;
    while (t--)
    {
        
        cin >> n ;
        for (int i = 1; i <= n; i++)
        {
            cin >> a[i];
        }
        sort(a + 1, a + n + 1);//排序
        ll it=unique(a + 1, a + n + 1)-a;//去重能稍微优化一点时间,不去重也行,但是其实用不到重复的数
        n = it - 1;
        ll l = 0, r = a[n];
        ll ans;
        while (l <= r)
        {
            ll mid = (l + r) / 2;
            if (check(mid))
            {
                r = mid -1;
                ans = mid;
            }
            else
            {
                l = mid + 1;
            }
        }
        cout << ans << endl;
    }
    return 0;
}

@ada; 回答一下

  • 请看👉 :【C++】运算符重载实现复数类的加减乘除(code c++)
  • 除此之外, 这篇博客: [C++ code]用两个栈实现队列;用队列实现栈中的  用两个队列实现栈。 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 请你仅使用两个队列实现一个后进先出的栈,并支持普通栈的全部四种操作(pushtoppop 和 empty)。

    为实现加入顺序为①②③,输出顺序为③②①

    ①先进入主队列

    主队列:①

    辅助队列:

    当②想进入主队列时,先将主队列中的出队并入队到辅助队列中

    主队列:

    辅助队列:①

    再把②加入主队列

    主队列:②

    辅助队列:①

    再将辅助队列中的数据出队并入队到主队列中

    主队列:②①

    辅助队列:

    同理,加入③,主队列先出

    主队列:

    辅助队列:②①

    主队列加入③

    主队列:③

    辅助队列:②①

    辅助队列放回主队列

    主队列:③②①

    辅助队列:

    主队列的出队即为③②①

    class MyStack {
    public:
        queue<int> que1,que2;
    
        MyStack() {
           
        }
        //将元素x压入栈顶
        void push(int x) {
             que2.push(x);
             while(!que1.empty()){
                 int val = que1.front();
                 que1.pop();
                 que2.push(val);
             }
             swap(que1,que2);
    
        }
        //移除并返回栈顶元素
        int pop() {
            int val = que1.front();
            que1.pop();
            return val;
        }
        //返回栈顶元素
        int top() {
            return que1.front();
        }
        //栈空返回true,否则返回false
        bool empty() {
             return que1.empty();
        }
    };
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632