codeforces 547A 548C

来源:互联网 发布:淘宝模特拍摄的业务 编辑:程序博客网 时间:2024/06/07 18:01

题目大意:有两个数h1,h2,每一次操作,h1=(x1*h1+y1)%m, h2=(x2*h2+y2),问多少次操作后,h1=a1,h2=a2,输出操作次数,不可能达到则输出-1.

思路:h=(x*h+y)%m,h的种类数是有限的,即h的值是循环出现的,这样我们就可以直接模拟,具体操作见代码注释。

#include<iostream>#include<cstdio>#include<cstring>#include<string>#include<cmath>#include<stack>#include<algorithm>#include<vector>#define mx 1000005#define y1 y12345#define inf 0x3f3f3f3f#define LL long long#define ULL unsigned long long#define mod 1000000007#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1using namespace std;const LL fit=1200000;               //修正值bool num[mx],shit[fit<<1];LL m,h1,a1,x1,y1,h2,a2,x2,y2;LL can(LL h,LL a,LL x,LL y){      memset(num,false,sizeof(num));    int ans=0;   do{        ans++;                   //记录多少次操作,h能变为a        h=(x*h+y)%m;        if(num[h])return -1;     //如果出现过的值再次出现,说明h能取到的值中没有a        num[h]=true;    } while(h!=a);    return ans;}int main(){    memset(shit,false,sizeof(shit));    cin>>m>>h1>>a1>>x1>>y1>>h2>>a2>>x2>>y2;    LL ans=-1;    LL ans1=can(h1,a1,x1,y1);    LL ans2=can(h2,a2,x2,y2);    if(ans1>0&&ans2>0){        if(ans1==ans2)ans=ans1;        else{            LL p1 = can (a1, a1, x1, y1);  //p1次操作后,a1能再次变为a1LL p2 = can (a2, a2, x2, y2);if(p1<1 && p2<1)ans=-1;    else{    if(p1<1)p1=0;    if(p2<1)p2=0;    while(ans1!=ans2){        int x=ans1-ans2;        if(shit[fit+x]){       //这里x可能为负数,加上修正值            ans1=-1;           //如果x值曾经出现过,说明ans1不可能等于ans2            break;        }        shit[fit+x]=true;        if(ans1<ans2)ans1+=p1;        else ans2+=p2;    }    ans=ans1;}        }    }    cout<<ans<<endl;    return 0;}



0 0
原创粉丝点击