Educational Codeforces Round 138 (Rated for Div. 2) E (01BFS)
题意: 给定一个 n∗m 的田地,让我们构造仙人掌墙,使得玩家不能从第 1 行,走到第 n 行。仙人掌墙需满足以下条件:1、任意两个仙人掌不可相邻。2、构造完的仙人掌墙可以阻断玩家从第 1 行走到第 n 行。并且田地中已有存在的初始仙人掌,我们不可删除,初始情况也同样满足任意两个仙人掌不相邻。我们需要在初始已有的仙人掌前提下增加尽可能少的仙人掌,构建仙人掌墙,问我们增加最少的仙人掌数量的情况下最终的田地形状,或者声明无法构建仙人掌墙,输出 NO 。
思路: 首先考虑,倘若田地中不存在仙人掌,那么我们的最优方案是为什么?由于仙人掌不可以相邻放置,那么最优情况就是将所有仙人掌对角放置,且恰好放置 m 个,对应 1−m 列,每列一个,且每相邻两列的仙人掌放置行坐标的绝对值不可超过 1 。一定可以保证该情况下,新添的仙人掌数量是最少的。如下图所示:
........
.......#
......#.
.....#..
....#...
...#....
#.#.....
.#......
,但在已有初始仙人掌存在的前提下,我们又该如何放置呢?我们可以从每 1 行的第 1 的下标跑短路,例如从第 1 行开始,那么我们最终的目标就是 (1,0) ⟹ (?,m−1) 该类短路由于边权仅为 0 和 1 ,因此我们可以直接使用 01 deque 来跑短路,且时间复杂度更优。最终跑完短路之后枚举 (0 ~ (n−1),m−1),找到最小增加仙人掌代价即可。然后逆向恢复,将最短路径上的所有 . 变成 # 即可,用一个 pre 来记录即可。需要注意本题由于只保证 n∗m<=4e5,因此直接开静态数组会 mle ,因此采用动态数组 vector 来开二维数组,且初始化所有点的距离为 INF。
代码:
#include<bits/stdc++.h>
using namespace std;
#define int long long
#pragma GCC optimize(3)
typedef pair<int,int>PII;
#define pf push_front
#define pb push_back
const int INF = 2e18;
int dx[]={-1,-1,1,1};
int dy[]={-1,1,1,-1};
void cf(){
int n,m;
cin>>n>>m;
vector<string>s(n);
vector<vector<int>> dist(n,vector<int>(m,INF));
vector<vector<PII>> pre(n,vector<PII>(m));
for(int i=0;i<n;i++){
cin>>s[i];
}
auto check=[&](int a,int b){
if(a<0||a>n-1||b<0||b>m-1)return false;
if(a>0&&s[a-1][b]=='#')return false;
if(a<n-1&&s[a+1][b]=='#')return false;
if(b>0&&s[a][b-1]=='#')return false;
if(b<m-1&&s[a][b+1]=='#')return false;
return true;
};
deque<PII>q;
for(int i=0;i<n;i++){
if(check(i,0)){
if(s[i][0]=='#'){
dist[i][0]=0;
q.pf({i,0});
}
else{
dist[i][0]=1;
q.pb({i,0});
}
}
}
while(q.size()){
auto [a,b]=q.front();
q.pop_front();
for(int i=0;i<4;i++){
int x=a+dx[i];
int y=b+dy[i];
if(check(x,y)){
if(dist[a][b]+(s[x][y]!='#')<dist[x][y]){
dist[x][y]=dist[a][b]+(s[x][y]!='#');
pre[x][y]={a,b};
if(s[x][y]=='#')q.pf({x,y});
else q.pb({x,y});
}
}
}
}
int ans=INF;
int local=-1;
for(int i=0;i<n;i++){
if(dist[i][m-1]<ans){
ans=dist[i][m-1];
local=i;
}
}
if(local==-1){
cout<<"NO"<<endl;
return;
}
else{
cout<<"YES"<<endl;
int nowx=local;
int nowy=m-1;
while(1){
s[nowx][nowy]='#';
if(nowy==0)break;
auto [a,b] = pre[nowx][nowy];
nowx=a;
nowy=b;
}
}
for(int i=0;i<n;i++){
cout<<s[i]<<endl;
}
}
signed main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int _=1;
cin>>_;
while(_--){
cf();
}
return 0;
}