【BZOJ1102/POI2007】山峰和山谷Grz

                               1102: [POI2007]山峰和山谷Grz

                                                 Time Limit: 10 Sec  Memory Limit: 162 MB
                                                              Submit: 998  Solved: 515

Description

  FGD小朋友特别喜欢爬山,在爬山的时候他就在研究山峰和山谷。为了能够让他对他的旅程有一个安排,他想
知道山峰和山谷的数量。给定一个地图,为FGD想要旅行的区域,地图被分为n*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*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
输入样例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 Output

输出样例1
2 1
输出样例2
3 3

HINT

解析:

       广搜即可。

       PS:hzwer的做法总是如此优秀啊orz!

代码:
 

#include <bits/stdc++.h>
using namespace std;
 
const int fx[10]={0,-1,-1,-1,0,0,1,1,1};
const int fy[10]={0,-1,0,1,-1,1,-1,0,1};
const int Max=1001000;
int n,m,ans1,ans2,head,tail,mx,mn;
int num[1005][1005],vis[1005][1005];
struct shu{int x,y;};
shu p[Max];
 
inline int get_int()
{
    int x=0,f=1;
    char c;
    for(c=getchar();(!isdigit(c))&&(c!='-');c=getchar());
    if(c=='-') {f=-1;c=getchar();}
    for(;isdigit(c);c=getchar()) x=(x<<3)+(x<<1)+c-'0';
    return x*f;
}
 
inline bool check(int x,int y)
{
    if(x<=0||x>n||y<=0||y>n) return 0;
    return 1;
}
 
inline void bfs(int s,int t)
{
    mx=mn=num[s][t];
    head=0,tail=1;
    p[1].x=s,p[1].y=t;
    while(head<tail)
    {
      int x=p[++head].x,y=p[head].y;
      for(int i=1;i<=8;i++)
      {
        int xx=x+fx[i],yy=y+fy[i];
        if(!check(xx,yy)) continue;
        mx = max(mx,num[xx][yy]),mn=min(mn,num[xx][yy]);
        if(num[xx][yy] == num[s][t] && !vis[xx][yy])
        {
          vis[xx][yy]=1;
          p[++tail].x=xx,p[tail].y=yy;
        }
      }
    }
    if(mx <= num[s][t] && mn <= num[s][t]) ans1++;
    if(mn >= num[s][t] && mx >= num[s][t]) ans2++;
}
 
int main()
{
    n=get_int();
    for(int i=1;i<=n;i++)
      for(int j=1;j<=n;j++) num[i][j]=get_int();
    for(int i=1;i<=n;i++)
      for(int j=1;j<=n;j++)
        if(!vis[i][j])
          bfs(i,j);
    cout<<ans1<<" "<<ans2<<"\n";
 
    return 0;
} 

猜你喜欢

转载自blog.csdn.net/m0_38083668/article/details/81637108