bzoj1706 [usaco2007 Nov]relays 奶牛接力跑 矩阵快速幂

时间:2019-09-28
本文章向大家介绍bzoj1706 [usaco2007 Nov]relays 奶牛接力跑 矩阵快速幂,主要包括bzoj1706 [usaco2007 Nov]relays 奶牛接力跑 矩阵快速幂使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目传送门

https://lydsy.com/JudgeOnline/problem.php?id=1706

题解

换个方法定义矩阵乘法:先加再取 \(\min\)

对于一个 \(n\times m\) 的矩阵 \(A\),和一个 \(m\times l\) 的矩阵 \(B\) 它们的乘积 \(C\) 是一个 \(n \times l\) 的矩阵。
\[ C_{i, j} = \min_{k=1}^m A_{i, k}+B_{k,j} \]


关于这个东西的结合律的证明和一般的矩阵乘法类似,直接带入就可以了。大家可以看一下我的另一篇博客。动态 DP 学习笔记 里面有提到。

然后显然就是先建出来邻接矩阵,然后求它的 \(n\) 次方,这个就是个矩阵快速幂了。

#include<bits/stdc++.h>

#define fec(i, x, y) (int i = head[x], y = g[i].to; i; i = g[i].ne, y = g[i].to)
#define dbg(...) fprintf(stderr, __VA_ARGS__)
#define File(x) freopen(#x".in", "r", stdin), freopen(#x".out", "w", stdout)
#define fi first
#define se second
#define pb push_back

template<typename A, typename B> inline char smax(A &a, const B &b) {return a < b ? a = b, 1 : 0;}
template<typename A, typename B> inline char smin(A &a, const B &b) {return b < a ? a = b, 1 : 0;}

typedef long long ll; typedef unsigned long long ull; typedef std::pair<int, int> pii;

template<typename I> inline void read(I &x) {
    int f = 0, c;
    while (!isdigit(c = getchar())) c == '-' ? f = 1 : 0;
    x = c & 15;
    while (isdigit(c = getchar())) x = (x << 1) + (x << 3) + (c & 15);
    f ? x = -x : 0;
}

const int N = 200 + 7;

int T, n, m, st, ed;
int b[N];

struct Edges { int u, v, w; } a[N];

struct Matrix {
    int a[N][N];
    
    inline Matrix() { memset(a, 0x3f, sizeof(a)); }
    inline Matrix(const int &x) {
        memset(a, 0x3f, sizeof(a));
        for (int i = 1; i <= n; ++i) a[i][i] = x;
    }
    
    inline Matrix operator * (const Matrix &b) {
        Matrix c;
        for (int k = 1; k <= n; ++k)
            for (int i = 1; i <= n; ++i)
                for (int j = 1; j <= n; ++j)
                    smin(c.a[i][j], a[i][k] + b.a[k][j]);
        return c;
    }
} A;

inline Matrix fpow(Matrix x, int y) {
    Matrix ans(0);
    for (; y; y >>= 1, x = x * x) if (y & 1) ans = ans * x;
    return ans;
}

inline void work() {
    std::sort(b + 1, b + (m << 1) + 1);
    n = std::unique(b + 1, b + (m << 1) + 1) - b - 1;
    for (int i = 1; i <= m; ++i) {
        int x = a[i].u, y = a[i].v, z = a[i].w;
        x = std::lower_bound(b + 1, b + n + 1, x) - b;
        y = std::lower_bound(b + 1, b + n + 1, y) - b;
        A.a[x][y] = A.a[y][x] = z;
    }
    
    printf("%d\n", fpow(A, T).a[std::lower_bound(b + 1, b + n + 1, st) - b][std::lower_bound(b + 1, b + n + 1, ed) - b]);
}

inline void init() {
    read(T), read(m), read(st), read(ed);
    for (int i = 1; i <= m; ++i)
        read(a[i].w), read(a[i].u), read(a[i].v),
        b[(i << 1) - 1] = a[i].u, b[i << 1] = a[i].v;
}

int main() {
#ifdef hzhkk
    freopen("hkk.in", "r", stdin);
#endif
    init();
    work();
    fclose(stdin), fclose(stdout);
    return 0;
}

原文地址:https://www.cnblogs.com/hankeke/p/bzoj1706.html