隐藏
「SDOI2009」HH去散步 - 矩阵快速幂 | Bill Yang's Blog

路终会有尽头,但视野总能看到更远的地方。

0%

「SDOI2009」HH去散步 - 矩阵快速幂

题目大意

    给出一个无向图,计算从$A$到达$B$的合法路径条数,要求经过了一条边$u\rightarrow v$后不立即通过同样的边回到$u$。
保证无自环,不保证无重边。


题目分析

若没有不走回头路的条件,就是一个简单的矩阵快速幂。
若包含走回头路的条件,其实也很简单,转成关于边的矩阵快速幂,在转移条件地方限制一下回头边即可。


代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdlib>
#include<climits>
#include<vector>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;

typedef long long LL;

inline const int Get_Int() {
int num=0,bj=1;
char x=getchar();
while(x<'0'||x>'9') {
if(x=='-')bj=-1;
x=getchar();
}
while(x>='0'&&x<='9') {
num=num*10+x-'0';
x=getchar();
}
return num*bj;
}

const int maxn=125,mod=45989;

struct Matrix {
LL n,m,a[maxn][maxn];
Matrix(LL n,LL m) {
init(n,m);
}
Matrix(LL n,LL m,char E) { //单位矩阵
init(n,m);
for(int i=1; i<=n; i++)a[i][i]=1;
}
void init(LL n,LL m) {
this->n=n;
this->m=m;
memset(a,0,sizeof(a));
}
LL* operator [] (const LL x) {
return a[x];
}
Matrix operator * (Matrix& b) {
Matrix c(n,b.m);
for(int i=1; i<=n; i++)
for(int j=1; j<=b.m; j++)
for(int k=1; k<=m; k++)
c[i][j]=(c[i][j]+a[i][k]*b[k][j])%mod;
return c;
}
void operator *= (Matrix& b) {
*this=*this*b;
}
Matrix operator ^ (LL b) {
Matrix ans(n,m,'e'),a=*this;
while(b>0) {
if(b&1)ans=ans*a;
a*=a;
b>>=1;
}
return ans;
}
};

struct Edge {
int from,to,id;
};

LL n,m,len,s,t,from[maxn],to[maxn],ans=0;
vector<Edge>edges[maxn];

void AddEdge(int x,int y,int id) {
edges[x].push_back((Edge) {
x,y,id
});
}

int inv(int id) {
if(id&1)return id+1;
return id-1;
}

int main() {
n=Get_Int();
m=Get_Int();
len=Get_Int();
s=Get_Int()+1;
t=Get_Int()+1;
for(int i=1; i<=m; i++) {
int x=Get_Int()+1,y=Get_Int()+1;
AddEdge(x,y,2*i-1);
AddEdge(y,x,2*i);
from[2*i-1]=x;
to[2*i-1]=y;
from[2*i]=y;
to[2*i]=x;
}
Matrix M(2*m,2*m);
for(int i=1; i<=2*m; i++) {
int Now=to[i];
for(Edge& e:edges[Now]) {
int Next=e.to;
if(e.id==inv(i))continue;
M[i][e.id]=1;
}
}
M=M^(len-1);
for(Edge& out:edges[s])
for(Edge& in:edges[t])
ans=(ans+M[out.id][inv(in.id)])%mod;
printf("%lld\n",ans);
return 0;
}
姥爷们赏瓶冰阔落吧~