HDU 2841 Visible Trees(容斥原理,数论)
2016-04-02 17:20
429 查看
Visible Trees
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2380 Accepted Submission(s): 989
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
2009 Multi-University Training Contest 3 - Host
by WHU
Recommend
gaojie
对于i,j,若存在k>=2,且k为i,j的约数,则i,j无法观测。故使用容斥原理可求解。
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<queue> #include<vector> #include<string> using namespace std; typedef long long LL; int m,n; const int MAXN=100008; int prime[MAXN]; bool vis[MAXN]; int tot; LL ans; int getPrime(int n){//求1~n的素数 tot=0; memset(vis,0,sizeof(vis)); for(int i=2;i<=n;i++){ if(!vis[i]){ prime[tot++]=i; } for(int j=0;j<tot&&i*prime[j]<=n;j++){ vis[i*prime[j]]=true; if(i%prime[j]==0){ break; } } } return tot; } void dfs(int dep,LL mul,int num){//容斥原理,dep表示使用的质数个数,mul表示乘积,num表示使用的数的编号 for(int i=num;i<tot&&prime[i]*mul<=min(m,n);i++){ LL tp=mul*prime[i]; if(dep&1){ ans+=(LL)(m/tp)*(n/tp); }else{ ans-=(LL)(m/tp)*(n/tp); } dfs(dep+1,tp,i+1); } } int main(){ getPrime(100000); int t; cin>>t; while(~scanf("%d %d",&m,&n)){ ans=(LL)m*n; dfs(0,1,0); printf("%I64d\n",ans); } return 0; }
相关文章推荐
- 147. Insertion Sort List
- 《JS高程》事件学习笔记
- 一个奇葩的SQL题,够强大。
- Somethings About 《c++编程思想》
- C++中placement new操作符
- Think in Java(二):初始化与清理
- Tomcat 配置详解/优化方案
- HDFS 架构解析
- Ubuntu Linux 安装wine 和 winetricks
- DuiLib(2)——几种控件的常规属性介绍
- IOS学习之——查看UDID 打包ipa 安装到客户手机上
- 格雷码的实现
- 北京VR视频外包团队:全景VR视频科普
- 常规功能和模块自定义系统 (cfcmms)—037模块记录(数据)的权限设计(2)
- Android Studio获取数字签名(SHA1)
- 模板引擎 Handlebars.js
- marathon参考(1)应用基础
- 西安商洛之行
- MVC |表单提交 Html.BeginForm
- vs2015 生成 cordova 页面中文乱码