题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2815
题目大意:一颗K叉树,让你找出最小的深度D,使该深度上的叶子数对P取模为N。
分析:高次同余方程K^D≡N(mod P)的求解问题。只是需要注意的是,如果N>P,那么显然是不存在的(这地方WA哭了)。
实现代码如下:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
typedef long long LL;
const int maxn=65535;
struct Hash
{
int a,b,next;
}hsh[maxn<<1];
int flg[maxn+66];
int top,idx;
void ins(int a,int b)
{
int k=b&maxn;
if(flg[k]!=idx)
{
flg[k]=idx;
hsh[k].next=-1;
hsh[k].a=a;
hsh[k].b=b;
return ;
}
while(hsh[k].next!=-1)
{
if(hsh[k].b==b) return ;
k=hsh[k].next;
}
hsh[k].next=++top;
hsh[top].next=-1;
hsh[top].a=a;
hsh[top].b=b;
}
int find(int b)
{
int k=b&maxn;
if(flg[k]!=idx) return -1;
while(k!=-1)
{
if(hsh[k].b==b) return hsh[k].a;
k=hsh[k].next;
}
return -1;
}
int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
int exgcd(int a,int b,int &x,int &y)
{
int t,ret;
if(!b)
{
x=1,y=0;
return a;
}
ret=exgcd(b,a%b,x,y);
t=x,x=y,y=t-a/b*y;
return ret;
}
int Inval(int a,int b,int n)
{
int x,y,e;
exgcd(a,n,x,y);
e=(LL)x*b%n;
return e<0?e+n:e;
}
int pow_mod(LL a,int b,int c)
{
LL ret=1;
a%=c;
while(b)
{
if(b&1) ret=ret*a%c;
a=a*a%c;
b>>=1;
}
return ret;
}
int BabyStep(int A,int B,int C)
{
top=maxn;
++idx;
LL buf=1%C,D=buf,K;
int i,d=0,tmp;
for(i=0;i<=100;buf=buf*A%C,i++)
if(buf==B) return i;
while((tmp=gcd(A,C))!=1)
{
if(B%tmp) return -1; //无解
++d;
C/=tmp;
B/=tmp;
D=D*A/tmp%C;
}
int M=(int)ceil(sqrt((double)C));
for(buf=1%C,i=0;i<=M;buf=buf*A%C,i++) ins(i,buf);
for(i=0,K=pow_mod((LL)A,M,C);i<=M;D=D*K%C,i++)
{
tmp=Inval((int)D,B,C);
int w;
if(tmp>=0&&(w=find(tmp))!=-1)
return i*M+w+d;
}
return -1;
}
int main()
{
int A,B,C;
while(scanf("%d%d%d",&A,&C,&B)!=EOF)
{
if(B>C)
{
puts("Orz,I can’t find D!");
continue;
}
B%=C;
int tmp=BabyStep(A,B,C);
if(tmp<0) puts("Orz,I can’t find D!");
else printf("%d\n",tmp);
}
return 0;
}