求循环节很关键。还有,得确定循环次数。
比如青蛙三次达到a1,花四次达到a2,那么循环12次时,也可以同时到达a1,a2
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<ctype.h>
#include<algorithm>
#include<deque>
#include<functional>
#include<iterator>
#include<vector>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#define CPY(A, B) memcpy(A, B, sizeof(A))
typedef long long LL;
typedef unsigned long long uLL;
const int MOD = int (1e9) + 7;
const int INF = 0x3f3f3f3f;
const LL INFF = 0x3f3f3f3f3f3f3f3fLL;
const double EPS = 1e-9;
const double OO = 1e20;
const double PI = acos (-1.0);
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
using namespace std;
int main() {
LL m,h1,h2,a1,a2,x1,x2,y1,y2,i;
LL p1,r1,p2,r2; p1=p2=r1=r2=-1;
scanf ("%I64d",&m);
scanf ("%I64d%I64d%I64d%I64d",&h1,&a1,&x1,&y1);
scanf ("%I64d%I64d%I64d%I64d",&h2,&a2,&x2,&y2);
for (i=1; i<=2*m; i++) {
h1= (h1*x1+y1) %m;
if (h1==a1) {
if (p1==-1) {p1=i;}//记录起点
else if (r1 == -1) {r1=i-p1;}//第二次到达时,减掉起点就是循环长度
}
h2 = (h2*x2+y2) %m;
if (h2==a2) {
if (p2==-1) {p2=i;}
else if (r2 == -1) {r2=i-p2;}
}
}
if (p1==-1||p2==-1) {
printf ("-1\n");
} else if (p1 == p2) {
printf ("%I64d\n",p1);//循环节一样长,那么第一次就可以达到
} else {
for (i=1; i<=2*m; i++) {//都小于m,所以最多循环2m次
if (p1<p2) { p1+=r1;}
else {p2+=r2;}
if (p1==p2) {
printf ("%I64d\n",p1);
return 0;
}
}
printf ("-1\n");
}
return 0;
}