传送门:http://www.spoj.com/problems/VLATTICE/
SPOJ Problem Set (classical)7001. Visible Lattice PointsProblem code: VLATTICE |
Consider a N*N*N lattice. One corner is at (0,0,0) and the opposite one is at (N,N,N). How many lattice points are visible from corner at (0,0,0) ? A point X is visible from point Y iff no other lattice point lies on the segment joining X and Y.
Input :
The first line contains the number of test cases T. The next T lines contain an interger N
Output :
Output T lines, one corresponding to each test case.
Sample Input :
3
1
2
5
Sample Output :
7
19
175
Constraints :
T <= 50
1 <= N <= 1000000
Added by: | Varun Jalan |
Date: | 2010-07-29 |
Time limit: | 7s |
Source limit: | 50000B |
Memory limit: | 256MB |
Cluster: | Pyramid (Intel Pentium III 733 MHz) |
Languages: | All except: NODEJS PERL 6 |
Resource: | own problem used for Indian ICPC training camp |
题意:0<=x,y,z<=n,求有多少对xyz满足gcd(x,y,z)=1。
题解:需要用到莫比乌斯反演,好久之前都看过这定律,直到今天做了这道题才弄懂。
首先我们介绍下莫比乌斯反演:
g(n)=sigma(d|n,f(d))
f(n)=sigma(d|n,u(d)*g(n/d))
u(d)定义
若d=1 那么μ(d)=1
若d=p1p2…pr (r个不同质数,且次数都唯一)μ(d)=(-1)^r
其余 μ(d)=0
其实还有一种写法:
g(n)=sigma(d|n,f(d))
f(n)=sigma(n|d,u(d/n)*g(d))
这里我们设g(x)为满足x | (i, j, k)的个数,f(x)为满足(i, j, k) = x的个数。
所以g(n)=sigma(d|n, f(d)) = [n/x] * [n/x] * [n/x]。
而题目要求f(1)等于多少,f(1)=sigma(1|d,u(d)*g(d))。
所以现在关键的是求u(d),可以通过线性筛选素数的方法求解u,详细请看下面代码。
然后还要加上三个平面上面的gcd,直接mu[i]*(n/i)*(n/i)*(n/i+3),二维的比三维的少一维-三个平面。
别忘了还有x,y,z三个轴。
好了,到这里全部的算法都以说清楚了……
AC代码:
10188459 | 2013-10-06 09:31:55 | xiaohao | Visible Lattice Points | accepted edit run | 4.65 | 15M |
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <list>
#include <deque>
#include <queue>
#include <iterator>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <cctype>
using namespace std;
#define si1(a) scanf("%d",&a)
#define si2(a,b) scanf("%d%d",&a,&b)
#define sd1(a) scanf("%lf",&a)
#define sd2(a,b) scanf("%lf%lf",&a,&b)
#define ss1(s) scanf("%s",s)
#define pi1(a) printf("%d\n",a)
#define pi2(a,b) printf("%d %d\n",a,b)
#define mset(a,b) memset(a,b,sizeof(a))
#define forb(i,a,b) for(int i=a;i<b;i++)
#define ford(i,a,b) for(int i=a;i<=b;i++)
typedef long long LL;
const int N=1000010;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const double eps=1e-7;
int mu[N];
LL x,pri[N];
bool vis[N];
void xiaohao_mu()//求莫比乌斯反演中的mu
{
mset(vis,0);mset(mu,0);
x=0;
LL n=1000000;
mu[1]=1;
for(LL i=2;i<=n;i++)
{
if(!vis[i])//筛选素数法
{
pri[x++]=i;
mu[i]=-1;//素数一定等于-1
}
for(LL j=0;j<x&&i*pri[j]<=n;j++)
{
vis[i*pri[j]]=1;
if(i%pri[j]) mu[i*pri[j]]=-mu[i];
else
{
mu[i*pri[j]]=0;
break;
}
}
}
}
int main()
{
xiaohao_mu();
int T;
LL n;
cin>>T;
while(T--)
{
cin>>n;
LL sum=3;//x,y,z轴上面的3个
for(LL i=1;i<=n;i++)
sum+=mu[i]*(n/i)*(n/i)*(n/i+3);
cout<<sum<<endl;
}
return 0;
}