Codeforces 1931D Divisible Pairs

problem link

Given the dual modulus, pure modular arithmetic deduction would unlikely suceed. However, under the two constraints, divide-and-conquer would be an intuitive direction.

Firstly, all elements of array a a a can be reduced to their remainder modulo x x x and y y y. For clarity, we’ll denote them as x i x_i xi and y i y_i yi. Then, if elements ( i , j ) (i,j) (i,j) qualifies as a beautiful pair x i + x j = x x_i+x_j=x xi+xj=x and y i = y j y_i=y_j yi=yj must hold.

In light of the y i = y j y_i=y_j yi=yj constraint, we can sort the elements their remainder modulo y y y (since elements with different y y y remainder values will not make a beautiful pair). Then, the problem is reduced to calculating the number of pairs in an interval that satisfies x i + x j = x x_i + x_j = x xi+xj=x, which can be solve with O ( n ) \mathcal O(n) O(n) complexity with a simple bin.

Due to the inevitable sorting process, the overal time complexity is O ( n log ⁡ n ) \mathcal O(n \log n) O(nlogn)

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<map>
using namespace std;
const long long Maxn=2e5+10;
struct node{
	long long x,y;
	bool operator <(const node &t)const
	{
		return t.y>y;
	}
}a[Maxn];
map <long long,long long> c;
long long n,ans;
inline long long read()
{
	long long s=0,w=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
	while(ch>='0' && ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
	return s*w;
}
int main()
{
	// freopen("in.txt","r",stdin);
	long long T=read();
	while(T--)
	{
		n=read(),ans=0;
		long long x=read(),y=read();
		for(long long i=1;i<=n;++i)
		{
			long long t=read();
			a[i].x=t%x,a[i].y=t%y;
		}
		sort(a+1,a+1+n);
		// for(long long i=1;i<=n;++i)
		// printf("%d %d\n",a[i].x,a[i].y);
		for(long long i=1;i<=n;++i)
		{
			long long j=i;
			while(j<=n && a[i].y==a[j].y)c[a[j++].x]++;
			for(long long k=i;k<j-1;++k)
			{
				// if(c[x-a[k].x]>0)printf("i = %d %d %d\n",i,c[x-a[k].x],a[k].y);
				c[a[k].x]--,ans+=c[(x-a[k].x)%x];
			}
			c[a[j-1].x]--;
			i=j-1;
		}
		printf("%lld\n",ans);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值