【矩阵乘法】图中长度为k的路径的计数

样例输入

4 2

0 1 1 0

0 0 1 0

0 0 0 1

1 0 0 0

样例输出

6

#include<cstdio>
#include<vector>
using namespace std;
typedef vector<int> vec;
typedef vector<vec> mat;
int n,m;
mat operator * (const mat &a,const mat &b)
{
	mat c(n,vec(n));
	for(int i=0;i<n;++i)
	  for(int j=0;j<n;++j)
	    for(int k=0;k<n;++k)
	      c[i][j]+=a[i][k]*b[k][j];
	return c;
}
mat Quick_Pow(mat x,int p)
{
	if(!p)
	  {
	  	mat t(n,vec(n));
	  	for(int i=0;i<n;++i)
	  	  t[i][i]=1;
	  	return t;
	  }
	mat res=Quick_Pow(x,p>>1);
	res=res*res;
	if(p&1) res=res*x;
	return res;
}
int main()
{
	mat a(n,vec(n));
	for(int i=0;i<n;++i)
	  for(int j=0;j<n;++j)
	    scanf("%d",&a[i][j]);
	a=Quick_Pow(a,m);
	int ans=0;
	for(int i=0;i<n;++i)
	  for(int j=0;j<n;++j)
	    ans+=a[i][j];
	printf("%d
",ans);
	return 0;
}
原文地址:https://www.cnblogs.com/autsky-jadek/p/4500607.html