題解 P3939 數顏色
阿新 • • 發佈:2021-06-20
Solution
對於兔子們按照顏色為第一關鍵字 , 位置為第二關鍵字排序 , 查詢個數時直接二分 , 相同顏色的修改不用管 , 不同顏色的修改不會改變統一顏色內的大小順序 , 直接修改不會影響有序性 .
時間複雜度 \(O(nlogn)\)
Code
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; int read() { int ret=0;char c=getchar(); while(c<'0'||c>'9')c=getchar(); while(c<='9'&&c>='0')ret=(ret<<3)+(ret<<1)+(c^48),c=getchar(); return ret; } const int maxn=3e5+5; int n,m; int a[maxn]; struct rabbit { int col,p; const bool operator <(const rabbit x)const{if(col!=x.col)return col<x.col;return p<x.p;} }r[maxn]; int main() { n=read();m=read(); for(int i=1;i<=n;i++) { a[i]=read(); r[i].col=a[i];r[i].p=i; } sort(r+1,r+n+1); while(m--) { int opt=read(); if(opt==1) { int nl,nr,c;nl=read();nr=read();c=read(); nr=upper_bound(r+1,r+n+1,rabbit{c,nr})-r-1; nl=lower_bound(r+1,r+n+1,rabbit{c,nl})-r; printf("%d\n",nr-nl+1); } else { int x=read(); if(a[x]==a[x+1])continue; int now=lower_bound(r+1,r+n+1,rabbit{a[x],x})-r;r[now].p=x+1; now=lower_bound(r+1,r+n+1,rabbit{a[x+1],x+1})-r;r[now].p=x; swap(a[x],a[x+1]); } } return 0; }