为什么二分答案不如顺序遍历快?
查看原帖
为什么二分答案不如顺序遍历快?
443675
紊莫turtle楼主2022/6/6 08:19

RT,我赛事的二分代码:

#include <bits/stdc++.h>
using namespace std;
inline int read(){int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}return x*f;}
inline void write(int x){if (x < 0) x = ~x + 1, putchar('-');if (x > 9) write(x / 10);putchar(x % 10 + '0');}
int prime[2000080],v[2000080];
void p(int n)
{
	memset(v,0,sizeof(v));
	int m=0;
	for(int i=2;i<=n;i++)
	{
		if(v[i]==0) {v[i]=i;prime[++m]=i;}
		for(int j=1;j<=m;j++)
		{
			if(prime[j]>v[i]||prime[j]>n/i) break;
			v[i*prime[j]]=prime[j];
		}
	}
}
int main()
{
	int T=read(),not0=0;
	p(2000076);
	for(int i=1;;i++)
	{
		if(prime[i]==0) 
		{
			not0=i;
			break;
		}
	}
	while(T--)
	{
		int n=read();
		if(n<2) cout<<1<<endl;
		else cout<<prime[upper_bound(prime+1,prime+not0+1,n)-prime-1]<<endl;
	}
	return 0;
}

用了个线筛,2.69s 而顺序遍历的代码(例如tj 1)用时只有2.42s 甚至他用的还是埃筛。

2022/6/6 08:19
加载中...