HUAS 1482 lsy的后宫(DP+矩阵快速幂)
这道题的DP是很好想的,令dp[i][j]表示第i个位置摆第j种妹子的方法数,j为0表示不摆妹子的方法数。
dp[i][j]=sigma(dp[i-1][k])(s[j][k]!='1').容易看出这是个递推式,于是可以用矩阵快速幂加速DP转移。
复杂度O(m^3*logn).
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# include <cstdio> # include <cstring> # include <cstdlib> # include <iostream> # include <vector> # include <queue> # include <stack> # include <map> # include <set> # include <cmath> # include <algorithm> using namespace std; # define lowbit(x) ((x)&(-x)) # define pi 3.1415926535 # define eps 1e-9 # define MOD 1000000007 # define INF 1000000000 # define mem(a,b) memset(a,b,sizeof(a)) # define FOR(i,a,n) for(int i=a; i<=n; ++i) # define FO(i,a,n) for(int i=a; i<n; ++i) # define bug puts("H"); # define lch p<<1,l,mid # define rch p<<1|1,mid+1,r # define mp make_pair # define pb push_back typedef pair<int,int> PII; typedef vector<int> VI; # pragma comment(linker, "/STACK:1024000000,1024000000") typedef long long LL; int Scan() { int res=0, flag=0; char ch; if((ch=getchar())=='-') flag=1; else if(ch>='0'&&ch<='9') res=ch-'0'; while((ch=getchar())>='0'&&ch<='9') res=res*10+(ch-'0'); return flag?-res:res; } void Out(int a) { if(a<0) {putchar('-'); a=-a;} if(a>=10) Out(a/10); putchar(a%10+'0'); } const int N=105; //Code begin... struct Matrix{LL matrix[N][N];}a, sa, unit, kk; char s[N][N]; int n, m; Matrix Mul(Matrix a, Matrix b) //矩阵乘法(%MOD) { Matrix c; FOR(i,0,m) FOR(j,0,m) { c.matrix[i][j]=0; FOR(l,0,m) c.matrix[i][j]+=(a.matrix[i][l]*b.matrix[l][j])%MOD; c.matrix[i][j]%=MOD; } return c; } Matrix Cal(int exp) //矩阵快速幂 { Matrix p=a, q=unit; if (exp==0) return q; while (exp!=1) { if (exp&1) exp--, q=Mul(p,q); else exp>>=1, p=Mul(p,p); } return Mul(p,q); } void init(){ FOR(i,0,m) unit.matrix[i][i]=kk.matrix[0][i]=1; FOR(i,0,m) a.matrix[i][0]=a.matrix[0][i]=1; FOR(i,1,m) FOR(j,1,m) if (s[i][j]=='0') a.matrix[j][i]=1; } int main () { LL ans=0; scanf("%d%d",&n,&m); FOR(i,1,m) scanf("%s",s[i]+1); init(); sa=Cal(n-1); sa=Mul(kk,sa); FOR(i,0,m) ans=(ans+sa.matrix[0][i])%MOD; printf("%lld\n",ans); return 0; }