BZOJ 1102: [POI2007]山峰和山谷Grz

简单bfs,暴露了我长久不打代码啥都忘光光的现实。
#include <bits/stdc++.h>
using namespace std;
const int N=1e3+5;
const int dx[8]={-1,-1,-1,0,0,1,1,1},dy[8]={-1,0,1,-1,1,-1,0,1}; 
int n,sg,sf,ans1,ans2;
int a[N][N];
bool vis[N][N];
struct node{int x,y;};
queue<node>q;//queue放在函数外面比较保险 

inline void bfs(int x,int y)
{
	q.push((node){x,y}); //山峰 
	vis[x][y]=true;
	while (q.size())
	{
		node u=q.front(); q.pop();
		//原来居然在这里写:vis[u.x][u.y]=true  然后一直TLE,没有发现...... 
		for (register int i=0; i<8; ++i)
		{
			int xx=u.x+dx[i],yy=u.y+dy[i];
			if (xx<1 || xx>n || yy<1 || yy>n) continue;
			if (a[xx][yy]>a[u.x][u.y]) sf=0;
			if (a[xx][yy]<a[u.x][u.y]) sg=0;
			if (a[xx][yy]==a[u.x][u.y] && !vis[xx][yy]) q.push((node){xx,yy}),vis[xx][yy]=true;
			//由于长时间没写代码了,居然忘记了vis[xx][yy]是在这个后面赋为true的 
		}
	}
}

inline int read()
{
	int ret=0,ff=1; char ch=getchar();
	while (!isdigit(ch)) {if (ch=='-') ff=-ff; ch=getchar();}
	while (isdigit(ch)) {ret=(ret<<3)+(ret<<1)+ch-'0'; ch=getchar();}
	return ret*ff; 
}

int main(){
	n=read();  //一百万的数据,还是用快读吧 
	for (register int i=1; i<=n; ++i)
	for (register int j=1; j<=n; ++j) a[i][j]=read();
	for (register int i=1; i<=n; ++i)
	for (register int j=1; j<=n; ++j) 
	if (!vis[i][j]) 
	{
		sf=sg=1;
		bfs(i,j);
		ans1+=sf; ans2+=sg;
	}
	printf("%d %d\n",ans1,ans2);
return 0;	
}
发布了64 篇原创文章 · 获赞 29 · 访问量 689

猜你喜欢

转载自blog.csdn.net/Dove_xyh/article/details/103752896