Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2931 Accepted Submission(s): 910
Problem Description
Have you learned something about segment tree? If not, don’t worry, I will explain it for you.
Segment Tree is a kind of binary tree, it can be defined as this:
- For each node u in Segment Tree, u has two values: Lu and Ru.
- If Lu=Ru, u is a leaf node.
- If Lu≠Ru, u has two children x and y,with Lx=Lu,Rx=⌊Lu+Ru2⌋,Ly=⌊Lu+Ru2⌋+1,Ry=Ru.
Here is an example of segment tree to do range query of sum.
Given two integers L and R, Your task is to find the minimum non-negative n satisfy that: A Segment Tree with root node's value Lroot=0 and Rroot=n contains a node u with Lu=L and Ru=R.
Input
The input consists of several test cases.
Each test case contains two integers L and R, as described above.
0≤L≤R≤109
LR−L+1≤2015
Output
For each test, output one line contains one integer. If there is no such n, just output -1.
Sample Input
6 7
10 13
10 11
Sample Output
7
-1
12
Author
ZSTU
Source
2015 Multi-University Training Contest 3
题目大意:给你一个给定区间,问能否有一个【0-n】为根的线段树,其某个子节点代表的区间在这棵树中。
思路:
1、根据线段树的特点,其某段区间【L,R】的左儿子是【L,(L+R)/2】,右儿子是【(L+R)/2+1,R】,那么我们逆向思考,如果给我一个儿子,确定他的父亲的区间,一直向上确定下去,早晚会确定到【0,ans】,那么这个ans就是一个可行解。
2、上述思路确定下来之后,开始建立Dfs的具体思路:
①假设当前区间是左儿子区间【L,R】那么其父区间为:【L,2*R-L】;
②假设当前区间是右儿子区间【L,R】那么其父区间为:【2*(L-1)-R,R】;
又根据有数值奇偶性的差距,我们还应该枚举两种情况:
③假设当前区间是左儿子区间【L,R】那么其父区间为:【L,2*R-L+1】;
④假设当前区间是右儿子区间【L,R】那么其父区间为:【2*(L-1)-R+1,R】;
然后我们Dfs,寻找每一种可行解,然后维护ans最小值。
3、然后是剪枝:
①L只能变小:L<0 return ;
②R只能变大:R的区间不可能最终枚举出来的ans>2R,那么我们就控制:当前R>给定R*2 return ;
Ac代码:
#include
#include
#include
using namespace std;
#define ll long long int
#define lson l,m,rt*2
#define rson m+1,r,rt*2+1
ll ans;
void Dfs(ll l,ll r,ll mubiaor)
{
if(l>r)return ;
if(l<0)return ;
if(r>mubiaor*2)return ;
if(l==0&&r!=0)
{
ans=min(ans,r);
}
Dfs(2*(l-1)-r,r,mubiaor);
Dfs(2*(l-1)-r+1,r,mubiaor);
Dfs(l,2*r-l,mubiaor);
Dfs(l,2*r-l+1,mubiaor);
}
int main()
{
ll l,r;
while(~scanf("%I64d%I64d",&l,&r))
{
if(l==r)
{
printf("%I64d\n",l);
continue;
}
ans=0x3f3f3f3f;
Dfs(l,r,r);
if(ans==0x3f3f3f3f)printf("-1\n");
else
{
printf("%I64d\n",ans);
}
}
}