It's a simple question, but there's a bunch of disgusting boundaries.
After gouging out the disgusting border:
Suppose we know that the cyclic section on both sides is B1,B2
Where H is the first time to reach the target is A1,A2
And know that for the answer T
T=a1+b1*t1=a2+b2*t2
You can enumerate T1 to see if there is a viable solution.
And because the LCM (B1,B2) began to circulate.
and B1*b2<=b1*mod
So we enumerate the range of T1 in [0,mod]
If there is no solution within this range, there must be no solution
#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include < Algorithm>using namespace Std;typedef Long long ll;bool vis[1000010];int mod,h,a,x,y;int Go (int h,int x,int y) {memset ( Vis,0,sizeof (VIS)); int Cnt=0;while (1) {if (Vis[h]) return-1;vis[h]=1;h= (1ll*h*x+y)%mod;++cnt;if (h==a) return CNT;} int main () {scanf ("%d", &mod), scanf ("%d%d%d%d", &h,&a,&x,&y), int a1=go (h,x,y), B1=go (a,x,y); scanf ("%d%d%d%d", &h,&a,&x,&y); int A2=go (h,x,y), B2=go (a,x,y); if (a1==-1| | A2==-1) {printf (" -1\n"); return 0;} if (b1==-1&&b2==-1) {if (A1==A2) printf ("%d\n", A1), Else printf (" -1\n"); return 0;} if (b1!=-1&&b2!=-1) {for (int i=0;i<=mod;++i) {if (a1+1ll*b1*i>=a2&& (A1+1LL*B1*I-A2)%b2==0) { Cout<<a1+1ll*b1*i<<endl;return 0;}} printf (" -1\n"); return 0;} Else{if (b1==-1) Swap (A1,A2), swap (B1,B2), if (a2>=a1&& (A2-A1)%b1==0) printf ("%d\n", A2), Else printf (" -1\n" );} return 0;}
Codeforces #305 A Mike and Frog