USACO: PROB The Castle

/*
ID: Jang Lawrence
PROG: castle
LANG: C++
*/
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#define mp make_pair
using namespace std;
typedef pair < int, int > pii;
int m,n;
bool is[55][55][4];
int num[3333],id[55][55];
bool in(int x,int y)
{
    return x>=1&&x<=n&&y>=1&&y<=m;
}
int dir[4][2]={-1,0,0,1,1,0,0,-1};
int ansn,anss,ansm,ansx,ansy,ansd;
void bfs()
{
    queue<pii> q;
    bool vis[55][55]={};
    int nu=0,mr=0;
    for(int i=1;i<=n;++i)
    for(int j=1;j<=m;++j)
    if(!vis[i][j])
    {
        vis[i][j]=1;
        q.push(mp(i,j));
        nu++;
        int k=0;
        while(!q.empty())
        {
            pii v=q.front();
            id[v.first][v.second]=nu;
            ++k;
            q.pop();
            for(int si=0;si<4;++si)
            {
                int x=v.first+dir[si][0],y=v.second+dir[si][1];
                if(in(x,y)&&!is[v.first][v.second][si]&&!vis[x][y])
                q.push(mp(x,y)),vis[x][y]=1;
            }
        }
        num[nu]=k;
    if(mr<k) mr=k;
    }
  ansn=nu,anss=mr,ansm=anss;
}
void update(int x,int y,int k)
{
    if(k==0)
    {
        if(id[x][y]!=id[x-1][y]&&x>=2&&num[id[x][y]]+num[id[x-1][y]]>ansm)
        {
            ansm=num[id[x][y]]+num[id[x-1][y]];
            ansx=x,ansy=y,ansd=k;
        }
    }
    else
    {
        if(id[x][y]!=id[x][y+1]&&y+1<=m&&num[id[x][y]]+num[id[x][y+1]]>ansm)
        {
            ansm=num[id[x][y]]+num[id[x][y+1]];
            ansx=x,ansy=y,ansd=k;
        }
    }
}
char st[]={"NESW"};
int main()
{
  #ifndef  DEBUG
  freopen("castle.in","r",stdin);
  freopen("castle.out","w",stdout);
  #endif
    scanf("%d%d",&m,&n);
    for(int i=1;i<=n;++i)
    for(int j=1;j<=m;++j)
    {
        int k;
        scanf("%d",&k);
        for(int d=0;d<4;++d)
        if(k&(1<<((d+1)%4))) is[i][j][d]=1;
    }
    bfs();
    for(int j=1;j<=m;++j)
    for(int i=n;i>=1;--i)
    for(int d=0;d<=1;++d)
    if(is[i][j][d])
    {
        update(i,j,d);
    }
    printf("%d\n%d\n%d\n%d %d %c\n",ansn,anss,ansm,ansx,ansy,st[ansd]);
    return 0;
}

你可能感兴趣的:(USACO: PROB The Castle)