Problem I. 整数反应
题意:
有n个整数,从左到右编号1到n,他们有0和1两种颜色,每个整数有且只有一种颜色,将它们按照编号从1到n的顺序依次放入S1,每当一个新整数x放入S1,必须选择与其不同颜色的数y发生反应,并将x+y放入S2,不存在这样的y。则不放入S1。处理完所有元素,求出s2中最小元素的最大值
思路:
这是一道二分题,我们可以利用二分思想去按照范围取中间值,将值传入check函数后,用两个multiset(这是一个不去重排序容器)来依次存颜色不同的两类数,每存一次,判断与其颜色不同的容器是否为空,若为空,直接插入,若不为空,将我们传入的值减去存的值记为z,并在颜色不同的容器中查找一个大于等于z的最小值,若存在,则删除该元素,不存在则返回,去改变范围,当都满足时,去改变范围使得满足条件的值尽可能大。
函数补充:
erase(iterator)//删除iterator指向的值,
s.lower_bound(k)//返回大于等于k的第一个元素的位置
s.upper_bound(k)//返回大于k的第一个元素的位置
s.empty() //判断set容器是否为空
代码:
#include<bits/stdc++.h>
using namespace std;
struct pi{
int num,col;
}a[100005];
int n;
bool check(int mid)
{
multiset<int>st0,st1;
for(int i=1;i<=n;i++)
{
if(a[i].col==0)
{
if(st1.empty())
{
st0.insert(a[i].num);
continue;
}
auto t=st1.lower_bound(mid-a[i].num);
if(t==st1.end())
return false;
else
st1.erase(t);
}
else
{
if(st0.empty())
{
st1.insert((a[i].num));
continue;
}
auto t=st0.lower_bound(mid-a[i].num);
if(t==st0.end())
return false;
else
st0.erase(t);
}
}
return true;
}
int main()
{
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i].num;
for(int i=1;i<=n;i++)
cin>>a[i].col;
int l=0,r=1e9,mid;
while(l<r)
{
mid=l+r+1>>1;
if(check(mid))
l=mid;
else
r=mid-1;
}
cout<<l<<'\n';
return 0;
}