有史以来第一次做出 g + 蒟蒻第一篇题解。
看了 Atcoder 的题解,什么流,不如 bfs 。
题意:给你一个 网格的所有障碍物,求是否可以从 走到 。
感性理解,首先直接存网格来跑DP或是其它的不可行,因为 高达 的数量级。
考虑什么时候是无解的。
从整体考虑,由于可以四处乱走,所以若无解,肯定至少有一条障碍物组成的线将这个网格分为两半,且 与 分别在两半部分中。
若找到一条碰到墙壁的障碍线,且碰到上或右且碰到左或下,那么就是无解的。
其实就是下面 种情况:
下面两种是有解的,即使碰到了两个墙壁:
其余没有碰壁的情况一定也有解。
那怎么去看有没有这样的障碍的线。
首先若一个地方是障碍,则它 相邻的障碍都是可以和它连在一起,形成一条障碍线。
考虑用 bfs ,保证复杂度,每次向 个方向转移。
那怎么考虑一个地方是否有障碍?由于数组存不下,直接用万能的 map 。
用 map 记录一个位置是否有障碍,并且这里把 map 不光用以判断一个地方是否有障碍,它还可以用以存储障碍的编号以便于跑 bfs 。
用 vis 数组表示一个障碍是否经历过,这样每个障碍都只会经过一次,时间复杂度为 ,Perfect。
Code:
#include<bits/stdc++.h>
#define int long long
#define code using
#define by namespace
#define XWC std;
#define f first
#define s second
#define debug(a,n)\
cout<<#a<<":";\
for(int i=1;i<=n;i++) cout<<#a<<"["<<i<<"]="<<a[i]<<" ";\
cout<<"\n";
#define ls (k<<1)
#define rs (k<<1|1)
code by XWC
template<typename T>
inline void read(T &x){
x=0;
char ch=getchar();
bool f=0;
while(ch<'0'||ch>'9'){
if(ch=='-') f=1;
ch=getchar();
}
while(ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
if(f) x=-x;
}
template<typename T,typename ...Args>
inline void read(T &tmp,Args &...tmps){
read(tmp);
read(tmps...);
}
int h,w,k;
const int N=2e5+10;
int r[N],c[N];
map<pair<int,int>,int> mp;
bool vis[N];
bool ur;//up or right
bool ld;//left or down
int dx[10]={-0x3f,1,1,1,0,0,-1,-1,-1};
int dy[10]={-0x3f,1,0,-1,1,-1,1,0,-1};
void bfs(int a){
queue<int> q;
q.push(a);
while(!q.empty()){
int u=q.front();
q.pop();
//碰到墙壁
if(r[u]==1) ur=true;
if(r[u]==h) ld=true;
if(c[u]==1) ld=true;
if(c[u]==w) ur=true;
if(vis[u]) continue;
vis[u]=true;
int x=r[u],y=c[u];
for(int i=1;i<=8;i++){//8方向扩展
if(mp.count({x+dx[i],y+dy[i]})){
q.push(mp[{x+dx[i],y+dy[i]}]);
}
}
}
}
signed main(){
read(h,w,k);
for(int i=1;i<=k;i++){
read(r[i],c[i]);
mp[{r[i],c[i]}]=i;//map存编号便于跑 bfs
}
for(int i=1;i<=k;i++){
if(!vis[i]){
ur=ld=false;
bfs(i);
if(ur&&ld){//满足条件则无解
cout<<"No";
return 0;
}
}
}
cout<<"Yes";//其它情况则有解
return 0;
}
