问题
https://vjudge.net/problem/UVA-11714
分析
最快的比较方法:构造淘汰赛制的那种方式,从下到上构造出一棵树,a,b两个节点的父亲是他们中较大的那个数。
所以找出最大值需要n-1次比赛,每次淘汰一个失败者,设最大值是A,A从叶子节点到根节点一共经历了(logn)+1层,经过了log(n)次比较,次最大值一定在这log(n)个数之间,所以需要log(n)-1次比较。
为什么一定在这log(n)个数之间?因为每次和A对比的数B都是一个子树中的最大值,剩下的值小于A,也小于这个最大值B,所以直接剔除。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long LL;
const int maxn=100000+5;
LL n;
int main(void){
while(scanf("%lld",&n)==1 && n){
printf("%lld\n",n-1+LL(ceil(log2(double(n))))-1);
}
return 0;
}