给定一个二进制矩阵。在一次操作中,您可以选择两个相邻的元素并反转它们的奇偶校验。该操作可以执行任意次。编写程序以检查数组的所有元素是否都可以转换为单个奇偶校验。
例子:
Input: a[] = {1, 0, 1, 1, 0, 1}
Output: Yes
Invert 2nd and 3rd elements to get {1, 1, 0, 1, 0, 1}
Invert 3rd and 4th elements to get {1, 1, 1, 0, 0, 1}
Invert 4th and 5th elements to get {1, 1, 1, 1, 1, 1}
Input: a[] = {1, 1, 1, 0, 0, 0}
Output: No
方法:由于仅需要翻转相邻的元素,因此奇偶校验的计数将给出问题的答案。一次仅翻转偶数个元素,因此,如果两个奇偶校验的计数都是奇数,则不可能使所有奇偶校验相同,否则可能。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to check if parity
// can be made same or not
bool flipsPossible(int a[], int n)
{
int count_odd = 0, count_even = 0;
// Iterate and count the parity
for (int i = 0; i < n; i++) {
// Odd
if (a[i] & 1)
count_odd++;
// Even
else
count_even++;
}
// Condition check
if (count_odd % 2 && count_even % 2)
return false;
else
return true;
}
// Drivers code
int main()
{
int a[] = { 1, 0, 1, 1, 0, 1 };
int n = sizeof(a) / sizeof(a[0]);
if (flipsPossible(a, n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation of the approach
public class GFG
{
// Function to check if parity
// can be made same or not
static boolean flipsPossible(int []a, int n)
{
int count_odd = 0, count_even = 0;
// Iterate and count the parity
for (int i = 0; i < n; i++)
{
// Odd
if ((a[i] & 1) == 1)
count_odd++;
// Even
else
count_even++;
}
// Condition check
if (count_odd % 2 == 1 && count_even % 2 == 1)
return false;
else
return true;
}
// Drivers code
public static void main (String[] args)
{
int []a = { 1, 0, 1, 1, 0, 1 };
int n = a.length;
if (flipsPossible(a, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
# Function to check if parity
# can be made same or not
def flipsPossible(a, n) :
count_odd = 0; count_even = 0;
# Iterate and count the parity
for i in range(n) :
# Odd
if (a[i] & 1) :
count_odd += 1;
# Even
else :
count_even += 1;
# Condition check
if (count_odd % 2 and count_even % 2) :
return False;
else :
return True;
# Driver Code
if __name__ == "__main__" :
a = [ 1, 0, 1, 1, 0, 1 ];
n = len(a);
if (flipsPossible(a, n)) :
print("Yes");
else :
print("No");
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to check if parity
// can be made same or not
static bool flipsPossible(int []a, int n)
{
int count_odd = 0, count_even = 0;
// Iterate and count the parity
for (int i = 0; i < n; i++)
{
// Odd
if ((a[i] & 1) == 1)
count_odd++;
// Even
else
count_even++;
}
// Condition check
if (count_odd % 2 == 1 && count_even % 2 == 1)
return false;
else
return true;
}
// Drivers code
public static void Main(String[] args)
{
int []a = { 1, 0, 1, 1, 0, 1 };
int n = a.Length;
if (flipsPossible(a, n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by 29AjayKumar
输出:
Yes