用什么算法可以解决这个问题?需要详细步骤
语言:c++
题目来源:codeforce
详情如图所示。
#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; 回答一下
请你仅使用两个队列实现一个后进先出的栈,并支持普通栈的全部四种操作(push
、top
、pop
和 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();
}
};