Visible Trees
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3134 Accepted Submission(s): 1388
Problem Description
There are many trees forming a m * n grid, the grid starts from (1,1). Farmer Sherlock is standing at (0,0) point. He wonders how many trees he can see.
If two trees and Sherlock are in one line, Farmer Sherlock can only see the tree nearest to him.
If two trees and Sherlock are in one line, Farmer Sherlock can only see the tree nearest to him.
Input
The first line contains one integer t, represents the number of test cases. Then there are multiple test cases. For each test case there is one line containing two integers m and n(1 ≤ m, n ≤ 100000)
Output
For each test case output one line represents the number of trees Farmer Sherlock can see.
Sample Input
2 1 1 2 3
Sample Output
1 5
Source
Recommend
gaojie
题意:人站在(0,0) 能看到多少树,一条直线上的树会被相互遮挡。
思路:素筛,求坐标为互质的点得个数。根据容斥原理可以求得每一排坐标不互质的点的个数。
第i排有m-[1,m]内与i不互质的点得个数,[1,m]上与i不互质的点得个数及为(1,m)中能整除i的质因子的数有几个。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAXN=1e5+5;
int prime[MAXN][10];
int cnt[MAXN];
void sieve(int n)
{
for(int i=2;i<=n;i++)
{
if(cnt[i]!=0) continue;
prime[i][0]=i;
cnt[i]=1;
for(int j=2;j*i<=n;j++)
prime[i*j][cnt[i*j]++]=i;
}
}
ll solve(int m,int n,int pos)
{
ll res=0;
for(int i=1;i<(1<<m);i++)
{
int num=0;
for(int j=i;j!=0;j>>=1) num+=j&1;
int lcm=1;
for(int j=0;j<m;j++)
{
if(i>>j&1)
{
lcm=lcm/__gcd(lcm,prime[pos][j])*prime[pos][j];
if(lcm>n) break;
}
}
if(num%2==0) res-=(ll)(n/lcm);
else res+=(ll)(n/lcm);
}
return res;
}
int main()
{
sieve(100005);
int t;
scanf("%d",&t);
while(t--)
{
int n,m;
scanf("%d%d",&n,&m);
ll ans=0;
for(int i=1;i<=n;i++)
{
ans+=(ll)m-solve(cnt[i],m,i);
// cout<<ans<<endl;
}
printf("%lld\n",ans);
}
return 0;
}