2242: [SDOI2011]計算器
Time Limit: 10 Sec Memory Limit: 512 MBSubmit: 3179 Solved: 1248
[Submit][Status][Discuss]
Description
Input
輸入包含多組數據。
Output
Sample Input
3 1
2 1 3
2 2 3
2 3 3
【樣例輸入2】
3 2
2 1 3
2 2 3
2 3 3
【數據規模和約定】
對於100%的數據,1<=y,z,p<=10^9,爲質數,1<=T<=10。
Sample Output
2
1
2
【樣例輸出2】
2
1
0
HINT
Source
這是一道題,也是3道題。。。前兩道SB題,最後一道要求y^x=z(mod p)的x值
由於費馬小定理,答案若存在一定不會>p-1
於是我們可以分塊亂搞
y^x=y^(k*sqrt(p)+i)=z (0<=i<sqrt(x))
即 y^i=z/(y^(k*sqrt(p))=z*inv(y^(k*sqrt(p)))=z*y^(k*sqrt(p)*(p-2)%(p-1))
哈希表亂搞即可
這個算法的學名叫大步小步算法--By mcfx
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<tr1/unordered_map>
using namespace std;
tr1::unordered_map<int,int>st;
int qmod(int a,int b,int p){
int tmp=a,ans=1;
for(int i=0;b>>i;i++,tmp=1ll*tmp*tmp%p)
if((b>>i)&1)ans=1ll*ans*tmp%p;
return ans;
}
void exgcd(int a,int b,int& d,int &x,int &y){
if(b==0){
x=1;y=0;d=a;
} else exgcd(b,a%b,d,y,x),y-=a/b*x;
}
int get(int y,int z,int p){
int d,x,m;
// printf("[%d,%d]",y,-p);
exgcd(y,p,d,x,m);
if(z%d!=0)return -1;
while(x<0)x+=p;
return 1ll*x*z%p;
}
int get2(int y,int z,int p){
if(y%p==0)return z==0?1:-1;
int mxs=sqrt(p)+1;
int f=qmod(y,mxs,p);
st.clear();
for(int i=0,j=1;i<mxs;++i,j=1ll*j*y%p)
if(!st.count(j))st[j]=i;
for(int i=0;i<=p;i+=mxs){
int ans=1ll*z*qmod(y,1ll*i*(p-2)%(p-1),p)%p;
if(st.count(ans))return st[ans]+i;
}
return -1;
}
void print(int x){
x==-1?printf("Orz, I cannot find x!\n"):printf("%d\n",x);
}
int main(){
int y,z,p,t,k,x;
scanf("%d%d",&t,&k);
while(t--){
scanf("%d%d%d",&y,&z,&p);
if(k==1)printf("%d\n",qmod(y,z,p));
else if(k==2)print(get(y,z,p));
else if(k==3)print(get2(y,z,p));
}
}