容斥原理 ---区间与集合的无关

https://ac.nowcoder.com/acm/problem/16513 传送门

题目描述

  若一个集合A内所有的元素都不是正整数N的因数,则称N与集合A无关。

  给出一个含有k个元素的集合A={a1,a2,a3,...,ak},求区间[L,R]内与A无关的正整数的个数。

  保证A内的元素都是素数

输入描述:

输入数据共两行:

第一行三个正整数L,R,k,意义如“题目描述”。

第二行k个正整数,描述集合A,保证k个正整数两两不相同。

输出描述:

输出数据共一行:

第一行一个正整数表示区间[L,R]内与集合A无关的正整数的个数

 

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<cmath>
#include<string>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
ll num[21];
ll sum,K;
void dfs(ll i,ll lcm,ll step,ll n){
	if(step&1){
		sum+=n/lcm;	
	}
	else sum-=n/lcm;
	for(int k=i+1;k<=K;k++){
		if(lcm*num[k]>n)continue;//this is the key of througing the big number range of the problem
		//because num[i] is a prime,so just do that num[i]*lcm; 
		dfs(k,lcm*num[k],step+1,n);
	}
}

int main(){
	ll L,R;
	cin>>L>>R>>K;
	for(int i=1;i<=K;i++){
		cin>>num[i];
	}
		sum=0;
		//caculate how many number which can be divived by any number of the set is smaller than L;
		for(int i=1;i<=K;i++){
			dfs(i,num[i],1,L-1);
		}
		ll sum0=sum;//book the sum
		sum=0;
		//caculate how many number which can be divived by any number of the set is smaller than R;
		for(int i=1;i<=K;i++){
			dfs(i,num[i],1,R);
		}
		cout<<R-L+1-sum+sum0<<endl;
return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值