版本比较
5.8
正文
增加 82 行删除 1 行
393 行未改动全部展开394395396397398398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479393 行未改动全部展开 return 0;}```时间复杂度:$O(n^2)$## E.P2845~~第一次见到搜索都还有绿题的~~
这道题非常复杂,听我慢慢说
首先我们直接用普通BFS肯定是行不通了,因为我们这里的迷宫可以走回头路到另一个可以开灯的房间。有一些房间就走不到,就导致有些灯打不开,就导致答案……
所以我们可以想一个方法:我们把开了灯的如果旁边已经有可以走的我们直接跳在那里,我们就可以完美的避开啦~```cpp line-numbers#include <bits/stdc++.h>using namespace std ;int n , m , ax , ay , bx , by , cnt ;struct node{ int x , y ;} ;vector <node> v[105][105] ;bool vis[105][105] , light[105][105] ;int dx[4] = {1 , -1 , 0 , 0} , dy[4] = {0 , 0 , 1 , -1} ;void bfs(){ queue <node> q //初始化 q.push({1 , 1}) ; vis[1][1] = light[1][1] = 1 ;//他走过并且亮着灯 while(!q.empty()) { node tmp = q.front() ; q.pop() ; int x = tmp.x , y = tmp.y ; for(auto now : v[x][y])//所有能开灯的 { int nx = now.x , ny = now.y ; if(light[nx][ny]) continue ; light[nx][ny] = 1 ;//亮灯 for(int d = 0 ; d < 4 ; d ++) { int sx = nx + dx[d] ; int sy = ny + dy[d] ; if(sx < 1 || sx > n || sy < 1 || sy > n) continue ; if(vis[sx][sy] && !vis[nx][ny])//旁边有可以到达的 { vis[nx][ny] = 1 ; q.push({nx , ny}) ; } } } for(int d = 0 ; d < 4 ; d ++) { int nx = x + dx[d] ; int ny = y + dy[d] ; if(nx < 1 || nx > n || ny < 1 || ny > n) continue ; if(light[nx][ny] && !vis[nx][ny])//亮着灯但没到达且可以到达的 { vis[nx][ny] = 1 ; q.push({nx , ny}) ; } } }}int main(){ cin >> n >> m ; for(int i = 1 ; i <= m ; i ++) { cin >> ax >> ay >> bx >> by ; v[ax][ay].push_back({bx , by}) ; } bfs() ; for(int i = 1 ; i <= n ; i ++) { for(int j = 1 ; j <= n ; j ++) { cnt += light[i][j] ;//亮着灯的 } } cout << cnt ; return 0 ;}```时间复杂度:$O(n^2+m)$太小了
反省A题中……