模板 BSGS
Posted hznumqf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了模板 BSGS相关的知识,希望对你有一定的参考价值。
BSGS存在的目的是求中x的解,BSGS算法要求A与C互质,且C为质数。
#pragma warning(disable:4996) #include<iostream> #include<algorithm> #include<bitset> #include<tuple> #include<unordered_map> #include<fstream> #include<iomanip> #include<string> #include<cmath> #include<cstring> #include<vector> #include<map> #include<set> #include<list> #include<queue> #include<stack> #include<sstream> #include<cstdio> #include<ctime> #include<cstdlib> #define pb push_back #define INF 0x3f3f3f3f #define inf 0x7FFFFFFF #define moD 1000000003 #define pii pair<ll,ll> #define eps 1e-8 #define equals(a,b) (fabs(a-b)<eps) #define bug puts("bug") #define re register #define fi first #define se second typedef long long ll; typedef unsigned long long ull; const ll MOD = 1e6 + 7; const int maxn = 1e6 +5; const double Inf = 10000.0; const double PI = acos(-1.0); using namespace std; #define mod 75643 struct Hash{ int ha; int id; int next; }a[mod]; int head[mod]; int top; void Insert(int x, int y){ int k = x % mod; a[top].ha = x; a[top].id = y; a[top].next = head[k]; head[k] = top++; } int Find(int x){ int k = x % mod; for (int i = head[k]; i != -1; i = a[i].next) if (a[i].ha == x) return a[i].id; return -1;//表示没有找到 } int BSGS(int a, int b, int c){ if (b == 1) return 0; memset(head, -1, sizeof(head)); top = 1;//一定要等于1 int m = sqrt(c); ll p = 1, x = 1; for (int i = 0; i < m; ++i) { Insert(p * b % c, i); p = p * a % c; } for (ll i = m; ; i += m){ x = x * p % c;//此时的p已经等于a^m int j = Find(x); if (j != -1) return i - j;//这里的i已经等于i*m了 if (i > c) break; } return -1; } int main() { int a, b, c; while (~scanf("%d%d%d", &c, &a, &b)) { int ans = BSGS(a, b, c); if (ans == -1) puts("no solution"); else printf("%d ", ans); } }
以上是关于模板 BSGS的主要内容,如果未能解决你的问题,请参考以下文章