hdu 2841(容斥原理)

Visible Trees

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


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

解题思路:

经画图推敲可以发现如果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[n].size(); i++)
	{
		int ep = v[n][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;
}



你可能感兴趣的:(数学)