xdoj1194----(bsgs-用数组实现链表 真的是好啊)

时间:2023-03-09 01:42:01
xdoj1194----(bsgs-用数组实现链表 真的是好啊)
 #include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long LL;
const LL q=;
const int a=;
const int mod=;
LL hs[mod],id[mod],head[mod],_next[mod];
int top;
inline void _inset (LL x, LL y) {
hs[top]=y; id[top]=x;// hs 是健值 id是映射的数
                 // 所有的值按序号保存 但要根据健值记录它们存放的位置
LL k=y%mod;
_next[top]=head[k];// 每个链表有一个虚拟头节点 用哈希函数确定应该插入哪个头节点
           // next 表示下一个元素存放的节点 用来连接链表
head[k]=top++;
}
LL _find (LL x) {
LL k=x%mod;
for (LL i=head[k];i!=-;i=_next[i])
if (hs[i]==x) return id[i];
return -;
}
LL bsgs (LL y) {
top=;
memset (head,-,sizeof(head));
LL t=sqrt (q)+;
LL tmp=;
for (int i=;i<t;i++) {
_inset (i,tmp*y%q);
tmp=tmp*a%q;
}
LL ans=;
for (int i=;i<=t;i++) {
ans=ans*tmp%q;
LL m=_find(ans);
if (m>=) return i*t-m;
}
return -;
}
LL q_pow (LL x,LL k) {
LL ans=;
while (k) {
if (k&) ans=ans*x%q;
k=k>>; x=x*x%q;
}
return ans;
}
int main ()
{
LL y1,y2;
while (~scanf ("%lld %lld",&y1,&y2)) {
LL x1=bsgs (y1);
LL x2=bsgs (y2);
if (x1==-||x2==-) printf ("No Solution\n");
else printf ("%lld\n",q_pow (y1,x2) );
}
return ;
}