题意分析
给出 $n$ 个点,$m$ 条有向边,每一步能够走 $2^k$ 条边,求从节点 $1$ 走到节点 $n$ 至少需要走几步。
因为一次能够 $2^k$ 条边,一个很自然的思路就是对于每一个节点 $x$,都找出所有其能够通过 $2^k$ 步走到的节点 $y_i$,然后建新图并连边 $(x,y_i)$。
然后,新图边权为 $1$,在新图上跑最短路即可。
考虑定义 $a_{i,j,k}\in{0,1}$ 表示原图上节点 $i$ 与节点 $j$ 之间是否存在一条长度为 $2^k$ 的路径。
那么,转移就有:
\[a_{i,j,k}=\bigvee_{w=1}^na_{i,w,k-1}\land a_{w,j,k-1}\]其中,$\lor$ 表示或运算,$\land$ 表示与运算。
$\mathcal O(n^3\log V)$ 转移即可,$V$ 为值域。
然后建图,再跑一遍最短路即可。
最短路可以实现 $\mathcal O(n\log n)$ 的,但没必要,直接使用 $\mathcal O\left(n^3\right)$ 的 Floyed 即可。
据说能够通过 bitset 实现 $\mathcal O\left(\dfrac{n^3\log V}{w}\right)=\mathcal O\left(n^3\right)$ 的算法复杂度,然而没必要我不会。
AC 代码
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<ctime>
#include<deque>
#include<queue>
#include<stack>
#include<list>
using namespace std;
constexpr const int N=50,M=1e4,K=64;
int n,build[N+1][N+1];
bool a[N+1][N+1][K+1];
int main(){
/*freopen("test.in","r",stdin);
freopen("test.out","w",stdout);*/
memset(build,0x3f,sizeof(build));
int m;
scanf("%d %d",&n,&m);
while(m--){
int u,v;
scanf("%d %d",&u,&v);
a[u][v][0]=true;
}
for(int k=1;k<=K;k++){
for(int w=1;w<=n;w++){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
a[i][j][k]|=a[i][w][k-1]&&a[w][j][k-1];
}
}
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
for(int k=0;k<=K;k++){
if(a[i][j][k]){
build[i][j]=1;
}
}
}
}
for(int k=1;k<=n;k++){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
build[i][j]=min(build[i][j],build[i][k]+build[k][j]);
}
}
}
printf("%d\n",build[1][n]);
/*fclose(stdin);
fclose(stdout);*/
return 0;
}