[SDOI2009] HH去散步

legendcn發表於2024-07-06

[SDOI2009] HH去散步

\(dp_{i_j}\) 表示第 \(i\) 個時刻,走到第 \(j\) 條邊的終點的方案數

轉移:從當前點 \(u\) 開始,列舉從 \(u\) 出發的所有點,向 \(dp_{i+1,to_u}\) 轉移

但是 \(t\) 非常大,所以需要使用矩陣快速冪

設初始矩陣為 \(\text{A}\),轉移矩陣為 \(\text{B}\),那麼答案矩陣 \(\text{C} = \text{A}\times\text{B}^{t-1}\)

// Problem: P2151 [SDOI2009] HH去散步
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P2151
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// https://codeforces.com/problemset/customtest

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair <int, int> pii;
# define int long long
# define rd(t) read <t> ()
# define mem(a, b) memset (a, b, sizeof (a))
# define fi first
# define se second
# define lc u << 1
# define rc u << 1 | 1
# define debug printf ("debug\n")
const int N = 155, M = N, mod = 45989; 
template <typename T> inline T read ()
{
    T s = 0; int w = 1; char c = getchar (); 
    for (; !isdigit (c); c = getchar ()) { if (c == '-') w = -1; }
    for (; isdigit (c); c = getchar ()) s = (s << 1) + (s << 3) + c - '0';
    return s * w;
}

int n, m, t, A, B; 
struct edge { int vtx, nxt; } e[M]; int h[N], idx; 
void add (int u, int v) { e[ ++ idx] = {v, h[u]}; h[u] = idx; } 
struct matrix
{
	int a[N][N]; 
	matrix () { mem (a, 0); } 
	matrix operator * (const matrix &b) const
	{
		matrix ans; 
		for (int i = 1; i < N; i ++ )
		{
			for (int k = 1; k < N; k ++ )
			{
				for (int j = 1; j < N; j ++ )
					ans.a[i][j] = (ans.a[i][j] + a[i][k] * b.a[k][j]) % mod; 
            }
        }
        return ans; 
    }
} a, b; 
matrix quick_pow (matrix ans, matrix a, int b)
{
	while (b)
	{
		if (b & 1) ans = ans * a; 
		a = a * a; 
		b >>= 1; 
    }
    return ans; 
}
int rev (int x) { return (x % 2 == 0 ? x - 1 : x + 1); }
signed main ()
{
	mem (h, -1); 
	n = rd (int), m = rd (int), t = rd (int); 
	A = rd (int) + 1, B = rd (int) + 1; 
	for (int i = 1; i <= m; i ++ )
	{
		int u = rd (int) + 1, v = rd (int) + 1; 
		add (u, v), add (v, u); 
	} 
	for (int i = 1; i <= idx; i ++ )
	{
		int u = e[i].vtx; 
		for (int j = h[u]; ~j; j = e[j].nxt)
		{
			if (i == rev (j)) continue; 
			b.a[i][j] ++ ; 
		}
    }
    for (int i = h[A]; ~i; i = e[i].nxt) a.a[1][i] ++ ; 
    matrix ans = quick_pow (a, b, t - 1); 
    int res = 0; 
    for (int i = h[B]; ~i; i = e[i].nxt)
    	res = (res + ans.a[1][rev (i)]) % mod; 
    printf ("%lld\n", res); 
    return 0; 
}

相關文章