Arpa’s obvious problem and Mehrdad’s terrible solution 思维
Posted 给杰瑞一块奶酪~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 ≤ 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.
Print a single integer: the answer to the problem.
2 3
1 2
1
6 1
5 1 2 3 4 1
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^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(); }
以上是关于Arpa’s obvious problem and Mehrdad’s terrible solution 思维的主要内容,如果未能解决你的问题,请参考以下文章
CodeForces - 742B Arpa’s obvious problem and Mehrdad’s terrible solution
CodeForces 742B Arpa’s obvious problem and Mehrdad’s terrible solution (暴力枚举)
A. Arpa’s hard exam and Mehrdad’s naive cheat 1000 / 数论 找规律
http://codeforces.com/contest/741/problem/B B. Arpa's weak amphitheater and Mehrdad's valuab
#383 Div1 Problem B Arpa's weak amphitheater.... (分组背包 && 并查集)
Codeforces 741B Arpa's weak amphitheater and Mehrdad's valuable Hoses