状压dp(排列)

题意

给你一串数字,长度为n(n<15),让你求所有排列中有多少个排列能整除d

思路

一个状压dp, d p [ s ] [ p ] dp[s][p] 表示当前 状态s 的 mod d的余数为p,s的范围就是(0~(1<<15)-1)
然后转移的话就是枚举当前状态没有的,然后加上该状态,更新到新状态。
比如 1 1 ( 2 ) 11_{(2)}
可以由 0 1 ( 2 ) 01_{(2)} 1 0 ( 2 ) 10_{(2)} 显然这就枚举了所有的排列情况.

code

#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
const int man = 2e5+10;
#define IOS ios::sync_with_stdio(0)
template <typename T>
inline T read(){T sum=0,fl=1;int ch=getchar();
for(;!isdigit(ch);ch=getchar())if(ch=='-')fl=-1;
for(;isdigit(ch);ch=getchar())sum=sum*10+ch-'0';
return sum*fl;}
template <typename T>
inline void write(T x) {static int sta[35];int top=0;
do{sta[top++]= x % 10, x /= 10;}while(x);
while (top) putchar(sta[--top] + 48);}
template<typename T>T gcd(T a, T b) {return b==0?a:gcd(b, a%b);}
template<typename T>T exgcd(T a,T b,T &g,T &x,T &y){if(!b){g = a,x = 1,y = 0;}
else {exgcd(b,a%b,g,y,x);y -= x*(a/b);}}
#ifndef ONLINE_JUDGE
#define debug(fmt, ...) {printf("debug ");printf(fmt,##__VA_ARGS__);puts("");}
#else
#define debug(fmt, ...)
#endif
typedef long long ll;
const ll mod = 1e9+7;
int dp[(1<<15)][100];

int main() {
    #ifndef ONLINE_JUDGE
        //freopen("in.txt", "r", stdin);
        //freopen("out.txt","w",stdout);
    #endif
    dp[0][0] = 1;
    int n,d;
    string s;
    cin >> n >> d;
    cin >> s;
    for(int i = 0;i < (1<<n);i++){
        for(int dd = 0;dd < d;dd++){
            for(int j = 0;j < s.size();j++){
                if(i&(1<<j))continue;
                //从上一个状态更新过来
                dp[i|(1<<j)][(dd*10+s[j]-'0')%d] += dp[i][dd];
            }
        }
    }
    cout << dp[(1<<n)-1][0] << endl;
    return 0;
}
原创文章 93 获赞 12 访问量 9000

猜你喜欢

转载自blog.csdn.net/weixin_43571920/article/details/105306928
今日推荐