Codeforces 920G

920G - List Of Integers

思路:容斥+二分

代码:

#include<bits/stdc++.h>
using namespace std;
#define ll long long 
#define pb push_back
#define mem(a,b) memset(a,b,sizeof(a))

vector<int>p;
ll ans=0;
void dfs(int k,int cnt,ll s,ll r){
    if(k==p.size()){
        if(cnt&1)ans-=r/s;
        else ans+=r/s;
        return ; 
    }
    dfs(k+1,cnt,s,r);
    dfs(k+1,cnt+1,s*p[k],r);
}
void init(ll n){
    p.clear();
    for(ll i=2;i*i<=n;i++){
        if(n%i==0){
            p.pb(i);
            while(n%i==0)n/=i;
        }
    }
    if(n>1)p.pb(n);
}
ll count(ll r){
    ans=0;
    dfs(0,0,1,r);
    return ans;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int T;
    int x,p,k;
    cin>>T;
    while(T--){
        cin>>x>>p>>k;
        init(p);
        ll t=count(x);
        ll l=x,r=1e18,m=(l+r)>>1;
        while(l<r){
            if(count(m)-t>=k)r=m;
            else l=m+1;
            m=(l+r)>>1;
        }
        cout<<m<<endl;
    }
    return 0;
} 
原文地址:https://www.cnblogs.com/widsom/p/8419339.html