hdu 2157(矩阵的快速幂)

题意:容易理解.

分析:如果对于矩阵的乘法懂的话,会很容易想到如何去做的,其实转化下就是关于矩阵的快速幂的求法,具体的为什么我们也不好说,自己去好好想想吧!!不过这个题目也挺坑爹的,那就是会有重边这种情况!!就是如果有一个点直接到另一个点有几条路的话只算一条!!

代码实现:

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
struct node{
    int p[25][25];
};
struct node suan(struct node a,struct node b,int n)//连个矩阵相乘
{
    int i,j,k;
    struct node c;
    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;
}
struct node haha(struct node a,int n,int k)
{
    int i,j;
    struct node b;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            if(i==j)
                b.p[i][j]=1;
            else
                b.p[i][j]=0;
    while(k)
    {
        if(k%2==1)
            b=suan(b,a,n);
        k=k/2;
        a=suan(a,a,n);
    }
    return b;
}
int main()
{
    int n,m,i,x1,x2,T;
    int S,E,k;
    struct node a,b;
    while(scanf("%d%d",&n,&m)!=EOF&&(n!=0||m!=0))
    {
        memset(a.p,0,sizeof(a.p));
        for(i=0;i<m;i++)
        {
            scanf("%d%d",&x1,&x2);
            a.p[x1][x2]=1;
        }
        scanf("%d",&T);
        while(T--)
        {
            scanf("%d%d%d",&S,&E,&k);
            b=haha(a,n,k);
            while(b.p[S][E]<0)//以后碰到取模的情况记得添加
                b.p[S][E]+=1000;
            printf("%d\n",b.p[S][E]);
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jiangjing/p/3105189.html