Saturday 20 December 2014

Problem Last ant on rod

Last ant on rod[C Program]

There are 'n' ants on a 'n+1' length rod. The ants are numbered from 1 to n and are initially placed at positions starting from position 1 till position n. They are moving either in left direction (denoted by '-1') or in the right direction (denoted by '1'). Whenever an ant crosses the boundary of the rod it falls off the rod. You are given the initial direction of the ants. Now, whenever two ants collide their direction switches, i.e. the ant going in left direction ('-1) changes it's direction towards right ('1') and the ant going in the right direction ('1') changes it's direction towards left ('-1'). Find last ant to fall off the rod. 

Note: In case two ants are falling simultaneously in the end print the index of the lower indexed ant. 

Input Format:
First line contains the integer 'n' denoting the total number of ants s.t.
                     1 <= n <= 1,000
Second line contains 'n' space separated numbers (either '1' or '-1') denoting the initial directions of the ants. 

Output Format:
Output a single integer which is the index (lower index in case two ants are falling simultaneously in the end) of the last ant to fall off the table.

Example:-
1.Input:-    2
             1 1
  Output:-   1
2.Input:-    3
             1 -1 -1
  Output:-   2

Program:-

#include<stdio.h>

int main(){
 int n,i,cn=0,in=0;
 scanf("%d",&n);
 int rod[2][n+1],vc[n+1];
 for(i=0;i<n;i++){
  scanf("%d",&rod[0][i]);
  rod[1][i]=i+1;
  vc[i]=1;
 }
 vc[n]=0;
 rod[0][n]=0;
 rod[1][n]=0;
 while(cn!=n){
  for(i=n;i>=0;i--){
   if((rod[0][i]==1&&i==n)||(rod[0][i]==1&&vc[i+1]==0)){
    if(i==n){
     cn++;
     in=rod[1][i];
     vc[i]=0;
     rod[0][i]=0;
     rod[1][i]=0;
    }else{
     vc[i+1]=1;
     vc[i]=0;
     rod[0][i+1]=rod[0][i];
     
     rod[1][i+1]=rod[1][i];
     
     rod[0][i]=0;
     rod[1][i]=0;
    }
   }
  } 
  for(i=0;i<=n;i++){
   if((rod[0][i]==-1&&i==0)||(rod[0][i]==-1&&vc[i-1]==0)){
    if(i==0){
     cn++;
     in=rod[1][i];
     vc[i]=0;
     rod[0][i]=0;
     rod[1][i]=0;
    }else{
     vc[i-1]=1;
     vc[i]=0;
     rod[0][i-1]=rod[0][i];
     rod[0][i]=0;
     rod[1][i-1]=rod[1][i];
     rod[1][i]=0;
    }
   }
  } 
  for(i=0;i<=n;i++){
   if(rod[0][i]==1&&rod[0][i+1]==-1){
    rod[0][i]=-1;
    rod[0][i+1]=1;
    i=i+1;
   }
  }
  
 }
 printf("%d",in);
 return 0;
}


------------X---------------X---------------X---------------X---------------X----

Input:-   10
          1 -1 1 1 -1 1 -1 1 -1 -1
Output:-  5


0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home