P2845 [USACO15DEC]Switching on the Lights 开关灯
2019-10-29

题目背景

来源:usaco-2015-dec

Farm John 最近新建了一批巨大的牛棚。这些牛棚构成了一个N*N的矩形网络。(1<n<100)

然而bessie十分怕黑,他想计算可以把多少个牛棚的灯打开。

题目描述

NNN*N个房间,组成了一张NNN*N的网格图,Bessie一开始位于左上角(1,1),并且只能上下左右行走。

一开始,只有(1,1)这个房间的灯是亮着的,Bessie只能在亮着灯的房间里活动。

有另外M条信息,每条信息包含四个数a,b,c,d,表示房间(a,b)里有房间(c,d)的灯的开关。

请计算出最多有多少个房间的灯可以被打开

说明/提示

这里,如果你看得懂英文的话,这里有样例的说明。

Here, Bessie can use the switch in (1,1)to turn on lights in (1,2)and (1,3). She can then walk to (1,3)and turn on the lights in (2,1),from which she can turn on the lights in (2,2). The switch in (2,3)is inaccessible to her, being in an unlit room. She can therefore illuminate at most 5 rooms.

手动机翻

在这里,贝茜可以使用 (1,1) 中的开关打开 (1,2) 和 (1,3) 中的灯。然后,她可以步行到(1,3)并打开(2,1)中的灯,从中她可以打开灯(2,2)。她无法进入(2,3)的开关,她住在一间没有照明的房间里。因此,她最多能照亮5个房间。

原题链接

Solve

BFS莽就完了。
就是得注意不是找几个房间可以走到,而是可以开几个房间的灯。

Code

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#define N 1000
using namespace std;
int n,m,ans;
int x1,y1,x2,y2;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
struct note{
	int x,y;
};
vector<note> g[N][N];
queue<note> q;
bool vis[N][N],fis[N][N];//vis是否房间开灯,fis是否被走到
void bfs(){
	q.push((note){1,1});vis[1][1]=true;fis[1][1]=true;ans=1;
	while(!q.empty()){
		note e=q.front();
		q.pop();
		int x=e.x,y=e.y;
		for(int i=0;i<g[x][y].size();i++){
			int xx=g[x][y][i].x,yy=g[x][y][i].y;
			if(!vis[xx][yy]){
				vis[xx][yy]=true;
				ans++;
			}
			if((fis[xx-1][yy]||fis[xx][yy+1]||fis[xx+1][yy]||fis[xx][yy-1])&&!fis[xx][yy]) fis[xx][yy]=true,q.push((note){xx,yy});
		}
		for(int i=0;i<4;i++){
			int xx=x+dx[i],yy=y+dy[i];
			if(!fis[xx][yy]&&vis[xx][yy]){
				fis[xx][yy]=true;
				q.push((note){xx,yy});
			}
		}
	}
}
int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;i++){
		scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
		g[x1][y1].push_back((note){x2,y2});
	}
	bfs();
	printf("%d",ans);
	return 0;
}

后言

附带一段神奇编译。

/tmp/tmpv278mza7/src: 在函数‘void bfs()’中:
/tmp/tmpv278mza7/src:24:16: 警告:comparison of integer expressions of different signedness: ‘int’ and ‘std::vector::size_type’ {aka ‘long unsigned int’} [-Wsign-compare]
for(int i=0;i<g[x][y].size();i++){
^~~~~~~~~~~~~~