zoukankan      html  css  js  c++  java
  • BSGS

    问题:

    解法:

    代码:

    #include <iostream>  
    #include <string.h>  
    #include <stdio.h>  
    #include <math.h>  
    //#include <bits/stdc++.h>
    using namespace std;
    #define ll long long
    ll x,y,hashmod=2277779;
    ll top,hash[3000000],value[3000000],stack[3000000];
    struct re
    {
        ll locate(ll x)
        {
            ll h=x%hashmod;
            while (hash[h]!=-1 && hash[h]!=x) ++h;
            return(h);
        }
        void insert(ll x,ll y)
        {
            ll pos=locate(x);
            if (hash[pos]==-1)
            { 
            hash[pos]=x;value[pos]=y;stack[++top]=pos;
            } 
        }
        ll get(ll x)
        {
            ll pos=locate(x);
          if (hash[pos]==x) return(value[pos]);
          else return(-1);
        }
        void clear()
        {
            while (top>0) hash[stack[top--]]=-1;
      }
      void init()
      {
          memset(hash,0xFF,sizeof(hash));
      }
    }hashh;
    ll gcd(ll a,ll b,ll &x,ll &y)
    {
        if (b==0)
        {
            x=1; y=0; return(a); 
      }
      ll tmp=gcd(b,a%b,y,x);
      y=y-(a/b)*x;
    }
    ll bsgs(ll a,ll b,ll c)
    {
      ll sqrtn=(ll)ceil(sqrt(c));
      ll base=1;
      hashh.clear();
      for (ll i=0;i<sqrtn;i++)
      {
          hashh.insert(base,i);
          base=base*a %c;
      }
      ll d=1;
      for (ll i=0;i<sqrtn;i++)
      {
          gcd(d,c,x,y);
          x=(x*b%c+c)%c;
          ll j=hashh.get(x);
          if (j!=-1) return(i*sqrtn+j);
          d=d*base %c;
      }
      return -1;
    }
    int main()
    {
        freopen("noip.in","r",stdin);
        freopen("noip.out","w",stdout);
        std::ios::sync_with_stdio(false);
        ll a,b,p;
        hashh.init();
        while (cin>>p>>a>>b)
        {
        ll ans=bsgs(a,b,p);
        if (ans==-1) cout<<"no solution"<<endl;
        else cout<<ans<<endl;
        }
        return(0);
    }
    View Code
  • 相关阅读:
    NOsql总结
    关于Swift中的指针的那些事
    并发控制的概念
    并发控制--Concurrency control--乐观、悲观及方法
    数据库的三大系统
    数据库沉思录
    代码结构化(分层)阅读
    代码阅读困难的原因
    数据库锁与并发
    SQLite事务、错误与自动回滚
  • 原文地址:https://www.cnblogs.com/yinwuxiao/p/8262900.html
Copyright © 2011-2022 走看看