题意
给一个有向图,从任意点开始走,最多走m步,求图案总数。
分析
令dp[i][j]表示走了j步最后到达i的方案数,则dp[i][j] = ∑dp[k][j-1].然后矩阵加速。(ps:这种矩阵加速求方案数常在字符串里面,AC自动机)。答案为∑dp[i][j],所以需要在加一维来纪录dp[i][j],j=[1,m].
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <climits>
using namespace std;
#define MEM(x,y) memset(x, y,sizeof x)
#define pk push_back
#define lson rt << 1
#define rson rt << 1 | 1
#define bug cout << "BUG HERE\n"
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> ii;
typedef pair<ii,int> iii;
const double eps = 1e-8;
const double pi = 4 * atan(1);
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 2015;
int nCase = 0;
int dcmp(double x){
if (fabs(x) < eps) return 0;
return x < 0?-1:1;
}
inline int read(){
char c = getchar();
while (!isdigit(c)) c = getchar();
int x = 0;
while (isdigit(c)) {
x = x * 10 + c - '0';
c = getchar();
}
return x;
}
struct Matrix {
int a[60][60];
int r, c;
Matrix(int r = 0,int c = 0) {
memset(a, 0,sizeof a);
this->r = r;
this->c = c;
}
Matrix operator * (const Matrix& rhs) const {
Matrix o(r, rhs.c);
for (int i = 1;i <= o.r;++i) {
for (int j = 1;j <= o.c;++j) {
int t = 0;
for (int k = 1;k <= c;++k) {
t = (t + a[i][k] * rhs.a[k][j]) % MOD;
}
o.a[i][j] = t % MOD;
}
}
return o;
}
};
Matrix Quick(Matrix ans, int k) {
Matrix o(ans.r, ans.c);
for (int i = 1;i <= o.r;++i)
o.a[i][i] = 1;
while(k) {
if (k & 1) o = o * ans;
ans = ans * ans;
k >>= 1;
}
return o;
}
int n, m;
int main(int argc, const char * argv[])
{
int kase;cin >> kase;
while(kase--) {
cin >> n >> m;
Matrix ans(n + 1, n + 1);
for (int i = 1;i <= n;++i) {
int t;cin >> t;
while(t--) {
int x;cin >> x;
ans.a[i][x] = 1;
}
}
for (int i = 1;i <= n + 1;++i)
ans.a[i][n+1] = 1;
ans = Quick(ans, m);
int sum = 0;
for (int i = 1;i <= n + 1;i++)
sum = (sum + ans.a[i][n+1]) % MOD;
cout << sum << endl;
}
return 0;
}