Trees in a Wood. UVA - 10214
题意:
给你x的范围【-a,a】。和y的范围【-b,b】。
求可以看到多少个点。
思路:
- 可以先把坐标轴上的点,单独拿掉,单独处理。(总共4个)
- 之后再单独看一个象限,因为其他的可以等效。
- 可以通过uva10820得到启发。
- 题目就是求有多少个点互质。
- 由于a范围比较小,b范围比较大,一列一列统计比较快。第x列能看到的树的个数等于0<y<=b的数中满足 gcd(x,y)= 1的y的个数。(但是b很大,所以可以分区间计算)
1<=y<=x:
有
phi(x)个,这是欧拉函数的定义。
x+1<=y<=2x: 有phi(x)个。因为 gcd(x+i,x)=gcd(x,i)
2x+1<=y<=3x: 有phi(x)个。因为 gcd(2x+i,x)=gcd(x,i)(辗转相除法的定义)
- 对于每个x要进行O(x)次直接判断,加上枚举x的所有可能,
- 复杂度为O( a 2 a^2 a2)
反思:
溢出了,wa了几发。。。qwq
AC
#include <iostream>
#include <cstdio>
#include <algorithm>
#define For(i,x,y) for(int i=(x); i<=(y); i++)
#define fori(i,x,y) for(int i=(x); i<(y); i++)
using namespace std;
typedef long long ll;
const int maxn = 2000 + 10;
const int maxm = 2e6 + 10;
int coPrime[maxn][maxn];
int phi[maxn];
int gcd(int x, int y){
if(y == 0) return x;
return gcd(y,x%y);
}
void init(){
fori(i,1,maxn)fori(j,1,maxn)if(gcd(i,j) == 1)coPrime[i][j] = 1;
phi[1] = 1;
fori(i,2,maxn)if(!phi[i]){
for(int j = i; j< maxn; j += i){
if(!phi[j]) phi[j] = j;
phi[j] = phi[j] / i*(i-1);
}
}
}
int main()
{
// ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
init();
int a, b;
while(scanf("%d%d", &a, &b)&&(a||b)){//cin>>a>>b, a||b){
ll tot = 1;
For(x,1,a){
int k = b / x;
tot += (ll)k * phi[x];
int res = b % x;
For(x1,1,res)tot += coPrime[x][x1];
}
ll n = (ll)a*b*4 + (ll)2*a + (ll)2*b;
double ans = (double)(4*tot) / (double)n;
printf("%.7f\n", ans);
}
return 0;
}