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;
}

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM