您的位置:首页 > 其它

hdu 2841(容斥原理)

2016-01-27 17:51 288 查看

Visible Trees

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)


[align=left]Problem Description[/align]
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.
 

[align=left]Input[/align]
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)

 

[align=left]Output[/align]
For each test case output one line represents the number of trees Farmer Sherlock can see.

 

[align=left]Sample Input[/align]

2
1 1
2 3

 

[align=left]Sample Output[/align]

1
5
解题思路:经画图推敲可以发现如果A1/B1=A2/B2那么就有一棵树看不到,所以就是找出Ai/Bi有多少种。再可以发现A/B中,如果A,B有大于1的公约数,则A=A'*D B=B'*D,那么A/B=A'/B',也就是存在另外一组数和这种相等,则问题转换成有多少对互质的数。接下来的步骤就是枚举从1-m,看1-n中有多少与之互质。确实感觉队列数组求容斥原理很快,而且很容易理解。AC:#include<iostream>
#include<cmath>
#include<vector>
using namespace std;

const int maxn = 100005;
vector<int> v[maxn];
int que[maxn];

void primeFactor()
{
for(int i = 0; i < maxn; i++)
v[i].clear();
for(int i = 2; i < maxn; i++)
{
int q = sqrt(i+0.5),tmp = i;
for(int j = 2; j <= q; j++)
{
if(tmp % j == 0)
{
v[i].push_back(j);
while(tmp % j == 0)
tmp /= j;
}
}
if(tmp > 1) v[i].push_back(tmp);
}
}

__int64 cal(__int64 n, __int64 t) //表示[1,t]的区间内,与n互为素数的个数
{
int num = 0;
que[num++] = 1;
for(int i = 0; i < v
.size(); i++)
{
int ep = v
[i];
int k = num;
for(int j = 0; j < k; j++)
que[num++] = que[j]*ep*(-1);
}
__int64 sum = 0;
for(int i = 0; i < num; i++)
sum += t / que[i];
return sum;
}

int main()
{
int t;
cin>>t;
primeFactor(); //找出所有数的质因子
while(t--)
{
int n,m;
cin>>m>>n;
__int64 ans = 0;
for(int i = 1; i <= m; i++)
ans += cal(i,n);
cout<<ans<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数学