FZU 1627 Revival's road【DP(矩阵快速幂)】

来源:互联网 发布:多线程cpu优化 编辑:程序博客网 时间:2024/05/21 03:56

Oaiei is idle, and recently he wants to travel around the country. In his country there are N cities, they are numbered from 1 to N. There are roads between some cities, but some are not directly connected with each other. Oaiei lives in the city 1, and he wants to go to city N. Now, he has a question. In k steps, he would like to know there are how many ways from city 1 to city N. You should note that althought there is a road between city A and city B, there is not necessarily a road between city B and city A.

Input
There are multiple tests. For each test, the first line contains three integers N、M and k(2<=N<=100,1<=M<=N*N,1<=k<=10^9), N denotes the number of cities, M denotes the number of roads between the N cities. Following M lines, each line contains two integers A and B, denoting there is a road between city A and city B.

Output
There are how many ways from city 1 to city N. Becase the answer can be very large, you should output the answer MOD 10000.

Sample Input
4 5 9
1 2
2 3
3 4
4 1
1 3
4 5 1
1 2
2 3
3 4
4 1
1 3
Sample Output
3
0

题意:给你M条有向边,总共需要走K步,求1走到N的方案数。

这是一道图论的动态规划求方案数的问题,可以用矩阵的计算进行优化,对于矩阵再用快速幂。

分析:每一次矩阵乘法 相当于对每个点累积了一下从别的点走过来的和
感觉这种思路十分巧妙。

#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>using namespace std;const int maxn = 1e2 + 5;int N, M, K;int a[105][105];int tmp[maxn][maxn];int res[maxn][maxn];const int mod = 10000;void multi(int a[][maxn], int b[][maxn], int n){    memset(tmp, 0, sizeof tmp);    for (int i = 1; i <= n; i++)    {        for (int j = 1; j <= n; j++)        {            for (int k = 1; k <= n; k++)            {                (tmp[i][j] += a[i][k] * b[k][j])%=mod;            }        }    }    for (int i = 1; i <= n; i++)    {        for (int j = 1; j <= n; j++)        {            (a[i][j] = tmp[i][j])%=mod;        }    }}void pow_multi(int a[][maxn], int n){    memset(res, 0, sizeof res);    for (int i = 1; i <= N; i++)//dwjz    {        res[i][i] = 1;    }    while (n)    {        if (n & 1)        {            multi(res, a, N);        }        multi(a, a, N);        n >>= 1;    }}int main(){    while (~scanf("%d%d%d", &N, &M, &K))    {        memset(a, 0, sizeof a);        for (int i = 0; i < M; i++)        {            int u, v;            scanf("%d%d", &u, &v);            a[u][v] = 1;            //a[v][u] = 1;        }        pow_multi(a, K);        printf("%d\n", res[1][N]);        //printf("%d\n", res[N][1]);    }    return 0;}