Sunday, January 19, 2014

Magic array

Problem
Given an array of +ve as well as -ve numbers, find out whether it is possible or not to convert it to 0 by adding/subtracting operations on all the elements.

Examples
arr[]={1,2,3}
1+2-3 = 0
Hence ans = YES

arr[]={3,6,2}
3+6-2 != 0
3-6-2 !=0
-3-6-2 !=0
-3-6+2 !=0
-3+6-2 !=0
-3+6+2 !=0
3-6+2 !=0
3+6+2 !=0
Hence ans= NO

Input/Output format:
First line will contain the number of test-cases t.
First line of each test-case contains a non-negative number n, the number of elements in the array.
Next line contains n positive or negative numbers.

#include <iostream>
using namespace std;

int main()
{
int t,A[100],n;
cin>>t;
while(t--)
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>A[i];
}
int sum=0;
for(int i=0;i<n;i++)
{
sum+=A[i];
}
if(sum == 0)
{
cout<<"Possible"<<endl;
}
else if(n > 1 && sum % 2 == 0)
{
cout<<"Possible"<<endl;
}
else
{
cout<<"Not possible"<<endl;
}
}
return 0;
}


Input:
5
5
1 2 3 4 5
4
-4 3 2 1
1
1
1
2
1
0

Output:
Not possible
Possible
Not possible
Not possible
Possible

No comments:

Post a Comment