多校赛3- Solve this interesting problem 分类: 比赛 2015-07-29 21:01 8人阅读 评论(0) 收藏

H - Solve this interesting problem
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Appoint description: 

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: $L_u$ and $R_u$. 
- If $L_u = R_u$, u is a leaf node. 
- If $L_u \neq R_u$, u has two children x and y,with $L_x = L_u$,$R_x = \lfloor \frac{L_u + R_u }{2}\rfloor$,$L_y = \lfloor \frac{L_u + R_u }{2}\rfloor + 1$,$R_y = R_u$. 
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 $L_{root} = 0$ and $R_{root} = n$ contains a node u with $L_u = L$ and $R_u = R$. 
 

Input

The input consists of several test cases. 
Each test case contains two integers L and R, as described above. 
$0 \leq L \leq R \leq 10^9$ 
$\frac{L}{R-L+1} \leq 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
 
比赛的时候在想如何判断是左右子树,没有想起来方法,比赛完才知道把它看成左右子树分别搜一遍就行
在补题的时候有一个终止条件不明白,请教了金巨巨,多谢金巨巨了
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <list>
#include <algorithm>

using namespace std;

const int MAX = int(10e9+10);

long long  n;

void DFS(long long L,long long  R)
{
    if(n&&R>=n)
    {
        return ;
    }
    if(L==0)
    {
        if(n)
        {

            n=min(n,R);
        }
        else
        {
            n=R;
        }
        return ;
    }
    if(L<R-L+1)
    {
        return ;
    }
    DFS(2*(L-1)-R,R);
    DFS(2*(L-1)+1-R,R);
    DFS(L,2*R-L);
    DFS(L,2*R+1-L);
}

int main()
{
    long long  L,R;
    while(~scanf("%I64d %I64d",&L,&R))
    {
        n=0;
        DFS(L,R);
        if(R==0)
        {
            printf("0\n");
            continue;
        }
        if(n)
            printf("%I64d\n",n);
        else
        {
            printf("-1\n");
        }
    }
    return 0;
}







版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-07-29 21:01  一骑绝尘去  阅读(152)  评论(0编辑  收藏  举报