hdu 5208 Where is Bob(數位dp)

題意:Alice和Bob各有一個選擇數的區間,2人各選一個異或是最後的值,Alice想讓這個數大,Bob想讓這個數小,2人都很聰明,Alice先選,問最後的數是多少?

做法:可以知道如果要異或爲1,那麼必須一個爲0,一個爲1,因爲Alice先選,所以若想那位爲1,如果Alice這位選0,Bob的數必須這位都是1,才能使得這位爲1。反之也一樣,所以就從高位往低位走進行搜索,記得上下界是會隨着選的數進行改變的。

當Bob的上界這位爲1,下界這位爲0的時候是需要朝2個方向進行搜索的,因而可能效率會非常低。所以這裏需要一個非常優秀的減枝,就是當Bob的上下界包含了Alice的上下界,那麼就不需要搜了,Alice後面無論怎麼選Bob都能選相同的使得後面的位全爲0。

我測了一下。當數據爲1 500000000 500000000 1000000000時,如果不加減枝dfs要跑7*10^7次,加了只需要跑32次。不過我不知道該如何證明這個複雜度。。

AC代碼:

//#pragma comment(linker, "/STACK:102400000,102400000")
#include<cstdio>
#include<ctype.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<vector>
#include<cstdlib>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<ctime>
#include<string.h>
#include<string>
#include<sstream>
#include<bitset>
using namespace std;
#define ll long long
#define ull unsigned long long
#define eps 1e-8
#define NMAX 100100
#define MOD 1000000007
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI acos(-1)
template<class T>
inline void scan_d(T &ret)
{
    char c;
    int flag = 0;
    ret=0;
    while(((c=getchar())<'0'||c>'9')&&c!='-');
    if(c == '-')
    {
        flag = 1;
        c = getchar();
    }
    while(c>='0'&&c<='9') ret=ret*10+(c-'0'),c=getchar();
    if(flag) ret = -ret;
}

int ans;
void dfs(int shu, int l1, int r1, int l2, int r2, int pos)
{
    if(pos == -1)
    {
        if(ans == 0 || shu > ans) ans = shu;
        return;
    }
    if(ans != 0 && shu+(1<<(pos+1))-1 < ans) return;
    if(l2 <= l1 && r2 >= r1)
    {
        if(ans == 0 || shu > ans) ans = shu;
        return;
    }
    if(l2 >= (1<<pos))
    {
        if(l1 < (1<<pos)) dfs(shu|(1<<pos),l1,r1 >= (1<<pos) ? (1<<pos)-1 : r1,l2^(1<<pos),r2^(1<<pos),pos-1);
        else dfs(shu,l1^(1<<pos),r1^(1<<pos),l2^(1<<pos),r2^(1<<pos),pos-1);
    }
    else if(r2 < (1<<pos))
    {
        if(r1 >= (1<<pos)) dfs(shu|(1<<pos),l1 >= (1<<pos) ? l1^(1<<pos) : 0, r1^(1<<pos),l2,r2,pos-1);
        else dfs(shu,l1,r1,l2,r2,pos-1);
    }
    else
    {
        if(r1 >= (1<<pos)) dfs(shu,l1 >= (1<<pos) ? l1^(1<<pos) : 0, r1^(1<<pos), 0, r2^(1<<pos), pos-1);
        if(l1 < (1<<pos)) dfs(shu,l1,r1 >= (1<<pos) ? (1<<pos)-1 : r1, l2,(1<<pos)-1,pos-1);
    }
}

int main()
{
#ifdef GLQ
    freopen("input.txt","r",stdin);
//    freopen("o1.txt","w",stdout);
#endif // GLQ
    int t,cas = 1;
    scanf("%d",&t);
    while(t--)
    {
        int x1,y1,x2,y2;
        scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
        ans = 0;
        dfs(0,x1,y1,x2,y2,30);
        printf("Case #%d: %d\n",cas++,ans);
    }
    return 0;
}


發佈了187 篇原創文章 · 獲贊 9 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章