luogu #3144. 「APIO 2019」奇怪装置

背景:

暑假集训正式开始(丰山正式旷掉) . . . ...
话说假期只有 10 d a y s 10days 了,作业(呵呵)。

题目传送门:

https://loj.ac/problem/3144

题意:

给出 n n 个区间以及 A , B A,B 。现在你要在每一个区间中根据公式算出其点对( x = ( ( t + t B ) ) m o d    A , y = ( t m o d    B ) x=((t+\lfloor\frac{t}{B}\rfloor)) \mod A,y=(t \mod B) )。现在你要求出不同点对的个数。

思路:

考虑算出 x = ( ( t + t B ) ) m o d    A , y = ( t m o d    B ) x=((t+\lfloor\frac{t}{B}\rfloor)) \mod A,y=(t \mod B) 的循环节。

t = 0 t=0 时, x = 0 , y = 0 x=0,y=0
t = k t=k 时,假设此时 x = 0 , y = 0 x=0,y=0 (因为一定会出现循环,且当前是第一次循环,那么循环节就是 k k ),有 x = ( ( k + k B ) ) m o d    A , y = ( k m o d    B ) x=((k+\lfloor\frac{k}{B}\rfloor)) \mod A,y=(k \mod B)

所以有 0 = ( k m o d    B ) 0=(k \mod B) ,即 k B k|B ,因此有:
0 = ( k + k B ) m o d    A 0=(k+\frac{k}{B}) \mod A

0 = k ( B + 1 ) B m o d    A 0=\frac{k(B+1)}{B} \mod A

等价于:
0 k ( B + 1 ) B ( m o d    A ) 0≡\frac{k(B+1)}{B}(\mod A)
插播一个知识(转载自:https://blog.csdn.net/linjiayang2016/article/details/80299904)

\quad a c b c ( m o d m ) ac≡bc\pmod m ,且 ( c , m ) = d (c,m)=d ,则 a b ( m o d m d ) a≡b\pmod{\dfrac{m}{d}}
  证明: a c b c ( m o d m ) \because ac≡bc\pmod m
      m a c b c \therefore m|ac-bc
      m c ( a b ) \therefore m|c(a-b)
     又 ( c , m ) = d \because (c,m)=d
      m d c d ( a b ) \therefore \frac md|\frac cd (a-b)
     又 ( c d , m d ) = 1 \because (\dfrac cd,\dfrac md)=1
      m d a b \therefore \frac md|a-b
     即 a b ( m o d m d ) a≡b\pmod{\dfrac{m}{d}}

那么有:
0 k B ( m o d    A gcd ( A , B + 1 ) ) 0≡\frac{k}{B}(\mod \frac{A}{\gcd(A,B+1)})

0 k ( m o d    A B gcd ( A , B + 1 ) ) 0≡k(\mod \frac{AB}{\gcd(A,B+1)})

因为 k k 为最小的正整数,所以 k = A B gcd ( A , B + 1 ) k=\frac{AB}{\gcd(A,B+1)}
即循环节为 A B gcd ( A , B + 1 ) \frac{AB}{\gcd(A,B+1)}

既然求出了这个,我们再用线段覆盖(去掉相同的数对)即可。

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long
using namespace std;
	int n,tot=0;
	LL A,B,len,ans=0;
	struct node{LL l,r;} a[2000010];
LL gcd(LL x,LL y)
{
	return !y?x:gcd(y,x%y);
}
bool cmp(node x,node y)
{
	return x.l==y.l?x.r<y.r:x.l<y.l;
}
int main()
{
	LL l,r;
	scanf("%d %lld %lld",&n,&A,&B);
	len=(A*B/gcd(A,B+1));
	for(int i=1;i<=n;i++)
	{
		scanf("%lld %lld",&l,&r);
		if(r-l+1>=len)
		{
			printf("%lld\n",len);
			return 0;
		}
		if(l%len<=r%len) a[++tot]=(node){l%len,r%len}; else a[++tot]=(node){l%len,len-1},a[++tot]=(node){0,r%len};
	}
	sort(a+1,a+tot+1,cmp);
	l=a[1].l,r=a[1].r;
	for(int i=2;i<=tot;i++)
	{
		if(a[i].l>r) {ans+=r-l+1;l=a[i].l,r=a[i].r;continue;}
		r=max(r,a[i].r);
	}
	ans+=r-l+1;
	printf("%lld",ans);
}

猜你喜欢

转载自blog.csdn.net/zsyz_ZZY/article/details/93708821