跳到正文

题解

题解:P16409 [Algo Beat Contest 004 E] Elusive Prime

lzx0921约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年5月3日
收录
2026年5月8日
更新
2026年11月11日
篇幅
约 5 分钟
题目
P16409

版本

  1. v1当前

题目。

赛时做法(瞎搞):

我们把 [3,106][3,10^6] 内的素数筛出来,对于 p′p' 它仍有可能是答案的必要条件是 (ap)=(ap′)\left(\frac{a}{p}\right) = \left(\frac{a}{p'}\right)。

然后我们不断的进行筛,直到筛出答案。

只有 17 次询问,我一开始选了前 17 个素数,然后选第一个没有被筛掉的,结果我发现只挂了 3 个点!

接着不断的优化素数(毕竟不是 NOI 赛制),最后在 {2,3 ,5,7,11,13,17 ,47,29,59,97,23 ,49987,6997,691,67,7951} 这一组只挂了 1 个点(16)!!

然后把输出改成输出从后往前第一个没被筛掉的,惊奇地发现(16)点过了。

考虑把正序(从前往后)和倒序(从后往前)结合,我是从 17 个中删掉了一个,改成询问 16 次,然后对正序的答案花费一次询问检验(返回值为 0 就是答案了),如果是就输出,不是就输出倒序的。

最后 AC 了!!!

code1
C++
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
#define rep(i,l,r) for(int i=(l);i<=(r);++i)
#define per(i,r,l) for(int i=(r);i>=(l);--i)

const int N=1e6+5,inf=1e6;
int n,a[N],tot,k;
bool vis[N];
ll pom(ll a,ll b,ll p){ll res=1;for(;b;b>>=1,a=a*a%p) if(b&1) res=res*a%p;return res;}
int get(int x,int p){
	if(x%p==0) return 0;
	return pom(x,(p-1)/2,p)==1?1:-1;
}
const int prime[]={2,3  ,5,7,11,13,17  ,47,29,59,97,23 ,49987,6997,691,67};
void solve(){
	memset(vis,true,sizeof vis);
	rep(i,0,15){
		int x=prime[i];
		cout<<"? "<<x<<endl;
		cin>>k;
		if(!k) return cout<<"! "<<x<<endl,void();
		rep(j,2,tot) if(get(x,a[j])!=k) vis[j]=false;
	}
	int ans;
	rep(i,2,tot) if(vis[i]) {ans=a[i];break;}
	cout<<"? "<<ans<<endl;
	cin>>k;
	if(!k) return cout<<"! "<<ans<<endl,void();
	rep(j,2,tot) if(get(ans,a[j])!=k) vis[j]=false;
	per(i,tot,2) if(vis[i]) return cout<<"! "<<a[i]<<endl,void();
}
int main(){
    rep(i,2,inf){
    	if(!vis[i]) a[++tot]=i;
    	rep(j,1,tot){
    		if(i*a[j]>inf) break;
    		vis[i*a[j]]=true;
    		if(i%a[j]==0) break;
		}
	}
	solve();
    return 0;
}

最后,我看别人的 code 似乎用的是随机化(我竟然没有想到),具体的操作是差不多的(把固定选改成随机选,不需要瞎搞选满 17 次就行了),只是更简单点(我果然还是蒟蒻)。

code2
C++
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
#define rep(i,l,r) for(int i=(l);i<=(r);++i)
#define per(i,r,l) for(int i=(r);i>=(l);--i)

const int N=1e6+5,inf=1e6;
int n,a[N],tot,k;
bool vis[N];
ll pom(ll a,ll b,ll p){ll res=1;for(;b;b>>=1,a=a*a%p) if(b&1) res=res*a%p;return res;}
int get(int x,int p){
	if(x%p==0) return 0;
	return pom(x,(p-1)/2,p)==1?1:-1;
}
mt19937 ra;
void solve(){
	memset(vis,true,sizeof vis);
	rep(i,1,17){
		int x=a[ra()%tot+1];
		cout<<"? "<<x<<endl;
		cin>>k;
		if(!k) return cout<<"! "<<x<<endl,void();
		rep(j,2,tot) if(get(x,a[j])!=k) vis[j]=false;
	}
	int ans;
	rep(i,2,tot) if(vis[i]) {ans=a[i];break;}
	cout<<"! "<<ans<<endl;
}
int main(){
    rep(i,2,inf){
    	if(!vis[i]) a[++tot]=i;
    	rep(j,1,tot){
    		if(i*a[j]>inf) break;
    		vis[i*a[j]]=true;
    		if(i%a[j]==0) break;
		}
	}
	solve();
    return 0;
}

所以这道题真的有人会写正确性对的解法吗?

原文