Hdu 5323 Solve this interesting problem【Dfs】

Solve this interesting problem

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<stdio.h>
#include<iostream>
#include<string.h>
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);
        }
    }
}





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值