ZOJ Monthly, March 2018
ZOJ Monthly, March 2018 Happy Sequence
Input
There are multiple test cases. The first line of the input contains an integer (about 50), indicating the number of test cases. For each test case:
The first and only line contains two integers and (), indicating the upper limit of the elements in the sequence and the length of the sequence.
Output
For each case output a single integer, indicating the number of happy sequences of length modulo
Sample Input
1 3 2
Sample Output
5
做法
记忆化搜索,设f[i][j]为长度为i,最后一个数字为j的串的个数,那么
f[i][j] = Σ(f[i-1][k]) 其中k为i的因数
这样复杂度为n^2
需要注意的是f[i][j]与询问无关,对于每组不同的数据,不用去初始化f数组,否则会超时
代码
1 #include<iostream> 2 using namespace std; 3 #include<cstdio> 4 #include<cstring> 5 #include<algorithm> 6 #include<vector> 7 #include<cmath> 8 typedef long long ll; 9 int bs; 10 const ll mod = 1000000007; 11 vector<int> zans; 12 vector<int> nz[3000]; 13 ll f[2100][2100]; 14 int main(){ 15 int t; 16 memset(nz,0,sizeof(nz)); 17 memset(f,-1,sizeof(f)); 18 for(int i=1;i<=2000;i++){ 19 for(int j=1;j<=i;j++){ 20 if(i%j==0) 21 nz[i].push_back(j); 22 } 23 } 24 scanf("%d",&t); 25 void deal(); 26 while(t--) 27 deal(); 28 } 29 typedef long long ll; 30 ll num[3000]; 31 ll fz[3000]; 32 ll dfs(int x,int y){ 33 if(x==1) 34 return 1; 35 if(f[x][y]!=-1) 36 return f[x][y]; 37 ll ans = 0; 38 for(int i=0;i<nz[y].size();i++){ 39 ans = ans + dfs(x-1,nz[y][i]); 40 if(ans>mod) 41 ans%=mod; 42 } 43 f[x][y]=ans; 44 return f[x][y]; 45 } 46 void deal(){ 47 int n,m; 48 scanf("%d%d",&n,&m); 49 ll ans = 0; 50 for(int i=1;i<=n;i++){ 51 ans = ans + dfs(m,i); 52 ans = ans%mod; 53 } 54 printf("%lld\n",ans); 55 }