The Rumbling CodeChef Solution

Problem -The Rumbling CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.

The Rumbling CodeChef Solution in C++17

#include <bits/stdc++.h>

using namespace std;

#ifdef PRADEEP
  #include "dbg.h" 
#else
  #define dbg(x...)
#endif

using ll = long long;

ostream& operator<<(ostream& os,const vector<int>& x) {
  for (const int& i : x) { os << i << ' '; }
  return os;
}

ostream& operator<<(ostream& os,const vector<double>& x) {
  for (const double& i : x) { os << setprecision(17) << i << ' '; }
  return os;
}

template <typename T>
void print(int t,const T& x) {
  cout << "Case #" << t << ": " << fixed << setprecision(10) << x << '\n';
}

// source : kactl (https://github.com/kth-competitive-programming/kactl/blob/main/content/data-structures/SegmentTree.h)
// query => [b ,e)
struct Tree {
  typedef int T;
  static constexpr T unit = INT_MIN;
  T f(T a, T b) { return max(a, b); }
  vector<T> s; int n;
  Tree(int n = 0, T def = unit) : s(2*n, def), n(n) {}
  void update(int pos, T val) {
    for (s[pos += n] = val; pos /= 2;)
      s[pos] = f(s[pos * 2], s[pos * 2 + 1]);
  }
  T query(int b, int e) { 
    T ra = unit, rb = unit;
    for (b += n, e += n; b < e; b /= 2, e /= 2) {
      if (b % 2) ra = f(ra, s[b++]);
      if (e % 2) rb = f(s[--e], rb);
  }
    return f(ra, rb);
  }
};

int main() 
{
  ios_base::sync_with_stdio(false); 
  cin.tie(nullptr);

  int T;
  cin >> T;

  for (int t = 1;t <= T;t++) {
    ll n, x, y;
    string s;
    cin >> n >> s >> x >> y;
    vector<ll> sfx(n + 2,0);
    vector<ll> pfx(n + 1,0);
    ll ans = 1e18;
    map<char,ll> L;
    L['W'] = 0; L['E'] = 2LL*min(x,y); L['N'] = min(y,3*x); L['S'] = min(x,3*y);

    map<char,ll> R;
    R['E'] = 0; R['W'] = 2LL*min(x,y); R['N'] = min(x,3*y); R['S'] = min(y,3*x);
    
    for (int i = n;i >= 1;i--) {
      sfx[i] = sfx[i + 1] + L[s[i -1]]; 
    }

    for (int i = 1;i <= n;i++) {
      pfx[i] = pfx[i - 1] + R[s[i - 1]];
    }

    ans = min(pfx[n], sfx[1]);

    for (int i = 1;i <= n;i++) {
      ans = min(ans, sfx[i + 1] + pfx[i]);
    }

    cout << ans << '\n';
  }

  return 0;
}

The Rumbling CodeChef Solution in C++14

#include <bits/stdc++.h>

#define MODE 0

#if MODE == 0
#define debug(x) cout << #x << ": " << x << endl
#define log(x) cout << x << endl
#else
#define debug(x)
#define log(x)
#endif

#define M 1000000007

using namespace std;
using ll = long long;

char msub(char a, char b) {
    return (4 + a - b) % 4;
}

void solve() {
    int n;
    cin >> n;
    
    string s;
    cin >> s;
    
    ll x, y;
    cin >> x >> y;
    
    ll mov[4];
    mov[0] = 0;
    mov[1] = min(x, 3 * y);
    mov[2] = min(2 * x, 2 * y);
    mov[3] = min(3 * x, y);
    
    map<char, char> val;
    val['N'] = 0;
    val['E'] = 1;
    val['S'] = 2;
    val['W'] = 3;
    
    ll cost = 0;
    for (char& c : s) {
        c = val[c];
        
        cost += mov[msub(3, c)];
    }
    
    ll mincost = cost;
    for (char& c : s) {
        cost -= mov[msub(3, c)];
        cost += mov[msub(1, c)];
        
        mincost = mincost < cost ? mincost : cost;
    }
    
    cout << mincost << '\n';
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(nullptr);

    int t;
    cin >> t;

    while (t--) {
        solve();
    }

    return 0;
}

