POJ 1091 - 跳蚤 (容斥)

本文探讨了一道经典的跳蚤问题,通过逆向思维解决数字组合种数的问题,并提供了详细的算法实现过程,包括如何利用最大公约数判断无解条件及通过枚举方法计算答案。

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

题目链接:
http://poj.org/problem?id=1091

题目大意:
给定N,M,有N+1个数字,最后一个必定为M,前面的数字小于等于M,跳蚤可以选择一个数字向左跳该长度,也可以向右,多次选择之后求跳蚤可以跳至左边一单位距离的位置的所有数字组合种数

分析:
顺序考虑很难想,不妨逆向思考,什么情况下跳蚤问题无解,这种问题一般很多地方都有涉及,比如换零钱,凑整之类,总之是在 gcd(a1,a2,,an)1 时,问题无解,所以枚举所有可以使N+1个数字不互质的可能情况种数,最后答案用 mnans 即可

实际上数据太水了,不然肯定是要开高精度的,光 mn 就爆 long long

代码:

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long ll;

const ll mod = 1e9+7;

int n,m;
int factor[10000],cnt;
int pr[10000];


ll quickpow(ll a,ll n)
{
    ll res = 1;
    while (n)
    {
        if (n&1)    res = res*a;
        a = a *a;
        n >>= 1;
    }
    return res;
}


void factorfind(int x)
{
    cnt = 0;
    for (int i = 2 ; i * i <= x ; i ++)
    {
        if (x%i==0)
        {
            factor[++cnt] = i;
            while (x%i==0)
                x /= i;
        }
    }
    if (x!=1)
        factor[++cnt] = x;
    return;
}

ll dfs(int now,int all,int pos)
{
    if (now==all)
    {
        int x = m;
        for (int i = 1; i <= all ; i ++)
            x /= pr[i];
        return quickpow(x,n);
    }
    ll res = 0;
    for (int i = pos ; i <= cnt; i ++)
    {
        pr[now+1] = factor[i];
        res += dfs(now+1,all,i+1);

    }
    return res;
}



ll solve(int t)
{
    return dfs(0,t,1);
}





int main(){



    while (~scanf("%d%d",&n,&m))
    {
        factorfind(m);
        ll ans = 0;
        for (int i = 1 ; i <= cnt ; i ++)
        {
            ll temp = solve(i);

            if (i&1)    ans += temp;
            else    ans -= temp;
        }
        ans = quickpow(m,n)-ans;
        printf("%lld\n",ans);

    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值