码迷,mamicode.com
首页 > 其他好文 > 详细

Hackerrank--XOR love (Math系列)

时间:2014-08-27 21:53:08      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   strong   for   

题目链接

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 }

 

Hackerrank--XOR love (Math系列)

标签:des   style   blog   http   color   os   io   strong   for   

原文地址:http://www.cnblogs.com/Stomach-ache/p/3940379.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!