【HDU】2841 - Visible Trees(容斥原理)

点击打开题目

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.
 

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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值