思路很简单,模拟一两个就知道了,输出当前最大项和排序后的相邻最大差值之和
快排一次要 n log(n) 会炸,只能 multiset log(n);被迫学习迭代器使用;
#include <bits/stdc++.h>
using namespace std;
const int max_n=2e5+5;
int n,q,p,x,a[max_n];
multiset<int>s,s2;
void solve()
{
cin>>n;
for(int i=1;i<=n;i++)cin>>a[i];
if(n==1){
cin>>q;
while(q--){
int l,r;cin>>l>>r;
cout<<r<<" ";
}
return;
}
for(int i=1;i<=n;i++)s.insert(a[i]);
for(auto i=++s.begin();i!=s.end();i++){
auto pre=i;--pre;
s2.insert(*i-*pre);
}
cin>>q;
while(q--){
cin>>p>>x;
auto i=s.find(a[p]),next=i,pre=i;next++,pre--;
if(i!=s.begin())s2.erase(s2.find(*i-*pre));
if(i!=--s.end())s2.erase(s2.find(*next-*i));
if(i!=s.begin()&&i!=--s.end())s2.insert(*next-*pre);
s.erase(i),s.insert(x),i=s.find(x),next=i,pre=i,next++,pre--;
if(i!=s.begin())s2.insert(*i-*pre);
if(i!=--s.end())s2.insert(*next-*i);
if(i!=s.begin()&&i!=--s.end())s2.erase(s2.find(*next-*pre));
a[p]=x;
cout<<*--s.end()+*--s2.end()<<" ";
}
cout<<endl;
s.clear();s2.clear();
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int _t;cin>>_t;
while(_t--){
solve();
}
return 0;
}
我T的代码:(原理一样)
#include <bits/stdc++.h>
using namespace std;
const int max_n=2e5+5;
int n,q,x,p,a[max_n];
struct node{int v,pos;};
vector<node>v;
map<int,int>mp;
set<int>s;
bool cmp(const node x,const node y){return x.v<y.v;}
void clear()
{
v.clear();
mp.clear();
s.clear();
}
int check(int m)
{
int l=0,r=n-1;
while(l+1<r){
int mid=(l+r)>>1;
if(v[mid].v>=m)r=mid;
else l=mid;
}
if(v[l].v==m)return l;
else return r;
}
void solve()
{
cin>>n;
if(n==1){
cin>>x>>q;
while(q--){
int l,r;cin>>l>>r;
cout<<r<<" ";
}
cout<<endl;
return;
}
for(int i=1;i<=n;i++){
cin>>x;
v.push_back((node){x,i});
a[i]=x;
}
sort(v.begin(),v.end(),cmp);
for(int i=1;i<n;i++){
int tem=v[i].v-v[i-1].v;
mp[tem]++;
s.insert(tem);
}
cin>>q;
while(q--){
cin>>p>>x;
int pos=check(a[p]);
if(pos!=n-1){
int tem=v[pos+1].v-v[pos].v;
mp[tem]--;
if(!mp[tem])s.erase(tem);
}
if(pos!=0){
int tem=v[pos].v-v[pos-1].v;
mp[tem]--;
if(!mp[tem])s.erase(tem);
}
if(pos!=0&&pos!=n-1){
int tem=v[pos+1].v-v[pos-1].v;
mp[tem]++;
s.insert(tem);
}
a[p]=x;v[pos].v=x;
sort(v.begin(),v.end(),cmp);
pos=check(x);
if(pos!=n-1){
int tem=v[pos+1].v-v[pos].v;
mp[tem]++;
s.insert(tem);
}
if(pos!=0){
int tem=v[pos].v-v[pos-1].v;
mp[tem]++;
s.insert(tem);
}
if(pos!=0&&pos!=n-1){
int tem=v[pos+1].v-v[pos-1].v;
mp[tem]--;
if(!mp[tem])s.erase(tem);
}
cout<<v.back().v+*s.rbegin()<<" ";
}
cout<<endl;
clear();
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int _t;cin>>_t;
while(_t--){
solve();
}
return 0;
}