题目链接
题目详情
You have an array . Answer queries of the following form:
If we change all elements in the range of the array to , will the sum of the entire array be odd? Note that queries are independent and do not affect future queries.
Input
Each test contains multiple test cases. The first line contains the number of test cases . The description of the test cases follows.
The first line of each test case consists of 2 integers and — the length of the array and the number of queries.
The second line of each test case consists of integers — the array a.
The next q lines of each test case consists of 3 integers — the queries.
It is guaranteed that the sum of nn over all test cases doesn't exceed , and the sum of doesn't exceed .
Output
For each query, output "YES" if the sum of the entire array becomes odd, and "NO" otherwise.
You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.
Example
input
2
5 5
2 2 1 3 2
2 3 3
2 3 4
1 5 5
1 4 9
2 4 3
10 5
1 1 1 1 1 1 1 1 1 1
3 8 13
2 5 10
3 8 10
1 10 2
1 9 100
output
YES
YES
YES
NO
YES
NO
NO
NO
NO
YES
题目大意及解题思路
大意:
这道题的大概意思是给定一个数组a,再给出多次操作,每次给出一个区间[l,r]和一个k,将这个区间内的所有数变成k,问进行了这样的操作之后能不能使得整个数组a的所有数的和为奇数!!!
解题思路:
我们最朴素的想法就是先求前1 ~ l-1的和以及r+1 ~ n的和,最后加上(r-l+1)个 k求出总和并判断是否为奇数。但是,我们运行的话会超时。并且我们看到了区间和,所以第一想到的应该就是前缀和算法,来降低程序的事件复杂度。这里我用a数组记录每个数,s数组记录前缀和(即前n项和)。这样时间复杂度会将为O(n),我们就可以顺利通过测试。
AC代码
#include<iostream>
#include<string>
using namespace std;
int a[200010],s[200010];
int main()
{
int t;
cin >> t;
while (t--)
{
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
s[i] = a[i] + s[i - 1];
}
while (m--)
{
int l, r, k;
cin >> l >> r >> k;
int sum = 0;
sum += k * (r - l + 1);
sum += (s[l - 1] + s[n] - s[r]);
if (sum % 2 != 0) cout << "YES" << endl;
else cout << "NO" << endl;
}
}
return 0;
}