当前位置: 首页 > news >正文

HDU 2841:Visible Trees ← 容斥原理

【题目来源】
http://acm.hdu.edu.cn/showproblem.php?pid=2841

【题目描述】
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.

【输入格式】
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)

【输出格式】
For each test case output one line represents the number of trees Farmer Sherlock can see.

【输入样例】
2
1 1
2 3

【输出样例】
1
5

【算法分析】
在计数时,必须注意无一重复,无一遗漏。为了使重叠部分不被重复计算,人们研究出一种计数方法,这种方法的基本思想是:先不考虑重叠的情况,把包含于某内容中的所有对象的数目先计算出来,然后再把计数时重复计算的数目排斥出去,使得计算的结果既无遗漏又无重复,这种计数的方法称为
容斥原理

针对本题,显然,若 (x,y) 能被看到,那么 (k*x, k*y) 都不能被看到(其中,k>1)。
因此,问题转化为求 1<=x<=n 且 1<=y<=m 有多个 <x,y> 满足 gcd(x,y)=1。
那么可以从 1~n 枚举 x,累计 1~m 中与 x 互质的个数。
对 x 分解素因子,容斥一下就可得到结果。

【算法代码】

#include <iostream>
#include <vector>
using namespace std;typedef long long LL;
vector<int> v;
int n,m;void pfac(int x) { //Find all the prime factors of xv.clear();for(int i=2; i*i<=x; i++) {if(x%i==0) {v.push_back(i);while(x%i==0) x/=i;}}if(x>1) v.push_back(x);
}int solve(int x) {int sum=0;for(int i=1; i<(1<<v.size()); i++) {int res=1,cnt=0;for(int j=0; j<v.size(); j++) {if(i & (1<<j)) {res*=v[j];cnt++;}}if(cnt & 1) sum+=x/res;else sum-=x/res;}return sum;
}int main() {int T;cin>>T;while(T--) {scanf("%d %d",&n,&m); //cin>>n>>m;LL ans=m;for(int i=2; i<=n; i++) {pfac(i);ans+=m-solve(m);}printf("%lld\n",ans);}
}/*
in:
2
1 1
2 3out:
1
5
*/




【参考文献】
https://www.cnblogs.com/00isok/p/10358598.html
https://blog.csdn.net/weixin_53746961/article/details/121175561
https://blog.csdn.net/weixin_43846139/article/details/105517437
https://www.cnblogs.com/crackpotisback/p/4846909.html
http://www.manongjc.com/detail/39-wpncookuuhcoyui.html
https://blog.csdn.net/weixin_30710457/article/details/98919034




 

http://www.lryc.cn/news/275048.html

相关文章:

  • 分布式数据之复制(Replication)
  • 【多线程】
  • 基于Vue开发的一个仿京东电商购物平台系统(附源码下载)
  • Nginx多ip部署多站点
  • Unity SVN更新提交小工具
  • 听GPT 讲Rust源代码--compiler(19)
  • redis单机部署
  • el-upload上传文件
  • 算法导论复习——CHP16 贪心算法
  • 【霹雳吧啦】手把手带你入门语义分割の番外12:U2-Net 源码讲解(PyTorch)—— 网络的搭建
  • phpstudy面板Table ‘mysql.proc‘ doesn‘t exist解决办法
  • 网安入门09-Sql注入(绕过方法梳理)
  • 本地计算机 上的 My5OL808 服务启动后停止,某些服务在未由其他服务或程序使用时将自动停止
  • 2023机器人行业总结,2024机器人崛起元年(具身智能)
  • go 语言中的类型判断
  • java基于ssm的房源管理系统+vue论文
  • RH850P1X芯片学习笔记-A/D Converter (ADCF)
  • 38 调优kafka
  • java推荐系统:好友推荐思路
  • java: 写入数据到HBase
  • 机器学习-基于Word2vec搜狐新闻文本分类实验
  • 5.vue学习笔记(数组变化的侦测+计算属性+Class绑定)
  • Java十种经典排序算法详解与应用
  • git常用命令及概念对比
  • 57、python 环境搭建[for 计算机视觉从入门到调优项目]
  • K8S-应用访问
  • 商智C店H5性能优化实战
  • Unity 使用 Plastic 同步后,正常工程出现错误
  • 详细设计文档该怎么写
  • 集团企业OA办公协同平台建设方案