campjls讲过模数循环节的问题,今天做cf才做到这类题
h1->a1的长度为len1,a1->a1的长度为cir1
h2->a2的长度为len2,a2->a2的长度为cir2
要注意特判,再用exgcd求
len1+cir1*t1 = len2+cir2*t2的一组整数解,把t1回代就是答案
//#pragma comment(linker,"/STACK:1024000000,1024000000") #include<iostream> #include<cstdio> #include<string> #include<cstring> #include<vector> #include<cmath> #include<queue> #include<stack> #include<map> #include<set> #include<algorithm> #include <stack> #include <list> using namespace std; const int SZ=1000010,INF=0x7FFFFFFF; typedef long long lon; lon exgcd(lon a,lon b,lon &x,lon &y,lon &d) { if(b==0) { x=1; y=0; d=a; return a; } lon gcd=exgcd(b,a%b,x,y,d); lon x2=x,y2=y; x=y2; y=x2-(a/b)*y2; return gcd; } int main() { std::ios::sync_with_stdio(0); //freopen("d:\1.txt","r",stdin); lon m; cin>>m; lon h1,a1,x1,y1,h2,a2,x2,y2; cin>>h1>>a1>>x1>>y1>>h2>>a2>>x2>>y2; set<pair<lon,lon>> st; st.insert(make_pair(h1,h2)); lon cnt1=0,cnt2=0,pri1=0,pri2=0,t1=0,t2=0; for(lon time=1;;++time) { lon newa1=(x1*h1+y1)%m,newa2=(x2*h2+y2)%m; if(newa1==a1) { if(cnt1==0)pri1=time; else if(cnt1==1) t1=time-pri1; ++cnt1; } if(newa2==a2) { if(cnt2==0)pri2=time; else if(cnt2==1)t2=time-pri2; ++cnt2; } if(pri1&&pri2&&t1&&t2)break; if(newa1==a1&&newa2==a2) { cout<<time<<endl; return 0; } if(time>1e7) { cout<<-1<<endl; return 0; } h1=newa1,h2=newa2; } lon x,y,d; exgcd(abs(t1),abs(t2),x,y,d); if(abs(pri1-pri2)%d==0) { x*=(pri2-pri1)/d; y*=(pri2-pri1)/d; y*=-1; if(x<0) { int beishu=abs((x)/(t2/d)); x=x+beishu*abs(t2/d); y=y+beishu*abs(t1/d); } if(y<0) { int num=0; num=abs((y)/(t1/d)); y=y+num*abs(t1/d); if(y<0) { ++num; y+=abs(t1/d); } x+=num*abs(t2/d); } if(x<0)x+=abs(t2/d); if(x>0&&y>0) { int num1=abs((x)/(t2/d)); int num2=abs((y)/(t1/d)); int miner=min(num1,num2); x-=miner*abs(t2/d); y-=miner*abs(t1/d); } cout<<pri1+x*t1<<endl; } else cout<<-1<<endl; return 0; }