题目
解题思路
因为:
1:x, y有很大的测试案列,二维数组浪费空间,并且可能无法分配那么大的空间。
2:有负数坐标。
所以:
1:使用链表
2:链表按x排序存储
代码
注意,在CCF答题栏选C++
因为for(int i = 0; i < 5; i++)这样的语句C编译不通过。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int x, y;
struct Node *next;
} Node, *List;
void insertSort(Node *head, int x1, int y1) {
//有头节点
Node *node = (Node *)malloc(sizeof(Node));
node->x = x1;
node->y = y1;
Node *p = head;
while (p->next != NULL && p->next->x < x1) p = p->next;
node->next = p->next;
p->next = node;
}
//检查x,y坐标是否在链表中
int check(Node *node, int x1, int y1) {
//无头节点
while (node != NULL && node->x < x1) node = node->next;
while (node != NULL && node->x == x1) {
if (node->y == y1) return 1;
node = node->next;
}
return 0;
}
int main() {
int n, x1, y1;
scanf("%d", &n);
Node *head = (Node *)malloc(sizeof(Node));
head->next = NULL;
for (int i = 0; i < n; i++) {
scanf("%d%d", &x1, &y1);
insertSort(head, x1, y1);
}
int grades[5] = {0};
Node *p = head->next;
while (p) {
x1 = p->x;
y1 = p->y;
if (check(head->next, x1 - 1, y1) && check(p->next, x1 + 1, y1)
&& check(head->next, x1, y1 - 1) && check(head->next, x1, y1 + 1)) {
int g = check(head->next, x1 - 1, y1 + 1) + check(p->next, x1 + 1, y1 + 1)
+ check(head->next, x1 - 1, y1 - 1) + check(p->next, x1 + 1, y1 - 1);
grades[g]++;
}
p = p->next;
}
for (int i = 0; i < 5; i++)
printf("%d\n", grades[i]);
return 0;
}