分析思路
刚开始看到n<=1000,想用一个二维数组来表示垃圾的位置,但后来发现用二维数组表示垃圾的位置是不现实的,因为位置坐标的绝对值小于等于10的9次方,这样就需要一个及其大的二维数组。后来转用结构体数组来表示垃圾的位置,结构体的定义如下。
struct Trash {//结构体Trash用于存储垃圾的位置
int x;
int y;
};
x表示垃圾的x坐标,y表示垃圾的y坐标。
因为垃圾点的数目n不超过1000,所以定义一个大小为1000的Trash数组。
当把n个垃圾点的位置坐标都存储到trash数组的前n个元素之后,对这n个位置进行遍历,判断每一个位置是否放置回收站,若可以放置回收站,则再进一步判断此回收站的得分。
源代码
#include <iostream>
#include<algorithm>
using namespace std;
struct Trash {//结构体Trash用于存储垃圾的位置
int x;
int y;
};
Trash trash[1000];//由子任务说明可知,最多有1000处垃圾
int n;
bool FindXY(int x, int y) {
for (int i = 0; i < n; i++) {
if (trash[i].x == x && trash[i].y == y)
return true;
}
return false;
}
//判断给定的位置是否是垃圾回收站
bool IsStation(Trash t) {
if (FindXY(t.x - 1, t.y) && FindXY(t.x + 1, t.y)
&& FindXY(t.x, t.y - 1) && FindXY(t.x, t.y + 1))
return true;
else
return false;
}
int main()
{
int score[5] = { 0 };//记录不同得分的回收站的数目
cin >> n;
for (int i = 0; i < n; i++) {
cin >> trash[i].x >> trash[i].y;
}
int count = 0;
//对每一个垃圾的位置进行遍历
for (int i = 0; i < n; i++) {
if (IsStation(trash[i])) {
if (FindXY(trash[i].x - 1, trash[i].y - 1))
count++;
if (FindXY(trash[i].x - 1, trash[i].y + 1))
count++;
if (FindXY(trash[i].x + 1, trash[i].y - 1))
count++;
if (FindXY(trash[i].x + 1, trash[i].y + 1))
count++;
score[count]++;
count = 0;
}
}
for (int i = 0; i < 5; i++)
cout << score[i] << endl;
}
附测试样例
7
1 2
2 1
0 0
1 1
1 0
2 0
0 1
2
0 0
-100000 10
11
9 10
10 10
11 10
12 10
13 10
11 9
11 8
12 9
10 9
10 11
12 11