hdu2157 how many ways 矩阵

邻接矩阵自乘k次中对应的即为方案数

因为乘法原则,所以每次乘都会统计出来

这想法不错

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define down(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
#define N 35
#define inf 1000
int n,m;

struct matrix
{
	int a[N][N];
	void clear()
	{
		memset(a,0,sizeof(a));
	}
}I;

matrix operator*(const matrix a,const matrix b)
{
	matrix anss;
	fo(i,0,m-1)
	fo(j,0,m-1)
	{
		anss.a[i][j]=0;
		fo(k,0,m-1)
		{
			anss.a[i][j]+=a.a[i][k]*b.a[k][j];
			anss.a[i][j]%=inf;
		}
	}
	return anss;
}

void getI()
{
	I.clear();
	fo(i,0,m-1)
	fo(j,0,m-1)
	if(i==j)I.a[i][j]=1;
	else I.a[i][j]=0;
}

matrix KSM(matrix a,int k)
{
	matrix ret=I;
	while(k)
	{
		if(k&1)ret=a*ret;
		a=a*a;
		k>>=1;
	}
	return ret;
}

int main()
{
	matrix A,ans;
	while(scanf("%d%d",&m,&n)!=EOF&&(n||m))
	{
		getI();
		A.clear();
		fo(i,1,n)
		{
			int x,y;
			scanf("%d%d",&x,&y);
			A.a[x][y]=1;
		}
		int t;scanf("%d",&t);
		while(t--)
		{
			int x,y,k;
			scanf("%d%d%d",&x,&y,&k);
			ans=KSM(A,k);
			printf("%d\n",ans.a[x][y]);
		}
	}
	return 0;
}


你可能感兴趣的:(hdu2157 how many ways 矩阵)