luogu P1494 [国家集训队]小Z的袜子

背景:

l u o g u luogu luogu智能推荐的,国家集训队水题。

题目传送门:

https://www.luogu.org/problemnew/show/P1494

题意:

求一段区间任选两个数(有顺序)相等的概率。

思路:

很裸的莫队啊。
考虑每一次当前这一个数多一或少一对答案的贡献即可。
在草稿本上推推即可。

代码:

#include<cstdio>
#include<cmath>
#include<algorithm>
#define LL long long
using namespace std;
	int n,m;
	LL now;
	int p[50010],block[50010],hsh[50010];
	struct node1{int x,y,id;} a[50010];
	struct node2{LL x,y;} ans[50010];
bool cmp(node1 x,node1 y)
{
	return block[x.x]==block[y.x]?x.y<y.y:x.x<y.x;
}
void move(int x,int d)
{
	if(d)
	{
		hsh[x]++;
		now+=(LL)hsh[x]*(hsh[x]-1)/2-(LL)(hsh[x]-1)*(hsh[x]-1-1)/2;
	}
	else
	{
		hsh[x]--;
		now-=(LL)(hsh[x]+1)*(hsh[x]+1-1)/2-(LL)hsh[x]*(hsh[x]-1)/2;
	}
}
LL gcd(LL x,LL y)
{
	return !y?x:gcd(y,x%y);
}
int main()
{
	scanf("%d %d",&n,&m);
	for(int i=1;i<=n;i++)
		scanf("%d",&p[i]);
	int u=sqrt(n);
	for(int i=1;i<=m;i++)
	{
		scanf("%d %d",&a[i].x,&a[i].y);
		a[i].id=i;
		block[i]=(i-1)/u+1;
	}
	sort(a+1,a+m+1,cmp);
	int l=1,r=0;
	for(int i=1;i<=m;i++)
	{
		if(a[i].x==a[i].y) {ans[a[i].id]=(node2){0,1};continue;}
		while(l<a[i].x) move(p[l++],0);
		while(l>a[i].x) move(p[--l],1);
		while(r<a[i].y) move(p[++r],1);
		while(r>a[i].y) move(p[r--],0);
		if(!now) ans[a[i].id]=(node2){0,1}; else ans[a[i].id]=(node2){now,(LL)(a[i].y-a[i].x+1)*(LL)(a[i].y-a[i].x+1-1)/2};
	}
	for(int i=1;i<=m;i++)
	{
		if(!ans[i].x&&ans[i].y==1) {printf("0/1\n");continue;}
		LL GCD=gcd(ans[i].x,ans[i].y);
		printf("%lld/%lld\n",ans[i].x/GCD,ans[i].y/GCD);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值