POJ2417

多次TLE後終於過了。。。

把if(hash.find(val)!=hash.end())改成if(hash[val])就過了。。。

裸的BSGS算法,甚至省去了很多特判的簡單題。

#include <cstdio>
#include <map>
#include <cmath>
#include <iostream>
using namespace std;
typedef long long LL;
map <LL,int> hash;
LL qpow(LL a,LL b,LL p)
{
    LL res=1;
    while(b)
    {
        if(b&1)
            res=res*a%p;
        b>>=1;
        a=a*a%p;
    }
    return res; 
}
int bsgs(LL a,LL b,LL p)
{
    hash.clear();
    LL t=ceil(sqrt(p));//sqrt分塊
    LL val=b%p;
    for(int j=0;j<=t;j++)
    {
        hash[val]=j;
        val=val*a%p;
    }
    a=qpow(a,t,p);
    val=1;
    for(int i=1;i<=t;i++)
    {
        val=val*a%p;
        if(hash[val])
            return ((i*t-hash[val])%p+p)%p;
    }
    return -1;
}
int main()
{
    LL a,p,b;
    while(~scanf("%lld%lld%lld",&p,&a,&b))
    {
        if(b==1)
        {
            printf("0\n");
            continue;
        }
        LL ans=bsgs(a,b,p);
        if(ans==-1)  printf("no solution\n");
        else printf("%lld\n",ans);
    }
    return 0; 
}

 

發佈了74 篇原創文章 · 獲贊 4 · 訪問量 5063
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章