bzoj2038

传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=2038

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

题解:莫队咯,实际上以前写过这道题,但是今天zfy又讲了一遍,真可谓温故而知新,对莫队的理解又更深了一些。

   莫队网上博客很多,就不说这个了,但是有一个小优化,似乎网上没提到过,就是我们在排序的时候对于偶数块我们,用右边节点位置从大到小排序,基数块,则从小到大,为什么自己想想,据说会比平常块30%哦。

代码:

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<algorithm>
 5 #include<cmath>
 6 #define maxn 50001
 7 #define ll long long 
 8 using namespace std;
 9 int read()
10 {
11     int x=0; char ch;
12     while (ch=(char)getchar(),ch<'0'||ch>'9');
13     while (x=x*10+ch-'0',ch=(char)getchar(),ch>='0'&&ch<='9');
14     return x; 
15 }
16 struct data {int l,r,id; ll a,b;} a[maxn];
17 int n,m,ans;
18 int c[maxn],pos[maxn];
19 ll s[maxn];
20 bool cmp(data a, data b)
21 {
22     if (pos[a.l]==pos[b.l]) 
23         if (pos[a.l]&1) return a.r<b.r;
24         else return a.r>b.r;
25     return pos[a.l]<pos[b.l];
26 }
27 bool cmp_id(data a, data b)
28 {
29     return a.id<b.id;
30 }
31 ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);}
32 ll sqr(ll x)
33 {
34     return (ll)x*x;
35 }
36 void init()
37 {
38     n=read(); m=read();
39     for (int i=1; i<=n; i++) c[i]=read();
40     int kk=int (sqrt(n));
41     for (int i=1; i<=m; i++)
42     {
43         a[i].l=read(); a[i].r=read(); a[i].id=i;
44     }
45     for (int i=1; i<=n; i++) pos[i]=(i-1) /kk+1;
46 }
47 void updata(int p,int add)
48 {
49     ans-=sqr(s[c[p]]);
50     s[c[p]]+=add;
51     ans+=sqr(s[c[p]]);
52 }
53 void work()
54 {
55     int r=0,l=1;
56     for (int i=1; i<=m; i++)
57     {
58         for (; r<a[i].r; r++) updata(r+1,1);
59         for (; r>a[i].r; r--) updata(r,-1);
60         for (; l<a[i].l; l++) updata(l,-1);
61         for (; l>a[i].l; l--) updata(l-1,1);
62         if (a[i].l==a[i].r)
63         {
64             a[i].a=0; a[i].b=1;
65             continue;
66         }
67         a[i].a=ans-(a[i].r-a[i].l+1);
68         a[i].b=(ll)(a[i].r-a[i].l)*(a[i].r-a[i].l+1);
69         ll k=gcd(a[i].a,a[i].b);
70         a[i].a/=k; a[i].b/=k;
71     }
72     
73 }
74 int main()
75 {
76     init();
77     sort(a+1,a+m+1,cmp);
78     work();
79     sort(a+1,a+m+1,cmp_id);
80     for (int i=1; i<=m; i++)
81     {
82          printf("%lld/%lld\n",a[i].a,a[i].b);
83     }
84 }
View Code

 

posted @ 2016-06-10 10:51  ACist  阅读(306)  评论(0编辑  收藏  举报