BZOJ 2242: [SDOI2011]计算器 [快速幂 BSGS]
生活随笔
收集整理的這篇文章主要介紹了
BZOJ 2242: [SDOI2011]计算器 [快速幂 BSGS]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2242: [SDOI2011]計算器
題意:求\(a^b \mod p,\ ax \equiv b \mod p,\ a^x \equiv b \mod p\),p是質數
這種裸題我竟然WA了好多次
第三個注意判斷a和b整除p的情況
#pragma GCC optimize ("O2") #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <map> using namespace std; typedef long long ll; #define fir first #define sec second inline int read() {char c=getchar(); int x=0, f=1;while(c<'0' || c>'9') {if(c=='-')f=-1; c=getchar();}while(c>='0' && c<='9') {x=x*10+c-'0'; c=getchar();}return x*f; }int a, b, p; ll Pow(ll a, int b, int p) {a%=p; ll ans=1;for(; b; b>>=1, a=a*a%p)if(b&1) ans=ans*a%p;return ans; } ll inv(int a, int p) {if(a%p==0) return -1;return Pow(a, p-2, p); } map<int, int> ma; ll ind(int a, int b, int p) {a%=p; b%=p;ma.clear();ll e=1; int m=sqrt(p)+0.5;for(int i=0; i<m; i++) {if(!ma.count(e)) ma[e]=i;e=e*a%p;}e=Pow(e, p-2, p);for(int i=0; i<m; i++) {if(ma.count(b)) return i*m + ma[b];b=b*e%p;}return -1; } int main() {//freopen("in","r",stdin);freopen("calc.in","r",stdin);freopen("calc.out","w",stdout);int T=read(), type=read();while(T--) {a=read(); b=read(); p=read();ll ans;if(type==1) ans=Pow(a, b, p);else if(type==2) {ans=inv(a, p);if(ans!=-1) ans=ans*b%p;}else ans=ind(a, b, p);if(ans==-1) puts("Orz, I cannot find x!");else printf("%lld\n", ans);} }轉載于:https://www.cnblogs.com/candy99/p/6652771.html
總結
以上是生活随笔為你收集整理的BZOJ 2242: [SDOI2011]计算器 [快速幂 BSGS]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 微信小程序消息模板
- 下一篇: 正则学习:组的定义及引用方式