bzoj2242

2242: [SDOI2011]計算器

Time Limit: 10 Sec  Memory Limit: 512 MB
Submit: 3179  Solved: 1248
[Submit][Status][Discuss]

Description

你被要求設計一個計算器完成以下三項任務:
1、給定y,z,p,計算Y^Z Mod P 的值;
2、給定y,z,p,計算滿足xy≡ Z ( mod P )的最小非負整數;
3、給定y,z,p,計算滿足Y^x ≡ Z ( mod P)的最小非負整數。

Input

 輸入包含多組數據。

第一行包含兩個正整數T,K分別表示數據組數和詢問類型(對於一個測試點內的所有數據,詢問類型相同)。
以下行每行包含三個正整數y,z,p,描述一個詢問。

Output

對於每個詢問,輸出一行答案。對於詢問類型2和3,如果不存在滿足條件的,則輸出“Orz, I cannot find x!”,注意逗號與“I”之間有一個空格。

Sample Input

【樣例輸入1】
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

【樣例輸出1】
2
1
2
【樣例輸出2】
2
1
0

HINT

Source

[Submit][Status][Discuss]




這是一道題,也是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));
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章