首页 > 代码库 > 【bzoj2120】 数颜色

【bzoj2120】 数颜色

http://www.lydsy.com/JudgeOnline/problem.php?id=2120 (题目链接)

题意:给出一个n个数,m个询问,每次询问一个区间或修改一个数,求区间内不同的数有多少个。

solution 
  分块。每次修改就暴力nlogn重新构块。 
  对于分块的话,代码很好理解。

代码:

// bzoj2120#include<algorithm>#include<iostream>#include<cstring>#include<cstdlib>#include<cstdio>#include<cmath>#include<vector>#define MOD 1000000007#define inf 2147483640#define LL long long#define free(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout);using namespace std;inline LL getint() {    LL x=0,f=1;char ch=getchar();    while (ch>‘9‘ || ch<‘0‘) {if (ch==‘-‘) f=-1;ch=getchar();}    while (ch>=‘0‘ && ch<=‘9‘) {x=x*10+ch-‘0‘;ch=getchar();}    return x*f;}const int maxn=1000010;int head[maxn],a[maxn],b[maxn],pre[maxn],pos[maxn],n,m,q,block;void reset(int x) {    int l=(x-1)*block+1,r=min(x*block,n);    for (int i=l;i<=r;i++) pre[i]=b[i];    sort(pre+l,pre+r+1);}void build() {    for (int i=1;i<=n;i++) {        b[i]=head[a[i]];        head[a[i]]=i;        pos[i]=(i-1)/block+1;    }    for (int i=1;i<=m;i++) reset(i);}int find(int x,int v) {    int l=(x-1)*block+1,r=min(x*block,n);    int f=l;    while (l<=r) {        int mid=(l+r)>>1;        if (pre[mid]<v) l=mid+1;        else r=mid-1;    }    return l-f;}int query(int l,int r) {    int ans=0;    if (pos[l]==pos[r]) {        for (int i=l;i<=r;i++) if (b[i]<l) ans++;    }    else {        for (int i=l;i<=block*pos[l];i++) if (b[i]<l) ans++;        for (int i=block*(pos[r]-1)+1;i<=r;i++) if (b[i]<l) ans++;    }    for (int i=pos[l]+1;i<pos[r];i++) ans+=find(i,l);    return ans;}void modify(int x,int y) {    for (int i=1;i<=n;i++) head[a[i]]=0;    a[x]=y;    for (int i=1;i<=n;i++) {        int t=b[i];        b[i]=head[a[i]];        if (t!=b[i]) reset(pos[i]);        head[a[i]]=i;    }}int main() {    scanf("%d%d",&n,&q);    for (int i=1;i<=n;i++) scanf("%d",&a[i]);    block=int(sqrt(n));    if (n%block>0) m=n/block+1;    else m=n/block;    build();    while (q--) {        char ch[10];        int x,y;        scanf("%s%d%d",ch,&x,&y);        if (ch[0]==‘Q‘)            printf("%d\n",query(x,y));        else modify(x,y);    }    return 0;}

  

【bzoj2120】 数颜色