# bzoj 1619: [Usaco2008 Nov]Guarding the Farm 保卫牧场（DFS）

☆ACM☆ 专栏收录该内容
222 篇文章 0 订阅

## 1619: [Usaco2008 Nov]Guarding the Farm 保卫牧场

Time Limit: 5 Sec   Memory Limit: 64 MB
Submit: 913   Solved: 411
[ Submit][ Status][ Discuss]

## Description

The farm has many hills upon which Farmer John would like to place guards to ensure the safety of his valuable milk-cows. He wonders how many guards he will need if he wishes to put one on top of each hill. He has a map supplied as a matrix of integers; the matrix has N (1 < N <= 700) rows and M (1 < M <= 700) columns. Each member of the matrix is an altitude H_ij (0 <= H_ij <= 10,000). Help him determine the number of hilltops on the map. A hilltop is one or more adjacent matrix elements of the same value surrounded exclusively by either the edge of the map or elements with a lower (smaller) altitude. Two different elements are adjacent if the magnitude of difference in their X coordinates is no greater than 1 and the magnitude of differences in their Y coordinates is also no greater than 1.

## Input

* Line 1: Two space-separated integers: N and M

* Lines 2..N+1: Line i+1 describes row i of the matrix with M space-separated integers: H_ij

## Output

* Line 1: A single integer that specifies the number of hilltops

8 7
4 3 2 2 1 0 1
3 3 3 2 1 0 1
2 2 2 2 1 0 0
2 1 1 1 1 0 0
1 1 0 0 0 1 0
0 0 0 1 1 1 0
0 1 2 2 1 1 0
0 1 1 1 2 1 0

## Sample Output

3

#include<stdio.h>
#include<algorithm>
using namespace std;
typedef struct Point
{
int h;
int x, y;
bool operator < (const Point &b) const
{
if(h>b.h)
return 1;
return 0;
}
}Point;
Point s[500005];
int n, m, a[705][705], flag[705][705];
int dir[8][2] = {1,0,0,1,-1,0,0,-1,1,-1,-1,1,1,1,-1,-1};
void Sech(int x, int y)
{
int dx, dy, i;
flag[x][y] = 1;
for(i=0;i<=7;i++)
{
dx = x+dir[i][0];
dy = y+dir[i][1];
if(dx<1 || dx>n || dy<1 || dy>m || flag[dx][dy] || a[dx][dy]>a[x][y])
continue;
Sech(dx, dy);
}
}
int main(void)
{
int i, j, ans, cnt = 0;
scanf("%d%d", &n, &m);
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf("%d", &a[i][j]);
s[++cnt].x = i, s[cnt].y = j;
s[cnt].h = a[i][j];
}
}
sort(s+1, s+cnt+1);
ans = 0;
for(i=1;i<=cnt;i++)
{
if(flag[s[i].x][s[i].y]==0)
{
Sech(s[i].x, s[i].y);
ans++;
}
}
printf("%d\n", ans);
return 0;
}

• 1
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

04-29 316

12-17 60
12-14 256
10-26 158
07-21 46
09-05 27
12-18 98