【一天一道编程题】之 Binary Queries

[复制链接]
1687|2
 楼主| michael_llh 发表于 2016-12-24 21:10 | 显示全部楼层 |阅读模式
本帖最后由 michael_llh 于 2016-12-24 21:11 编辑

Binary Queries
Some problems appear hard though they are very easy. Today Aakash is stuck in a range query problem. He has been given an array with only numbers 0 and 1. There are two types of queries -
0 L R : Check whether the number formed from the array elements L to R is even or odd and print EVEN or ODD respectively. Number formation is the binary number from the bits status in the array L to R
1 X : Flip the Xth bit in the array
Input
First line contains a number N and Q as input. Next line contains N space separated 0 or 1. Next Q lines contain description of each query
Output
Output for only query type 0 L R whether the number in range L to R is "EVEN" or "ODD" (without quotes).
Constraints
1≤ N ≤ 10^6
1≤ L ≤ R ≤ 10^6
1≤ Q ≤ 10^6

1≤ XN
sample input:
5 2
1 0 1 1 0
1 2
0 1 4
sample output:
ODD

Comes from:





题目解析:
这个题目其实是这个意思:
有两种类型的queries
1. 0 L R:这个模式的是说以0开头,这个数字是从左边第L开始到右边第R结束的数字组成,同时是一个二进制数,比如说110,那么对应这个数就是6,我们要判断这个二进制数是奇数还是偶数
2.1 X:这种模式下的就是要翻转第X个元素的值,比如说0变成1,1变成0这样。
输入格式:
第一行会有两个数字,N和Q,那么对于N表示的是下一行有多少个0和1构成的二进制数,Q则是表示接下来有几行来说明这个query。简单说,这几行就是query判断的规则。
输出格式:
如果是满足query第一种就输出“EVEN”或者“ODD”
下面就是数据约束说明了,这里不再复制了。
其实分析好题目后就很简单了,参考代码如下:


  1. #include <iostream>
  2. using namespace std;

  3. int main()
  4. {
  5.      ios_base::sync_with_stdio(false);
  6.     int N=0;
  7.     int Q=0;
  8.     int sum=0;
  9.     int L =0;
  10.     int R =0;
  11.     int check = 0;
  12.     int x=0;
  13.     cin >> N >> Q;
  14.     char* array = new char[N];
  15.     if(N<0 || Q < 0)
  16.         return -1;
  17.     else if(N > 1){
  18.         for(int i=0; i<N; i++){
  19.             cin >> array[i];
  20.         }
  21.         while (Q--) {
  22.             cin >> check;
  23.             if (check) {
  24.                 cin >> x;
  25.                 array[x - 1] = array[x - 1] ^ 1;  
  26.             }
  27.             else {
  28.                 cin >> L >> R;
  29.                 cout << (('0' == array[R - 1]) ? "EVEN" : "ODD") << endl;
  30.             }
  31.         }
  32.     }
  33.     return 0;
  34. }



 楼主| michael_llh 发表于 2016-12-25 09:25 | 显示全部楼层
yyy71cj 发表于 2016-12-25 09:04
万千宇宙0、1起,看到这帖,又仿佛回到了科学大爆发时代,一个小小的火花,或许就是未来的一大片 ...

恩!**分享!
 楼主| michael_llh 发表于 2016-12-25 09:46 | 显示全部楼层
yyy71cj 发表于 2016-12-25 09:44
分享者的付出,希望读者能懂!**并加油!

好嘞!
您需要登录后才可以回帖 登录 | 注册

本版积分规则

22

主题

381

帖子

8

粉丝
快速回复 在线客服 返回列表 返回顶部