QM8A editorial

PROBLEM LINK:

Practice

Contest

Author: Chandan Boruah

Tester: Chandan Boruah

Editorialist: Chandan Boruah

DIFFICULTY:

EASY

PREREQUISITES:

Basic Maths.

PROBLEM:

Given a 2D array of integers find the minimum number of swaps required to convert the array to alternating odd and even numbers.

QUICK EXPLANATION:

Count the number of positions in which the array is not in alternating in odd/even sequence. Print the minimum of that count/2 and total (elements-count)/2.

EXPLANATION:

Count the positions in which the array is not in odd/even sequence. That divide by 2 would be the number of swaps needed. But if the alternating odd/even sequence starts with the other (odd and not even or even and not odd) number type then we need to calculate for that too. So the number to be printed is the minimum of count/2,(elements-count)/2.

Solution in CS:

using System;
class some
{
	public static void Main()
	{
		int n=int.Parse(Console.ReadLine());
		while((n--)>0)
		{
			string[]ss=Console.ReadLine().Split();
			int x=int.Parse(ss[0]);
			int y=int.Parse(ss[1]);
			int[,]arr=new int[x,y];
			for(int i=0;i<x;i++)
			{
				ss=Console.ReadLine().Split();
				for(int j=0;j<y;j++)
				{
					arr[i,j]=int.Parse(ss[j])%2;
				}
			}
			int[,]check=new int[x,y];
			for(int i=0;i<x;i++)
			{
				int j=0;
				if(i%2==0)j++;
				for(;j<y;j+=2)
				{
					check[i,j]=1;
				}
			}
			int count=0;
			for(int i=0;i<x;i++)
			{
				for(int j=0;j<y;j++)
				{
					if(arr[i,j]==check[i,j])
						count++;
				}
			}
			Console.WriteLine(Math.Min(count/2,(x*y-count)/2));
		}
	}
}
1 Like