Visible Trees
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2577 Accepted Submission(s): 1102
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.
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.
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)
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
1 1
2 3
Sample Output
1
5
5
题意:在(0,0)点观察一个起始点为(1,1)点的n*m矩阵,矩阵每个位置都有树,问最多能看到多少棵树??
假设在(0,0)点可以看到点(A,B),那么(k*A,k*B)(k>1)都是看不到的,所以在这条斜率上能看到的两个点必然互质。所以题目就变成了在[1,m]内与x(1<=x<=n)互质的数有多少个了。这时我们的第一想法是欧拉函数,但是不行,因为是[1-m]范围内,只有当x==m时才可以用,所以我们将x分解质因数,假设 x=p1p2..那么在[1,m]与x不互质的数必然是pi的倍数,所以我们这里就要用容斥原理来解了。给出状压版本。
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long LL; int e[]; void devide(int n,int &id){
for(int i=;i*i<=n;i++){
if(n%i==){
e[id++] = i;
while(n%i==) n/=i;
}
}
if(n>) e[id++] = n;
}
int main()
{
int n,m;
int tcase;
scanf("%d",&tcase);
while(tcase--){
scanf("%d%d",&n,&m);
LL ans = m;
for(int i=;i<=n;i++){
int id = ;
devide(i,id);
int sum = ;
for(int j=;j<(<<id);j++){
int cnt = ,l=;
for(int k=;k<id;k++){
if((j>>k)&){
cnt++;
l*=e[k];
}
}
if(cnt&){
sum+=m/l;
}else{
sum-=m/l;
}
}
ans+=(LL)(m-sum);
}
printf("%lld\n",ans);
}
}