problem link : https://www.codech
ef.com/problems/RUMBLING
I have written code for this question but i am unable to find mistake in my code why it is giving wrong answer.
Please help!
Here is my code :
#include<bits/stdc++.h>
using namespace std;
#define ll long int
#define endl "\n"
char getDir(char c,int corac)
{
if(corac == 1) // clockwise
{
if(c =='W') return 'N';
if(c =='N') return 'E';
if(c =='E') return 'S';
if(c =='S') return 'W';
}
else // anticlockwise
{
if(c =='W') return 'S';
if(c =='N') return 'W';
if(c =='E') return 'N';
if(c =='S') return 'E';
}
}
int getEnergy(int ci,int ni,char cd,int x,int y)
{
if(ci>ni)
{
// means final position in west
int cE = 0,acE=0;
char d = cd;
while(d != 'W')
{
d = getDir(d,1);
cE += x;
}
d = cd;
while(d != 'W')
{
d = getDir(d,-1);
acE += y;
}
return min(cE,acE);
}
else
{
// means final position in east
int cE = 0,acE=0;
char d = cd;
while(d != 'E')
{
d = getDir(d,1);
cE += x;
}
d = cd;
while(d != 'E')
{
d = getDir(d,-1);
acE += y;
}
return min(cE,acE);
}
}
int ans(string d,int n,int x,int y)
{
int ei = -1;
int lsum = 0;
int nsum = 0;
for(int i=0;i<n;i++)
{
int e1 = getEnergy(i,ei,d[i],x,y);
int e2 = getEnergy(i,i+1,d[i],x,y);
lsum += e1;
nsum += e2;
if(lsum > nsum)
{
ei = i;
lsum = 0;
nsum = 0;
}
}
// got correct position
int answer = 0;
for(int i=0;i<n;i++) // calculate energy needed
{
int t;
if(i==ei)
{
t = getEnergy(i,i+1,d[i],x,y);
}
else
{
t = getEnergy(i,ei,d[i],x,y);
}
answer += t;
}
return answer;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll t;cin>>t;
while(t--)
{
int n;cin>>n;
string d;
cin>>d;
int x,y;
cin>>x>>y;
cout<<ans(d,n,x,y)<<endl;
}
}