458 - Lost in WHU

题目链接:

http://acm.whu.edu.cn/weblearn/problem/458

思路:本题考查对floyd的理解。本质上是求 从1到n经过不超过t条途径的方案总数。

         floyd 的本质 x--->k--->y 的方案数 = x--->k的方案数 * k-->y的方案数。

#include 
using namespace std;
typedef long long LL;
const int mod = 1000000007;
int n;

template 
T Add(T x, int p) {
    return x >= p ? x - p : x;
}

struct MATRIX {
    vector > s;

    MATRIX() {}
    MATRIX(size_t a, size_t b) {
        resize(a, b);
    }
    inline size_t row() const {
        return s.size();
    }
    inline size_t col() const {
        return s.at(0).size();
    }
    void resize(size_t a, size_t b) {
        s.resize(a);
        for (size_t i = 0; i < a; ++i) {
            s[i].resize(b);
        }
    }
    void clear() {
        for (auto& i : s) {
            for (auto& j : i) {
                j = 0;
            }
        }
    }

    MATRIX operator * (const MATRIX& b) const {
        MATRIX ans(row(), b.col());
        if (col() == b.row())
            for (size_t i = 0; i < row(); ++i)
                for (size_t j = 0; j < b.col(); ++j)
                    for (size_t k = 0; k < col(); ++k)
                        (ans.s[i][j] += (LL)s[i][k] * b.s[k][j] % mod) %= mod;
         return ans;
    }
    MATRIX operator + (const MATRIX& b) const {
        MATRIX ans(row(), col());
        for (size_t i = 0; i < row(); ++i) {
            for (size_t j = 0; j < col(); ++j) {
                ans.s[i][j] = Add(s[i][j] + b.s[i][j], mod);
            }
        }
        return ans;
    }
};
MATRIX mypow( MATRIX a,int b ){
    MATRIX res = a;
    b--;
    while(b){
        if(b&1) res = res* a;
        b>>=1;
        a = a*a;
    }
    return res;
}
MATRIX a;
MATRIX solve( int len ){
    if( len == 1 ) return a;
    MATRIX tmp = solve(len/2);
    MATRIX tt = mypow( a,len>>1 );
    tmp = tmp + tmp * tt;
    if(len&1)tmp = tmp + mypow( a,len );
    return tmp;
}
int main(){
    int m;
    while(2==scanf("%d%d",&n,&m)) {
        a.resize(n, n);
        a.clear();
        for (int x, y, i = 1; i <= m; i++) {
            scanf("%d%d", &x, &y);
            a.s[x - 1][y - 1] = 1;
            a.s[y - 1][x - 1] = 1;
        }
        for (int i = 0; i < n; i++) {
            a.s[n - 1][i] = 0;
        }
        //a.s[n-1][n-1] = 1;*/
        int t;
        scanf("%d", &t);
        MATRIX res = solve(t);
        //MATRIX res = mypow(a,t);
        printf("%d\n", res.s[0][n - 1]);
    }
    return 0;
}

 

你可能感兴趣的:(floyd)