被卡掉了。权值线段树维护,对于2操作,起始就是交换元素后,更新rt[x]和rt[x+1]
主席树
#include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 10,M = 1e6 + 10;
int rt[N],len[N];
int a[N];
#define ls(x) t[x].ls
#define rs(x) t[x].rs
#define sum(x) t[x].sum
struct LSegmentTree{
int ls,rs,sum;
}t[M<<5];
int idx = 0;
int build(int l,int r){
int root = ++idx;
sum(root) = 0;
if(l == r) return root;
int mid = (l + r) >> 1;
ls(root) = build(l,mid);
rs(root) = build(mid+1,r);
return root;
}
int update(int p,int l,int r,int pos){
int root = ++idx;
ls(root) = ls(p),rs(root) = rs(p),sum(root) = sum(p) + 1;
if(l == r) return root;
int mid = (l + r) >> 1;
if(pos <= mid) ls(root) = update(ls(p),l,mid,pos);
else rs(root) = update(rs(p),mid+1,r,pos);
return root;
}
int query(int lp,int rp,int l,int r,int pos){
if(l == r) return sum(rp) - sum(lp);
int mid = (l + r) >> 1;
if(pos <= mid) return query(ls(lp),ls(rp),l,mid,pos);
else return query(rs(lp),rs(rp),mid+1,r,pos);
}
signed main(){
rt[0] = build(1,N);
int n,m; scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++) scanf("%d",a+i),rt[i] = update(rt[i-1],1,N,a[i]);
for(int i=1;i<=m;i++){
int op; scanf("%d",&op);
if(op == 1){
int l,r,c; scanf("%d %d %d",&l,&r,&c);
printf("%d\n",query(rt[l-1],rt[r],1,N,c));
}else{
int x; scanf("%d",&x);
swap(a[x],a[x+1]);
rt[x] = update(rt[x-1],1,N,a[x]);
rt[x+1] = update(rt[x],1,N,a[x+1]);
}
}
return 0;
}
vector存每个位置,然后二分。
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 10;
int a[N];
vector<int> ve[N];
signed main(){
IOS
int n,m; cin>>n>>m;
for(int i=1;i<=n;i++) cin>>a[i],ve[a[i]].push_back(i);
while(m --){
int op; cin>>op;
if(op == 1) {
int l,r,c; cin>>l>>r>>c;
if(ve[c].size() == 0){
cout<<0<<endl;
continue;
}
l = lower_bound(ve[c].begin(),ve[c].end(),l) - ve[c].begin();
r = upper_bound(ve[c].begin(),ve[c].end(),r) - ve[c].begin();
int ans = r - l;
cout<<ans<<endl;
}else{
int x; cin>>x;
int k1 = a[x],k2 = a[x+1];
swap(a[x],a[x + 1]);
*lower_bound(ve[k1].begin(),ve[k1].end(),x) = x + 1;
*lower_bound(ve[k2].begin(),ve[k2].end(),x + 1) = x;
}
}
return 0;
}