提交数: 18, 通过率: 38.89%, 平均分: 40.56
题目描述:
假设有一个32*32的黑白图像,那么这个黑白图像是可以用一棵四叉树表现出来的。方法是按行、列等分成两份,就一共有四份。按图中的序号表示它的子节点。若某个子节点全黑或全白,则用黑(f,即full)和白(p,即empty)表示,若一个子节点区域有黑有白,就用灰节点(p)表示,并继续递归其子节点。例如下图表示。
1510059385513514800.png
现在给定两棵四叉树的前序遍历,请把它们转化成图以后相加(例如上图),并求出转化成图以后黑色像素的个数。注意:整个图是1024个像素。
输入格式:
第一行一个正整数,表示输入有n(n<=10)组数据。随后第2行到第n2+1行,第i组数据为第i2行和第i*2+1行,两个字符串,表示两棵树的前序遍历。输入保证合法,不需要校验。
输出格式:
一共n行,每行一个字串,格式为“There are number black pixels.”。number为这个数据点中所含的黑色像素的个数。
样例输入:
3
ppeeefpffeefe
pefepeefe
peeef
peefe
peeef
peepefefe
样例输出:
There are 640 black pixels.
There are 512 black pixels.
There are 384 black pixels.
提示:
若无法看懂样例,可以告诉你:第一组数据与说明中的图相符合。
本题除n以外没有给定其他数据范围。因为其他数据范围可通过题意推导所得。
注:有没人帮帮做一下,谢谢!!!!!!!
def build_image(tree_str, size, start_x, start_y, image):
if not tree_str:
return
node_type = tree_str[0]
if node_type == 'f': # full (black)
for i in range(start_x, start_x + size):
for j in range(start_y, start_y + size):
image[i][j] = 1 # black
elif node_type == 'p': # empty (white)
for i in range(start_x, start_x + size):
for j in range(start_y, start_y + size):
image[i][j] = 0 # white
elif node_type == 'e': # mixed (gray)
half_size = size // 2
# Process the 4 quadrants
build_image(tree_str[1:], half_size, start_x, start_y, image) # top-left
build_image(tree_str[1 + 1 * (half_size ** 2):], half_size, start_x, start_y + half_size, image) # top-right
build_image(tree_str[1 + 2 * (half_size ** 2):], half_size, start_x + half_size, start_y, image) # bottom-left
build_image(tree_str[1 + 3 * (half_size ** 2):], half_size, start_x + half_size, start_y + half_size, image) # bottom-right
def merge_images(image1, image2):
merged_image = [[0] * 32 for _ in range(32)]
for i in range(32):
for j in range(32):
# Black if either is black; White if both are white
if image1[i][j] == 1 or image2[i][j] == 1:
merged_image[i][j] = 1 # black
else:
merged_image[i][j] = 0 # white
return merged_image
def count_black_pixels(image):
count = 0
for i in range(32):
for j in range(32):
if image[i][j] == 1:
count += 1
return count
# Input reading
n = int(input("Enter number of test cases: "))
for _ in range(n):
tree1 = input("Enter first tree preorder string: ").strip()
tree2 = input("Enter second tree preorder string: ").strip()
# Create images for the two trees
image1 = [[0] * 32 for _ in range(32)]
image2 = [[0] * 32 for _ in range(32)]
build_image(tree1, 32, 0, 0, image1)
build_image(tree2, 32, 0, 0, image2)
# Merge images
merged_image = merge_images(image1, image2)
# Count black pixels
black_pixel_count = count_black_pixels(merged_image)
# Output result
print(f"There are {black_pixel_count} black pixels.")
来自AI: