kikit
6/24/2016 - 5:16 PM

Find number of subarrays with even sum

Find number of subarrays with even sum

/*
http://ideone.com/xeKHJH
http://www.geeksforgeeks.org/find-number-subarrays-even-sum/
http://www.practice.geeksforgeeks.org/problem-page.php?pid=948
*/

#include <iostream>
#include <string>
#include <vector>
using namespace std; 

int countEvenSum(int a[], int n){
	int count = 0;
	for(int i=0; i<n; i++){
		int sum = 0;
		for(int j=i; j<n; j++){
			sum += a[j];
			if(sum % 2 == 0)
				count++;
		}
	}
	return count;
}
int main() {
	int t, n;
	cin >> t;
	while(t--){
		cin >> n;
		int a[101];
		for(int i=0; i<n; i++)
			cin >> a[i];
		
			cout << countEvenSum(a, n) << endl;
	}
	return 0;
}
/*
http://ideone.com/0eFi2g
http://www.geeksforgeeks.org/find-number-subarrays-even-sum/
http://www.practice.geeksforgeeks.org/problem-page.php?pid=948
*/

#include <iostream>
#include <string>
#include <vector>
using namespace std; 

int countEvenSum(int a[], int n){
	int temp[2] = {1, 0};
	int result = 0, sum=0;
	
	for(int i=0; i<n; i++){
		sum = ((sum + a[i]) % 2 + 2) % 2;
		temp[sum]++;
	}
	
	result = result + (temp[0] * (temp[0] - 1) / 2);
	result = result + (temp[1] * (temp[1] - 1) / 2);
	
	return result;
}
int main() {
	int t, n;
	cin >> t;
	while(t--){
		cin >> n;
		int a[101];
		for(int i=0; i<n; i++)
			cin >> a[i];
		
			cout << countEvenSum(a, n) << endl;
	}
	return 0;
}