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:
题意:
给一个青蛙和一个花浇水,他们每次会长高(%m),求一个最少的时间能使得frog到a1高度,flower到a2高度。
解题思路:
做2*m次操作,如果在第一次能到a1(a2),那么第二次也能到。
然后暴力。
AC代码:
#include <bits/stdc++.h>
using namespace std;
#define int long long
vector<int> ans1, ans2;
main()
{
int m;
scanf("%lld",&m);
int h1, a1;
scanf("%lld%lld",&h1, &a1);
int x1, y1;
scanf("%lld%lld",&x1, &y1);
int h2, a2;
scanf("%lld%lld",&h2, &a2);
int x2, y2;
scanf("%lld%lld",&x2, &y2);
int tot = 0;
while(tot <= 2*m)
{
if(h1 == a1)
ans1.push_back(tot);
if(h2 == a2)
ans2.push_back(tot);
tot++;
h1 = (x1 * h1 + y1) % m;
h2 = (x2 * h2 + y2) % m;
}
if(ans1.empty() || ans2.empty())
{
printf("-1");
return 0;
}
int t1 = ans1[0];
int t2 = ans2[0];
int s1 = ans1[1] - ans1[0];
int s2 = ans2[1] - ans2[0];
for(int i = 1; i <= 5e6; i++)
{
if(t1 == t2)
{
printf("%lld",t1);
return 0;
}
if(t1 < t2)
t1 += s1;
else
t2 += s2;
}
printf("-1");
return 0;
}