bnuoj 34985 Elegant String DP+矩阵快速幂

题目链接:http://acm.bnu.edu.cn/bnuoj/problem_show.php?pid=34985

We define a kind of strings as elegant string: among all the substrings of an elegant string, none of them is a permutation of "0, 1,…, k".
Let function(n, k) be the number of elegant strings of length n which only contains digits from 0 to k (inclusive). Please calculate function(n, k).
INPUT
Input starts with an integer T (T ≤ 400), denoting the number of test cases.
Each case contains two integers, n and k. n (1 ≤ n ≤ 1018) represents the length of the strings, and k (1 ≤ k ≤ 9) represents the biggest digit in the string
2
1 1
7 6
OUTPUT
For each case, first output the case number as "Case #x: ", and x is the case number. Then output function(n, k) mod 20140518 in this case.
Case #1: 2
Case #2: 818503
source:2014 ACM-ICPC Beijing Invitational Programming Contest
 
题意:首先定义一个串elegant string:在这个串里的任何子串都没有包括0~k的一个全排列,现在给出n和k,要求求出长度为n的elegant string的个数。
解法:DP+矩阵快速幂。我们先用DP推出递推公式,然后用矩阵快速幂解决这个公式。具体思想如下:
定义DP数组:dp[12][12](dp[i][j]表示长度为 i 时字符串末尾连续有 j 个不同数字,例:1233末尾只有一个数字3,2234末尾有3个:2,3,4)。
以第二组数据为例:n=7   k=6
 
初始化:dp[1][1]=k+1,dp[1][2,,,k]=0;
dp[i+1][1]=dp[i][1]+dp[i][2]+dp[i][3]+dp[i][4]+dp[i][5]+dp[i][6]
dp[i+1][2]=6*dp[i][1]+dp[i][2]+dp[i][3]+dp[i][4]+dp[i][5]+dp[i][6]
dp[i+1][3]=5*dp[i][2]+dp[i][3]+dp[i][4]+dp[i][5]+dp[i][6]
dp[i+1][4]=4*dp[i][3]+dp[i][4]+dp[i][5]+dp[i][6]
dp[i+1][5]=3*dp[i][4]+dp[i][5]+dp[i][6]
dp[i+1][6]=2*dp[i][5]+dp[i][6]
把递推式改为如下矩阵:
bnuoj 34985 Elegant String  DP+矩阵快速幂
 
然后我们就可以用快速幂来解决了
 #include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#define inf 0x7fffffff
using namespace std;
typedef long long ll;
const int maxn=;
const ll mod=; ll n,k;
struct matrix
{
ll an[maxn][maxn];
}A,B;
matrix multiply(matrix x,matrix y)
{
matrix sum;
memset(sum.an,,sizeof(sum.an));
for (int i= ;i<=k ;i++)
{
for (int j= ;j<=k ;j++)
{
for (int k2= ;k2<=k ;k2++) {
sum.an[i][j]=(sum.an[i][j]+x.an[i][k2]*y.an[k2][j]%mod);
if (sum.an[i][j]>=mod) sum.an[i][j] -= mod;
}
}
}
return sum;
}
matrix power(ll K,matrix q)
{
matrix temp;
for (int i= ;i<=k ;i++)
{
for (int j= ;j<=k ;j++)
temp.an[i][j]= i==j ;
}
while (K)
{
if (K&) temp=multiply(temp,q);
q=multiply(q,q);
K >>= ;
}
return temp;
}
int main()
{
int t,ncase=;
scanf("%d",&t);
while (t--)
{
scanf("%lld%lld",&n,&k);
if (n==)
{
printf("Case #%d: %d\n",ncase++,k+);continue;
}
matrix q;
for (int i= ;i<=k ;i++)
{
for (int j= ;j<=k ;j++)
{
if (j>=i) q.an[i][j]=(ll);
else if (j==i-) q.an[i][j]=(ll)(k+-i);
else q.an[i][j]=(ll);
}
}
q=power(n-,q);
// for (int i=1 ;i<=k ;i++)
// {
// for (int j=1 ;j<=k ;j++)
// cout<<q.an[i][j]<<" ";
// cout<<endl;
// }
ll ans=;
for (int i= ;i<=k ;i++)
{
ans=(ans+(ll)q.an[i][]*(ll)(k+))%mod;
}
printf("Case #%d: %lld\n",ncase++,ans);
}
return ;
}
 
 
 
 
后续:感谢提出宝贵的意见。。。。
 
上一篇:php的amqp扩展 安装(windows) rabbitmq学习篇


下一篇:使用copy再次实现Circle类,保证不能有内存泄漏问题