51node1439 互质对(容斥原理)
来源:互联网 发布:麦卡锡主义 知乎 编辑:程序博客网 时间:2024/06/04 19:15
51node1439
题目
中文题目
思路
引用2997ms的话:
“如果已知当前集合中互质的个数为ans,那么加入或者删除某个元素最后的结果也就是ans加上或减去该元素与集合中元素互质的个数。
所以要求的就是一个数与集合中各个数之间互质的个数。
做法是把每一个数拆成各个质数因子的乘积,然后对这些质数进行排列组合,那6来说,先假设将所有元素都是与6互质的,然后这里面减去因子有2的(与6一定不互质了),再减去因子有3的,但是这里面减的话,有部分减重复了,就是因子既有2又有3的,所以又要加上因子6的个数,使用容斥原理最终得到结果。”
代码
#include <iostream>#include <algorithm>#include <cmath>#include <vector>#include <string>#include <cstring>#include <cstdio>using namespace std;typedef long long ll;const int maxn=200010;const int maxm=500010;vector<int>prime[maxm];int cnt[maxm],n,q,x;int val[maxn],vis[maxn];void init(){ for(int e=2; e<maxm; e++) { if(!prime[e].size()) for(int i=e; i<maxm; i+=e) { prime[i].push_back(e); } }}int cal(int n,int type){ int ans=0; for(ll mark=1; mark<(1<<prime[n].size()); mark++) { ll odd=0; ll mul=1; for(ll i=0; i<prime[n].size(); i++) { if(mark&(1<<i)) { odd++; mul*=prime[n][i]; } } if(odd&1) ans+=cnt[mul]; else ans-=cnt[mul]; cnt[mul]+=type; } return ans;}int main(){ init(); scanf("%d %d",&n,&q); for(int i=1; i<=n; i++) scanf("%d",&val[i]); ll ans=0; int one=0; int now=0; for(int i=0; i<q; i++) { scanf("%d",&x); if(vis[x]==0) { vis[x]=1; if(val[x]==1) { ans+=one+now; one++; } else { ans+=one+(now-cal(val[x],1)); now++; } } else { vis[x]=0; if(val[x]==1) { ans-=(one-1)+now; one--; } else { ans-=one+(now-cal(val[x],-1)); now--; } } printf("%I64d\n",ans); } return 0;}
0 0
- 51node1439 互质对(容斥原理)
- 51nod 1439:互质对 容斥原理 深搜!!!
- 51Nod 1439 互质对 容斥原理
- 互质对(51nod1439)
- 【51Nod1439】互质对
- 51Nod-1439-互质对
- hdu4135 互斥+容斥原理
- GDUT1141:求互质对数(递推 )
- 51nod1284 容斥原理
- hdu1695 (容斥原理)
- hdu1695 (容斥原理)
- UESTC1720(容斥原理)
- 容斥原理(转载)
- hdu1796(容斥原理)
- 容斥原理(SOJ3082)
- HDU1695(容斥原理)
- hdu4135(容斥原理)
- hdu1796(容斥原理)
- 增强for循环和普通for循环的区别
- C#连接SQLite的字符串
- 外卖案例_第一讲_搭建页面框架
- http://kymjs.com/code/2016/05/08/01
- OWASP TOP 10概述
- 51node1439 互质对(容斥原理)
- 汉字转拼音(PinYin)
- JSP页面请求处理过程
- Java面试题大全(Java基础十三)
- USB Host and Accessory
- Android的Activity的生命周期
- C#创建基本图表(Chart Controls)
- Android Studio 使用优化
- 大型网站技术架构(五):基于java的大型网站