bzoj2038: [2009国家集训队]小Z的袜子(hose) [莫队]

Description

作为一个生活散漫的人,小Z每天早上都要耗费很久从一堆五颜六色的袜子中找出一双来穿。终于有一天,小Z再也无法忍受这恼人的找袜子过程,于是他决定听天由命……
具体来说,小Z把这N只袜子从1到N编号,然后从编号L到R(L 尽管小Z并不在意两只袜子是不是完整的一双,甚至不在意两只袜子是否一左一右,他却很在意袜子的颜色,毕竟穿两只不同色的袜子会很尴尬。
你的任务便是告诉小Z,他有多大的概率抽到两只颜色相同的袜子。当然,小Z希望这个概率尽量高,所以他可能会询问多个(L,R)以方便自己选择。

Input

输入文件第一行包含两个正整数N和M。N为袜子的数量,M为小Z所提的询问的数量。接下来一行包含N个正整数Ci,其中Ci表示第i只袜子的颜色,相同的颜色用相同的数字表示。再接下来M行,每行两个正整数L,R表示一个询问。

Output

包含M行,对于每个询问在一行中输出分数A/B表示从该询问的区间[L,R]中随机抽出两只袜子颜色相同的概率。若该概率为0则输出0/1,否则输出的A/B必须为最简分数。(详见样例)

Sample Input

6 4
1 2 3 3 3 2
2 6
1 3
3 5
1 6

Sample Output

2/5
0/1
1/1
4/15
【样例解释】
询问1:共C(5,2)=10种可能,其中抽出两个2有1种可能,抽出两个3有3种可能,概率为(1+3)/10=4/10=2/5。
询问2:共C(3,2)=3种可能,无法抽到颜色相同的袜子,概率为0/3=0/1。
询问3:共C(3,2)=3种可能,均为抽出两个3,概率为3/3=1/1。
注:上述C(a, b)表示组合数,组合数C(a, b)等价于在a个不同的物品中选取b个的选取方案数。
【数据规模和约定】
30%的数据中 N,M ≤ 5000;
60%的数据中 N,M ≤ 25000;
100%的数据中 N,M ≤ 50000,1 ≤ L < R ≤ N,Ci ≤ N。

卡了一晚的莫队
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<cmath>
 5 #include<algorithm>
 6 using namespace std;
 7 
 8 typedef long long ll;
 9 typedef pair<ll,ll> PLL;
10 
11 struct ask{
12     int L,R,id;
13 };
14 
15 const int maxn=50001,maxm=50001;
16 
17 int CL=1,CR=0,n,m,tim;
18 int color[maxn],c[maxn];
19 ll s[maxn],ans=0;
20 ask qq[maxm];
21 PLL answer[maxm];
22 
23 inline bool cmp(const ask &n1,const ask &n2){
24     return c[n1.L]==c[n2.L]?n1.R<n2.R:n1.L<n2.L;
25 }
26 
27 inline ll mu(ll num){
28     return num*num;
29 }
30 
31 inline ll gcd(ll a,ll b){
32     return b==0?a:gcd(b,a%b);
33 }
34 
35 inline void update(int pos,int add){
36     ans-=mu(s[color[pos]]);
37     s[color[pos]]+=add;
38     ans+=mu(s[color[pos]]);
39 }
40 
41 void init(){
42     scanf("%d%d",&n,&m);  tim=sqrt(n);
43     for(int i=1;i<=n;i++)
44         scanf("%d",&color[i]);
45     for(int i=1;i<=n;i++)
46         c[i]=(i-1)/tim+1;
47     for(int i=0;i<m;i++)
48         scanf("%d%d",&qq[i].L,&qq[i].R),qq[i].id=i;
49     sort(qq,qq+m,cmp);
50 }
51 
52 void solve(){
53     for(int i=0;i<m;i++){
54         ask q=qq[i];
55         while(CL<q.L)  update(CL++,-1);
56         while(CL>q.L)  update(--CL,1);
57         while(CR<q.R)  update(++CR,1);
58         while(CR>q.R)  update(CR--,-1);
59         if(q.L==q.R){
60             answer[q.id].first=0;
61             answer[q.id].second=1;
62         }
63         else{
64             answer[q.id].first=ans-(q.R-q.L+1);
65             answer[q.id].second=(ll)(q.R-q.L+1)*(q.R-q.L);
66             ll k=gcd(answer[q.id].first,answer[q.id].second);
67             answer[q.id].first/=k;
68             answer[q.id].second/=k;
69         }
70     }
71     for(int i=0;i<m;i++)
72         printf("%lld/%lld
",answer[i].first,answer[i].second);
73 }
74 
75 int main(){
76     //freopen("temp.in","r",stdin);
77     init();
78     solve();
79     return 0;
80 }

原文地址:https://www.cnblogs.com/ZYBGMZL/p/7152757.html