Xor Sum (01字典树)基础的字典树题目

初学字典树的可以拿这道题练练手。

题目链接:传送门

题目大意:给你n个数,有m次询问,每次给个数,问:这个数与n个数中的哪个数的异或值最大,输出它。

给大家两种写法;
1。数组的写法:

#include 
#include 
#include 

using namespace std;
//typedef __int64 ll;
typedef long long ll;

const int M = 55;
const int N = M*1e5;

struct Node
{
    ll val;
    int l;
    int r;

    void clear()
    {
        l = r = -1;
    }
} node[N];

int p;
ll a, t[M];

void insert (int& root, int d, ll u)
{
    if (root == -1)
    {
        root = p++;
        node[root].clear();
    }

    if (d == -1)
    {
        node[root].val = u;
        return;
    }

    if (u & t[d])
        insert(node[root].r, d - 1, u);
    else
        insert(node[root].l, d - 1, u);
}

void query(int root, int d, ll u)
{

    if (d == -1)
    {
        printf("%lld\n", node[root].val);
        return;
    }

    if (((u & t[d]) && node[root].l != -1) || node[root].r == -1)
        query(node[root].l, d - 1, u);
    else
        query(node[root].r, d - 1, u);
}

int main ()
{
    int cas, n, m;
    scanf("%d", &cas);

    t[0] = 1;
    for (int i = 1; i < 55; i++)
        t[i] = t[i-1] * 2;

    for (int i = 1; i <= cas; i++)
    {
        p = 0;
        int root = -1;

        scanf("%d%d", &n, &m);
        for (int j = 0; j < n; j++)
        {
            scanf("%lld", &a);
            insert(root, 50, a);
        }

        printf("Case #%d:\n", i);
        for (int j = 0; j < m; j++)
        {
            scanf("%lld", &a);
            query(root, 50, a);
        }
    }
    return 0;
}

2。指针的写法:

#include
#include
#include
using namespace std;
typedef long long ll;

ll a,wei[56];
struct node
{
    node *left,*right;
    bool l,r;
    ll data;
    void clean()
    {
        l=0;
        data=0;
        r=0;
    }
};
void build(node *head,int f)
{
    if(f==-1)
    {
        head->data=a;
        return ;
    }
    if(a&wei[f])
    {
        if(head->r==0)
        {
            head->r=1;
            head->right=new node;
            head->right->clean();
        }
        build(head->right,f-1);
    }
    else
    {
        if(head->l==0)
        {
        head->l=1;
            head->left=new node;
            head->left->clean();
        }
        build(head->left,f-1);
    }
}
void query(node *head,ll f)
{
    if(f==-1)
    {
        printf("%lld\n",head->data);
        return ;
    }
    //printf("                   fjhd\n");
    if(((a&wei[f])&&head->l==1)||head->r==0)
        query(head->left,f-1);
    else query(head->right,f-1);
}
int main()
{
    int t,tt=1;
    wei[0]=1;
    for(int i=1; i<=55; i++)
        wei[i]=wei[i-1]*2;
    scanf("%d",&t);
    while(t--)
    {
        int n,m;
        scanf("%d%d",&n,&m);
        node *head=new node;
        head->clean();
        for(int i=0; iscanf("%lld",&a);
            build(head,50);
        }
        printf("Case #%d:\n",tt++);
        for(int i=0; iscanf("%lld",&a);
            query(head,50);
        }
    }
    return 0;
}

你可能感兴趣的:(ACM,算法,字符串&&字典树)