Luogu P2845 [USACO15DEC]Switching on the Lights 开关灯(bfs)

P2845 [USACO15DEC]Switching on the Lights 开关灯

题意

题目背景

来源:usaco-2015-dec

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

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

题目描述

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

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

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

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

输入输出格式

输入格式:

第一行,两个数:(N,M(1<m<200000));

(2-m+1)行:坐标((x_1,y_1),(x_2,y_2))代表房间的坐标((x_1,y_1))及可以点亮的房间的坐标((x_2,y_2));

输出格式:

一个数,最多可以点亮的房间数。

输入输出样例

输入样例#1:

3 6
1 1 1 2
2 1 2 2
1 1 1 3
2 3 3 1
1 3 1 2
1 3 2 1

输出样例#1:

5

说明

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

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.

思路

我们来水这道题吧。 --Mercury
(cdots)
这题怎么做啊??? --Mercury

显然可以用广搜解决。记录两个数组(vis)(bri),分别表示是否走过一个点以及某个点的灯是否打开了。广搜过程中遍历到某个点,我们就看与它相邻的点是否开了灯,如果开了,那么就能到达,加入队列以继续广搜。然后,我们还要看它有几个开关,把他们都打开之后开了灯的房间是否有相邻的可以到达的点。如果有,说明这间新开灯的房间也可以到达,加入队列以继续广搜。最后我们就能遍历到所有的能到达的点。统计答案即可。

AC代码

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
int n,m,ans;
int a[4]={-1,+0,+1,+0};
int b[4]={+0,-1,+0,+1};
vector<PII>G[105][105];
bool vis[105][105],bri[105][105];
int read()
{
    int re=0;char ch=getchar();
    while(!isdigit(ch)) ch=getchar();
    while(isdigit(ch)) re=(re<<3)+(re<<1)+ch-'0',ch=getchar();
    return re;
}
bool range(int x,int y){return x>=1&&x<=n&&y>=1&&y<=n;}
int main()
{
    n=read(),m=read();
    while(m--)
    {
        int x=read(),y=read(),z=read(),w=read();
        G[x][y].push_back(make_pair(z,w));
    }
    vis[1][1]=bri[1][1]=true;ans=1;
    queue<PII>Q;
    Q.push(make_pair(1,1));
    while(!Q.empty())
    {
        int x=Q.front().first,y=Q.front().second;Q.pop();
        for(int i=0;i<4;i++)
        {
            int xx=x+a[i],yy=y+b[i];
            if(range(xx,yy)&&!vis[xx][yy]&&bri[xx][yy])
            {
                vis[xx][yy]=true;
                Q.push(make_pair(xx,yy));
            }
        }
        for(int i=0;i<G[x][y].size();i++)
        {
            int xx=G[x][y][i].first,yy=G[x][y][i].second;
            if(!bri[xx][yy]) bri[xx][yy]=true,ans++;
            if(vis[xx][yy]) continue;
            for(int j=0;j<4;j++)
            {
                int xxx=xx+a[j],yyy=yy+b[j];
                if(range(xxx,yyy)&&vis[xxx][yyy])
                {
                    vis[xx][yy]=true;
                    Q.push(make_pair(xx,yy));
                    break;
                }
            }
        }
    }
    printf("%d",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/coder-Uranus/p/9892806.html