CodeFroces 812B Sagheer, the Hausmeister(BFS)

来源:互联网 发布:sql两表关联查询 编辑:程序博客网 时间:2024/05/29 23:23

题意,给出一个大楼,1代表这个课室灯亮着,0代表关着。你从左下角出发,每移动一格花费一分钟,问最小的花费时间。

做法很简单,我是直接bfs,从左下角出发,先把这层楼的灯全关了,然后生成一个到下一层的左楼梯和右楼梯的情况压入队列中,然后走到最后统计一下输出即可,1A。

代码如下:

#include<bits/stdc++.h>using namespace std;typedef pair<int, int> pii;int G[20][105], num[20];int n, m, Min = 0x3f3f3f3f;struct node{int x, y, cnt;};void bfs(){node now, next;queue<node >q;now.x = 0;now.y = 0;now.cnt = 0;q.push(now);while(!q.empty()){now = q.front();q.pop();if(num[now.x]){int c = 0;if(now.y == 0){for(int i = 0; i < m; i++){if(G[now.x][i])c++;if(c == num[now.x]){now.cnt += i;if(now.x == n){Min = min(Min, now.cnt);break;}next.x = now.x + 1;next.y = 0;next.cnt = now.cnt + i + 1;q.push(next);next.x = now.x + 1;next.y = m - 1;next.cnt = now.cnt + (m - i);q.push(next);break;}}} else {for(int i = m - 1; i >= 0; i--){if(G[now.x][i])c++;if(c == num[now.x]){now.cnt += m - i - 1;if(now.x == n){Min = min(Min, now.cnt);break;}next.x = now.x + 1;next.y = 0;next.cnt = now.cnt + i + 1;q.push(next);next.x = now.x + 1;next.y = m - 1;next.cnt = now.cnt + m - i;q.push(next);break;}}}} else {now.x++;now.cnt++;q.push(now);}}}int myget(){char ch = getchar();while(ch < '0' || ch > '9')ch = getchar();return ch - 48;}int main(){cin >> n >> m;m += 2;for(int i = n - 1; i >= 0; i--){int cnt = 0;for(int j = 0; j < m; j++){G[i][j] = myget();if(G[i][j])cnt++;}num[i] = cnt;}for(int i = n - 1; i >= 0; i--)if(num[i] == 0)n--;elsebreak;n--;if(n < 0)cout << "0" << endl;else{bfs();cout << Min << endl;}return 0;}

代码看起来有点长但是很好写,很多地方是重复的。