链接:http://acm.hdu.edu.cn/showproblem.php?pid=5323
题目背景就是线段树。输入一个区间,问,能构成这个区间的线段树的最大区间是多少(总区间是【0,n】)。
对于当前这个区间,向上dfs。
dfs的理由,在代码里注释了
<span style="font-size:14px;">#include<cstdio>
#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<ctime>
#include<set>
#include<map>
#include<algorithm>
using namespace std;
long long ans;
void dfs(long long l,long long r){
if(l==0){
if(ans==-1)ans=r;
else ans=min(ans,r);
return;
}
if(ans!=-1&&r>=ans)return;//超过当前ans的话,就不继续算了
if(l<0)return;//如果l小于0,这个区间就错了
if(l<r-l+1)return;//当前这个区间左边的那个区间,区间最大是【0到l-1】,长度为l,那么当前区间长度最长也是l,不会超过l。关键剪枝!
dfs(l-r+l-2,r);//两种情况,左子树和右子树,如果总区间是奇数长度,那么左子树长度=右子树长度+1
dfs(l-r+l-1,r);//如果总区间是偶数长度,那么左子树长度=右子树长度
dfs(l,r+r-l+1);//然后分别把当前区间作为左子树和右子树,总长度分别是奇数偶数区间,一共4种情况
dfs(l,r+r-l);
}
int main()
{
// freopen("D://input.txt","r",stdin);
int n,m;
while(scanf("%d%d",&n,&m)!=EOF){
if(n==m){
printf("%d\n",n);
continue;
}
ans=-1;
dfs(n,m);
printf("%I64d\n",ans);
}
return 0;
}
</span>