1586. Threeprime Numbers
Time limit: 1.0 second
Memory limit: 64 MB
Memory limit: 64 MB
Rest at the sea is wonderful! However, programmer Pasha became awfully bored of lying on a beach in Turkey; so bored that he decided to count the quantity of three-digit prime numbers. This turned out to be so interesting that he then started to study threeprime numbers. Pasha calls an integer a threeprime number if any three consecutive digits of this integer form a three-digit prime number. Pasha had already started working on the theory of the divine origin of such numbers when some vandals poured water on Pasha and cried some incomprehensible words like “Sonnenstich!”, “Colpo di sole!”, and “Coup de soleil!”
You are to continue Pasha’s work and find out how often (or rare) threeprime numbers are.
Input
The input contains an integer
n (3 ≤
n ≤ 10000).
Output
Output the quantity of
n-digit threeprime numbers calculated modulo 10
9 + 9.
Sample
input | output |
---|---|
4 | 204 |
Problem Author: Denis Musin
Problem Source: ACM ICPC 2007–2008. NEERC. Eastern Subregion. Yekaterinburg, October 27, 2007
Problem Source: ACM ICPC 2007–2008. NEERC. Eastern Subregion. Yekaterinburg, October 27, 2007
Difficulty: 159
Printable version
Submit solution
Discussion (22)
All submissions (6829) All accepted submissions (3071) Solutions rating (2253)
代码:
/*
n位数,要求找所有连续三位数是素数的数的个数; 数位dp;
dp[i][j][k]:表示i位数的最高位是j,次高位是k时threeprime的数目;
通过i-1位数来推出i位的情况;就是枚举k就可以啦。。
初始化dp[3][i][j]的情况。。
状态转移方程:dp[i][j][k] += dp[i - 1][k][m];那么j和k都不能为0;
*/
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 1e4+7;
ll mod = 1e9+9;
int n;
ll dp[maxn][11][11];
bool prime[maxn];
void getprime()
{
memset(dp, 0, sizeof(dp));
for(int i = 2; i < maxn; i++) prime[i] = true;
for(int i = 2; i*i < maxn; i++)
if(prime[i])
for(int j = i*i; j < maxn; j+=i) prime[j] = false;
for(int i = 100; i < 1000; i++) if(prime[i]) dp[3][i/100][(i%100)/10]++;
for(int i = 4; i < maxn; i++)
{
for(int j = 1; j < 10; j++)
{
for(int k = 1; k < 10; k++)
{
for(int m = 0; m < 10; m++)
{
if(prime[(j*100)+(k*10)+m]) {
dp[i][j][k] += dp[i - 1][k][m];
dp[i][j][k] %= mod;
}
}
}
}
}
}
int main()
{
getprime();
//freopen("in.txt", "r", stdin);
while(~scanf("%d",&n))
{
ll sum = 0;
for(int i = 1; i < 10; i++)
for(int j = 0; j < 10; j++)
sum = (sum + dp[n][i][j]) % mod;
printf("%lld\n", sum);
}
return 0;
}