The Rumbling CodeChef Solution in PYTH 3

# cook your dish here
T=int(input(""))
for _ in range(T):
    N = int(input(""))
    line=input("")
    X,Y = map(int, input("").rstrip().split(' '))
    costs={}
    DIRECTIONS= {'N':0, 'E':1, 'S':2, 'W':3}
    
    for direction_val in DIRECTIONS.values():
        for dest_direction in ('E', 'W'):
            dest_direction_val = DIRECTIONS[dest_direction]
            costs[(direction_val, dest_direction_val)] = \
                min(X*((dest_direction_val-direction_val)%4),\
                Y*((direction_val-dest_direction_val)%4))
                
    min_sum = 0
    for i in range(N):
        min_sum += costs[(DIRECTIONS[line[i]], DIRECTIONS['W'])]
    curr_sum = min_sum
    for i in range(N):
        curr_sum = curr_sum - costs[(DIRECTIONS[line[i]], DIRECTIONS['W'])] + costs[(DIRECTIONS[line[i]], DIRECTIONS['E'])]
        if min_sum > curr_sum:
            min_sum = curr_sum
           
    print(min_sum)

The Rumbling CodeChef Solution in C

#include <stdio.h>

long long int mini(long long int x, long long int y){
	return x > y ? y : x;
}

int main(void) {
	int t;
	scanf("%d",&t);
	while(t--){
		int n,i;
		scanf("%d",&n);
		char s[n+1];
		scanf("%s",s);
		long long int x,y;
		scanf("%lld %lld",&x,&y);
		long long int pre[n+2],suf[n+2];
		pre[0]=0,suf[n]=0;
		for(i=0;i<n;i++){
			if(s[i] == 'S')
			pre[i+1] = mini(3*x,y) + pre[i];
			else if(s[i] == 'W')
			pre[i+1] = mini(2*x, 2*y) + pre[i];
			else if(s[i] == 'N')
			pre[i+1] = mini(x, 3*y) + pre[i];
			else
			pre[i+1] = pre[i];
		}
		
		
		for(i=n-1;i>=0;i--){
			if(s[i] == 'S')
			suf[i] = mini(x, 3*y) + suf[i+1];
			else if(s[i] == 'E')
			suf[i] = mini(2*x,2*y) + suf[i+1];
			else if(s[i] == 'N')
			suf[i] = mini(3*x, y) + suf[i+1];
			else
			suf[i] = suf[i+1];
		}
		
		long long int ans = 1e18;
		for(i=0;i<=n;i++)
			ans = mini(ans, pre[i] + suf[i]);
			
		printf("%lld\n",ans);
		
	}
	return 0;
}

The Rumbling CodeChef Solution in JAVA

import java.io.IOException;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.StringTokenizer;

import java.io.OutputStream;
import java.io.PrintWriter;

public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        InputReader in = new InputReader(inputStream);
        OutputStream outputStream = System.out;
        PrintWriter out = new PrintWriter(outputStream);
        Task task = new Task();
        int numCases = in.nextInt();
        for (int i = 1; i <= numCases; i++) {
            task.solve(in, out);
        }
        out.close();
    }

    static class Task {
        private int n;
        private long x, y;
        private long[] e, w;
        private String s;

        public void solve(InputReader in, PrintWriter out) {
            n = in.nextInt();
            s = in.next();
            x = in.nextLong();
            y = in.nextLong();
            e = new long[n];
            w = new long[n];
            for (int i = 0; i < n; i++) {
                char c = s.charAt(i);
                if (c == 'N') {
                    e[i] = Math.min(x, 3 * y);
                    w[i] = Math.min(y, 3 * x);
                } else if (c == 'S') {
                    e[i] = Math.min(y, 3 * x);
                    w[i] = Math.min(x, 3 * y);
                } else if (c == 'E') {
                    e[i] = 0;
                    w[i] = Math.min(2 * x, 2 * y);
                } else if (c == 'W') {
                    e[i] = Math.min(2 * x, 2 * y);
                    w[i] = 0;
                }
                if (i > 0) {
                    e[i] += e[i - 1];
                    w[i] += w[i - 1];
                }
            }
            long ans = Math.min(e[n - 1], w[n - 1]);
            for (int i = 0; i < n - 1; i++) {
                ans = Math.min(ans, e[i] + w[n - 1] - w[i]);
            }
            out.println(ans);
        }
    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }
    }
}

