题目
该有向图有 n(n<=10) 个节点,节点从 1 至 n 编号,windy 从节点 1 出发,他必须恰好在 t(t<=1e9) 时刻到达节点 n。
现在给出该有向图,你能告诉 windy 总共有多少种不同的路径吗?
答案对 2009 取模。
注意:windy 不能在某个节点逗留,且通过某有向边的时间严格为给定的时间。
有向图用邻接矩阵的形式给出,a[i][j]只为0-9之间的字符
思路来源
https://www.luogu.com.cn/problemnew/solution/P4159
题解
如果a[i][j]=0/1,这题就是矩阵快速幂的sb题,然而现在0-9,记w为a[i][j]的值
怎么办,拆点,把原来一个点拆成9个点,i点对应新矩阵的9*i到9*i+8,像链表一样,前到后的距离为1
只有点号为9*i的点是真实的点,拆点之后的路径,仍然只能有一条路径从原9*i指向9*j,且距离为w
若w为0跳过,否则由9*i+(w-1)向9*j连一条边,代表i的第w-1个点到j的第0个点的距离为1
这样i到j的距离为w,且没有新的边,然后矩阵快速幂就可以了
代码
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
const int MOD = 2009;
const int MAXN = 102;
const int N = 13;
struct mat {
ll c[MAXN][MAXN];
int m, n;
mat(){
memset(c, 0, sizeof(c));
m=n=MAXN;
}
mat(int a, int b) : m(a), n(b) {
memset(c, 0, sizeof(c));
}
void clear(){
memset(c, 0, sizeof(c));
}
mat operator * (const mat& temp) {
mat ans(m, temp.n);
for (int i = 0; i < m; i ++)
for (int j = 0; j < temp.n; j ++)
{
for (int k = 0; k < n; k ++)
ans.c[i][j] += c[i][k] * temp.c[k][j];//能不取模 尽量不取模
//这里maxn=2 故不会超过ll 视具体情况 改变取模情况
ans.c[i][j]%=MOD;
}
return ans;
}
friend mat operator ^(mat M, ll n) //幂次一般为ll
{
mat ans(M.m, M.m);
for (int i = 0; i < M.m; i ++)
ans.c[i][i] = 1;
while (n > 0) {
if (n & 1) ans = ans * M;
M = M * M;
n >>= 1;
}
return ans;
}
};
int n,m,t;
char s[N];
int main(){
scanf("%d%d",&n,&t);
mat a(9*n,9*n);
for(int i=0;i<n;++i){
for(int j=0;j<8;++j){//0-8
a.c[9*i+j][9*i+j+1]=1;
}
scanf("%s",s);
int v;
for(int j=0;j<n;++j){
v=s[j]-'0';
if(!v)continue;
a.c[9*i+v-1][9*j]=1;
}
}
a=a^(a,t);
printf("%lld\n",a.c[0][9*(n-1)]);
return 0;
}