题解:P17218 [ICPC 2017 Nanning R] The Game of Life

· · 题解

本题只需按照题目操作即可。

题目传送门

题目描述

本题有多组测试数据。

对于每一个测试数据,都包含一个 n 和 m,表示该细胞矩阵为 n 列 m 行,如果为 “.”,就是死亡,如果为 “\#”,就是存活,然后有四个条件(详情请看题目),每次模拟即可。

但是这里棋盘是无限的,不过我们可以敏锐的观察到我们的模拟次数是有限的,那么实际处理范围也是有限的。

模拟思路

AC 代码

本题变量名可能有点随意,勿喷!

#include<bits/stdc++.h>
using namespace std;
int t,n,m,maxx,d,tot,x,a,aa,b,bb;
char ch[666][666],sh[666][666];
bool z,zz,zzz,zzzz;
string s;
int main(){
    cin>>t;
    while(t--){
        cin>>n>>m;
        for(int i=1;i<=660;i++){
            for(int j=1;j<=660;j++){
                ch[i][j]='.';
            }
        }
        tot=0;
        for(int i=1;i<=n;i++){
            cin>>s;
            for(int j=330;j<330+m;j++){
                ch[i+330][j]=s[j-330];
                if(ch[i+330][j]=='#')tot++;
            }
            a=1+330;
            aa=n+330;
            b=330;
            bb=330+m-1;
        }//读入
        maxx=tot;
        d=0;
        for(int k=1;k<=321;k++){
            for(int i=a-1;i<=aa+1;i++){
                for(int j=b-1;j<=bb+1;j++){
                    x=0;
                    if(ch[i-1][j]=='#')x++;
                    if(ch[i-1][j-1]=='#')x++;
                    if(ch[i-1][j+1]=='#')x++;
                    if(ch[i][j-1]=='#')x++;
                    if(ch[i][j+1]=='#')x++;
                    if(ch[i+1][j]=='#')x++;
                    if(ch[i+1][j-1]=='#')x++;
                    if(ch[i+1][j+1]=='#')x++;
                    if(ch[i][j]=='#'){
                        if(x<2||x>3)sh[i][j]='.';
                        else sh[i][j]='#';
                    }
                    else if(x==3)sh[i][j]='#';
                    else sh[i][j]='.';
                }
            }
            tot=0;
            z=zz=zzz=zzzz=0;
            for(int i=a-1;i<=aa+1;i++){
                for(int j=b-1;j<=bb+1;j++){
                    if(sh[i][j]=='#'){
                        tot++;
                        if(i==a-1)z=1;
                        if(i==aa+1)zz=1;
                        if(j==b-1)zzz=1;
                        if(j==bb+1)zzzz=1;
                    }
                    ch[i][j]=sh[i][j];
                }
            }
            if(z)a--;
            if(zz)aa++;
            if(zzz)b--;
            if(zzzz)bb++;
            if(tot>maxx){
                maxx=tot;
                d=k;
            }
        }//维护
        cout<<d<<" "<<maxx<<" "<<tot<<endl;//输出
    }
    return 0;
}