杭电2841 Visible Trees(容斥原理第二题)
2014-12-17 17:48
369 查看
Visible Trees
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1610 Accepted Submission(s): 664
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
/* 题目大意:从1---n与1---m的矩阵,问从(0,0)点看,如果是一排只能看到第一个点,能看到多少个点,相当于所有点与(0,0)点连线,能得到多少条线。可知,lcm相当于斜率,当(x/lcm,y/lcm)时,不在一条线上 挺经典的,容斥原理,相当于求1---n与1---m的互质的点的个数 加油!!! Time:2014-12-17 17:43 */ #include<cstdio> #include<cstring> #include<vector> #include<algorithm> using namespace std; typedef long long LL; const int MAX=100000+10; vector<int>fac[MAX]; bool vis[MAX]; void Del(){ memset(vis,0,sizeof(vis)); for(int i=0;i<MAX;i++)fac[i].clear(); for(int i=2;i<MAX;i++){ if(!vis[i]){ fac[i].push_back(i); for(int j=i+i;j<MAX;j+=i){ vis[j]=true; fac[j].push_back(i); } } } } LL Get_ans(int n,int m){ LL cnt=0; int k=fac .size(); int maxn=1<<k; for(int x=1;x<maxn;x++){ int num=0,val=1; for(int i=0;i<k;i++){ if(x&(1<<i)){ num++; val*=fac [i]; } } if(num&1) cnt+=m/val; else cnt-=m/val; } return m-cnt; } int main(){ int T,n,m; Del(); scanf("%d",&T); while(T--){ scanf("%d%d",&n,&m); if(n>m)swap(n,m);//后边是循环1<<m次,如果差的多话,可以减少很多循环次数 LL ans=m;//注意:n=1时,有m个,不是n个 for(int i=2;i<=n;i++) ans+=Get_ans(i,m); printf("%lld\n",ans); } return 0; }
相关文章推荐
- 杭电2841 容斥定理求1到n之间和x互质的数的总数
- HDU 2841-Visible Trees(容斥)
- 杭电1695 GCD(容斥原理三题)
- 杭电2841 Visible Trees---质因数分解相关题型
- 杭电2841 容斥定理求1到n之间和x互质的数的总数
- HDU 2841 Visible Trees -gcd+莫比乌斯
- HDU 2841 Visible Trees (数论,容斥原理)
- 容斥原理详解 以及代码的剖析 结合实例hdu4135
- 容斥原理 专题
- 组合数形式的容斥原理
- 容斥原理学习
- njust1922(容斥原理统计区间内与n互质的个数)
- 【HDU】2841 Visible Trees
- hdu 2841 Visible Trees【容斥原理】
- [置顶] 专题:有关容斥原理和子集枚举的一些问题
- [思维+容斥原理] hdu 2841 Visible Trees
- HDU 2841 Visible Trees
- 容斥原理求1~r中有多少个数与n互素
- hdu 2841 Visible Trees (容斥原理)
- 容斥的原理及广义应用