正方形
Description
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
Input
The first line of input contains N, the number of test cases. Each test case begins with an integer 4 <= M <= 20, the number of sticks. M integers follow; each gives the length of a stick - an integer between 1 and 10,000.
Output
For each case, output a line containing "yes" if is is possible to form a square; otherwise output "no".
Sample Input
3 4 1 1 1 1 5 10 20 30 40 50 8 1 7 2 6 4 4 3 5 10 4 5 3 2 1 4 2 3 2 1
前面的458表示是有几个数据啊,我晕
Sample Output
yes no yes no
大致题意:给定一系列长度的小木棍,问能否以某种方式组合成一个正方形?
需要用上所有的木棍的
输入
if __name__ == '__main__': sticks = list(map(int, input().split())) if sum(sticks) % 4 != 0: #如果木棍的长度不能被4整除那不可能构成正方形 print("no") exit(0) sticks.sort(reverse = True) reclength = sum(sticks)//4 #每条边的长度 n = len(sticks) vis = [False for i in range(n)] if DFS(1, 0, -1): print("yes") else: print("no")
只需要接收一行输入,不同棍子的长度即可。
如何是一个正方形呢,就是四条长度相同的棍子组合,如果能够组合出四根,那么就是可以组合成为一个正方形的。
那我们可以根据上一题的经验,写出对于给定长度的木棍能否凑出4根,如果可以,print('yes')
DFS
def DFS(stick, length, pos): if length == 0: sign = True else: sign = False if stick == 4: return True for i in range(pos + 1, n): if vis[i]: continue if length + sticks[i] == reclength: vis[i] = True if DFS(stick + 1, 0, -1): return True vis[i] = False return False elif length + sticks[i] < reclength: vis[i] = True if DFS(stick, length + sticks[i], i): return True vis[i] = False return False if sign: return False return False
每次的小于可以从i
开始,而等于的那个DFS需要从-1
开始,因为前面可能会漏掉一些
完整代码
def DFS(stick, length, pos): if length == 0: sign = True else: sign = False if stick == 4: return True for i in range(pos + 1, n): if vis[i]: continue if length + sticks[i] == reclength: vis[i] = True if DFS(stick + 1, 0, -1): return True vis[i] = False return False elif length + sticks[i] < reclength: vis[i] = True if DFS(stick, length + sticks[i], i): return True vis[i] = False return False if sign: return False return False if __name__ == '__main__': sticks = list(map(int, input().split())) if sum(sticks) % 4 != 0: #如果木棍的长度不能被4整除那不可能构成正方形 print("no") exit(0) sticks.sort(reverse = True) reclength = sum(sticks)//4 #每条边的长度 n = len(sticks) vis = [False for i in range(n)] if DFS(1, 0, -1): print("yes") else: print("no")
input
2 3 1 4 5 2 2 1
output
yes
input
2 3 1 4 1 1 1 1 1 2 2 1
output
yes