Visible Trees
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2664 Accepted Submission(s): 1157
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
如果想通了为什么用容斥原理,解题用上一篇博客的模版就不难了。
观察一下,一棵树的坐标是 x , y ,如果GCD ( x , y ) == 1 ,那么这棵树可以看见,所以问题就变成了,从1 ~ h 有多少数与 i (1 ~ w )互质。
代码如下:
#include <cstdio>
#include <algorithm>
using namespace std;
int p[1000000];
int num;
void pr(int x) //求x的质因子
{
num = 0;
for (int i = 2 ; i * i <= x ; i++)
{
if (x % i == 0)
{
p[num++] = i;
while (x % i == 0)
x /= i;
}
}
if (x > 1)
p[num++] = x;
}
int solve(int n) //1~n中不与k互质的数
{
int ans = 0;
for (int i = 1; i < (1 << num) ; i++) //其二进制位为1,表示这些质因数被用到
{
int ant = 0; //用奇数个质因数加,偶数个减
int t = 1;
for (int j = 0 ; j < num ; j++)
{
if ((1 << j) & i)
{
t *= p[j];
ant++;
}
}
if (ant & 1) //奇数加
ans += n / t;
else
ans -= n / t;
}
return ans;
}
int main()
{
int u;
int w,h;
__int64 ans;
scanf ("%d",&u);
while (u--)
{
scanf ("%d %d",&w,&h);
ans = h;
for (int i = 2 ; i <= w ; i++)
{
pr(i); //分解i的质因数
ans += h - solve(h); //与i互质的数
}
printf ("%I64d\n",ans);
}
return 0;
}