[POI2007]山峰和山谷Grz

Description
FGD小朋友特别喜欢爬山,在爬山的时候他就在研究山峰和山谷。为了能够让他对他的旅程有一个安排,他想知道山峰和山谷的数量。给定一个地图,为FGD想要旅行的区域,地图被分为\(n\times n\)的网格,每个格子(i,j) 的高度w(i,j)是给定的。若两个格子有公共顶点,那么他们就是相邻的格子。(所以与(i,j)相邻的格子有(i-1, j-1),(i-1,j),(i-1,j+1),(i,j-1),(i,j+1),(i+1,j-1),(i+1,j),(i+1,j+1))。我们定义一个格子的集合S为山峰(山谷)当且仅当:1.S的所有格子都有相同的高度。2.S的所有格子都联通3.对于s属于S,与s相邻的s’不属于S。都有ws > ws’(山峰),或者ws < ws’(山谷)。你的任务是,对于给定的地图,求出山峰和山谷的数量,如果所有格子都有相同的高度,那么整个地图即是山峰,又是山谷。

Input
第一行包含一个正整数n,表示地图的大小(1<=n<=1000)。接下来一个\(n\times n\)的矩阵,表示地图上每个格子的高度。(0<=w<=1000000000)

Output
应包含两个数,分别表示山峰和山谷的数量。

Sample Input 1
5
8 8 8 7 7
7 7 8 8 7
7 7 7 7 7
7 8 8 7 8
7 8 8 8 8

Sample Output 1
2 1

Sample Input 2
5
5 7 8 3 1
5 5 7 6 6
6 6 6 2 8
5 7 2 5 8
7 1 0 1 7

Sample Outpu 2
3 3

HINT


bfs水题,为什么会有那么多人想到用dfs???应该是我太菜了……
bfs拓展的时候记录一下自己本身是山谷还是山峰,如果都是,那么不合法;如果都不是,两个答案都加;否则是哪个就加哪个

/*program from Wolfycz*/
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 0x7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
inline int read(){
	int x=0,f=1;char ch=getchar();
	for (;ch<'0'||ch>'9';ch=getchar())	if (ch=='-')    f=-1;
	for (;ch>='0'&&ch<='9';ch=getchar())	x=(x<<1)+(x<<3)+ch-'0';
	return x*f;
}
inline void print(int x){
	if (x>=10)     print(x/10);
	putchar(x%10+'0');
}
const int N=1e3;
const int dx[8]={-1,-1,-1,0,0,1,1,1};
const int dy[8]={-1,0,1,-1,1,-1,0,1};
int map[N+10][N+10];
int hx[N*N+10],hy[N*N+10];
bool vis[N+10][N+10];
int n,Peak,Valley;
bool in_map(int x,int y){return x>0&&x<=n&&y>0&&y<=n;}
void bfs(int x,int y){
	int head=1,tail=1;
	hx[1]=x,hy[1]=y,vis[x][y]=1;
	bool peak=0,valley=0;//peak山峰,valley山谷 
	for (;head<=tail;head++){
		int nx=hx[head],ny=hy[head];
		for (int k=0;k<8;k++){
			int tx=nx+dx[k],ty=ny+dy[k];
			if (!in_map(tx,ty))	continue;
			if (map[tx][ty]==map[nx][ny]&&!vis[tx][ty]){
				hx[++tail]=tx,hy[tail]=ty;
				vis[tx][ty]=1;
				continue;
			}
			if (map[tx][ty]<map[nx][ny])	peak=1;
			if (map[tx][ty]>map[nx][ny])	valley=1;
		}
	}
	if (peak&&valley)	return;
	if (!peak&&!valley)	Peak++,Valley++;
	if (peak)	Peak++;
	if (valley)	Valley++;
}
int main(){
	n=read();
	for (int i=1;i<=n;i++)	for (int j=1;j<=n;j++)	map[i][j]=read();
	for (int i=1;i<=n;i++)	for (int j=1;j<=n;j++)	if (!vis[i][j])	bfs(i,j);
	printf("%d %d\n",Peak,Valley);
	return 0;
}
posted @ 2018-04-22 09:33  Wolfycz  阅读(296)  评论(0编辑  收藏  举报