Time Limit: 2 second(s) | Memory Limit: 32 MB |
Given a set of digits S, and an integer n, you have to find how many n-digit integers are there, which contain digits that belong to S and the difference between any two adjacent digits is not more than two.
Input
Input starts with an integer T (≤ 300), denoting the number of test cases.
Each case contains two integers, m (1 ≤ m < 10) and n (1 ≤ n ≤ 10). The next line will contain m integers (from 1 to 9) separated by spaces. These integers form the set S as described above. These integers will be distinct and given in ascending order.
Output
For each case, print the case number and the number of valid n-digit integers in a single line.
Sample Input | Output for Sample Input |
3 3 2 1 3 6 3 2 1 2 3 3 3 1 4 6 | Case 1: 5 Case 2: 9 Case 3: 9 |
Note
For the first case the valid integers are
11
13
31
33
66
题意:求长度为n的每一位都属于集合S且相邻位差的绝对值<=2的数的个数。
解析:套模板记忆化搜索。
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int t;
int m, n;
int a[11];
int dp[11][11];
int cas;
int dfs (int i, int s, bool z)
{
if (i == -1)
return 1;
if (!z && dp[i][s] != -1)
return dp[i][s];
int d, res = 0;
for (int d = 0; d < m; d++){
if (z)
res += dfs(i - 1, a[d], 0);
else if (abs(a[d] - s) <= 2)
res += dfs(i - 1, a[d], 0);
}
return z ? res : dp[i][s] = res;
}
int main()
{
scanf("%d", &t);
for (cas = 1; cas <= t; cas++){
scanf("%d%d", &m, &n);
for (int i = 0; i < m; i++){
scanf("%d", &a[i]);
}
memset (dp, -1, sizeof(dp));
printf("Case %d: %d\n", cas, dfs(n - 1, 0, 1));
}
return 0;
}
一个简单的数位dp,挺好的入门题。
dp[i][j]定义为长度为i,最高位为J的数的个数。
状态转移方程为:
for(int i=2;i<=n;i++)
for(int j=1;j<=9;j++)
if(a[j])//只能用给定的数
{
for(int k=j-2;k<=j+2;k++)
if(k>=1&&k<=9)
dp[i][j]+=dp[i-1][k];
}
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int m,n,ans;
bool a[10];
int dp[15][15];
void unit()
{
memset(dp,0,sizeof(dp));
for(int i=1;i<=9;i++)
if(a[i]) dp[1][i]=1;
}
void solve()
{
for(int i=2;i<=n;i++)
for(int j=1;j<=9;j++)
if(a[j]){
for(int k=j-2;k<=j+2;k++)
if(k>=1&&k<=9)
dp[i][j]+=dp[i-1][k];
}
ans=0;
for(int i=1;i<=9;i++)
ans+=dp[n][i];
}
int main()
{
int T,t,i,x;
cin>>T;
for(t=1;t<=T;t++){
cin>>m>>n;
memset(a,0,sizeof(a));
for(i=1;i<=m;i++){
cin>>x;
a[x]=1;
}
unit();
solve();
printf("Case %d: %d\n",t,ans);
}
return 0;
}