【題解】ZeroJudge b062: 1. 城市道路連通網

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=b062
【解題想法】矩陣快速冪

#include <iostream>
#include <cstring>
using namespace std;

int m, x, y, n, ans;
string str;
struct mat{
    int a[32][32];
    mat(){
        memset(a, 0, sizeof(a));
    }
    mat operator *(const mat &b)const{
        mat ret;
        for (int i = 0; i < m; i++){
            for (int j = 0; j < m; j++){
                for (int k = 0; k < m; k++){
                    ret.a[i][j] += a[i][k] * b.a[k][j];
                }
            }
        }
        return ret;
    }
};

int main() {
    while (cin >> m){
        mat ma;
        for (int i = 0; i < m; i++){
            cin >> str;
            for (int j = 0; j < m; j++){
                ma.a[i][j] = str[j]-'0';
            }
        }
        cin >> x >> y >> n;
        mat mt;
        mt.a[x-1][0] = 1;
        ans = 0;
        for (int i = 0; i < n; i++){
            mt = ma * mt;
            ans += mt.a[y-1][0];
        }
        cout << ans << "\n";
    }
}
分享本文 Share with friends