跑路

Problem’s Website

  • 跑路

    Solution

  • 根据题意,是最短路问题,观察数据范围,我们可以直接使用通俗易懂、儒雅随和的Floyd。
  • 但分析样例,发现这道题并不是简单的Floyd,要尽量使道路为2的次方倍,我们可以维护一个倍增数组f[i][j][k],表示从i到j走2^k步能否到达,先枚举一遍图,找出可以1s到达的两点,然后再跑Floyd。

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #define gc getchar()
    using namespace std;
    int sc() {
    int xx = 0, ff = 1; char cch = gc;
    while(cch < '0' || cch > '9') {
    if(cch == '-') ff = -1; cch = gc;
    }
    while(cch >= '0' && cch <= '9') {
    xx = (xx << 1) + (xx << 3) + (cch ^ '0'); cch = gc;
    }
    return xx * ff;
    }
    int n, m;
    int vis[60][60];
    bool f[60][60][70];
    int main() {
    memset(vis, 0x3f, sizeof(vis));
    n = sc(); m = sc();
    for(int i = 1; i <= m; i++) {
    int from = sc(), to = sc();
    vis[from][to] = 1;
    f[from][to][0] = 1;
    }
    for(int i = 1; i <= 64; i++)
    for(int j = 1; j <= n; j++)
    for(int k = 1; k <= n; k++)
    for(int l = 1; l <= n; l++)
    if(f[j][k][i - 1] && f[k][l][i - 1]) {
    f[j][l][i] = 1;
    vis[j][l] = 1;
    }
    for(int i = 1; i <= n; i++)
    for(int j = 1; j <= n; j++)
    for(int k = 1; k <= n; k++)
    vis[j][k] = min(vis[j][k], vis[j][i] + vis[i][k]);
    printf("%d\n", vis[1][n]);
    return 0;
    }
    // dyyyyyyy

rp++