題目分析:
題目很長,讀懂之后就很簡單。描述里面還有一點混淆視聽,前景色在本體里面是用不到的,色塊怎么前景色的嘛。
題目大概意思就是:將圖片切割成小圖片,每個小圖片用一個色塊塊,色塊的顏色取小圖片內所有像素的均值(向下取整),按他的編碼輸出。
- 空格代表色塊,對應的字符串表示其顏色, 每一行最后需要一個換行符
- 色塊顏色和默認背景色相同,則使用默認背景色的命令
- 色塊顏色與當前的背景色相同,且不使用換背景色的命令(直接添加‘ ’)
- 每行色塊掃描完成后,將背景色重置為默認顏色
- 輸出的字符使用ASCII碼(16進制,大寫)
- 輸出結果不換行
提交代碼(80分):
class Pixle(): def __init__(self, r, g, b): self.r = r self.g = g self.b = b m,n = map(int, input().split()) p,q = map(int, input().split()) esc = '\\x1B\\x5B' #ESC[ a_chr = '\\x3B' # ; a_0 = '\\x30' # 0 a_48 = '\\x34\\x38\\x3B\\x32\\x3B' # 48;2; a_m = '\\x6D' # m a_space = '\\x20' # ' ' a_n = '\\x0A' # '\n' cur_r, cur_g, cur_b = 0,0,0 color = [[Pixle(0,0,0) for i in range(m)] for i in range(n)] for i in range(n): for j in range(m): tmp = input() if len(tmp) == 4: color[i][j].r = int(tmp[1] + tmp[1], 16) color[i][j].g = int(tmp[2] + tmp[2], 16) color[i][j].b = int(tmp[3] + tmp[3], 16) elif len(tmp) == 2: t = int(tmp[1] + tmp[1], 16) color[i][j].r = t color[i][j].g = t color[i][j].b = t else: color[i][j].r = int(tmp[1:3], 16) color[i][j].g = int(tmp[3:5], 16) color[i][j].b = int(tmp[5:7], 16) w = m//p # sub-block wide h = n//q # sub-block high color_block = [[0 for i in range(w)] for i in range(h)] # color block for i in range(h): for j in range(w): r = g = b = 0 for k in range(q): # q * p block for l in range(p): r += color[i * q + k][j * p + l].r g += color[i * q + k][j * p + l].g b += color[i * q + k][j * p + l].b color_block[i][j] = Pixle(r // (p*q), g // (p*q), b // (p*q)) # average rst = [] # result list for i in range(h): for j in range(w): block = color_block[i][j] r,g,b = block.r, block.g, block.b if r == cur_r and g == cur_g and b == cur_b: pass elif r == 0 and g == 0 and b == 0: cur_r, cur_g, cur_b = 0, 0, 0 #reset current color rst.append(esc) rst.append(a_0) rst.append(a_m) else: tmp_r, tmp_g, tmp_b = [], [], [] cur_r, cur_g, cur_b = r, g, b for _ in str(r): tmp_r.append('\\'+hex(ord(_))[1:]) # ascii code for _ in str(g): tmp_g.append('\\'+hex(ord(_))[1:]) for _ in str(b): tmp_b.append('\\'+hex(ord(_))[1:]) r,g,b = ''.join(tmp_r),''.join(tmp_g),''.join(tmp_b) rst.append(esc) rst.append(a_48) rst.append(r) rst.append(a_chr) rst.append(g) rst.append(a_chr) rst.append(b) rst.append(a_m) rst.append(a_space) # insert space if cur_r != 0 or cur_g != 0 or cur_b != 0: # current color is not default color rst.append(esc) rst.append(a_0) rst.append(a_m) cur_r, cur_g, cur_b = 0, 0, 0 # reset rst.append(a_n) # insert '\n' rst_str = "".join(rst) # get string print(rst_str, end='') # no line feed