您的位置:首页 > 其它

【容斥原理】HDU2841 Visible Trees

2016-03-11 13:52 405 查看
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.

 

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

<pre name="code" class="html">题意:有一个n*m的矩阵上布满了树(矩阵从(1,1)开始),现在有一个农夫站在(0,0)点,
问农夫可以看到多少棵树,其中如果这些树在一条线上那么只能看到最前面的那棵树,</span>
首先考虑只能看到一条线上最前面的那棵树这个条件,对于坐标 比如 (2,3)(4,6)(6,9)。。等
这些坐标是在一条直线上的 可以看出其除了(2,3) 其他的都是由(2,3)的x坐标*k y坐标*k 得到的,
拓展出来就是对于 任意坐标 (x,y) 令a=x/gcd(x,y) b=y/gcd(x,y) 那么那些和(x,y)
在一条直线的点的坐标可以表示为 (x+(-)a*k,y+(-)b*k) ,显然(a,b) 是这条线上的第一个点,
即农夫可以看到的点,所以总的问题就可以转换为求x∈(1,n)y∈(1,m)范围内满足 x,y互质的坐标的个数
枚举(1,n)内的x坐标 ,求x与(1,m)内互质的数个数。


代码:(注意数据是long long型)

#include<iostream>
#include<vector>
#define LL long long
using namespace std;
LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
struct node{int x,cnt;};
const int N=100005;
int p
,is
,np=0;
//  素数筛选;
void getPrim()
{
is[0]=is[1]=1;
for(int i=2;i<N;i++){
if(!is[i]){
p[++np]=i;
for(int j=i*2;j<N;j+=i) is[j]=1;
}
}
}
//  分解质因数;
vector<node> factor(LL n)
{
vector<node>ans;
node t;
for(int i=1;p[i]*p[i]<=n;i++){
if(n%p[i]==0){
t.x=p[i];t.cnt=0;
while(n%p[i]==0) t.cnt++,n/=p[i];
ans.push_back(t);
}
}
if(n!=1) t.cnt=1,t.x=n,ans.push_back(t);
return ans;
}
//  容斥原理;
LL solve(LL n,LL m)
{
LL res=0;
vector<node>a;
a=factor(n);
int k=a.size();
for(int i=1;i<(1<<k);i++){
int cnt=0;
for(int j=i;j;j>>=1) cnt+=j&1;
LL lcm=1;
for(int j=0;j<k;j++){
if(i>>j&1){
lcm=lcm/gcd(lcm,a[j].x)*a[j].x;
if(lcm>n) break;
}
}
if(cnt&1) res+=m/lcm;
else res-=m/lcm;
}
return m-res;
}
int main()
{
LL t,n,m;
cin>>t;
getPrim();
while(t--){
cin>>n>>m;
LL ans=0;
for(int i=1;i<=n;i++){
ans+=solve(i,m);
}
cout<<ans<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  容斥原理