The last stage of Football World Cup is played using the play-off system.
There are n teams left in this stage, they are enumerated from 1 to n. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the fourth, the fifth — with the sixth, and so on. It is guaranteed that in each round there is even number of teams. The winner of each game advances to the next round, the loser is eliminated from the tournament, there are no draws. In the last round there is the only game with two remaining teams: the round is called the Final, the winner is called the champion, and the tournament is over.
Arkady wants his two favorite teams to play in the Final. Unfortunately, the team ids are already determined, and it may happen that it is impossible for teams to meet in the Final, because they are to meet in some earlier stage, if they are strong enough. Determine, in which round the teams with ids a and b can meet.
The only line contains three integers n, a and b (2 ≤ n ≤ 256, 1 ≤ a, b ≤ n) — the total number of teams, and the ids of the teams that Arkady is interested in.
It is guaranteed that n is such that in each round an even number of team advance, and that a and b are not equal.
In the only line print “Final!” (without quotes), if teams a and b can meet in the Final.
Otherwise, print a single integer — the number of the round in which teams a and b can meet. The round are enumerated from 1.
Input |
---|
4 1 2 |
Output |
1 |
Input |
---|
8 2 6 |
Output |
Final! |
Input |
---|
8 7 5 |
Output |
2 |
In the first example teams 1 and 2 meet in the first round.
In the second example teams 2 and 6 can only meet in the third round, which is the Final, if they win all their opponents in earlier rounds.
In the third example the teams with ids 7 and 5 can meet in the second round, if they win their opponents in the first round.
题意:n支球队,依次编号1, 2, 3, …, n,每次比赛从相邻的两个中选一个进入下一轮。问编号为a1 和a2的两支球队可能在第几轮进行比赛。
思路:这其实是一个二叉树结构,在两支队伍不断赢得比赛进入决赛的路线是唯一的,而最早的交点就是最近的公共祖先。
用样例2和样例3简单演示一下为什么是最近的公共祖先吧
下图是比赛的历程
为了让2 6相遇,只可能是下面的路线
而为了让5 7相遇则不需要走那么远
接下来的问题是怎么来寻找最近祖先。其实与其说在寻找最近祖先,不如说寻找一个子树覆盖的区间同时包含a1和a2,我是用二分的思想实现的。
#include
int main() {
int n=0,a1=0, a2=0,temp=0;
scanf("%d %d %d", &n, &a1, &a2);
if (a1 > a2) {//调整a1 a2的顺序方便比较
temp = a1;
a1 = a2;
a2 = temp;
}
int i, l, r;
int tot = 0;
//记录树的高度
temp = n;
while (temp>0) { tot++; temp /= 2; }
//二分法寻找合适的区间
//i记录的是从根节点开始进入下一层的次数
for (i = 1, l = 1, r = n; l+1 < r; ++i) {
if ((l + r) / 2 >=a2) {
r = (l + r) / 2; continue;
}
else if ((l + r) / 2 + 1 <= a1) {
l = (l + r) / 2 + 1; continue;
}
else break;
}
//区间是整个范围,说明最近公共祖先是根结点
if (l ==1&& r==n)printf("Final!\n");
//总层数-i就是答案
else printf("%d\n", tot-i);
}