Visible Trees
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3078 Accepted Submission(s): 1360
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
思路:gcd(i,j)不为1的点都不能看见,直接容斥即可,可以使用莫比乌斯反演。
# include <iostream>
# include <cstdio>
# include <cstring>
# include <algorithm>
# define ll long long
using namespace std;
const int maxn = 1e5;
short mu[maxn+3];
int prime[maxn+3];
bool bo[maxn+3];
void get_table()
{
mu[1] = 1;
memset(bo, 0, sizeof(bo));
for(int i=2; i<=maxn; ++i)
{
if(!bo[i])
{
prime[++prime[0]] = i;
mu[i] = -1;
}
for(int j=1; j<=prime[0]&&prime[j]*i<=maxn; ++j)
{
bo[i*prime[j]] = 1;
if(i % prime[j] == 0)
{
mu[i*prime[j]] = 0;
break;
}
else
mu[i*prime[j]] = -mu[i];
}
}
for(int i=1; i<=maxn; ++i)
mu[i] += mu[i-1];//前缀和,用于分块。
}
int main()
{
get_table();
int t, n, m, j;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
if(n > m) swap(n, m);
ll ans = 0;
for(int i=1; i<=n; i=j+1)
{
j = n/(n/i);//分块优化。
ans += (ll)(mu[j]-mu[i-1])*(n/i)*(m/i);
}
printf("%lld\n",ans);
}
return 0;
}