欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

整数划分问题--DFS

程序员文章站 2022-05-08 19:06:07
...

单点时限:1000ms
内存限制:256MB

描写叙述
Given two positive integers N and M, please divide N into several integers A1, A2, …, Ak (k >= 1), so that:
1. 0 < A1 < A2 < … < Ak;
2. A1 + A2 + … + Ak = N;
3. A1, A2, …, Ak are different with each other;
4. The product of them P = A1 * A2 * … * Ak is a multiple of M;
How many different ways can you achieve this goal?
输入
Two integers N and M. 1 <= N <= 100, 1 <= M <= 50.
输出
Output one integer – the number of different ways to achieve this goal, module 1,000,000,007.
例子输入
7 2
例子输出
4
例子提示
There are 4 different ways to achieve this goal for the sample:
A1=1, A2=2, A3=4;
A1=1, A2=6;
A1=2, A2=5;
A1=3, A2=4.

思路就是暴力 , 把全部情况都试一下.

#include <iostream>
using namespace std;

typedef unsigned long long ull;
ull N, M;
ull r = 0;
const ull MOD = 1000000007;

void dfs (ull i, ull s, ull p) {
    if (s == N) {
        if (p % M == 0) r++;
        return;
    }
    for (ull j = i + 1; j < N - s + 1; j++) {
        dfs (j, s + j, p * j);
    }
}

int main () {
    cin >> N >> M;
    dfs (0, 0, 1); 
    cout << r % MOD << endl;
    return 0;
}