zoukankan      html  css  js  c++  java
  • 数据结构(莫队算法):HH的项链

    问题描述:
    HH有一串由各种漂亮的贝壳组成的项链。HH相信不同的贝壳会带来好运,所以每次散步
    完后,他都会随意取出一段贝壳,思考它们所表达的含义。HH不断地收集新的贝壳,因此,
    他的项链变得越来越长。有一天,他突然提出了一个问题:某一段贝壳中,包含了多少种不同
    的贝壳?这个问题很难回答。。。因为项链实在是太长了。于是,他只好求助睿智的你,来解
    决这个问题。
    输入格式:
    第一行:一个整数N,表示项链的长度。
    第二行:N个整数,表示依次表示项链中贝壳的编号(编号为0到1000000之间的整数)。
    第三行:一个整数M,表示HH询问的个数。
    接下来M行:每行两个整数,L和R(1 ≤ L ≤ R ≤ N),表示询问的区间。
    输出格式:
    M行,每行一个整数,依次表示询问对应的答案。
    样例输入:
    6
    1 2 3 4 3 5
    3
    1 2
    3 5
    2 6
    样例输出:
    2
    2
    4
    数据范围:
    对于20%的数据,N ≤ 100,M ≤ 1000;
    对于40%的数据,N ≤ 3000,M ≤ 200000;
    对于100%的数据,N ≤ 50000,M ≤ 200000。

      

     1 #include <algorithm>
     2 #include <iostream>
     3 #include <cstring>
     4 #include <cstdio>
     5 #include <cmath>
     6 using namespace std;
     7 const int N=50010,M=200010,K=1000010;
     8 int num[K],hsh[K],a[N],n,Q,block,cnt;
     9 int ql[M],qr[M],p[M],ans[M],tmp,tim;
    10 bool cmp(int x,int y){
    11     return (ql[x]-1)/block!=(ql[y]-1)/block?ql[x]<ql[y]:qr[x]<qr[y];
    12 }
    13 void Add(int x){
    14     if(!num[x])tmp++;
    15     num[x]++;
    16 }
    17 void Min(int x){
    18     if(num[x]==1)tmp--;
    19     num[x]--;
    20 }
    21 int main(){
    22     freopen("diff.in","r",stdin);
    23     freopen("diff.out","w",stdout);
    24     ios::sync_with_stdio(false);
    25     cin.tie(NULL);cout.tie(NULL);
    26     cin>>n;
    27     for(int i=1,x;i<=n;i++){
    28         cin>>x;
    29         if(!hsh[x])hsh[x]=++cnt;
    30         a[i]=hsh[x];
    31     }
    32     cin>>Q;
    33     for(int i=1;i<=Q;i++)    
    34         cin>>ql[i]>>qr[i],p[i]=i;
    35     block=(int)sqrt(n+0.5);
    36     sort(p+1,p+Q+1,cmp);
    37     int l=1,r=0;
    38     for(int i=1;i<=Q;i++){
    39         while(ql[p[i]]<l)Add(a[--l]);
    40         while(ql[p[i]]>l)Min(a[l++]);
    41         while(qr[p[i]]>r)Add(a[++r]);
    42         while(qr[p[i]]<r)Min(a[r--]);            
    43         ans[p[i]]=tmp;
    44     }
    45     for(int i=1;i<=Q;i++)
    46         cout<<ans[i]<<"
    ";    
    47     return 0;
    48 }
  • 相关阅读:
    php.ini中Magic_Quotes_Gpc开关设置
    This is the Manual for Quagga 1.2.0. Quagga is a fork of GNU Zebra
    Are virtual interfaces supported on Quagga v0.98.3 (on Debian GNU/Linux 2.6.16)?
    [quagga-users 8071] Re: Virtual interfaces / aliases supported?
    quagga-0.99.20mr2.1
    Equal Cost Multipath Load Sharing
    (ECMP) Equal-cost multi-path routing
    Multipath suport not working in quagga 0.98.6
    Android-x86-7.1.1
    Android
  • 原文地址:https://www.cnblogs.com/TenderRun/p/5863465.html
Copyright © 2011-2022 走看看