F - Teleporter and Closed off (atcoder.jp)
已知每个点向后面m个点的连边情况,0->没连,1->连了,
从中间开始枚举,如果不经过当前点,从第一个点到最后一个点要经过几个点
从第一个点跑正向边宽搜和从最后一个点跑反向边宽搜
中间枚举两端的中间点
输入1
5 2
11
01
11
10
00
输出1
2 3 2
输入2
6 3
101
001
101
000
100
000
输出2
-1 3 3 -1
#include <iostream>
#include <bits/stdc++.h>
#include <cstring>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#define x first
#define y second
#define pb emplace_back
#define fu(i,a,b) for(int i=a;i<=b;i ++ )
#define fd(i,a,b) for(int i=a;i>=b;i -- )
#define endl '\n'
#define ms(x,y) memset(x,y,sizeof x)
#define ios ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
typedef long long LL;
typedef vector<vector<LL>> VVL;
typedef vector<LL> VL;
typedef vector<int> VI;
typedef vector<vector<int>> VVI;
typedef pair<int,int> PII;
typedef pair<double,double> PDD;
typedef pair<double,int> PDI;
typedef pair<char,int> PCI;
typedef pair<string,int> PSI;
typedef pair<int,string> PIS;
typedef pair<LL,LL> PLL;
typedef __int128 i128;
typedef unsigned long long ULL;
const int N = 1e6+ 10,M = N * 4,INF = 0x3f3f3f3f ;
const double eps = 1e-8;
int n,m,k,idx;
inline void solve()
{
cin >> n >> m;
VVI ed1(n),ed2(n); // 正向边,反向边
fu(i,0,n-1)
{
string s;
cin >> s;
fu(j,1,m)
if(s[j-1] == '1')
{
ed1[i].push_back(i + j);
ed2[i + j ].push_back(i);
}
}
auto bfs = [&](VVI &ed,int s)
{
queue<int> q; q.push(s);
VI dist(n,-1);dist[s] = 0;
while(q.size())
{
int t = q.front();q.pop();
for(auto x: ed[t])
if(dist[x] == -1 )
{
dist[x] = dist[t] + 1;
q.push(x);
}
}
return dist;
};
// 从第一个点开始走正向边 返回值 为能通过传送门到第一个点的距离
auto d1 = bfs(ed1,0);
// 从最后一个点开始走反向边 返回值 为能通过传送门到最后一个点的距离
auto d2 = bfs(ed2,n-1);
VI ans(n,-1);
fu(i,0,n-1)
for(auto x : ed1[i]) // 枚举能到的下一个点
{
// 正向边 能到当前这个点, 反向边能到 下一个点
if(d1[i] != -1 && d2[x] != -1 )
{
int res = d1[i] + d2[x] + 1;
// j 是 i 和 x之间的点 不经过 j 前面只到i 后面从x到n-1
for(int j = i + 1 ;j < x ;j ++ )
if(ans[j] > res || ans[j] == - 1 )
ans[j] = res ;
}
}
fu(i,1,n-2)
cout << ans[i] << " \n"[i == n- 2] ;
}
signed main()
{
// freopen("1.txt","w",stdout);
ios
int t=1;
// cin>>t;
int now = 1;
while(t -- )
{
// cout<<"Case ";
// cout<<"Scenario #";
// cout<< now ++ <<": ";
// cout<< now ++ <<": \n";
solve();
}
return 0;
}