Bzoj 2038 洛谷1494 [2009国家集训队]小Z的袜子(hose) 这辈子都学不会的莫队算法
题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=2038
https://www.luogu.org/problemnew/show/P1494
题目描述
作为一个生活散漫的人,小Z每天早上都要耗费很久从一堆五颜六色的袜子中找出一双来穿。终于有一天,小Z再也无法忍受这恼人的找袜子过程,于是他决定听天由命……
具体来说,小Z把这N只袜子从1到N编号,然后从编号L到R(L 尽管小Z并不在意两只袜子是不是完整的一双,甚至不在意两只袜子是否一左一右,他却很在意袜子的颜色,毕竟穿两只不同色的袜子会很尴尬。
你的任务便是告诉小Z,他有多大的概率抽到两只颜色相同的袜子。当然,小Z希望这个概率尽量高,所以他可能会询问多个(L,R)以方便自己选择。
然而数据中有L=R的情况,请特判这种情况,输出0/1。
输入输出格式
输入格式:
输入文件第一行包含两个正整数N和M。N为袜子的数量,M为小Z所提的询问的数量。接下来一行包含N个正整数Ci,其中Ci表示第i只袜子的颜色,相同的颜色用相同的数字表示。再接下来M行,每行两个正整数L,R表示一个询问。
输出格式:
包含M行,对于每个询问在一行中输出分数A/B表示从该询问的区间[L,R]中随机抽出两只袜子颜色相同的概率。若该概率为0则输出0/1,否则输出的A/B必须为最简分数。(详见样例)
输入输出样例
输入样例#1:
6 4
1 2 3 3 3 2
2 6
1 3
3 5
1 6
输出样例#1:
2/5
0/1
1/1
4/15
说明
30%的数据中 N,M ≤ 5000;
60%的数据中 N,M ≤ 25000;
100%的数据中 N,M ≤ 50000,1 ≤ L < R ≤ N,Ci ≤ N。
据说本题是莫队算法最好的入门的题,只能说你们都好强呀,我太菜了。
乍一看题目不晓得如何用莫队写,然后考虑区间贡献来说。
借鉴别人一个推倒的过程:(链接:https://www.cnblogs.com/MashiroSky/p/5914637.html)
原来的区间贡献sigma(sum[i]*(sum[i]-1)/2)/((R-L-1)*(R-L)) 然后上式可以变成求区间sighm(sum[i]*sum[i])-(R-L+1)/(R-L+1)*(R-L)
这样就可以用莫队算法了 莫队ans算sum[i]的影响就OK了,最后输出的是最简式子,所以需要gcd一下。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 50005;
int c[maxn];//袜子
int pos[maxn];//储存块
ll sum[maxn];
ll ans;
struct node{
int l;
int r;
int id;
ll A;
ll B;
}no[maxn];
bool cmp(node a,node b)
{
if(pos[a.l]==pos[b.l])
return a.r < b.r;
return a.l < b.l;
}
bool cmp_id(node a,node b)
{
return a.id < b.id;
}
void uppdate(int id,int valu)
{
ans = ans - ( sum[c[id]] * sum[c[id]]);
sum[c[id]] = sum[c[id]] + valu;
ans = ans + (sum[c[id]] * sum[c[id]]);
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%d",&c[i]);
int block=(int)sqrt(n);//分块
for(int i=1;i<=n;i++)
pos[i]=(i-1)/block+1;
for(int i=1;i<=m;i++)
{
scanf("%d%d",&no[i].l,&no[i].r);
no[i].id=i;
}
sort(no+1,no+1+m,cmp);
int l=1;
int r=0;
for(int i=1;i<=m;i++)
{
for(;r<no[i].r;r++) uppdate(r+1,1);
for(;r>no[i].r;r--) uppdate(r,-1);
for(;l<no[i].l;l++) uppdate(l,-1);
for(;l>no[i].l;l--) uppdate(l-1,1);
if(no[i].l==no[i].r)
{
no[i].A=0;
no[i].B=1;
continue;
}
no[i].A = ans -(no[i].r - no[i].l + 1);
no[i].B = (ll)(no[i].r - no[i].l + 1)*(no[i].r - no[i].l);
ll temp=__gcd(no[i].A,no[i].B);
no[i].A/=temp;
no[i].B/=temp;
}
sort(no+1,no+1+m,cmp_id);
for(int i=1;i<=m;i++)
printf("%lld/%lld\n",no[i].A,no[i].B);
return 0;
}
上一篇: 了解胃痛不能吃什么,让胃病不再加重