HDU-2157 How many ways?

How many ways??

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2179    Accepted Submission(s): 814


Problem Description
春天到了, HDU校園裏開滿了花, 奼紫嫣紅, 非常美麗. 蔥頭是個愛花的人, 看着校花校草競相開放, 漫步校園, 心情也變得舒暢. 爲了多看看這迷人的校園, 蔥頭決定, 每次上課都走不同的路線去教室, 但是由於時間問題, 每次只能經過k個地方, 比方說, 這次蔥頭決定經過2個地方, 那他可以先去問鼎廣場看看噴泉, 再去教室, 也可以先到體育場跑幾圈, 再到教室. 他非常想知道, 從A 點恰好經過k個點到達B點的方案數, 當然這個數有可能非常大, 所以你只要輸出它模上1000的餘數就可以了. 你能幫幫他麼?? 你可決定了蔥頭一天能看多少校花哦
 

Input
輸入數據有多組, 每組的第一行是2個整數 n, m(0 < n <= 20, m <= 100) 表示校園內共有n個點, 爲了方便起見, 點從0到n-1編號,接着有m行, 每行有兩個整數 s, t (0<=s,t<n) 表示從s點能到t點, 注意圖是有向的.接着的一行是兩個整數T,表示有T組詢問(1<=T<=100),
接下來的T行, 每行有三個整數 A, B, k, 表示問你從A 點到 B點恰好經過k個點的方案數 (k < 20), 可以走重複邊。如果不存在這樣的走法, 則輸出0
當n, m都爲0的時候輸入結束
 

Output
計算每次詢問的方案數, 由於走法很多, 輸出其對1000取模的結果
 

Sample Input
4 4 0 1 0 2 1 3 2 3 2 0 3 2 0 3 3 3 6 0 1 1 0 0 2 2 0 1 2 2 1 2 1 2 1 0 1 3 0 0
 

Sample Output
2 0 1 3

第一次接觸這樣的題,之前也不清楚矩陣可以這樣使用。用A[i][j] = 1表示存在i到j的通路,令B = A * A,則B[i][j] = ∑A[i][k] * A[k][j],即從i到j經過兩條邊的路徑數目(k爲中轉點,枚舉k),同理,B * A爲i到j經過3條邊的路徑數目,求k條邊 ,二分求A^k.



#include"cmath"
#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"

using namespace std;

#define mod 1000
#define MAX 25

struct matrix
{
    int mat[MAX][MAX];
};

matrix m,ans;

int maze[MAX][MAX];

matrix matrixmul(matrix a,matrix b)
{
    matrix c;
    for(int i = 0;i < MAX;i++)
    {
        for(int j = 0;j < MAX;j++)
        {
            c.mat[i][j] = 0;
            for(int k = 0;k < MAX;k++)
            {
                c.mat[i][j] += a.mat[i][k] * b.mat[k][j];
            }
            c.mat[i][j] %= mod;
        }
    }
    return c;
}

void quickpow(int x)
{
    while(x)
    {
        if(x % 2)
        {
            ans = matrixmul(ans,m);
        }
        x /= 2;
        m = matrixmul(m,m);
    }
}

void initial()
{
    for(int i = 0;i < MAX;i++)
    {
        for(int j = 0;j < MAX;j++)
        {
            ans.mat[i][j] = (i == j ? 1 : 0);
            m.mat[i][j] = maze[i][j];
        }
    }
}

int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m) && (n+m))
    {
        int s,t;
        memset(maze,0,sizeof(maze));
        while(m--)
        {
            scanf("%d%d",&s,&t);
            maze[s][t] = 1;
        }
        int tt;
        scanf("%d",&tt);
        while(tt--)
        {
            int st,en,cnt;
            initial();
            scanf("%d%d%d",&st,&en,&cnt);
            quickpow(cnt);
            printf("%d\n",ans.mat[st][en]%mod);
        }
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章