Monday, January 4, 2010

Minimal Swap



The basic logic is
that after swapping all the rows of the input chip-matrix are arranged in a
descending order of the ASCII values of the characters when seen from behind.



You are given an N x N matrix. The chips are represented by B and R. You can swap any two adjacent rows of the matrix. Your goal is to have all the black chips in the matrix below or on the main diagonal.


Input


The
first line of input gives the number of cases. The first line of each
test case has one integer, N. Each of the next N lines contains N
characters. Each character is either R or B.


Output 


For
each input case print the minimum number of row swaps needed to have
all the black chips in the matrix below or on the main diagonal.


 


Sample Input 


2


2


BR


BB


3


RRB


BRR


RBR


 


Sample Output 


0


2



#include<stdio.h>



#include<string.h>





int main()





{

   
char str1[10][10],dummy[10],str2[10][10];



   
int cases,i=0,n,j,m,count,l,k,ans[100];



   
scanf("%d",&cases);//Taking the number of test-cases.



   
while(i<cases)





   
{

          count=0;



          scanf("%d",&n);//Taking
the number of characters in a row.



          //Taking the chip-matrix in a 2-D
character array.



          for(j=0;j<n;j++)



          {



                                scanf("%s",str1[j]);



          }



          //Copying the input into another 2-D
character array for reversal purpose.



          for(j=0;j<n;j++)



          {strcpy(str2[j],str1[j]);}



          //Reversing the characters of each
row in the original array.



          for(m=0;m<n;m++)



          {



              k=0;



              for(l=n-1;l>=0;l--)



              {



                   str1[m][l]=str2[m][k];



                   k++;



              }



          }



          //Bubble sorting the rows in the
decreasing order.



          for(m=0;m<n;m++)



          {



              for(l=m;l<=n-m;l++)



              {



                  
if(strcmp(str1[l],str1[l+1])<0 && (l+1)<n)



                   {



                         strcpy(dummy,str1[l]);



                        
strcpy(str1[l],str1[l+1]);



                         strcpy(str1[l+1],dummy);



                         count++;



                   }



                                }



          }



          //Storing the swap-count of each case
in the ans array.



          ans[i]=count;



          i++;



   
}



   
//Printing the swap-counts.



  
 for(i=0;i<cases;i++)



   
{printf("%d\n",ans[i]);}                                                                                                                                                               



   
return 0;



}



2
2
BR
BB
3
RRB
BRR
RBR

0
2                 

No comments:

Post a Comment