hdu 2157 矩阵 (没想到也可以这个用矩阵 做)




  http://acm.hdu.edu.cn/showproblem.php?pid=2157


题意:求从点s 走k步 到点 t  的方法种数

 

#include<iostream>
#include<string.h>
using namespace std;
struct node{int p[22][22];};
node a,b;
int n;

node cheng(node a,node b)
{
    node c;
    int i,j,k;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
        {
            c.p[i][j]=0;
            for(k=0;k<n;k++)
                c.p[i][j]=(c.p[i][j]+a.p[i][k]*b.p[k][j])%1000;
        }
    return c;
}

void solve(int n)
{
    while(n)
    {
        if(n%2==1)
            b=cheng(a,b);
        a=cheng(a,a);
        n/=2;
    }
}

int main()
{
    int i,j,m,T,s,t,A,B,k,ss[22][22];
    while(scanf("%d%d",&n,&m))
    {
        if(n==0&&m==0)
            break;
        memset(ss,0,sizeof(ss));
        while(m--)
        {
            scanf("%d%d",&s,&t);
            ss[s][t]=1;
        }
        scanf("%d",&T);
        while(T--)
        {
            for(i=0;i<n;i++)
                for(j=0;j<n;j++)
                    a.p[i][j]=ss[i][j];
            scanf("%d%d%d",&A,&B,&k);
            for(i=0;i<n;i++)
                for(j=0;j<n;j++)                 //单位矩阵 b
                   if(i==j)    b.p[i][j]=1;
                   else     b.p[i][j]=0;
            solve(k);
            if(b.p[A][B]<0)
                printf("%d\n",b.p[A][B]+1000);
            else printf("%d\n",b.p[A][B]);
        }
    }
    return 0;
}

 

posted @ 2013-05-30 20:33  galaxy77  阅读(156)  评论(0编辑  收藏  举报