| 试题编号: | 201912-2 |
| 试题名称: | 回收站选址 |
| 时间限制: | 1.0s |
| 内存限制: | 512.0MB |
| 问题描述: |
经过读题分析,本题难点在于如何唯一表示坐标点,容易想到hash表的方式。C++语言的unordered_map哈希表键不支持pair类型或者自定义结构体,故将坐标点转而表示为一个用逗号分隔横纵坐标的字符串唯一表示,判断上下左右坐标点是否存在时只需要根据逗号标记解析出横纵坐标的整数表示,进行改变后再转换为标准字符串键的方式查询是否存在,注意使用哈希表的成员方法find查询哈希表的键,否则在键不存在时会出现大量零值二元组产生错误。使用Python语言的字典,通过元组作为键表示坐标点,值表示为真可以很方便地实现唯一表示,只需要注意在每次读入横纵坐标后转换为整数类型作为元组存入字典即可。这里给出两种语言的AC题解。
3. C++代码程序实现:#include4. Python代码程序实现:using namespace std; const int slen=12; int main() { int scores[5]={0},score=0; int n,x=0,y=0; char xi[slen],yi[slen]; memset(xi,0,sizeof(xi)); memset(yi,0,sizeof(yi)); scanf("%d",&n); unordered_map pos; for (int i=0;i scanf("%s %s",xi,yi); pos[string(xi)+","+string(yi)]=true; } for (auto p:pos) { int comma=p.first.find(","); x=stoi(p.first.substr(0,comma),nullptr); y=stoi(p.first.substr(comma+1),nullptr); string left=to_string(x-1)+","+to_string(y); string right=to_string(x+1)+","+to_string(y); string up=to_string(x)+","+to_string(y+1); string down=to_string(x)+","+to_string(y-1); if (pos.find(left)!=pos.end()&&pos.find(right)!=pos.end()&&pos.find(up)!=pos.end()&&pos.find(down)!=pos.end()) { score=0; for (int i=x-1;i<=(x+1);i+=2 ) { for (int j=y-1;j<=(y+1) ;j+=2 ) { if (pos.find(to_string(i)+","+to_string(j))!=pos.end()) { ++score; } } } ++scores[score]; } } for (int i=0;i<5 ;++i ) { printf("%dn",scores[i]); } return 0; }
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Time : 2022/6/10 08:01
@Author : Albert Darren
@Contact : 2563491540@qq.com
@File : Py1-201912-2.py
@Version : Version 1.0.0
@Description : TODO
@Created By : PyCharm
"""
n = int(input())
# 准备一个列表依次表示得分为0、1、2、3和4的回收站选址个数
scores = [0, 0, 0, 0, 0]
# 准备一个坐标字典,使用元组作为键表示坐标点,值表示为真
pos = {}
for i in range(n):
x, y = input().split()
pos[(int(x), int(y))] = True
for x, y in pos:
up = (x, y + 1)
down = (x, y - 1)
left = (x + 1, y)
right = (x - 1, y)
if up in pos.keys() and down in pos.keys() and left in pos.keys() and right in pos.keys():
score = 0
for i in range(x - 1, x + 2, 2):
for j in range(y - 1, y + 2, 2):
if (i, j) in pos.keys():
score += 1
scores[score] += 1
for i in scores:
print(i)
5.提交AC结果:



