Light OJ -1161 Extreme GCD (容斥)
来源:互联网 发布:无锡华云数据地址 编辑:程序博客网 时间:2024/06/15 16:20
All of you know that GCD means the greatest common divisor. So, you must have thought that this problem requires finding some sort of GCD. Don’t worry, you are absolutely right!
Given N positive integers, not necessarily distinct, how many ways you can take 4 integers from the N numbers such that their GCD is 1.
Input
Input starts with an integer T (≤ 20), denoting the number of test cases.
Each case starts with an integer N (4 ≤ N ≤ 10000). The next line contains N integers separated by spaces. The integers will be positive and not greater than 10000.
Output
For each case, print the case number and the number of ways you can take the integers as mentioned above.
Sample Input
3
4
2 4 6 1
5
1 2 4 6 8
10
12 46 100 131 5 6 7 8 9 10
Sample Output
Case 1: 1
Case 2: 4
Case 3: 195
题意
给n个数,问 从中选出四个数他们的gcd 是1 的方案有多少种。
思路
1.首先直接算方案数感觉很复杂,所以我们可以考虑算方案数的补集。比如说我知道有x个数是2的倍数 那么C(x,4) 这些方案数的gcd就不是1 而是2。那么我们可以轻松的算出那些gcd不是1的方案,然后用总的C(n,4)减去即可。
2.其次需要考虑去重。
举个例子,6是2 的倍数 也是3的倍数 也是6的倍数如果一些数,既是2 的倍数也是 6的倍数那么我在减的时候 就会将这些方案减很多次。 所以我在减去2的倍数的方案时,需要2的倍数的方案里不包含6的倍数的方案。那么这就变成了一个递推的过程(或者说是容斥)具体见代码。
#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>using namespace std;long long ans[10005];long long f[10005];long long C(long long n){ return n*(n-1)*(n-2)*(n-3)/24;}void js(int x){ for(int i=1;i*i<=x;i++){ if(x % i==0){ f[i]++; if(i*i!=x){ f[x/i]++; } } }}int main(){ freopen("in.txt","r",stdin); int T,cas=0,n,x; scanf("%d",&T); while(T--){ printf("Case %d: ",++cas); scanf("%d",&n); memset(f,0,sizeof f); for(int i=1;i<=n;i++){ scanf("%d",&x); js(x); } for(int i=10000;i>=1;i--){ ans[i]=C(f[i]); for(int j=i*2;j<=10000;j+=i) ans[i]-=ans[j]; } printf("%lld\n",ans[1]); } return 0;}
- Light OJ -1161 Extreme GCD (容斥)
- Light OJ 1414 February 容斥
- Light OJ 1117 Helping Cicada(容斥)
- Light OJ 1095 Arrange the Numbers (容斥)
- Light oj 1414 - February 29【容斥原理】
- 【Light OJ 1414】February 29(容斥原理)
- 【Light-oj】-1414 - February 29(容斥原理)
- NBUT1613 GCD(容斥)
- GCD 容斥原理
- heal gcd+容斥
- Light OJ 1375 LCM Extreme 欧拉函数 (或 莫比乌斯反演 ?)
- 51nod oj 1678 lyk与gcd 【容斥定理+打表】
- GCD Extreme(II) UVA11426
- spoj 3871. GCD Extreme
- SPOJ 3871 GCD Extreme
- spoj GCDEX - GCD Extreme
- GCD Extreme 【FZU--1969】
- uva11426 GCD - Extreme (II)
- 硬件加速
- java并发(3)ThreadLocal的使用及实现原理(实现原理)
- Servlet生命周期
- Flask和@app.route(1)
- 红黑树与AVL树的区别
- Light OJ -1161 Extreme GCD (容斥)
- 关于ActivityA中的FragmentA启动ActivityB时,FragmentA中的startActivityForResult回调的问题
- 第二章 MyBatis入门
- 移动端]专用的meta
- spring源码学习之路---环境搭建(一)
- Linux安装jdk,tomcat以及mysql并且发布项目
- 【规则引擎】关于规则引擎
- HDU
- Windows命令查看文件的MD5/SHA1/SHA256