Hackerrank--XOR love (Math系列)

题目链接

Devendra loves the XOR operation very much which is denoted by  sign in most of the programming languages. He has a list A of N numbers and he wants to know the answers of M queries. Each query will be denoted by three numbers i.e. K,P,R .

For query K,P and R, he has to print the value of the KPRsum which can be described as given below. As the value of the KPRsum can be large. So, print it modulus(109+7).

KPRsum=i=PR1j=i+1R(K(A[i]A[j]))

Input Format
The first line contains an integer N, i.e., the number of the elements in the list. List is numbered from 1 to N
Next line will contain N space seperated integers. 
Third line will contain a number M i.e. number of queries followed by M lines each containing integers K,P&R.

Output Format
Print M lines, ith line will be answer of ith query. Answer will be 0 in case of P=R.

Constraints
1N105 
1A[i]106 
1M105 
0K106 
1PRN

Sample Input

3
1 2 3
2
1 1 3
2 1 3

Sample Output

5
4

Explanation

For first query, it will will be

(1(12))+(1(13))+(1(23))=5

 话说这题又让我想起了去年南京赛区的一道题目,题目难度属于中等,不过当时是没有想出来。

这题算是那个题目的简单版吧,因为每次只需要选两个数。

题目意思就是:给出一个数列,有m个询问,每次询问给出三个数,k, p, r。

求从数组的区间[p, r]内任意选出两个数a[i], a[j], (i > j),每次得到一个数:k^a[i]^a[j],将其进行累加.

输出最终的和。

Accepted Code:

 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 typedef long long LL;
 5 const int MOD = 1e9 + 7;
 6 const int MAX_N = 100050;
 7 int a[MAX_N], d[22][MAX_N];
 8 int n, m, k, p, r;
 9 
10 int main(void) {
11     ios::sync_with_stdio(false);
12     cin >> n;
13     for (int i = 1; i <= n; i++) cin >> a[i];
14     
15     for (int i = 0; i < 20; i++) {
16         d[i][0] = 0;
17         for (int j = 1; j <= n; j++) {
18             d[i][j] = d[i][j - 1] + ((a[j]&(1<<i)) ? 1 : 0);
19         }
20     }
21     
22     cin >> m;
23     while (m--) {
24         cin >> k >> p >> r;
25         LL ans = 0;
26         for (int i = 0; i < 20; i++) {
27             LL ones = d[i][r] - d[i][p - 1];
28             LL zeros = r - p + 1 - ones;
29             if (0 == (k & (1<<i))) ans = (ans + ones * zeros * (1<<i)) % MOD;
30             else ans = (ans + (ones * (ones - 1) + zeros * (zeros - 1)) / 2 * (1<<i)) % MOD;
31         }
32         cout << ans << endl;
33     }
34     return 0;
35 }

 

转载于:https://www.cnblogs.com/Stomach-ache/p/3940379.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值