codeforces 548 C Mike and Frog

来源:互联网 发布:淘宝双十一红包套现 编辑:程序博客网 时间:2024/05/01 14:58
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard 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 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.

Sample test(s)
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:



不失为一道好题吧……只是比赛的时候,方程式列错了……写了错误的代码


不过要是没写错,用了正确的姿势,在最后的半个钟头时间里……


我能够想到系数为0这个坑么。。。。。又或许。。。直接ptest,然后挂,肯定是这样。。。

#include<map>#include<string>#include<cstring>#include<cstdio>#include<cstdlib>#include<cmath>#include<queue>#include<vector>#include<iostream>#include<algorithm>#include<bitset>#include<climits>#include<list>#include<iomanip>#include<stack>#include<set>using namespace std;typedef long long ll;int m;int gcd(int a,int b){return b==0?a:gcd(b,a%b);}int cnt(int x,int h,int y){return int((ll(x)*h+y)%m);}int vis[1000010],num1,num2;void work(int h,int x,int y,int a){int sum=0;vis[h]++;while(1){sum++;h=cnt(x,h,y);if(h==a){if(num1==-1)num1=sum;else if(num2==-1){num2=sum;return;}}vis[h]++;if(vis[h]==3)return;}}int main(){cin>>m;int h1,a1,x1,y1,h2,a2,x2,y2;cin>>h1>>a1>>x1>>y1>>h2>>a2>>x2>>y2;num1=num2=-1;work(h1,x1,y1,a1);if(num1==-1){cout<<-1;return 0;}if(num2==-1)num2=num1;int a_num1=num1,a_num2=num2;memset(vis,0,sizeof(vis));num1=num2=-1;work(h2,x2,y2,a2);if(num1==-1){cout<<-1;return 0;}if(num2==-1)num2=num1;if(a_num1==a_num2){if(num1==num2){if(a_num1==num1)cout<<num1;elsecout<<-1;}else{int t=a_num1-num1;if(t<0||t%(num1-num2)!=0)cout<<-1;elsecout<<a_num1;}return 0;}if(num1==num2){int t=num1-a_num1;if(t<0||t%(a_num1-a_num2)!=0)cout<<-1;elsecout<<num1;return 0;}if(abs(a_num1-num1)%gcd(num2-num1,a_num2-a_num1)!=0){cout<<-1;return 0;}for(int i=0;;i++)if((num1-a_num1+ll(i)*(num2-num1))%(a_num2-a_num1)==0){cout<<num1+ll(i)*(num2-num1);break;}}


0 0