Codeforces Round #235 (Div. 2) D. Roman and Numbers(狀壓dp),

來源:互聯網
上載者:User

Codeforces Round #235 (Div. 2) D. Roman and Numbers(狀壓dp),

Roman and Numberstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard output

Roman is a young mathematician, very famous in Uzhland. Unfortunately, Sereja doesn't think so. To make Sereja change his mind, Roman is ready to solve any mathematical problem. After some thought, Sereja asked Roma to find, how many numbers are close to number n, modulo m.

Number x is considered close to number n modulo m, if:

  • it can be obtained by rearranging the digits of number n,
  • it doesn't have any leading zeroes,
  • the remainder after dividing number x by m equals 0.

Roman is a good mathematician, but the number of such numbers is too huge for him. So he asks you to help him.

Input

The first line contains two integers: n (1 ≤ n < 1018) and m (1 ≤ m ≤ 100).

Output

In a single line print a single integer — the number of numbers close to number n modulo m.

Sample test(s)input
104 2
output
3
input
223 4
output
1
input
7067678 8
output
47
Note

In the first sample the required numbers are: 104, 140, 410.

In the second sample the required number is 232.


題意:給出一個數字num和m,問通過重新排列num中的各位元字中有多少個數(mod m)=0,直接枚舉全排列肯定不行,可以用狀壓dp來搞..

dp[S][k]表示選了num中的S且(mod m)=k的方案種數,初始條件dp[0][0]=1,轉移方為dp[i|1<<j[(10*k+num[j])%m]+=dp[i}[k];,注意到是多重排列,所以還需要除去重複的。代碼如下:


#include <iostream>#include <cstring>using namespace std;typedef long long ll;ll dp[1<<18][100],c[20];//dp[S][k]表示選了num中的S且(mod m)=k的方案種數int main(int argc, char const *argv[]){char num[20];int m;while(cin>>num>>m) {memset(dp,0,sizeof dp);memset(c,0,sizeof c);dp[0][0]=1;ll div=1,sz=strlen(num),t=1<<sz;for(int i=0;i<sz;i++) {div*=(++c[num[i]-='0']);//可重排列最後要除的除數n1!*n2!*...nk!}for(int i=0;i<t;i++) {for(int j=0;j<sz;j++)if(!(i&1<<j)) {//集合S中不含j才轉移if(num[j]||i){//至少一個不為0保證無前置0for(int k=0;k<m;k++) {dp[i|1<<j][(10*k+num[j])%m]+=dp[i][k];}}}}cout<<dp[t-1][0]/div<<endl;}return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.