2011-12-24 57 views
2

假设,我们有以下的树:如何确定树中的元素(锦标赛括号)?

1 
    9 
2 
     13 
3 
    10 
4 
      15 
5 
    11 
6 
     14 
7 
    12 
8 

凡元件(匹配):
1-8是第1轮
9-12是第2轮
13-14是圆的3
15是圆4

如何确定树中的元素“n”的圆形?

我现在的公式是:

total_rounds = floor(log(totalTeams,2)); 

matches_per_round = (totalTeams/pow(2, current_round)) 

next_match_id = (totalTeams/2) + ceil(match_id/2) 

total_matches = total_teams - 1 
+0

如果这是作业,请标记为这样。 – 2011-12-24 14:23:09

+0

不幸的是没有 – fozzy 2011-12-24 14:27:37

回答

6

试想树反向编号。

15 
    7 
14 
     3 
13 
    6 
12 
      1 
11 
    5 
10 
     2 
9 
    4 
8 

在这种情况下,它只是数字的对数,向下舍入。现在我们简单地从轮数中减去这个数字,我们就完成了。

reverse_number = total_matches - match_number + 1; 
reverse_match_round = floor(log(reverse_number, 2)); 
match_round = total_rounds - match_round; 

(注意,reverse_match_round实际上是0指数的,不像match_round。然而,由于我们从total_rounds减去它,它更容易保持这种方式比1索引它。如果你喜欢它1索引,只需在最后两行添加+1)。