51node1439 互质对(容斥原理)

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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值