CF742B Arpa’s obvious problem and Mehrdad’s terrible solution (数论)

codeforces链接:https://codeforces.com/problemset/problem/742/B

CF742B 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.

输入格式

First line contains two integers $ n $ and $ x $ ( $ 1<=n<=10{5},0<=x<=10 $ ) — the number of elements in the array and the integer $ x $ .

Second line contains $ n $ integers $ a_{1},a_{2},...,a_{n} $ ( $ 1<=a_{i}<=10^{5} $ ) — the elements of the array.

输出格式

Print a single integer: the answer to the problem.

输入输出样例 #1

输入 #1

2 3
1 2

输出 #1

1

输入输出样例 #2

输入 #2

6 1
5 1 2 3 4 1

输出 #2

2

说明/提示

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⨁(A⨁B)=B。
我们可以在输入的时候统计输入的数字的个数,答案则是累加每次输入的时候num[i]^x的数字的数量
至于为什么是便输入边计算,是因为题目说明了选择的两个数字ai和aj,i<j的,我们将输入的数字当成aj
这样的话才可以保证最后答案的正确性,统计的cnt的数量才是前面的数量

题解

#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10;
typedef long long ll;
int n,x;
int num[N];
int cnt[2*N];
ll ans=0;
int main()
{
    cin>>n>>x;
    for(int i=1;i<=n;i++)
    {
        cin>>num[i];
        ans+=cnt[num[i]^x];
        cnt[num[i]]++;

    }
    cout<<ans<<endl;
    return 0;
}
posted @ 2025-05-25 21:35  屈臣  阅读(23)  评论(0)    收藏  举报