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 微信小程序消息模板
- 下一篇: 正则学习:组的定义及引用方式