The 7th National Championship java test question 4: Robot Tower

Robot tower


There are two costumes for the robot performance cheerleader of X planet, A and B. What they performed this time was to build a robot tower.
similar:

     A
    B B    
   A B A  
  A A B B  
 B B B A B 
A B A B B A

The rules for tower formation in the team are:
A can only stand on the shoulders of AA or BB.
B can only stand on the shoulders of AB or BA.
Your task is to help the cheerleader to calculate how many kinds of towers can be formed given the number of people A and B. Enter a line of two integers M and N, separated by spaces (0<M, N<500), respectively representing the number of persons A and B, to ensure the rationality of the number of persons. An integer is required to indicate the number of patterns that can be produced.
For example:
User input:
1 2 The
program should output:
3
Another example:
User input:
3 3 The
program should output:
4
Ideas:
The values ​​of A and B we input first determine the number of floors of the tower, because the title says to ensure that the number of people is reasonable Sex, no matter how many people A and B are given, the number of towers that can be piled up must be uniquely determined. We start from the last layer to traverse all the possibilities of the last layer, and then recurse layer by layer in a recursive manner. c[r+1][l]==c[r+1][l+1] This is when the following letters are equal, the current position must be a, and vice versa.
program:

a=list(map(int,input().split()))
s=sum(a)
ab=[1,2]
for i in range(2,1000):
    if s==((i+1)*i)//2:
        o=i
        break
try:
    c=[[0 for i1 in range(o+1)]for i in range(o+1)]
    con=0
    def ck(i,r,l):
        if a[i]-1>=0:
                    c[r][l]=ab[i]
                    a[i]-=1
                    if l>=r:
                        dfs(r-1,0)
                    else:
                        dfs(r,l+1)
                    c[r][l]=0
                    a[i]+=1
    def dfs(r,l):
        global con
        if r==-1:
            con+=1
            return
        elif r==o-1:
            for i in range(2):
                ck(i,r,l)
        elif c[r+1][l]==c[r+1][l+1]:
            ck(0,r,l)
        elif c[r+1][l]!=c[r+1][l+1]:
            ck(1,r,l)

    dfs(o-1,0)
    print(con)
except:
    print(0)

Reprinting is prohibited. Only for self-study. No responsibility for program errors.

Guess you like

Origin blog.csdn.net/weixin_46640345/article/details/112737070