怎么才能让下面这段代码在时间限制为1s时过
  • 板块P2257 YY的GCD
  • 楼主_0000000_
  • 当前回复2
  • 已保存回复2
  • 发布时间2025/8/2 19:41
  • 上次更新2025/8/3 10:29:46
查看原帖
怎么才能让下面这段代码在时间限制为1s时过
1438191
_0000000_楼主2025/8/2 19:41

我在其他的oj网站上做题,这题的时间限制是1s,空间限制为256MB,以下为我的代码,希望有大佬能帮帮忙%%%

#include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
vector<bool> nopr;
vector<int> pr,sum;
vector<long long> qzh;
vector<char> mu;
int most;
inline int read()
{
    int x=0;
    char ch=getchar();
    while(ch<'0'||ch>'9')
    {
        ch=getchar();
    }
    while(ch>='0'&&ch<='9')
        x=x*10+ch-'0',ch=getchar();
    return x;
}
void write(long long x)
{
	static short stack[10],top(0);
    do{
    	stack[++top]=x%10;
    	x/=10;
	}while(x);
	while(top)
	{
		putchar(stack[top--]|48);
	}
	putchar('\n');
    return;
}
long long ans(int n,int m)
{
	if(n==0||m==0)
	{
		return 0;
	}
	long long res=0;
	for(register int l=1,r;l<=m;l=r+1)
	{
		float nc=n/l,mc=m/l;;
		r=min(n/nc,m/mc);
		res+=(qzh[r]-qzh[l-1])*nc*mc;
	}
	return res;
}
int main()
{
	int t;
	vector<int> n,m;
	t=read();
	n.resize(t+1,0);
	m.resize(t+1,0);
	for(register int i=t;i>0;--i)
	{
		n[i]=read();
		m[i]=read();
		if(n[i]<m[i])
		{
			swap(n[i],m[i]);
		}
		most=max(most,n[i]);
	}
	nopr.resize(most+1,0);
	mu.resize(most+1,0);
	sum.resize(most+1,0);
	qzh.resize(most+1,0);
	nopr[1]=1;
	mu[1]=1;
	for(register int i=2;i<=most;++i)
	{
		if(!nopr[i])
		{
			pr.push_back(i);
			mu[i]=-1;
		}
		for(register int j=0;j<pr.size()&&i*pr[j]<=most;++j)
		{
			int tpr=i*pr[j];
			nopr[tpr]=1;
			if(i%pr[j]==0)
			{
				break;
			}
			mu[tpr]=-mu[i];
		}
	}
	for(register int i=0;i<pr.size();++i)
	{
		for(int j=1;pr[i]*j<=most;++j)
		{
			sum[j*pr[i]]+=mu[j];
		}
	}
	for(register int i=2;i<=most;++i)
	{
		qzh[i]=qzh[i-1]+sum[i];
	}
	for(register int i=t;i>0;--i)
	{
		write(ans(n[i],m[i]));
	}
	return 0;
}
2025/8/2 19:41
加载中...