python实现 CCF201812-3 CIDR合并

 

试题编号:201812-3
试题名称:CIDR合并
时间限制:1.0s
内存限制:512.0MB
问题描述:



样例输入

2
1
2

样例输出

1.0.0.0/8
2.0.0.0/8

样例输入

2
10/9
10.128/9

样例输出

10.0.0.0/8

样例输入

2
0/1
128/1

样例输出

0.0.0.0/0

 60分代码(只进行排序即可)

from copy import deepcopy

n = int(input())
value = [1]                             # 通过ip前缀求匹配集
temp = 1                                # 如101.5.5/24,匹配集最大为:101.5.5.255
for i in range(1, 32):                  # value[5] = 255
    temp = temp + 2 ** i
    value.append(temp)

    
# 将ip地址转化为标准型
ip_list = []
for i in range(n):
    temp = input()
    point_num = temp.count('.')
    if point_num == 3 and '/' in temp:   # 标准型
        temp = temp
    elif '/' not in temp:                # 省略长度型
        if point_num == 0:
            temp = temp + ".0.0.0/8"
        elif point_num == 1:
            temp = temp + ".0.0/16"
        elif point_num == 2:
            temp = temp + '.0/24'
        else:
            temp = temp + '/32'
    else:                                # 省略后缀型
        temp = temp.split('/')
        if point_num == 0:
            temp = temp[0] + ".0.0.0/" + temp[1]
        elif point_num == 1:
            temp = temp[0] + '.0.0/' + temp[1]
        elif point_num == 2:
            temp = temp[0] + '.0/' + temp[1]
    ip = deepcopy(temp)
    temp = temp.split('/')
    temp[0] = temp[0].split('.')
    ans = 0                              # 将ip地址转化为十进制形式
    for j in range(4):
        a = int(temp[0][j])
        ans += a * (256 ** (3-j))
    end = 32 - int(temp[1])

    ip_list.append([ans, int(temp[1]), ip, value[end-1]])
    # ip前缀的匹配集范围为:[ans, ans + value[end-1]]

##print(value)
##print(ip_list)
# 第一步:排序
sort = sorted(ip_list, key=lambda x: (x[0], x[1])) # 只进行排序就有60分
for s in sort:
    print(s[2])

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值