• HDU 2157 How many ways??


    矩阵快速幂。

    先构造邻接矩阵,这个矩阵的K次方,就表示从从i到j有几种走法。

    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    using namespace std;
    
    int n,m;
    const int maxn=20;
    const int MOD=1000;
    struct Matrix
    {
        int A[25][25];
        Matrix operator*(Matrix b);
    };
    
    Matrix Matrix::operator*(Matrix b)
    {
        Matrix c;
        memset(c.A,0,sizeof(c.A));
        int i,j,k;
        for(i=1; i<=n; i++)
            for(j=1; j<=n; j++)
                for(k=1; k<=n; k++)
                    c.A[i][j]=(c.A[i][j]+(A[i][k]*b.A[k][j])%MOD)%MOD;
        return c;
    }
    
    int main()
    {
        int i,j;
        while(~scanf("%d%d",&n,&m))
        {
            if(n==0&&m==0) break;
            Matrix JZ;
            Matrix CS;
            memset(JZ.A,0,sizeof(JZ.A));
            memset(CS.A,0,sizeof(CS.A));
            for(i=0; i<m; i++)
            {
                int u,v;
                scanf("%d%d",&u,&v);
                u++;
                v++;
                CS.A[u][v]=1;
            }
    
            int T;
            scanf("%d",&T);
    
            while(T--)
            {
                int s,t,k;
                Matrix c;
                scanf("%d%d%d",&s,&t,&k);
                s++;
                t++;
                for(i=1; i<=n; i++)
                    for(j=1; j<=n; j++)
                        JZ.A[i][j]=CS.A[i][j];
                for(i=1; i<=n; i++)
                    for(j=1; j<=n; j++)
                    {
                        if(i==j) c.A[i][j]=1;
                        else c.A[i][j]=0;
                    }
                while(k>0)
                {
                    if(k%2==1) c=c*JZ,k--;
                    else JZ=JZ*JZ,k=k/2;
                }
                printf("%d
    ",c.A[s][t]);
            }
        }
        return 0;
    }
  • 相关阅读:
    进制
    流程控制
    运算符
    格式化输出
    数据结构-树的遍历
    A1004 Counting Leaves (30分)
    A1106 Lowest Price in Supply Chain (25分)
    A1094 The Largest Generation (25分)
    A1090 Highest Price in Supply Chain (25分)
    A1079 Total Sales of Supply Chain (25分)
  • 原文地址:https://www.cnblogs.com/zufezzt/p/4665315.html
Copyright © 2020-2023  润新知