Python入门习题(49)——CCF CSP认证考试真题:回收站选址

CCF CSP认证考试真题(201912-2):回收站选址

问题描述

试题编号: 201912-2
试题名称: 回收站选址
时间限制: 1.0s
内存限制: 512.0MB

在这里插入图片描述在这里插入图片描述
在这里插入图片描述

解题思路

  1. 对于每一个有垃圾的坐标点(x, y),(1)令坐标点(x, y)的初始得分为-1。表示该处不满足给分的前两个条件。(2)查看上下左右4个相邻坐标点上是否都有垃圾,如果都有,则(2-a)令该坐标的得分为0。(2-b)检查该坐标点的4个对角坐标点,任一个对角坐标点有垃圾,那么得分加1。
  2. 如何快速判断坐标点(x, y)有没有垃圾?对于Python语言,用字典来存储<坐标点(x, y),得分>,能够做到在常量时间内检索得出坐标点(x, y)有没有在字典中出现。如果(x, y)在字典中出现,就表明该处有垃圾。

参考代码

n = int(input())

coord_score_dict = { }  #存储<坐标点(x, y),得分> 
for i in range(n):
    x, y = [int(s) for s in input().split()]
    coord_score_dict[(x, y)] = -1  #得分-1表示不满足第二个条件

for x, y in coord_score_dict:
    if (x+1, y) in coord_score_dict and (x-1, y) in coord_score_dict and \
        (x, y-1) in coord_score_dict and (x, y+1) in coord_score_dict:
        coord_score_dict[(x, y)] = 0  #得分0表示满足前两个条件
        if (x-1, y-1) in coord_score_dict:
            coord_score_dict[(x, y)] += 1  #得分加1
        if (x-1, y+1) in coord_score_dict:
            coord_score_dict[(x, y)] += 1
        if (x+1, y+1) in coord_score_dict:
            coord_score_dict[(x, y)] += 1
        if (x+1, y-1) in coord_score_dict:
            coord_score_dict[(x, y)] += 1

score_counts = [0] * 5
for x, y in coord_score_dict:
    if coord_score_dict[(x, y)] >= 0:
        score_counts[coord_score_dict[(x, y)]] += 1  #累加各个得分的次数

for i in range(5):
    print(score_counts[i])

测试用例

  1. 题目描述给出的第一组测试用例。有一个坐标点得分为2。
    样例输入
    7
    1 2
    2 1
    0 0
    1 1
    1 0
    2 0
    0 1
    样例输出
    0
    0
    1
    0
    0

  2. 题目描述给出的第二组测试用例。所有坐标点的得分都为0。出现坐标坐标,而且坐标的绝对值很大。
    样例输入
    2
    0 0
    -100000 10
    样例输出
    0
    0
    0
    0
    0

  3. 题目描述给出的第三组测试用例。2个坐标点得1分,1个坐标点得2分。
    样例输入
    11
    9 10
    10 10
    11 10
    12 10
    13 10
    11 9
    11 8
    12 9
    10 9
    10 11
    12 11
    样例输出
    0
    2
    1
    0
    0

  4. n=1的边界情形。
    样例输入
    1
    0 0
    样例输出
    0
    0
    0
    0
    0

  5. 坐标点得4分的情形。在第一组测试用例基础上扩展得到。
    样例输入
    9
    1 2
    2 1
    0 0
    1 1
    1 0
    2 0
    0 1
    0 2
    2 2
    样例输出
    0
    0
    0
    0
    1

小结

  1. 运用Python语言的字典来求解本题,既简洁又高效。用其他语言来编写程序的话,建议采用类似数据结构。
  2. 覆盖坐标点得4分的情形的测试用例是必要的,可以验证计算得分的代码无误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值