poj 2417 Discrete Logging (BSGS算法)

题目链接

题意:

Given a prime P, 2 <= P < 231, an integer B, 2 <= B < P, and an integer N, 1 <= N < P, compute the discrete logarithm of N, base B, modulo P. That is, find an integer L such that BL == N (mod P)

思路:bsgs算法

详情见BSGS算法笔记

然后被map的count坑了一下? 我想判断map中某个key是否存在,用count会TLE,find也会TLE,[]可以通过....不太懂,复杂度不都是log吗,差常数?还是有人会退化?

不过似乎[]比较安全就对了。

/* ***********************************************
Author :111qqz
Created Time :2017年07月23日 星期日 11时11分00秒
File Name :2417.cpp
************************************************ */
 1#include <cstdio>
 2#include <cstring>
 3#include <iostream>
 4#include <algorithm>
 5#include <vector>
 6#include <queue>
 7#include <set>
 8#include <map>
 9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define PB push_back
14#define fst first
15#define sec second
16#define lson l,m,rt<<1
17#define rson m+1,r,rt<<1|1
18#define ms(a,x) memset(a,x,sizeof(a))
19typedef long long LL;
20#define pi pair < int ,int >
21#define MP make_pair
 1using namespace std;
 2const double eps = 1E-8;
 3const int dx4[4]={1,0,0,-1};
 4const int dy4[4]={0,-1,1,0};
 5const int inf = 0x3f3f3f3f;
 6LL p,b,n;
 7map<LL,LL>Hash;
 8map<LL,LL>::iterator it;
 9inline LL ksm(LL a,LL b,LL MOD)
10{
11    LL res = 1LL;
12    while (b)
13    {
14	if (b&1) res = (res*a)%MOD;
15	b = b >> 1;
16	a = (a*a)%MOD;
17    }
18    return res;
19}
20LL BSGS(LL a,LL b ,LL p) // a^x = b (mod p),求x 
21{
22    a%=p;
23    b%=p;
24    if (!a&&!b) return 1;
25    if (!a) return -1;
26    Hash.clear();
27    LL m = ceil(sqrt(double(p)));
28    LL tmp = b;
29    for (LL j = 0 ; j <= m ; j++)
30    {
31	Hash[tmp]=j;
32	tmp = (tmp*a)%p;
33    }
34    tmp = ksm(a,m,p);
35    LL ret = 1;
1    for (LL i = 1  ; i <= m+1 ; i++)
2    {
3	ret = ret*tmp%p;
4	if (Hash[ret]) return i*m-Hash[ret]; //注意处理下%....虽然其实不处理也没关系...
5    }
6    return -1;
 1}
 2int main()
 3{
 4        #ifndef  ONLINE_JUDGE 
 5       // freopen("./in.txt","r",stdin);
 6  #endif
 7	while (~scanf("%lld%lld%lld",&p,&b,&n))   // B^L = n(mod p)
 8	{
 9	    LL ans = BSGS(b,n,p);
10	    if (ans==-1) printf("no solution\n");
11	    else printf("%lld\n",(ans%p+p)%p);
12	}
1  #ifndef ONLINE_JUDGE  
2  fclose(stdin);
3  #endif
4    return 0;
5}