CodeForces

来源:互联网 发布:sql select as语句 编辑:程序博客网 时间:2024/06/05 22:52

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.

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.

Input

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.

Output

Print the minimum number of seconds until Xaniar reaches height a1 and Abol reaches height a2 or print -1 otherwise.

Examples
input
54 21 10 12 3
output
3
input
10231 21 01 21 1
output
-1
Note

In the first sample, heights sequences are following:

Xaniar: 

Abol: 



C语言AC代码

#include<stdio.h>int main(){    long long m,h1,h2,a1,a2,x1,x2,y1,y2;    long long i,p1,p2,len1,len2;    while(scanf("%I64d",&m)!=EOF)    {        p1=p2=len1=len2=-1;        scanf("%I64d%I64d",&h1,&a1);        scanf("%I64d%I64d",&x1,&y1);        scanf("%I64d%I64d",&h2,&a2);        scanf("%I64d%I64d",&x2,&y2);        for(i=1;i<=2*m;i++)        {            h1=(x1*h1+y1)%m;            h2=(x2*h2+y2)%m;            if(h1==a1)            {                if(p1==-1)                    p1=i;                if(len1==-1)                    len1=i-p1;            }            if(h2==a2)            {                if(p2==-1)                    p2=i;                if(len2==-1)                    len2=i-p2;            }        }        if(p1==0||p2==0)            printf("-1\n");        else if(p1==p2)            printf("%I64d",p1);        else        {            for(i=1;i<=2*m;i++)            {                if(p1<p2)                    p1=p1+len1;                else                    p2=p2+len2;                if(p1==p2)                {                    printf("%I64d\n",p1);                    return 0;                }            }            printf("-1\n");        }    }    return 0;}
思路:1找出循环,2*m肯定可以发现,第一次找到,第二次找到循环的距离

2利用循环看有没有相交的

心得:多思考


原创粉丝点击