Codeforces Round #491 (Div. 2)----E Bus Number

    菜,借鉴了别人的写法,原本以为是推理组合数公式,但是情况太复杂了,也不知道怎么枚举,可能是dfs用的不太熟练这题给我们一个数字,这个数字里面每一个出现了的数字至少选一个,至多选出现次数个,用这些数字去排列有多少种情况。带重复数字的排列数,全排列之后除以每一个数的重数的全排列即可。

    那么这道题,我们可以暴力的dfs出所有数排列情况,因为算排列数和数字出现的先后没有关系,所以我们可以枚举0~9,这10个数字的出现次数,并且用一个数组记录下每一个数字用了多少次,在递归到10的时候,通过公式计算出排列的总情况数,然后减去0放在开头的情况。因为0放在开头相当于先排好了一个0的位置,那么剩下的sum-1个数字,做全排列,就是0放在开头的情况个数。

    代码如下

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL a[10],b[100],fac[100] = {1};
LL num,ans = 0;
void init(){
    while (num) {
        a[num%10]++;
        num /= 10;
    }
    for (int i=1; i<=19; i++)
        fac[i] = fac[i-1] * i;
}
void dfs(int x){
    if (x == 10) {
        LL now = 1,sum = 0,as;
        for (int i=0; i<10; i++) {
            now *= fac[b[i]];
            sum += b[i];
        }
        now = fac[sum] / now;
        if (b[0] >= 1) {
            as = fac[b[0]-1];
            for (int i=1; i<10; i++) {
                as *= fac[b[i]];
            }
            now -= fac[sum-1]/as;
        }
        ans += now;
        return;
    }
    for (int i=1; i<=a[x]; i++) {
        b[x] = i;
        dfs(x+1);
    }
    if (a[x] == 0)
        dfs(x+1);
}
int main(){
    cin >> num;
    init();
    dfs(0);
    cout << ans << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/CCCCTong/article/details/81044925