【搜索 ex-BFS】bzoj2346: [Baltic 2011]Lamp

时间:2021-11-14 21:54:57

关于图中边权非零即一的宽度优先搜索

Description

译自 BalticOI 2011 Day1 T3「Switch the Lamp On」
有一种正方形的电路元件,在它的两组相对顶点中,有一组会用导线连接起来,另一组则不会。
有 N×MN\times MN×M 个这样的元件,你想将其排列成 NNN 行 MMM 列放在电路板上。电路板的左上角连接电源,右下角连接灯泡。
【搜索  ex-BFS】bzoj2346: [Baltic 2011]Lamp
试求:至少要旋转多少个正方形元件才能让电源与灯泡连通,若无解则输出 NO SOLUTION。


题目分析

记得之前谁的讲课里提到过这种“ex-BFS”?

只需要在队列拓展的时候稍作更改:边权为一时在队尾插入;边权为零在队头插入。正确性可以由反证法得到。

 #include<bits/stdc++.h>

 struct point
{
int x,y;
point(int a=, int b=):x(a), y(b) {}
};
int n,m,dis[][];
char str[][];
std::deque<point> q; bool legal(int x, int y)
{
return x>=&&y>=&&x<=n&&y<=m;
}
bool check(int x, int y)
{
return str[x][y]=='\\';
}
void update(int x, int y, int v)
{
if (dis[x][y] > v){
dis[x][y] = v;
if (q.empty()||v > dis[q.front().x][q.front().y])
q.push_back(point(x, y));
else q.push_front(point(x, y));
}
}
int main()
{
memset(dis, 0x3f3f3f3f, sizeof dis);
scanf("%d%d",&n,&m);
if ((n+m)%){
puts("NO SOLUTION");
return ;
}
for (int i=; i<=n; i++) scanf("%s",str[i]+);
dis[][] = , q.push_front(point(, ));
while (q.size())
{
point tt = q.front();
q.pop_front();
if (legal(tt.x+, tt.y+)){
if (check(tt.x+, tt.y+))
update(tt.x+, tt.y+, dis[tt.x][tt.y]);
else update(tt.x+, tt.y+, dis[tt.x][tt.y]+);
}
if (legal(tt.x+, tt.y-)){
if (check(tt.x+, tt.y))
update(tt.x+, tt.y-, dis[tt.x][tt.y]+);
else update(tt.x+, tt.y-, dis[tt.x][tt.y]);
}
if (legal(tt.x-, tt.y+)){
if (check(tt.x, tt.y+))
update(tt.x-, tt.y+, dis[tt.x][tt.y]+);
else update(tt.x-, tt.y+, dis[tt.x][tt.y]);
}
if (legal(tt.x-, tt.y-)){
if (check(tt.x, tt.y))
update(tt.x-, tt.y-, dis[tt.x][tt.y]);
else update(tt.x-, tt.y-, dis[tt.x][tt.y]+);
}
}
printf("%d\n",dis[n][m]);
return ;
}

END