Codeforces Round #305 (Div. 2) 548E. Mike and Foam 容斥

本文介绍了一种竞赛编程题目解决方案,该方案通过维护数值出现次数并使用容斥原理来高效计算集合中互质对的数量。适用于编程竞赛及算法优化场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:
给n和m,还有n个数m组操作
每个操作有一个x
一开始是一个空集合,如果x被插入过集合,就把x扔出来,否则插入集合。求集合里互质的对数。
思路:
维护一个ans,和num[val]数组代表val出现的次数,然后每次插入和删除通过容斥来更新ans

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<map>
#include<set>
using namespace std;
#define lowbit(x) (x&(-x))
typedef long long LL;
const int maxn = 1000005;
const int inf=(1<<28)-1;
int fac[maxn],len;
LL cnt,tot;
int num[maxn];
void get_fac(int x)
{
    len=0;
    for(int i=2;i*i<=x;++i)
    if(x%i==0)
    {
        fac[++len]=i;
        while(x%i==0) x/=i;
    }
    if(x>1) fac[++len]=x;
}
LL res;
void add(int pos,LL val,int flag,int ope)
{
    if(pos==len+1)
    {
        if(!flag) return ;
        if(!ope) num[val]--;
        if(flag%2) res+=num[val];
        else res-=num[val];
        if(ope) num[val]++;
        return ;
    }
    add(pos+1,val*fac[pos],flag+1,ope);
    add(pos+1,val,flag,ope);
}
int A[maxn];
bool vis[maxn];
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    tot=cnt=0;
    for(int i=1;i<=n;++i) scanf("%d",&A[i]);
    while(m--)
    {
        int x;
        scanf("%d",&x);
        get_fac(A[x]);
        res=0;
        if(!vis[x])
        {
            vis[x]=1;
            add(1,1,0,1);
            //printf("***%lld\n",res);
            cnt+=tot-res;
            tot++;
            printf("%lld\n",cnt);
        }
        else
        {
            vis[x]=0;
            add(1,1,0,0);
            //printf("***%lld\n",res);
            tot--;
            cnt-=tot-res;
            printf("%lld\n",cnt);
        }

    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值