【bzoj4542】[Hnoi2016]大数

  1 #include<algorithm>
  2 #include<iostream>
  3 #include<cstdlib>
  4 #include<cstring>
  5 #include<cstdio>
  6 #include<cmath>
  7 using namespace std;
  8  
  9 typedef long long LL;
 10   
 11 #define N 100010
 12  
 13 struct Node
 14 {
 15     LL val;
 16     int id;
 17 }md[N];
 18  
 19 struct data
 20 {
 21     int l,r,id;
 22 }ask[N];
 23  
 24 char s[N];
 25  
 26 LL c[N],d[N],h[N];
 27 LL a[N];
 28  
 29 LL p;
 30 int m,n;
 31 int l,r;
 32  
 33 int len,K;
 34  
 35 int cmp(Node aa,Node bb)
 36 {
 37     return aa.val<bb.val;
 38 }
 39  
 40 int cmp2(data aa,data bb)
 41 {
 42     return aa.l/K==bb.l/K ? aa.r<bb.r : aa.l<bb.l;
 43 }
 44  
 45 void work()
 46 {
 47     for (int i=1;i<=len;i++)
 48     {
 49         d[i]=d[i-1]+((s[i-1]-'0')%p ? 0 : i);
 50         c[i]=c[i-1]+((s[i-1]-'0')%p==0);
 51     }
 52     scanf("%d",&m);
 53     while (m--)
 54     {
 55         scanf("%d%d",&l,&r);
 56         printf("%lld\n",d[r]-d[l-1]-(c[r]-c[l-1])*(l-1));
 57     }
 58 }
 59  
 60 int main()
 61 {
 62     scanf("%lld",&p);
 63     scanf("%s",s);
 64     len=strlen(s);
 65     K=sqrt(len)+1;
 66     if (p==2 || p==5)
 67     {
 68         work();
 69         return 0;
 70     }
 71     LL res=1;
 72     for (int i=len-1;i>=0;i--)
 73     {
 74         md[i].val=(md[i+1].val+(s[i]-'0')*res)%p;
 75         md[i].id=i;
 76         res=res*10%p;
 77     }
 78     md[len].id=len;
 79     sort(md,md+len+1,cmp);
 80     res=0;
 81     for (int i=0;i<=len;i++)
 82     {
 83         if (i && md[i].val!=md[i-1].val)
 84             res++;
 85         h[md[i].id]=res;
 86     }
 87     scanf("%d",&m);
 88     for (int i=0;i<=m;i++)
 89     {
 90         scanf("%d%d",&ask[i].l,&ask[i].r);
 91         ask[i].l--;
 92         ask[i].id=i;
 93     }
 94     sort(ask,ask+m,cmp2);
 95     int L(0),R(-1);
 96     res=0;
 97     for (int i=0;i<m;i++)
 98     {
 99         while (R<ask[i].r)
100             res+=c[h[++R]]++;
101         while (R>ask[i].r)
102             res-=--c[h[R--]];
103         while (L>ask[i].l)
104             res+=c[h[--L]]++;
105         while (L<ask[i].l)
106             res-=--c[h[L++]];
107         a[ask[i].id]=res;
108     }
109     for (int i=0;i<m;i++)
110         printf("%lld\n",a[i]);
111     return 0;
112 }

 

posted @ 2016-05-14 17:09  Yangjiyuan  阅读(243)  评论(0编辑  收藏  举报