Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h1 and height of Abol is h2. Each second, Mike waters Abol and Xaniar.
![](https://i-blog.csdnimg.cn/blog_migrate/fe53d5a0a13bcd430d14047ba104eba6.png)
So, if height of Xaniar is h1 and height of Abol is h2, after one second height of Xaniar will become and height of Abol will become
where x1, y1, x2 and y2 are some integer numbers and
denotes the remainder of amodulo b.
Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is a1 and height of Abol is a2.
Mike has asked you for your help. Calculate the minimum time or say it will never happen.
The first line of input contains integer m (2 ≤ m ≤ 106).
The second line of input contains integers h1 and a1 (0 ≤ h1, a1 < m).
The third line of input contains integers x1 and y1 (0 ≤ x1, y1 < m).
The fourth line of input contains integers h2 and a2 (0 ≤ h2, a2 < m).
The fifth line of input contains integers x2 and y2 (0 ≤ x2, y2 < m).
It is guaranteed that h1 ≠ a1 and h2 ≠ a2.
Print the minimum number of seconds until Xaniar reaches height a1 and Abol reaches height a2 or print -1 otherwise.
5 4 2 1 1 0 1 2 3
3
1023 1 2 1 0 1 2 1 1
-1
题意:h1=(h1*x1+y1)%m,h2=(h2*x2+y2)%m,问h1==a1 且h2==a2的最近时刻是多少。
思路:首先,我们要找出从h1->a1的时间a,a1->a1的循环节b,h2->a2的时间c,a2->a2的循环节d,假设其中有一些不存在就特判,如果均存在的话就是找一个最小的值,使得a+bx=c+dy=t,我们不难看出t的最大值为max(a,c)+b*d ,所以只要枚举x的值即可。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
int T,t,n;
int d1[1000010],d2[1000010];
bool v1[1000010],v2[1000010];
ll m,h1,a1,x1,y1,h2,a2,x2,y2;
ll a,b,c,d;
int main()
{
int j,k,p;
ll i,r;
scanf("%I64d%I64d%I64d%I64d%I64d%I64d%I64d%I64d%I64d",&m,&h1,&a1,&x1,&y1,&h2,&a2,&x2,&y2);
for(i=h1,p=0;!v1[i];p++)
{
d1[i]=p;
v1[i]=1;
i=(i*x1+y1)%m;
}
a=d1[a1];
if(a<d1[i])
b=0;
else
b=p-d1[i];
for(i=h2,p=0;!v2[i];p++)
{
d2[i]=p;
v2[i]=1;
i=(i*x2+y2)%m;
}
c=d2[a2];
if(c<d2[i])
d=0;
else
d=p-d2[i];
if(!v1[a1] || !v2[a2])
printf("-1\n");
else if(!b && !d)
{
if(a==c)
printf("%I64d\n",a);
else
printf("-1\n");
}
else if(!b)
{
if(a>=c && (a-c)%d==0)
printf("%I64d\n",a);
else
printf("-1\n");
}
else if(!d)
{
if(c>=a && (c-a)%b==0)
printf("%I64d\n",c);
else
printf("-1\n");
}
else
{
r=max(a,c)+b*d;
for(i=a;i<=r;i+=b)
if(i>=c && (i-c)%d==0)
break;
if(i<=r)
printf("%I64d\n",i);
else
printf("-1\n");
}
}