Codeforces Round #305 (Div. 2) C题 (数论)
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.
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.
Print the minimum number of seconds until Xaniar reaches height a1 and Abol reaches height a2 or print -1 otherwise.
5
4 2
1 1
0 1
2 3
3
1023
1 2
1 0
1 2
1 1
-1
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #define LL long long using namespace std; int vist[1000007]; void gao(LL h,LL a,LL x,LL y,LL &t,LL &l,LL m){ t=l=0; memset(vist,-1,sizeof(vist)); vist[h]=0; while(true){ // cout<<x*h+y<<endl; h=(x*h+y)%m; // cout<<h<<endl; l++; if(vist[h]>-1){ l=t=-1; return ; } vist[h]=l; if(h==a){ break; } } // cout<<"YES"<<endl; LL tmp=l; t=l; while(true){ h=(x*h+y)%m; l++; if(vist[h]>tmp){ t=-1; break; } vist[h]=l; if(h==a) { break; } } if(t!=-1) l=l-tmp; else l=tmp; } LL gcd(LL a,LL b){ if(b==0) return a; return gcd(b,a%b); } int main(){ LL m,a1,h1,x1,y1,a2,h2,y2,x2,t1,l1,t2,l2; // while(scanf("%I64d",&m)!=EOF){ cin>>m; // scanf("%d%d%d%d",&h1,&a1,&x1,&y1); cin>>h1>>a1>>x1>>y1; gao(h1,a1,x1,y1,t1,l1,m); // scanf("%d%d%d%d",&h2,&a2,&x2,&y2); cin>>h2>>a2>>x2>>y2; gao(h2,a2,x2,y2,t2,l2,m); // printf("l1=%lld t1=%lld l2=%lld t2=%lld\n",l1,t1,l2,t2); if(t1==-1&&t2==-1){ if(l1==l2)//printf("%d\n",l1); cout<<l1<<endl; else puts("-1"); } else if(t1==-1||t2==-1){ if(l1==-1||l2==-1) puts("-1"); else{ // if(l1==l2) cout<<l1<<endl; if(t1==-1){ if(l1<t2) puts("-1"); else if((l1-t2)%l2==0){ // printf("%d\n",(l1-t2)/l2); cout<<l1<<endl; } else puts("-1"); } else if(t2==-1){ if(l2<t1) puts("-1"); else if((l2-t1)%l1==0){ // printf("%d\n",(l2-t1)/l1); cout<<l2<<endl; } else puts("-1"); } } } else{ if(t1>t2){ swap(t1,t2),swap(l1,l2); } // printf("l1=%lld t1=%lld l2=%lld t2=%lld\n",l1,t1,l2,t2); if(abs(t2-t1)%gcd(l2,l1)!=0) puts("-1"); else{ int k=0; while(true){ if((t2+k*l2-t1)%l1==0) break; k++; } // printf("%d\n",t2+k*l2); cout<<t2+k*l2<<endl; } } // } return 0; }