bzoj1875 [SDOI2009]HH去散步 矩阵快速幂

题目传送门

https://lydsy.com/JudgeOnline/problem.php?id=1875

题解

如果没有这个“不能立刻沿着刚刚走来的路走回”,那么这个题就是一个常规的矩阵乘法。

考虑一下这个限制怎么解决。因为限制的是边,我们不妨考虑和边有关的矩阵。

首先把一条无向边拆成两个有向边,如果边 \(A\) 的终点和边 \(B\) 的起点相同,那么我们就说从边 \(A\) 通向边 \(B\)。但是,同源的有向边(也就是从同一条无向边拆成的两条有向边)之间不能建边。

但是为了能够区分出来从 \(S\)\(T\) 的路径,我们建立两个虚点,从 \(SS\)\(S\) 的一条边和从 \(T\)\(TT\) 的边。

然后我们把这个东西跑一边矩阵快速幂即可。


时间复杂度 \(O(m^3\log n)\)

#include<bits/stdc++.h>

#define fec(i, x, y) (int i = head[x], y = g[i].to; i; i = g[i].ne, y = g[i].to)
#define dbg(...) fprintf(stderr, __VA_ARGS__)
#define File(x) freopen(#x".in", "r", stdin), freopen(#x".out", "w", stdout)
#define fi first
#define se second
#define pb push_back

template<typename A, typename B> inline char smax(A &a, const B &b) {return a < b ? a = b, 1 : 0;}
template<typename A, typename B> inline char smin(A &a, const B &b) {return b < a ? a = b, 1 : 0;}

typedef long long ll; typedef unsigned long long ull; typedef std::pair<int, int> pii;

template<typename I> inline void read(I &x) {
	int f = 0, c;
	while (!isdigit(c = getchar())) c == '-' ? f = 1 : 0;
	x = c & 15;
	while (isdigit(c = getchar())) x = (x << 1) + (x << 3) + (c & 15);
	f ? x = -x : 0;
}

const int N = 120 + 4;
const int P = 45989;

int n, m, T, st, ed;
char s[N];

struct Edge { int to, ne; } g[N << 1]; int head[N], tot = 1;
inline void addedge(int x, int y) { g[++tot].to = y, g[tot].ne = head[x], head[x] = tot; }
inline void adde(int x, int y) { addedge(x, y), addedge(y, x); }

inline int smod(int x) { return x >= P ? x - P : x; }
inline void sadd(int &x, const int &y) { x += y; x >= P ? x -= P : x; }
inline int fpow(int x, int y) {
	int ans = 1;
	for (; y; y >>= 1, x = x * x % P) if (y & 1) ans = ans * x % P;
	return ans;
}

struct Matrix {
	int a[N][N];
	
	inline Matrix() { memset(a, 0, sizeof(a)); }
	inline Matrix(const int &x) {
		memset(a, 0, sizeof(a));
		for (int i = 1; i <= m; ++i) a[i][i] = x;
	}
	
	inline Matrix operator * (const Matrix &b) {
		Matrix c;
		for (int k = 1; k <= m; ++k)
			for (int i = 1; i <= m; ++i)
				for (int j = 1; j <= m; ++j)
					sadd(c.a[i][j], a[i][k] * b.a[k][j] % P);
		return c;
	}
} A;

inline Matrix fpow(Matrix x, int y) {
	Matrix ans(1);
	for (; y; y >>= 1, x = x * x) if (y & 1) ans = ans * x;
	return ans;
}
inline void work() {
	addedge(++n, st), addedge(ed, ++n), m = tot;
	for (int x = 0; x <= n; ++x)
		for fec(i, x, y) for fec(j, y, z) if ((i ^ j) != 1) A.a[i][j] = 1;
	A = fpow(A, T + 1);
	printf("%d\n", A.a[m - 1][m]);
}

inline void init() {
	read(n), read(m), read(T), read(st), read(ed);
	int x, y;
	for (int i = 1; i <= m; ++i) read(x), read(y), adde(x, y);
}

int main() {
#ifdef hzhkk
	freopen("hkk.in", "r", stdin);
#endif
	init();
	work();
	fclose(stdin), fclose(stdout);
	return 0;
}
posted @ 2019-09-28 21:35  hankeke303  阅读(135)  评论(0编辑  收藏  举报