首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【HDU】2841 - Visible Trees(容斥原理)

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

作者头像
FishWang
发布2025-08-27 09:00:23
发布2025-08-27 09:00:23
2710
举报

点击打开题目

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

代码语言:javascript
复制
   2
1 1
2 3

Sample Output

代码语言:javascript
复制
   1
5

Source

2009 Multi-University Training Contest 3 - Host by WHU

如果想通了为什么用容斥原理,解题用上一篇博客的模版就不难了。

观察一下,一棵树的坐标是 x , y ,如果GCD ( x , y ) == 1 ,那么这棵树可以看见,所以问题就变成了,从1 ~ h 有多少数与 i (1 ~ w )互质。

代码如下:

代码语言:javascript
复制
#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;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Visible Trees
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档