跟省选day2讲的一道题好像...
#include<cstdio> #include<cstdlib> #include<algorithm> #include<queue> #include<cstring> using namespace std; inline char nc() { static char buf[100000],*p1=buf,*p2=buf; if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; } return *p1++; } inline void read(int &x) { char c=nc(),b=1; for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1; for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b; } inline void read(char *s){ char c=nc(); int len=0; for (;c!='F' && c!='R' && c!='.';c=nc()); for (;c=='F' || c=='R' || c=='.';s[++len]=c,c=nc()); s[++len]=0; } const int N=4005; int n,m; char Map[N][N]; int dis[N][N]; const int dx[]={0,0,1,-1}; const int dy[]={1,-1,0,0}; struct abcd{ int x,y; abcd(int x=0,int y=0):x(x),y(y) { } abcd nxt(int k){ return abcd(x+dx[k],y+dy[k]); } char clr() { return Map[x][y]; } }; queue<abcd> Q; inline void bfs(abcd s) { queue<abcd> q; abcd u; q.push(s); while (!q.empty()){ u=q.front(); q.pop(); for (int k=0;k<4;k++) if (u.x+dx[k]>0 && u.x+dx[k]<=n && u.y+dy[k]>0 && u.y+dy[k]<=m) if (u.nxt(k).clr()==u.clr() && !dis[u.x+dx[k]][u.y+dy[k]]) { dis[u.x+dx[k]][u.y+dy[k]]=dis[s.x][s.y]; q.push(u.nxt(k)); Q.push(u.nxt(k)); } } } inline void bfs(){ abcd u; Q.push(abcd(1,1)); dis[1][1]=1; bfs(abcd(1,1)); // for (int i=1;i<=n;i++,putchar('\n')) for (int j=1;j<=m;j++,putchar(' ')) printf("%d",dis[i][j]); printf("\n"); while (!Q.empty()) { u=Q.front(); Q.pop(); for (int k=0;k<4;k++) if (u.x+dx[k]>0 && u.x+dx[k]<=n && u.y+dy[k]>0 && u.y+dy[k]<=m) if (u.nxt(k).clr()!='.' && u.nxt(k).clr()!=u.clr() && !dis[u.x+dx[k]][u.y+dy[k]]) { dis[u.x+dx[k]][u.y+dy[k]]=dis[u.x][u.y]+1; Q.push(u.nxt(k)); bfs(u.nxt(k)); // for (int i=1;i<=n;i++,putchar('\n')) for (int j=1;j<=m;j++,putchar(' ')) printf("%d",dis[i][j]); printf("\n"); } } } int main() { freopen("t.in","r",stdin); freopen("t.out","w",stdout); read(n); read(m); for (int i=1;i<=n;i++) read(Map[i]); bfs(); int ans=0; for (int i=1;i<=n;i++) for (int j=1;j<=m;j++) ans=max(ans,dis[i][j]); printf("%d\n",ans); return 0; }
时间: 2024-11-09 09:26:23