试题编号: | 201812-3 |
试题名称: | CIDR合并 |
时间限制: | 1.0s |
内存限制: | 512.0MB |
问题描述: | 样例输入 2 样例输出 1.0.0.0/8 样例输入 2 样例输出 10.0.0.0/8 样例输入 2 样例输出 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])