CF1227E Arson In Berland Forest 题解

· · 题解

思路

首先从所有未被烧毁的树出发走 T 步,我们可以找到所有不能被点燃的树,当 T 越小时,可以点燃的树就越多,若一个 T 有解,那对于 T'\le T,T' 也一定是有解的,也就是说,答案具有单调性,我们可以二分。

考虑判定,我们确定了所有可以点燃的树后,我们还需要把这些树全部点燃检查一遍与输入是否一样,因为刚刚我们只是保证了所有没被烧毁的树一定不会被烧毁,有一些本来应该被烧毁的这时候不一定会被烧毁,所以还要再模拟一遍检查一下。

代码

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
int n,m;
vector<bool>vis[1000005],ori[1000005],now[1000005];
const int dx[]={1,1,1,-1,-1,-1,0,0};
const int dy[]={1,-1,0,1,-1,0,1,-1};
struct path
{
    int x,y,step;
};
queue<path>q;
void bfs(int t)
{
    while(!q.empty())
    {
        path a=q.front();
        q.pop();
        if(vis[a.x][a.y])
            continue;
        vis[a.x][a.y]=true;
        for(int i=0;i<8;i++)
        {
            int nowx=a.x+dx[i];
            int nowy=a.y+dy[i];
            if(nowx<0||nowy<0||nowx>=n||nowy>=m||vis[nowx][nowy]||a.step>=t)
                continue;
            q.push({nowx,nowy,a.step+1});
        }
    }
}

bool check(int t)
{
    for(int i=0;i<n;i++)
    {
        vis[i].clear();
        for(int j=0;j<m;j++)
        {
            vis[i].push_back(false);
            if(!ori[i][j])
                q.push({i,j,0});
        }   
    }
    bfs(t);
    for(int i=0;i<n;i++)
    {
        now[i].clear();
        for(int j=0;j<m;j++)
        {
            if(!vis[i][j])
            {
                now[i].push_back(true);
                q.push({i,j,0});
            }
            else
                now[i].push_back(false);
        }
        vis[i].clear();
        for(int j=0;j<m;j++)
            vis[i].push_back(false);
    }
    bfs(t);
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(ori[i][j]!=vis[i][j])
                return false;
        }
    }
    return true;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>m;
    for(int i=0;i<m+2;i++)  
        ori[0].push_back(false);
    for(int i=1;i<=n;i++)
    {
        string t;
        cin>>t;
        ori[i].push_back(false);
        for(char c:t)
            ori[i].push_back(c=='X');
        ori[i].push_back(false);
    }
    for(int i=0;i<m+2;i++)
        ori[n+1].push_back(false);
    n+=2,m+=2;
    int l=-1,r=min(n,m)+1;
    while(l+1!=r)
    {
        int mid=(l+r)>>1;
        if(check(mid))
            l=mid;  
        else
            r=mid;
    }
    cout<<l<<"\n";
    check(l);
    n-=2,m-=2;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
            cout<<((now[i][j])?'X':'.');
        cout<<"\n";
    }
    return 0;
}