Find Your Gift - GIFTSRC CodeChef March Cook-OFF Easy
Find Your Gift Problem Code: GIFTSRC – Codechef March COOK-OFF EaSY 2020 DIV2
Welcome back to my blog,
Here is the link to the question
Our main aim is to find the coordinates of the gift.
Given Chef should never
perform multiple consecutive moves along the same axis of the grid. If there
are multiple consecutive instructions to move along the same axis (left/right
or up/down), he should perform only the first of these moves.
So first, I will construct a
string with no consecutive moves in same axis.
L and R share same y axis and
U and D share same x axis. So, we have to check if they are consecutive in
given string. If they are consecutive, we have to remove the second character.
After constructing, our new
string we can traverse along the string and calculate the coordinates of the
gift easily.
Here is my code in java.
Please go through it for more clarification.
--------------------------------------------------------------------------------------------------------------------------------------
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be
"Main" only if the class is public. */
class Codechef
{
public
static void main (String[] args) throws java.lang.Exception
{
//
your code goes here
Scanner
s=new Scanner(System.in);
int
t=s.nextInt();
while(t-->0)
{
int n=s.nextInt();
String sc=s.next();
for(int i=0;i<sc.length()-1;i++)
{
if(sc.charAt(i)==sc.charAt(i+1) ||(
sc.charAt(i)=='L'&& sc.charAt(i+1)=='R')||(
sc.charAt(i+1)=='L'&& sc.charAt(i)=='R') ||
(sc.charAt(i)=='U'&& sc.charAt(i+1)=='D')||(sc.charAt(i+1)=='U'&&
sc.charAt(i)=='D'))
{
sc=sc.substring(0, i+1) +
sc.substring(i+2);
i--;
}
}
int x=0,y=0;
for(int i=0;i<sc.length();i++)
{
if(sc.charAt(i)=='L')
x--;
else if(sc.charAt(i)=='R')
x++;
else if(sc.charAt(i)=='U')
y++;
else
y--;
}
System.out.print(x+" "+y);
System.out.println("");
}
s.close();
}
}
Comments
Post a Comment