1. 程式人生 > >poj 1091 跳蚤(n元一次不定方程+斥容原理)

poj 1091 跳蚤(n元一次不定方程+斥容原理)

題意:

給一張卡片,上面寫著N + 1個自然數,其中最後一個數是M,並且前N個數不超過M,並允許數字相同。

一隻跳蚤每次可以選擇從卡片上任意選擇一個自然數S,向左或向右跳S個單位長度。

求最後能跳到左邊1個單位長度的N + 1元組個數是多少。

解析:

設卡片上的標號是a1,a2,a3,a4,...,an,M,跳蚤跳對應標號的次數為x1,x2,x3,x4,...,xn,x(n + 1)。

那麼由題意可列出方程:a1*x1 + a2*x2 + a3*x3 + a4*x4 +... + an*xn + M*x(n + 1) = 1.

這個n+1元一次方程有解的充要條件是(a1,a2,a3,a4,...,an,M) = 1.

由於正面比較難剛,所以反面考慮,即所有的情況-各個數的gcd不為1的情況。

從M入手,若各個數最大公約數不為1,則各個數必存在一個或多個M的約數。

因此先將M的約數Pi分出來,然後應用斥容原理:

公約數不為1的數列個數 T = t(1) - t(2) + t(3) - t(4) + ...

其中t(n)代表數列中的數同時能被幾個M的約數所約,比如t(2),是所有Pi中取2搭配,最後累加(M / (Pi × Pj))^ n.

(M / (Pi × Pj))^ n. 這個式子的解釋是所有數小於M,除掉倆公約數就是剩下的數的最大值,因為可以重複取,這個數的^n就是不同數列的個數。

最後加加減減就是總的個數了。

程式碼:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long

using namespace std;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = 4 * atan(1.0);
const double ee = exp(1.0);

const int maxn = 64;
LL n, m;
LL mCdNum;
LL mCd[maxn];
LL tCd[maxn];
LL resAns;

void Divide(LL x)
{
    LL tempM = m;
    mCdNum = 0;
    for (LL i = 2; i * i <= tempM; i++)
    {
        if (tempM % i == 0)
        {
            while (tempM % i == 0)
            {
                tempM /= i;
            }
            mCd[++mCdNum] = i;
        }
    }
    if (tempM != 1)
    {
        mCd[++mCdNum] = tempM;
    }
}

LL myPow(LL a, LL x)
{
    if (x == 0)
        return 1;
    LL r = myPow(a, x >> 1);
    LL res = r * r;
    if (x % 2)
        res = res * a;
    return res;
}

void Dfs(LL pos, LL deep, LL num)
{
    if (deep == num)
    {
        LL tempM = m;
        for (LL i = 1; i <= num; i++)
            tempM /= tCd[i];
        resAns += myPow(tempM, n);
    }
    else
    {
        for (LL i = pos + 1; i <= mCdNum; i++)
        {
            tCd[deep + 1] = mCd[i];
            Dfs(i, deep + 1, num);
        }
    }
}

int main()
{
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
#endif // LOCAL
    while (scanf("%lld%lld", &n, &m) == 2)
    {
        Divide(m);
        LL ans = 0;
        for (LL i = 1; i <= mCdNum; i++)
        {
            resAns = 0;
            Dfs(0, 0, i);
            if (i % 2)
                ans += resAns;
            else
                ans -= resAns;
        }
        ans = myPow(m, n) - ans;
        printf("%lld\n", ans);
    }
    return 0;
}