Codeforces Round #679
问题简化:
先给你6个数 a1 ~ a6
还有n个数b1 ~ bn
对于 b[i](1<=i<=n) 选择a1 ~ a6的任意一个减去,问最后b数组中的最大值与最小值的差的最小值为多少
分析:
首先dp肯定不行的 数字太大状态不能储存 硬着头皮想也想不出来
既然我们不知道到底该减哪个数 索性都减一遍 变成六个数
对于每个bi 每个ai都减一次放进数组c中,最后形成一个长度为6*n的数组c,排序
用尺取法判断是否n个数都已经覆盖即可跟新答案
#include<bits/stdc++.h>
using namespace std;
#define lowbit(x) x&(-x)
#define ll long long
const int maxn=6e5+5;
struct node{
int val,id;
}a[maxn];
int base[10],vis[maxn];
int n,tot,num,ans=1e9,now=1;
bool cmp(node a,node b){
return a.val<b.val;
}
int main(){
for(int i=1;i<=6;i++)scanf("%d",&base[i]);
cin>>n;
for(int i=1;i<=n;i++){
int x;
scanf("%d",&x);
for(int j=1;j<=6;j++)
a[++tot].id=i,a[tot].val=x-base[j];
}
sort(a+1,a+1+tot,cmp);
for(int i=1;i<=tot;i++){
if(vis[a[i].id]==0)num++;
vis[a[i].id]++;
while(num==n){
ans=min(a[i].val-a[now].val,ans);
vis[a[now].id]--;
if(vis[a[now].id]==0)num--;
now++;
}
}
cout<<ans<<endl;
return 0;
}
分析:
首先正推肯定是不行的 因为对于前面出现的‘+’ 我们对该位置具体填入哪个数完全没有头绪
那就考虑逆着推 用栈即可
判断不合理的情况
如果当前栈为空 却为‘+’ 也就是下方没有删除的了 不合理
如果加入的元素比栈顶元素大 那么一定不合理 因为我们每次取得最小值 在栈里面 上一次不可能比下一次还大
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<stack>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e6+100;
typedef long long LL;
LL pre[maxn],cnt=0;
stack<LL>s;
struct P{
char op;
LL num;
}shu[maxn];
int main(void)
{
LL n;cin>>n;
for(LL i=1;i<=2*n;i++){
char str;LL num;
cin>>str;
if(str=='+'){
shu[i].op=str;
}
else if(str=='-'){
cin>>num;
shu[i].op=str;
shu[i].num=num;
}
}
for(LL i=2*n;i>=1;i--)
{
if(shu[i].op=='-'&&(!s.empty()&&s.top()>shu[i].num||s.empty())){
s.push(shu[i].num);
}
else if(shu[i].op=='+'){
if(!s.empty())
{
pre[++cnt]=s.top();
s.pop();
}
}
else {
cout<<"NO"<<endl;return 0;
}
}
if(!s.empty()){
cout<<"NO"<<endl;return 0;
}
cout<<"YES"<<endl;
for(LL i=cnt;i>=1;i--){
cout<<pre[i]<<" ";
}
cout<<endl;
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)