zoukankan      html  css  js  c++  java
  • Arpa’s obvious problem and Mehrdad’s terrible solution 思维

    There are some beautiful girls in Arpa’s land as mentioned before.

    Once Arpa came up with an obvious problem:

    Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that , where is bitwise xor operation (see notes for explanation).

    Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem.

    Input

    First line contains two integers n and x (1 ≤ n ≤ 105, 0 ≤ x ≤ 105) — the number of elements in the array and the integer x.

    Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the elements of the array.

    Output

    Print a single integer: the answer to the problem.

    Example
    Input
    2 3
    1 2
    Output
    1
    Input
    6 1
    5 1 2 3 4 1
    Output
    2
    Note

    In the first sample there is only one pair of i = 1 and j = 2. so the answer is 1.

    In the second sample the only two pairs are i = 3, j = 4 (since ) and i = 1, j = 5 (since ).

    A bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.

    这道题一开始没看懂啥意思,后来才明白原来是异或^,a^b=c,那么a^c=b;抓住这一点就好做了,所有的ai去异或x得到cnt,然后记录cnt,看看数组里面有几个cnt就好了,可以开个map,注意结果可能超过long 要用long long

    代码:

    #include <iostream>
    #include <cstdio>
    #include <map>
    using namespace std;
    int n,x,a[100000];
    map<int,int> mark;
    void input()
    {
        cin>>n>>x;
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
            mark[a[i]]++;
        }
    }
    long long check()
    {
        long long cnt,ans=0;
        for(int i=0;i<n;i++)
        {
            cnt=a[i]^x;
            ///x如果是0 那么 任意一个数q q^0=q;
            if(a[i]==cnt)ans+=mark[cnt]-1;
            else ans+=mark[cnt];
        }
        return ans/2;
    }
    int main()
    {
        input();
        cout<<check();
    }
  • 相关阅读:
    何谓B/S架构,C/S架构,SOA架构?
    Android牟利之道广告平台的介绍
    软件开发工具介绍
    jQuery Mobile 入门教程
    程序员的编辑器——VIM
    优秀程序员值得借鉴的一些信息
    程序员必备利器——敏捷软件
    PhoneGap Build的使用
    PhoneGap简单介绍
    ceph16.2.6 cephfs mds源码阅读
  • 原文地址:https://www.cnblogs.com/8023spz/p/7221570.html
Copyright © 2011-2022 走看看