Summer Training day4 Mod Tree 大步小步法求离散对数模板

 
  The picture indicates a tree, every node has 2 children. 
  The depth of the nodes whose color is blue is 3; the depth of the node whose color is pink is 0. 
  Now out problem is so easy, give you a tree that every nodes have K children, you are expected to calculate the minimize depth D so that the number of nodes whose depth is D equals to N after mod P.
Input
The input consists of several test cases. 
Every cases have only three integers indicating K, P, N. (1<=K, P, N<=10^9)
Output
The minimize D. 
If you can’t find such D, just output “Orz,I can’t find D!”
Sample Input
3 78992 453
4 1314520 65536
5 1234 67
Sample Output
Orz,I can’t find D!
8
20

求离散对数的模板题

代码:

#include <iostream>
#include <cstdio>
#include <cmath> 
#include <map> 
#include <algorithm>
#include <set> 
using namespace std;
typedef long long LL;
int K,P,N;
LL mod_pow(LL x,LL p,LL mod)
{
       LL ans = 1;
       while(p > 0)
       {
              if(p & 1)
                     ans = (x * ans)%mod;
              x = (x*x) % mod;
              p >>= 1;
       }
       return (ans + mod )% mod; 
}
LL exgcd(LL a, LL b, LL& x, LL& y)
{
  if(!b){ x = 1; y = 0; return a; }
  LL ret = exgcd(b, a % b, x, y);
  LL tmp = x; x = y;
  y = tmp - a/b*y;
  return ret;
}
LL mod_inverse(LL a,LL m)
{
       LL x,y;
       exgcd(a,m,x,y);
       return (m+x%m)%m;
}
LL BSGS(LL a,LL b,LL MOD){
	LL m = sqrt(MOD + 0.5);
	//if(m * m < MOD) m++;
	LL am = mod_pow(a,m,MOD);
	LL inv_am = mod_inverse(am,MOD);
	map<LL,LL> mp;
	//baby step
	LL aj = 1;
	mp[1] = m; // ÓÃm±íʾ0 
	for(int j = 1;j < m;j++){
		aj = aj * a % MOD; 
		if(!mp[aj]) mp[aj] = j;
		
	}
	//giant step
	LL inv_am_i = b % MOD;
	if(mp[inv_am_i]) return mp[inv_am_i] % m;
	for(int i = 1;i < m;i++){
		inv_am_i = inv_am_i * inv_am % MOD;
		if(mp[inv_am_i]) return i * m + (mp[inv_am_i] % m);
	}
	return -1;
}

LL ex_BSGS(LL a,LL b,LL MOD){
	LL g,c = 0,v = 1;
	while((g = __gcd(a,MOD)) != 1){
		if(b % g) return -1;
		MOD /= g;
		b /= g;
		v = v * a / g % MOD;
		c++;
		if(b == v) return c;
	}
	b = b * mod_inverse(v,MOD) % MOD;
	LL ret = BSGS(a,b,MOD);
	return ~ret?ret + c:ret;
}
int main(){
	while(cin>>K>>P>>N){
		LL ans = ex_BSGS(K,N,P);
		if(ans == -1 || N >= P){
			printf("Orz,I can’t find D!\n");
		}
		else{
			printf("%lld\n",ans);
		}
	}
	return 0;
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值