Subject address: Ural 1586
First, define a prime 3D array to record the prime number. If I * 100 + J * 10 + K is a prime number, Mark prime [I] [J] [k] as 1, otherwise, the value is 0. in this way, the subsequent processing is very convenient.
Then define a three-dimensional DP array. DP [N] [I] [J] indicates the number of prime numbers when the ten digits of the current N bits are I and the single digit is J, at this time, the State needs to be transferred from prime [k] [I] [J] to prime number, so the state transition equation is:
If (prime [J] [k] [H]) DP [I] [k] [H] + = DP [I-1] [J] [k]
The Code is as follows:
#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <stdlib.h>#include <math.h>#include <ctype.h>#include <queue>#include <map>#include <set>#include <algorithm>using namespace std;const int mod=1e9+9;int prime[11][11][11], dp[10001][10][10];int main(){ int i, j, k, n, h, x, flag, sum; memset(prime,0,sizeof(prime)); memset(dp,0,sizeof(dp)); for(i=1; i<=9; i++) { for(j=0; j<=9; j++) { for(k=1; k<=9; k++) { x=i*100+j*10+k; flag=0; for(h=2; h<=sqrt(x); h++) { if(x%h==0) { flag=1; break; } } if(!flag) prime[i][j][k]=1; dp[3][j][k]+=prime[i][j][k]; } } } scanf("%d",&n); for(i=4;i<=n;i++) { for(j=0;j<=9;j++) { for(k=0;k<=9;k++) { for(h=0;h<=9;h++) { if(prime[j][k][h]) { dp[i][k][h]+=dp[i-1][j][k]; dp[i][k][h]%=mod; } } } } } sum=0; for(i=0;i<=9;i++) { for(j=0;j<=9;j++) { sum+=dp[n][i][j]; sum%=mod; } } printf("%d\n",sum); return 0;}
Ural 1586 threeprime numbers (DP)