Problem Description
CRB is now playing Jigsaw Puzzle.
There are N kinds of pieces with infinite supply.
He can assemble one piece to the right side of the previously assembled one.
For each kind of pieces, only restricted kinds can be assembled with.
How many different patterns he can assemble with at most M pieces? (Two patterns P and Q are considered different if their lengths are different or there exists an integer j such that j-th piece of P is different from corresponding piece of Q.)

Input
There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
The first line contains two integers N, M denoting the number of kinds of pieces and the maximum number of moves.
Then N lines follow. i-th line is described as following format.
k a1 a2 … ak
Here k is the number of kinds which can be assembled to the right of the i-th kind. Next k integers represent each of them.
1 ≤ T ≤ 20
1 ≤ N ≤ 50
1 ≤ M ≤ 105
0 ≤ k ≤ N
1 ≤ a1 < a2 < … < ak ≤ N

Output
For each test case, output a single integer - number of different patterns modulo 2015.

Sample Input

1
3 2
1 2
1 3
0

Sample Output

6

题意:
有n(1<=n<=50)种纸片,每种无限个。
我们每次可以仿制一张卡片,放到被仿制卡片的右边。
我们想知道,使用0~m(1<=m<=1e5)张纸后可以创造出多少种图案。

解法:

一开始首先我们得到的是一个矩阵。
aij表示图案i可以在右侧仿制出图案j
然后就矩阵快速幂搞一下就可以啦~
然后这道题就是要求
求A^0+A^1+A^2+…+A^m
对于这个问题,首先看下单个的怎么求。

那么求和怎么办??

官方题解提供了一种更强的做法:

时间效率快了至少5倍啊!太厉害了!
是怎么实现的呢?
设原矩阵为
AB
CD
那么新矩阵就成了
AB0
CD0
111
如果m=1,我们返回a^0,即单位矩阵,只存在对角线元素n+1个
如果m=2,我们返回a^1,即如下原矩阵,结果也对
AB0 AB0
CD0 CD0
111 111
如果m=3,对于我们返回的矩阵
左上角的n*n矩阵依然会得到原矩阵平方的结果,也就相当于求得了A^2
然后下面这个111……就把之前的全部结果都存进来了
而且形成的矩阵永远是
AB0
CD0
XX1的样子,太巧妙了。即只要加一行就可以AC啦。

#include <bits/stdc++.h>
using namespace std;
const int mod = 2015;
struct Matrix{
    int a[55][55];
    void init(){
        memset(a, 0, sizeof(a));
    }
    void init2(){
        init();
        for(int i=0; i<55; i++) a[i][i]=1;
    }
}A;
Matrix operator * (Matrix a, Matrix b)
{
    Matrix ret;
    ret.init();
    for(int i=0; i<55; i++){
        for(int j=0; j<55; j++){
            for(int k=0; k<55; k++){
                ret.a[i][j] = (ret.a[i][j] + a.a[i][k]*b.a[k][j]%mod) % mod;
            }
        }
    }
    return ret;
}
Matrix qsm(Matrix a, int n)
{
    Matrix ret;
    ret.init2();
    while(n)
    {
        if(n&1) ret = ret*a;
        a=a*a;
        n>>=1;
    }
    return ret;
}
int main()
{
    int T, n, m;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d %d", &n,&m);
        A.init();
        for(int i=0; i<n; i++){
            int k,x;
            scanf("%d",&k);
            for(int j=0; j<k; j++){
                scanf("%d", &x);
                A.a[i][x-1] = 1;
            }
        }
        for(int i=0; i<=n; i++) A.a[i][n]=1;
        A = qsm(A, m-1);
        int ans = 0;
        for(int i=0; i<=n; i++){
            for(int j=0; j<=n; j++){
                ans = (ans + A.a[i][j])%mod;
            }
        }
        printf("%d\n", ans%mod);
    }
    return 0;
}