The Rumbling CodeChef Solution in PYPY 3

import sys
from math import *
from collections import *
inp = lambda: sys.stdin.buffer.readline().decode().strip()
out=sys.stdout.write
# n=int(inp())
# arr=list(map(int,inp().split()))
for _ in range(int(inp())):
    n=int(inp())
    s=inp()
    x,y=map(int,inp().split())
    east,west={-1:0},{-1:0}
    for idx in range(n):
        if s[idx]=="E": 
            east[idx]=east[idx-1]
            west[idx]=west[idx-1]+2*min(x,y)
        elif s[idx]=="W": 
            west[idx]=west[idx-1]
            east[idx]=east[idx-1]+2*min(x,y)
        elif s[idx]=="N":
            west[idx]=west[idx-1]+min(y,3*x)
            east[idx]=east[idx-1]+min(x,3*y)
        else:
            west[idx]=west[idx-1]+min(3*y,x)
            east[idx]=east[idx-1]+min(3*x,y)
    ans=sys.maxsize
    for i in range(n+1):
        ans=min(ans,east[i-1]+west[n-1]-west[i-1])
    print(ans)

The Rumbling CodeChef Solution in PYTH

def Energy(direction, standing, X, Y):
    if standing == 'L':
        if direction == 'N':
            return min(3*(X),Y)
        elif direction == 'S':
            return min(X,3*Y)
        elif direction == 'E':
            return min(2*X,2*Y)
        else:
            return 0
    elif standing == 'R':
        if direction == 'S':
            return min(3*(X),Y)
        elif direction == 'N':
            return min(X,3*Y)
        elif direction == 'W':
            return min(2*X,2*Y)
        else:
            return 0

def calculate(arr, N, standing, X, Y, ans):
    
    sum_ = 0
    if standing == 0:
        for i in range(N):
            
            if i >= standing:
                sum_ = sum_ + Energy(arr[i], 'L', X, Y)
            else:
                sum_ = sum_ + Energy(arr[i], 'R', X, Y)
        ans[standing] = sum_
    else:
        ans[standing] = ans[standing-1] - Energy(arr[standing-1], 'L', X, Y) + Energy(arr[standing-1], 'R', X, Y)
        
    return ans[standing]
    
    
    
T = int(raw_input())
while(T):
    N = int(raw_input())
    arr = raw_input()
    X, Y = map(int, raw_input().split())
    min_ = float('inf')
    ans = [-1]*(N+1)
    for j in range(N+1):
        min_ = min(min_, calculate(arr, N, j, X, Y, ans ))
    print(min_)
    T = T-1
            

The Rumbling CodeChef Solution in C#

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;

namespace Codeforces
{
    public class Program
    {
        public static int GetInt() => int.Parse(Console.ReadLine());
        public static long GetLong() => long.Parse(Console.ReadLine());

        public static int[] GetIntArray() => Console.ReadLine().Trim().Split(' ').Select(int.Parse).ToArray();
        public static long[] GetLongArray() => Console.ReadLine().Trim().Split(' ').Select(long.Parse).ToArray();
        public static double[] GetDoublesArray() => Console.ReadLine().Trim().Split(' ').Select(d => Convert.ToDouble(d, CultureInfo.InvariantCulture)).ToArray();

        public static string[] GetLines(int n)
        {
            var ans = new string[n];
            for (int i = 0; i < n; i++)
            {
                ans[i] = Console.ReadLine();
            }
            return ans;
        }

        public static long Gcd(long a, long b) => b == 0 ? a : Gcd(b, a % b);
        public static long Gcd(long[] a) => a.Aggregate(a[0], (x, y) => Gcd(x, y));
        public static long Lcm(long a, long b) => a * b / Gcd(a, b);
        public static long Lcm(IEnumerable<int> a) => a.Aggregate(1L, (x, y) => Lcm(x, y));
        public static void Swap(ref long a, ref long b)
        {
            long t = a;
            a = b;
            b = t;
        }

