HDU5536 chip factory 【01字典树】

来源:互联网 发布:安全软件下载 编辑:程序博客网 时间:2024/06/05 21:57

HDU5536 第一道字典树。2015 长春站ACM-ICPC的一道题 据说现场赛O(n^3)可以过

看了网上大牛代码以后顿悟了自己敲的。。。感觉好腻害。花了两小时弄懂代码。。第一次敲这么复杂的树  留个纪念

#include<stdio.h>#include<math.h>#include<iostream>#include<string.h>#include<algorithm>int a[1010];using namespace std;int root ;int tot ;struct node{    int size;    int ch[2];    node()    {        size = 0;    }};node node[100005];void INSERT(int x){    int r = root;    int c;    for(int k = 30; k >=0 ; k--)    {        if(x&(1<<k))            c = 1;        else            c = 0;        if(!node[r].ch[c])            node[r].ch[c] = ++tot;        r = node[r].ch[c];        node[r].size++;    }}void DELETE(int x){    int r = root;    int c;    for(int k = 30; k >=0; k--)    {        if(x&(1<<k))            c = 1;        else            c = 0;        node[node[r].ch[c]].size--;        r = node[r].ch[c];    }}int QUERY(int x){    int r = root;    int c;    for(int k = 30; k >=  0; k--)    {        if(x&(1<<k))            c = 1;        else            c = 0;        if(c==1)        {            if(node[r].ch[0]&&node[node[r].ch[0]].size)            {                r = node[r].ch[0];            }            else            {                r = node[r].ch[1];                x^=(1<<k);            }        }        else        {            if(node[r].ch[1]&&node[node[r].ch[1]].size)            {                r = node[r].ch[1];                x^=(1<<k);            }            else            {                r = node[r].ch[0];            }        }    }    return x;}int main(){    int T;    int n;    scanf("%d",&T);    while(T--)    {        tot = 1; root = 1;        scanf("%d",&n);        for(int i = 0 ; i < n ; i++)        {            scanf("%d",&a[i]);            INSERT(a[i]);        }        int ans = (a[0]+a[1])^a[2];        for(int i = 0 ; i < n ; i++)        {            DELETE(a[i]);            for(int j = i+1 ; j < n ;j++)            {                DELETE(a[j]);                ans = max(ans,QUERY(a[i]+a[j]));//                cout<<QUERY(a[i]+a[j]);                INSERT(a[j]);            }            INSERT(a[i]);        }        cout<<ans<<endl;        for(int i = 0 ; i <= tot;i++)        {            node[i].ch[0] = 0;            node[i].ch[1] = 0;            node[i].size = 0;        }    }    return 0;}


0 0
原创粉丝点击