Codeforces 1360C. Similar Pairs Solution
Let e — be the number of even numbers in the array, and o — be the number of odd numbers in the array. Note that if the parities of e and of o do not equal, then the answer does not exist. Otherwise, we consider two cases:
e and o — are even numbers. Then all numbers can be combined into pairs of equal parity.
e and o — are odd numbers. Then you need to check whether there are two numbers in the array such that the modulus of their difference is 1. If there are two such numbers, then combine them into one pair. e and o will decrease by 1 and become even, then the solution exists as shown in the previous case.
Solution in C++:
///**********ALLAH IS ALMIGHTY************///
///AH Tonmoy
///Department of CSE,23rd batch
///Islamic University,Bangladesh
- #include <bits/stdc++.h>
- using namespace std;
- int main()
- {
- int n,i,f,e,o,t,d;
- cin>>t;
- while(t--)
- {
- e=0,o=0,f=0;
- cin>>n;
- int a[n+9];
- for(i=0; i<n; i++)
- {
- cin>>a[i];
- if(a[i]%2==1)
- o++;
- else
- e++;
- }
- sort(a,a+n);
- for(i=1;i<n;i++)
- {
- d=a[i]-a[i-1];
- if(d==1)
- {
- f=1;
- break;
- }
- }
- if(e%2!=o%2)
- cout<<"NO"<<endl;
- else if(e%2==0&&o%2==0)
- cout<<"YES"<<endl;
- else if (e%2==1&&o%2==1&&f==1)
- cout<<"YES"<<endl;
- else
- cout<<"NO"<<endl;
- }
- }
No comments