传送门:>Here<

题意:给出一张有向图,问从点A到点B恰好经过k个点(包括终点)的路径方案数

解题思路

一道矩阵乘法的好题!妙哉~

话说把矩阵乘法放在图上好神奇,那么跟矩阵唯一有关的就是邻接矩阵……

考虑邻接矩阵在这道题里的含义也就是从A到B经过1个点的方案数——能到达或不能到达。而当邻接矩阵自乘时,假设自乘一次得到矩阵B,则$b[i][j] = \sum\limits_{}{}g[i][k]*g[k][j]$。因此k就作为了枚举的中介点,由于最后得到的项是累积的,所以自乘一次以后就得到了经过2个点的方案数。因此自乘k-1即能得到经过k个点的方案数。

此时,乘法的意义就成为了每一次累积$(i->k)的方案数 * (k->j)的方案数 \  (起点终点固定)$

Code

/*By DennyQi*/
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
#define r read()
#define Max(a,b) (((a)>(b)) ? (a) : (b))
#define Min(a,b) (((a)<(b)) ? (a) : (b))
using namespace std;
typedef long long ll;
const int MAXN = ;
const int MAXM = ;
const int INF = ;
inline int read(){
int x = ; int w = ; register int c = getchar();
while(c ^ '-' && (c < '' || c > '')) c = getchar();
if(c == '-') w = -, c = getchar();
while(c >= '' && c <= '') x = (x << ) + (x << ) + c - '', c = getchar(); return x * w;
}
int N,M,K,Q,x,y,A,B;
int g[][],a[][],b[][],ans[][][];
inline void Init(){
memset(g, , sizeof(g));
}
inline void Matrix_mul(){
memset(ans, , sizeof(ans));
for(int num = ; num <= ; ++num){
for(int i = ; i <= N; ++i){
ans[num][i][i] = ;
}
}
for(int num = ; num <= ; ++num){
for(int i = ; i <= N; ++i){
for(int j = ; j <= N; ++j){
b[i][j] = ;
for(int k = ; k <= N; ++k){
b[i][j] = (b[i][j] + ans[num-][i][k] * g[k][j]) % ;
}
}
}
for(int i = ; i <= N; ++i){
for(int j = ; j <= N; ++j){
ans[num][i][j] = b[i][j];
}
}
}
}
int main(){
for(;;){
N = r, M = r;
if(!N && !M) break;
Init();
for(int i = ; i <= M; ++i){
x = r+, y = r+;
g[x][y] = ;
}
Matrix_mul();
Q = r;
while(Q--){
A = r, B = r, K = r;
printf("%d\n", ans[K][A+][B+] % );
}
}
return ;
}

最新文章

  1. Codeforces 划水
  2. Result Maps collection already contains value for
  3. nyoj366_D的小L_字典序_全排列
  4. 【图像处理】ISP 图像传感器camera原理
  5. Python3基础 assert关键字 成功啥事没有,失败了就报错
  6. [翻译]The Neophyte&#39;s Guide to Scala Part 12: Type Classes
  7. 文件墙 CFilewall
  8. Examples_08_04
  9. 数据流程redux学习(一)
  10. DNS分析之 dnsdict6 使用方法
  11. PHP - curl实现采集
  12. linux挂载windows共享文件夹
  13. Android简易实战教程--第十六话《SharedPreferences保存用户名和密码》
  14. 树莓派中QT实现串口通讯
  15. linux服务查看
  16. anaconda虚拟环境管理,从此Python版本不用愁
  17. 安装Cuda9.0+cudnn7.3.1+tensorflow-gpu1.13.1
  18. vue中输入框聚焦,自动跳转下一个输入框
  19. NET设计模式 第二部分 结构性模式(9):装饰模式(Decorator Pattern)
  20. 模态推出 全屏 隐藏tabbar

热门文章

  1. Xamarin Android ListView 控件使用
  2. SNMP 获取交换机端口相关信息
  3. koa入门
  4. Python_每日习题-0008-九九乘法表
  5. new、getInstance()、newInstance()、Class.forName()
  6. 如何让vba与java的TripleDES算法通用
  7. [2017BUAA软工助教]团队建议
  8. PHP安装pecl扩展--通用
  9. 【学习总结】Git学习-参考廖雪峰老师教程二-安装Git
  10. mybatis两种开发方式