code forces 548C:Mike and frog

C. Mike and Frog
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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 a modulo 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
5
4 2
1 1
0 1
2 3
output
3
input
1023
1 2
1 0
1 2
1 1
output
-1
Note
In the first sample, heights sequences are following:

Xaniar:

Abol:

题目原文:http://codeforces.com/problemset/problem/548/C
库省略

using namespace std;
ll m,h1,h2,a1,a2,x1,x2,y,y2;
ll firs1=-1,firs2=-1,siz1=-1,siz2=-1;
int main()
{
    cin>>m;
    cin>>h1>>a1>>x1>>y;
    cin>>h2>>a2>>x2>>y2;
    for(int i=0;i<2*m;i++)
    {
        h1 = (h1*x1+y)%m;
        if(h1==a1)
        {
            if(firs1==-1)
                firs1 = i+1;
            else
                if(siz1 == -1)
                    siz1 = i-firs1+1;
        }
        h2 = (h2*x2+y2)%m;
        if(h2 == a2)
        {
            if(firs2==-1)
                firs2 = i+1;
            else
                if(siz2==-1)
                siz2 = i-firs2+1;
        }
    }
    if(firs1==-1 || firs2==-1)
        cout<<-1;
    else
        if(firs1 == firs2)
            cout<<firs1;
    else
    {
        for(int i=1;i<=2*m;i++)
        {
            if(firs1<firs2)
                firs1+=siz1;
            else
                firs2+=siz2;
            if(firs1==firs2)
            {
                cout<<firs1;
                return 0;
            }
        }
        cout<<-1;
    }
    return 0;
}

题目意思是给出公式(h*x+y)%m,然后分别给出两个物体的a,h,x,y,问通过公式,两个物体能否同时到达a1和a2。思路很简单,同时按照公式算下去,主要还是能否找到循环节,假如一个循环节过去了但还是没有找到正确答案的话,就直接输出-1,所以我开了两个变量,一个是第一个数,还有一个就是循环姐的长度。写的时候要注意把i设置成从1开始。

原文地址:https://www.cnblogs.com/NightRaven/p/9333269.html