HDU5323 Solve this interesting problem 暴力DFS

来源:互联网 发布:简单的拼图软件 编辑:程序博客网 时间:2024/06/05 08:31


Solve this interesting problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)


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 LuRu, 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 valueLroot=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.
0LR109
LRL+12015
 

Output
For each test, output one line contains one integer. If there is no such n, just output -1.
 

Sample Input
6 710 1310 11
 

Sample Output
7-112
 

Source
2015 Multi-University Training Contest 3

题意:给定一对L,R。问是否存在一个线段树【0,n】他的一个区间为【L,R】。
思路:每次dfs,往这个区间的左边或者右边加一个区间,根据线段树的性质,左区间的长度=右区间长度,或者+1.可以将这个设置为dfs的剪枝条件。当L==0时,R就是搜到的答案之一,取最小值即可。

#include<cstdio>#include<cstring>#define LL __int64LL n;inline bool check(LL L,LL R,LL mid){    if(L<0) return 0;    if(mid!=(L+R)/2) return 0;    if(L>mid) return 0;    if(mid>=R) return 0;    return 1;}void dfs(LL L,LL R){    if(L==0)    {        if(n==-1||R<n) n=R;        return ;    }    LL tmp=R-L+1;    if(L<tmp) return;    LL Lt=L-tmp;    if(check(Lt,R,L-1)) dfs(Lt,R);    Lt--;    if(check(Lt,R,L-1)) dfs(Lt,R);    LL Rt=R+tmp;    if(check(L,Rt,R)) dfs(L,Rt);    Rt--;    if(check(L,Rt,R)) dfs(L,Rt);}int main(){    LL L,R;    while(~scanf("%I64d %I64d",&L,&R))    {        n=-1;        dfs(L,R);        printf("%I64d\n",n);    }    return 0;}


0 0
原创粉丝点击