门票

https://loj.ac/problem/10041

题目描述

  给定一个数列,a0=1,ai+1 = (A×ai + ai mod B)mod C。求第一个出现重复项的标号。

思路

  由于给定答案不会超过2×106,所以我们可以暴力枚举数列的每一项,再快速判断是否存在即可。显然这道题可以用map搞过去,不过散列表也是一个不错的选择。我们对结果取一个合适的模数,然后插入散列表中,再查找即可,由于数列不会太长,所以可以较快查找。当然你可以用开放寻址法优化,不过数组开的大一些链不太长并不会T。

代码

#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const ull mod=2e6+3;
ull nxt[2000005],poi[mod+5],key[2000005],tot;
void insert(ull x)
{
    ull h=x%mod;
    nxt[++tot]=poi[h];
    poi[h]=tot;
    key[tot]=x;
}
bool check(ull x)
{
    ull h=x%mod;
    for(int i=poi[h];i;i=nxt[i])
        if(key[i]==x)return 1;
    return 0;
}
int main() 
{
    ull a,b,c,cnt,x;
    scanf("%llu%llu%llu",&a,&b,&c);
    x=1;cnt=0;
    while(1)
    {
        insert(x);
        x=(a*x+x%b)%c;
        cnt++;
        if(check(x)||cnt>2000000)break ;
    }
    if(cnt>2000000)printf("-1");
    else printf("%llu",cnt);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/fangbozhen/p/11621868.html
今日推荐