【发布时间】:2015-06-08 21:06:26
【问题描述】:
问题的链接是 - spoj question
我尝试通过这种方法解决问题 - N 范围内的对数 = N-1 范围内的对数 + 一些新对。
但我不知道还应该在此处进行哪些优化以避免 TLE。我还阅读了有关 euler totient 函数的信息,但无法真正理解这种方法。我已经阅读了 4 种计算欧拉 phi 的方法,但我猜都需要相同的 O(n^2)。
P.S - 我只是想知道关于应该采用什么方法而不是直接解决方案的提示。提示会做。 提前非常感谢。
我对这个问题的代码是 -
#include<stdio.h>
typedef unsigned long long int ull;
ull a[100000] = {0};
inline ull g()
{
ull n=0;
char ch;
ch = getchar_unlocked();
while(ch < '0' || ch > '9')
ch = getchar_unlocked();
while(ch >= '0' && ch <= '9') {
n = (n<<3) + (n<<1) + (ch - '0');
ch = getchar_unlocked();
}
return n;
}
ull gcd( ull a , ull b)
{
if(b == 0)
return a;
else
return gcd(b , a % b);
}
ull find(ull n)
{
if(n == 0 || n == 1)
return n;
else if(a[n] != 0)
return n;
else
return find(n-1);
}
ull range(ull n)
{
ull c, i, nf,t;
nf = find(n);
c = a[nf];
t = nf;
nf++;
while(nf <= n) {
a[nf] = a[t];
for(i = 2 ; i <= nf ; i++) {
ull gd = gcd(i,nf);
if(gd > 1) {
c++;
a[nf]++;
}
}
nf++;
}
return c;
}
int main()
{
ull t = g();
ull i = 1;
while(t--) {
ull n = g();
if(a[n] == 0)
a[n] = range(n);
printf("Case %llu: %llu\n",i++,a[n]);
}
return 0;
}
【问题讨论】:
-
如果您发布代码,请至少解释一下您的变量!
-
@ShubhamSharma 对此感到抱歉。下次我会记住这一点。
标签: c algorithm greatest-common-divisor