HDU 5297 Y sequencew(容斥+收敛迭代)

探讨了如何从无限长正整数序列中去除特定幂次数后的第n个数的求解方法。采用预处理技术和容斥原理进行优化,通过迭代逼近目标值。

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

题目:从1开始的无限长正整数序列(1,2,3,4,5,...),剖去所有可以写成a^b的数(2<=b<=r),求第n个数是多少。

解析:首先对于每一个r处理出对应容斥的数字,用vector记录下来以降低复杂度。

开始的时候同样像的是二分,超时……看了一篇题解后,考虑序列的性质,向前迭代时是不断收敛的。(具体看代码)

[code]:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<vector>
#include<cmath>
#include<cstdlib>

#define pb push_back
using namespace std;
typedef long long LL;
typedef pair<int,int> P;
const double eps = 1e-6;


void divide(int) __attribute__((optimize("O3")));
void preprocess() __attribute__((optimize("O3")));
LL func(LL) __attribute__((optimize("O3")));
void sol() __attribute__((optimize("O3")));

LL n;int r;
vector<P> G[63];

void divide(int n){
    int i,j,mx = 0,cnt = 0,tmp = n;
    for(i = 2;i*i <= n;i++){
        if(n%i) continue;
        cnt++;
        mx = max(mx,i);
        n /= i;
        if(n%i==0) return;
    }
    if(n != 1){
        cnt++;
        mx = max(mx,n);
    }
    for(i = mx;i <= 62;i++){
        G[i].pb(P(tmp,(cnt&1)?-1:1));
    }
}

void preprocess(){
    int i,j;
    for(i = 2;i <= 62;i++){
        divide(i);
    }
}

LL func(LL x){
    int i,j,a,b;
    LL res = x-1;
    for(i = 0;i < G[r].size();i++){
        a = G[r][i].first;b = G[r][i].second;
        res += b*(LL)floor(pow(x+eps,1.0/a)-1);
    }
    return res;
}

void sol(){
//for(int i = 0;i < G[r].size();i++) printf("%d %d\n",G[r][i].first,G[r][i].second);
    LL temp,ans = n;
    while(1){
        temp = func(ans);
//printf("%I64d %I64d",ans,temp);getchar();
        if(temp == n) break;
        ans += n-temp;
    }
    printf("%I64d\n",ans);
}

/*void sol(){
    LL lb,rb,mid;
    lb = 0,rb = 0x7fffffffffffffff;
    while(rb-lb>1){
        mid = (lb+rb)>>1;
        if(func(mid)<=n) lb = mid;
        else rb = mid;
    }
    printf("%I64d\n",lb);
}*/

int main(){
    int i,j,cas;
    preprocess();
    scanf("%d",&cas);
    while(cas--){
        scanf("%I64d%d",&n,&r);
        sol();
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值