【bzoj 2242】【SDOI2011】计算器 代码(C++)

题目链接:
http://www.lydsy.com/JudgeOnline/problem.php?id=2242
题解:
说不上题解,第一问直接快速幂,第二问就是裸地求同余方程,第三问貌似是什么BSGS算法,感觉挺厉害的,好像也是这类方程的模板做法。注意long long的问题
代码:

#include
#include
#include
#include
#include
#include
#include
using namespace std;
int k,T;
int a,b,p;
long long ans;
void ksm(int x)
{
    if (x==1)
    {
        ans=(ans*a)%p;
        return ;
    }
    ksm(x/2);
    ans=(ans*ans)%p;
    if (x%2==1)
    ans=(ans*a)%p;
    return ;
}
int ex_gcd(long long a,long long b,long long &d,long long &x,long long &y)
{
    if (b==0)
    {   
        d=a;x=1;y=0;
    }
    else
    {
        ex_gcd(b,a%b,d,x,y);
        int t=y;
        y=-(a/b*y-x);
        x=t;
    }
}
map<int,int>vis;
int BSGS()
{
    ans=1;
    vis.clear();
    a%=p;
    if (a==0&&b==0) return 1;
    if (a==0) return -1;
    long long m=ceil(sqrt(p));
    long long t=1;
    for (long long i=1;iif (!vis[t]) vis[t]=i;
    }
    ksm(p-m-1);
    long long ine=1;
    for (long long k=0;kint i=vis[b*ine%p];
        if (i)
        {
            if (i==m+1) i=0;
            long long x=k*m+i;
            int zans=(int)x;
            return zans;
        }
        ine=ine*ans%p;
    }
    return -1;
}
int main()
{
//  freopen("calc.in","r",stdin);
//  freopen("calc.out","w",stdout);
    scanf("%d%d",&T,&k);
    while(T--)
    {
        scanf("%d%d%d",&a,&b,&p);
        if (k==1)
        {
            ans=1;
            ksm(b);
            int zans=(int)ans;
            printf("%d\n",zans);
        }
        if (k==2)
        {
            long long d,x,y;
            ex_gcd(a,p,d,x,y);
            if (b%d!=0)
            printf("Orz, I cannot find x!\n");
            else
            {
                x=((x*(b/d))%(p/d)+p/d)%(p/d);
                int zans=(int)x;
                printf("%d\n",zans);
            }
        }
        if (k==3)
        {
            int p=BSGS();
            if (p==-1)
                        printf("Orz, I cannot find x!\n");
            else printf("%d\n",p);
        } 
    }
}

你可能感兴趣的:(oi之路)