CodeFroces 812B Sagheer, the Hausmeister(BFS)

题意,给出一个大楼,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--;
		else
			break;
	n--;
	if(n < 0)
		cout << "0" << endl;
	else{
		bfs();
		cout << Min << endl;
	}
	return 0;
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值