        public static void Swap(ref int a, ref int b)
        {
            int t = a;
            a = b;
            b = t;
        }
        public static int Ceil(int a, int b) => (a + b - 1) / b;

        public static void OutputSequence(IEnumerable<long> x) => Console.WriteLine($" >>  " + string.Join(", ", x));

        public static string Rev(string s) => string.Concat(s.ToArray().Reverse());

        public static int ArithmeticDifference(int[] a)
        {
            if (a.Length == 1)
                return 0;
            a = a.Select(_ => _ - a[0]).ToArray();
            int diff = a[1] - a[0];
            for (int i = 0; i < a.Length - 1; i++)
            {
                if (a[i + 1] - a[i] != diff)
                {
                    return -1;
                }
            }
            return diff;
        }

        public static bool IsStrictlyAscending(int[] a)
        {
            if (a.Length < 2)
                return true;
            for (int i = 1; i < a.Length; i++)
            {
                if (a[i - 1] >= a[i])
                    return false;
            }
            return true;
        }

        public static bool AllEqual(IEnumerable<int> a)
        {
            int t = a.First();
            return a.All(val => val == t);
        }

        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            for (int i = 0; i < t; i++)
                Solve();
        }

        // ans cost to look right, cost to look left
        public static long[] F(char c, long x, long y)
        {
            long[] ans = new long[2];
            switch (c)
            {
                case 'N':
                    ans = new long[] { Math.Min(x, 3 * y), Math.Min(x * 3, y) };
                    break;
                case 'E':
                    ans = new long[] { 0, Math.Min(x * 2, 2*y) };
                    break;
                case 'S':
                    ans = new long[] { Math.Min(3*x, y), Math.Min(x, 3*y) };
                    break;
                case 'W':
                default:
                    ans = new long[] { Math.Min(2*x, 2 * y), 0 };
                    break;
            }
            return ans;
        }

        public static void Solve()
        {
            long n = GetLong();
            string s = Console.ReadLine();
            var a = GetLongArray();
            long x = a[0];
            long y = a[1];

            var anwer = s.Select(c => F(c, x, y))
                         .Select(arr => new { toright = arr[0], toleft = arr[1] })
                         .ToArray();

            long[] pref = new long[n+1];
            long[] suff = new long[n + 1];
            for(int i=0; i<n; i++)
            {
                pref[i + 1] = pref[i] + anwer[i].toright;
                suff[i+1] = suff[i] + anwer[n-1-i].toleft;
            }
            //OutputSequence(pref);
            //OutputSequence(suff);
            long best = long.MaxValue;
            for(int i=0; i<n+1; i++)
            {
                //pref [i]= i schauen rechts
                //suff[i] i schauen nach links
                best = Math.Min(best, pref[i] + suff[n-i]);
            }

#if DEBUG
            Console.Write("Anwser is -----------> ");
#endif
            Console.WriteLine(best);
        }
    }
}

The Rumbling CodeChef Solution in GO

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	tc := readNum(reader)

	var buf bytes.Buffer

	for tc > 0 {
		tc--
		n := readNum(reader)
		S, _ := reader.ReadString('\n')
		X, Y := readTwoNums(reader)
		res := solve(n, X, Y, S)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}
	fmt.Print(buf.String())
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

var D = []byte("NESW")

func solve(n int, X, Y int, S string) int64 {

	turn := func(a, b byte, Z int64, delta int) int64 {
		var i int
		for i < len(D) && D[i] != a {
			i++
		}
		var res int64
		for a != b {
			res += Z
			i = (i + delta) % 4
			a = D[i]
		}
		return res
	}

	check := func(a, b byte) int64 {
		return min(turn(a, b, int64(X), 1), turn(a, b, int64(Y), 3))
	}

	var right int64

	for i := n - 1; i >= 0; i-- {
		// try to face W
		right += check(S[i], 'W')
	}

	best := right
	var left int64

	for i := 0; i < n; i++ {
		right -= check(S[i], 'W')
		left += check(S[i], 'E')
		best = min(best, left+right)
	}

	return best
}

func min(a, b int64) int64 {
	if a <= b {
		return a
	}
	return b
}
The Rumbling CodeChef Solution Review:

In our experience, we suggest you solve this The Rumbling CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the The Rumbling CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this The Rumbling CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *