Chef and Wedding Arrangements CodeChef Solution

Problem -Chef and Wedding Arrangements 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.

Chef and Wedding Arrangements CodeChef Solution in C++17


#include<bits/stdc++.h>
using namespace std;
#define all(arr) arr.begin(),arr.end()
#define rep(i,s,e) for(int i=s;i<e;i++)
#define lli long long int
#define ll long long
const ll INF=1e18;
const int mod=1e9+7;
int dfs(int start,int end,vector<int>&dp,vector<int>&arr,int k){
	if(dp[start]!=-1){return dp[start];}
	vector<int>cnt(101,0);int c=0,val=INT_MAX;
	for(int i=start;i<end;i++){
		if(cnt[arr[i]]==0){cnt[arr[i]]++;}
		else{
			val=min(val,dfs(i,end,dp,arr,k)+k+c);cnt[arr[i]]++;
			if(cnt[arr[i]]==2){c+=2;}else{c++;}
		}
	}val=min(val,c);
	return dp[start]=val;
}
int main(){
	ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	int t;cin>>t;
	while(t--){
		int n,k;cin>>n>>k;vector<int>arr(n);for(int i=0;i<n;i++){cin>>arr[i];}
		vector<int>dp(n,-1);
		cout<<k+dfs(0,n,dp,arr,k)<<"\n";
	}	
	return 0;
}

Chef and Wedding Arrangements CodeChef Solution in C++14

#include<bits/stdc++.h>
#define ll long long
using namespace std;

int dp[1005];

int mincost(int k, vector<int> &v, int st, int end){
    if(st>end) return 0;
    if(dp[st]!=-1) return dp[st];
    int ans = INT_MAX;
    int sum=0;
    unordered_map<int,int> mp;
    for(int i=st;i<=end;i++){
        if(mp.find(v[i])==mp.end()){
            mp[v[i]]++;
        }
        else if(mp[v[i]]==1){
            mp[v[i]]++;
            sum += 2;
        }
        else if(mp[v[i]]>1){
            mp[v[i]]++;
            sum += 1;
        }
        ans = min(ans, sum + k+ mincost(k,v,i+1,end));
    }
    return dp[st] = ans;
}

int main(){
    int t;
    cin>>t;
    while(t--){
        memset(dp,-1,sizeof(dp));
        int n,k;
        cin>>n>>k;
        vector<int> v(n);
        for(int i=0;i<n;i++){
            cin>>v[i];
        }
        int ans = mincost(k,v,0,n-1);
        cout<<ans<<endl;
    }
}

Chef and Wedding Arrangements CodeChef Solution in PYTH 3

# cook your dish here
t = int(input())
for _ in range(t):
    n, cost = list(map(int, input().split()))
    guest = list(map(int, input().split()))
    
    dp = [0] * (n + 1)
    
    dp[0] = 0
    dp[1] = cost
    
    for i in range(2, len(dp)):
        d = {}
        arg = 0
        dp[i] = cost + dp[i - 1]
        
        for j in range(i, 0, -1):
            d[guest[j - 1]] = d.get(guest[j - 1], 0) + 1 
            if d[guest[j - 1]] == 2:
                arg += 2
            elif d[guest[j - 1]] > 2:
                arg += 1
            
            dp[i] = min(dp[i], cost + arg + dp[j - 1])
    print(dp[n])    

Chef and Wedding Arrangements CodeChef Solution in C

#include <stdio.h>
#include<stdlib.h>
int min(int a, int b)
{
    if(a < b)
    {
        return a;
    }
    return b;
}

int finder(int i,int K, int* dp, int *a)
{
    if(dp[i] != -1)
    {
        return dp[i];
    }
    int F[100];
    for(int i=0; i<100; i++)
    {
        F[i] = 0;
    }
    int sum = 0;
    int min = -1;
    int temp;
    for(int j = i; j>=0; j--)
    {
        F[a[j]]++;
        if(F[a[j]] == 2)
        {
            sum += 2;
        }
        else if(F[a[j]] > 2)
        {
            sum ++;
        }
        
        if(j == 0)
        {
            temp = sum + K;
        }
        else
        {
            temp = sum + K + finder(j-1,K,dp,a);
        }
        
        if(min == -1)
        {
            min = temp;
        }
        else if(temp < min)
        {
            min = temp;
        }
    }
    
    return dp[i] = min;
}

int main(void) {
	// your code goes here
	int T;
	scanf("%d", &T);
	while(T--)
	{
	    int N,K;
	    scanf("%d%d", &N, &K);
	    int a[N];
	    for(int i=0; i<N; i++)
	    {
	        scanf("%d", a + i);
	        a[i] -= 1;
	    }
	    int dp[N];
	    for(int i=0; i<N; i++)
	    {
	        dp[i] = -1;
	    }
	    dp[0] = K;
	    printf("%d\n",finder(N-1,K,dp,a));
	}
	return 0;
}

Chef and Wedding Arrangements CodeChef Solution in JAVA

// package com.company;

import java.util.*;
import java.lang.*;
import java.io.*;

class Solution{
    static class FastReader{
        BufferedReader br;
        StringTokenizer st;

        public FastReader(){
            br= new BufferedReader(new InputStreamReader(System.in));
        }

        // here next methode is defined
        String next(){
            while(st== null || !st.hasMoreElements()){
                try{
                    st= new StringTokenizer(br.readLine());
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt(){
            return Integer.parseInt(next());
        }
        long nextLong(){
            return Long.parseLong(next());
        }
        double nextDouble(){
            return Double.parseDouble(next());
        }
        String nextLine(){
            String str="";
            try{
                if(st.hasMoreTokens()){
                    str= st.nextToken("\n");
                }else{
                    str= br.readLine();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
            return str;
        }
    }

    static FastReader s= new FastReader();
    public static void main(String[] args) throws Exception{
        int t= s.nextInt();
        while(t-->0){
           solve();
        }
    }


    static void solve(){
        int n= s.nextInt();
        int k= s.nextInt();

        int [] arr= new int[n+1];
        for(int i=1;i<=n;i++){
            arr[i]=s.nextInt();
        }

        int [] dp = new int[n+1];
        dp[0]=0;
        for(int i=1;i<=n;i++){
            dp[i]= dp[i-1]+k;
            int clash=0;
            Map<Integer,Integer> mp= new HashMap<>();

            for(int j=i;j>0;j--){
                mp.put(arr[j],mp.getOrDefault(arr[j],0)+1);
                if(mp.get(arr[j])==2){
                    clash+=2;
                }else if(mp.get(arr[j])>2){
                    clash++;
                }
                dp[i]= Math.min(dp[i],dp[j-1]+k+clash);
            }
        }
        System.out.println(dp[n]);
    }
    static boolean check(int[] arr,int beg,int end){

        Arrays.sort(arr,beg,end+1);

        if(is_sorted(arr)){
            return true;
        }
        else
            return false;
    }
    static boolean is_sorted(int []arr){
        int n= arr.length;

        for(int i=1;i<n;i++){
            if(arr[i]<arr[i-1])
                return false;
        }
        return true;
    }

}

Chef and Wedding Arrangements CodeChef Solution in PYPY 3

def solve(arr,n,k):
    dp = [0]*(n+1)
    for i in range(1,n+1):
        hash_map = dict()
        arg = 0
        dp[i] = k + dp[i-1]
        for j in range(i,0,-1):
            hash_map[arr[j-1]] = hash_map.get(arr[j-1],0)+1
            if hash_map[arr[j-1]] == 2:
                arg += 2
            elif hash_map[arr[j-1]]>2:
                arg+=1
            dp[i] = min(dp[i],k + arg + dp[j-1])
    return dp[n]    

for _ in range(int(input())):
    n,k = map(int,input().split())
    arr = list(map(int,input().split()))
    print(solve(arr,n,k))

Chef and Wedding Arrangements CodeChef Solution in PYTH

t = int(raw_input())
for i in range(t):
	st = raw_input().split()
	N = int(st[0])
	K = int(st[1])
	v = N*K
	F = [0 for x in range(N+1)]
	st = raw_input().split()
	for x in range(1,N+1):
		F[x] = int(st[x-1])
	# endfor x
	V = [v for x in range(N+1)]
	V[0] = 0
	for p in range(1,N+1):
		v = V[p-1] + K
		S1 = set()
		S2 = set()
		for k in range(p,N+1):
			n = F[k]
			if n in S2:
				v += 1
			else:
				if n in S1:
					v += 2
					S2.add(n)
				else:
					S1.add(n)
				# endif
			# endif
			if v < V[k]:
				V[k] = v
			# endif
		# endfor k
	# endfor p
	print V[N]
# endfor i

Chef and Wedding Arrangements CodeChef Solution in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
//using mystruct = System.Int64;
//using Mod = System.Int64;

public sealed class Solution : CoreLibs
{
    internal static void __initStatic()
    {
        checked
        {
            //#region YOUR STATIC CODE (1A) . . . . . . . . . . .
            multiTCsInit();
            // . . . . . . . . .
            
            //#endregion . . . . . . . . . . . . . . . . . . . .
        }
    }
    public void __main()
    {
        checked
        {
            //#region YOUR OUTER CODE (2B) . . . . . . . . . . .
            var n = read();
            var k = read();
            var f = repeat(n, read)
                .ll_1()
                ;
            var F = 111;
            //
            var dp = new long[1111];
            foreach (var jj in seq(1, n))
            {
                var ff = new long[F];
                var min = long.MaxValue;
                var bb = 0;
                foreach (var ii in rev(1, jj))
                {
                    // ii..jj within 1 same table
                    var aa = dp[ii - 1];
                    var freq = ff[f[ii]]++;
                    switch (freq)
                    {
                        case 0: break;
                        case 1: bb += 2; break;
                        default: bb++; break;
                    }
                    var tmp = aa + bb;
                    min = Math.Min(min, tmp);
                }
                dp[jj] = min + k;
            }
            writeNumber(dp[n]);
            writeLine();
            //#endregion . . . . . . . . . . . . . . . . . . .
        }
    }
    //#region YOUR HELPER CODE (3C) . . . . . . . . . . . . .
    
    //#region new class & struct . . . . . . . . . . . . . . .
    
    //#endregion . . . . . . . . . . . . . . . . . . . . . . .
    //#endregion . . . . . . . . . . . . . . . . . . . . . . .
}


// additional plugable library
static partial class CoreExtension
{
    // EXTENSION . . . . . . . . . . . . . . . . . . . . . . . . . . .

}
public partial class CoreLibs
{
    // METHODS & CLASSES . . . . . . . . . . . . . . . . . . . . . . . . . . .
    
    // . . . . . . . . . . . . . . . . . . . . . . . . . . . .
    #region STDIO
#if !DEBUG
    static void Main() { __stdioMain(); }
#endif
    static void __stdioMain() { __stdioMain(Console.OpenStandardInput(), Console.OpenStandardOutput()); }
    public static void __stdioMain(System.IO.Stream input, System.IO.Stream output)
    {
        Console.SetIn(new System.IO.StreamReader(new System.IO.BufferedStream(input)));
        if (!INTERACTIVE_FLUSH) Console.SetOut(new System.IO.StreamWriter(new System.IO.BufferedStream(output)));
        var cnt = MULTI_TCs ? int.Parse(Console.ReadLine()) : 1;
        for (var i = 1; i <= cnt; i++)
        {
            if (MULTI_TCs_STRING_FORMAT != null) Console.Write(MULTI_TCs_STRING_FORMAT, i);
            new Solution().__main();
            separatorAutoString = null;
            if (EXIT) break;
        }
        Console.Out.Flush();
    }
    static bool INIT, MULTI_TCs, INTERACTIVE_FLUSH, EXIT;
    static string MULTI_TCs_STRING_FORMAT = null;
    static void stdioInit(bool multiTCs) { INIT = true; MULTI_TCs = multiTCs; }
    public static void stdioInit() { stdioInit(false); }
    public static void interactiveInit() { INTERACTIVE_FLUSH = true; stdioInit(false); }
    public static void multiTCsInit(string tCaseStringFormat = null) { MULTI_TCs_STRING_FORMAT = tCaseStringFormat; stdioInit(true); }
    public static void codejamInit() { multiTCsInit("Case #{0}: "); }
    public static void shopeeHackerEarthInit(bool multiTCs) { if (multiTCs) multiTCsInit("Case {0}: "); else stdioInit(); }
    public static void Exit() { EXIT = true; }
    int validateInitCtor = 1 / (INIT ? 1 : 0);
    // OUTput
    public static string separatorAutoString = null;
    public static void writeLine() { Console.WriteLine(); }
    public static void writeSeparator() { if (!string.IsNullOrEmpty(separatorAutoString)) { Console.Write(separatorAutoString); } }
    public static void writeText(char c) { Console.Write(c); writeSeparator(); }
    public static void writeText(string s) { Console.Write(s); writeSeparator(); }
    public static void writeNumber(long i64) { Console.Write(i64); writeSeparator(); }
    public static void writeNumber(int i32) { Console.Write(i32); writeSeparator(); }
    public static void writeNumber(double dec) { Console.Write(dec); writeSeparator(); }
    // INput
    static void EOF() { throw new System.IO.EndOfStreamException(); }
    static Queue<string> queue = new Queue<string>(1024 * 128);
    const char[] nullCharArr = null;
    public static string readWordString()
    {
        while (queue.Count == 0)
        {
            var line = Console.ReadLine().Split(nullCharArr, StringSplitOptions.RemoveEmptyEntries);
            foreach (var s in line) queue.Enqueue(s);
        }
        return queue.Dequeue();
    }
    /// <summary>
    /// Long64.
    /// </summary>
    public static long read() { return long.Parse(readWordString()); }
    public static long read(out long i64) { return (i64 = read()); }
    public static string read(out string str) { return (str = readWordString()); }
    public static double read(out double dec) { return (dec = double.Parse(readWordString())); }
    #endregion
}


#region Core helper library
[DebuggerNonUserCode]
public partial class CoreLibs
{
    public static bool SLOW = false;
    static CoreLibs() { Solution.__initStatic(); }
    public static long GTcId;
    public static IEnumerable<long> seq(long low, long high, long skip = 1) { checked { for (var i = low; i <= high; i += skip) yield return i; } }
    public static IEnumerable<long> rev(long low, long high, long skipPositive = 1) { checked { for (var i = high; i >= low; i -= skipPositive) yield return i; } }
    public static T[] collect<T>(params T[] elemS) { return elemS; }
    public static T? optional<T>(bool hasValue, T value) where T : struct { return hasValue ? new T?(value) : null; }
    public static T identity<T>(T obj) { return obj; }
    public static T? optional<T>(T value) where T : struct { return value; }
    public static void assert(bool truthy) { if (!truthy) { Debug.Fail("ASSERT"); var a = 0; a /= a; } }
    public static void assert<T>(T actual, T expected) { if (!Equals(actual, expected)) { Debug.WriteLine("SALAH {0} / BENAR {1}", actual, expected); assert(false); } }
    [Conditional("DEBUG")]
    public static void pause(bool condition = true) { if (condition) Debugger.Break(); }
    public static List<T> list<T>(T ignored) { return new List<T>(); }
    public static T? optional<T>(bool hasValue, Func<T> calc) where T : struct { return hasValue ? calc() : new T?(); }
    public static long countLength(long left, long right, long fallback = 0) { return left > right ? fallback : checked(right - left + 1); }
    public static long getRight(long left, long count) { return checked(left + count - 1); }
    public static long getLeft(long count, long right) { return checked(right - count + 1); }
    public static double div(double a, double b) { assert(b != 0); return a / b; }
    public static long ceil(long a, long b) { return a / b + (a % b == 0 ? 0 : 1); }
    public static void loop(long count, Action act) { while (count-- > 0) act(); }
    public static IEnumerable<T> repeat<T>(long count, Func<T> getter) { while (count-- > 0) yield return getter(); }
    public static bool eq(double a, double b, double precision = 1e-9) { checked { return a - precision < b && a + precision > b; } }
    public static void swap<T>(ref T a, ref T b) { var temp = a; a = b; b = temp; }
    public static bool isOdd(long val) { return val % 2 != 0; }
    public static bool isEven(long val) { return val % 2 == 0; }
    public static T computeMemo<T>(ref T memoAns, Func<T, T> func) { return (memoAns = func(memoAns)); }
    //
    [Conditional("DEBUG")]
    public static void debug<T>(T s) where T : IConvertible { if (SLOW) { lock (Console.Out) { Debug.Write(s); } } }
    [Conditional("DEBUG")]
    public static void debugln<T>(T s) where T : IConvertible { if (SLOW) { lock (Console.Out) { Debug.WriteLine(s); } } }
    public struct PairStruct<Ta, Tb> { public readonly Ta A; public readonly Tb B; public PairStruct(Ta a, Tb b) { A = a; B = b; } }
    public static PairStruct<Ta, Tb> pair<Ta, Tb>(Ta a, Tb b) { return new PairStruct<Ta, Tb>(a, b); }
    public static bool fullyContainedWithinInterval(long inLeft, long inRight, long outLeft, long outRight) { inLeft.lrAssert(inRight); outLeft.lrAssert(outRight); return inLeft >= outLeft && inRight <= outRight; }
    public static bool intersectInterval(long aLeft, long aRight, long bLeft, long bRight) { aLeft.lrAssert(aRight); bLeft.lrAssert(bRight); return !(aRight < bLeft || aLeft > bRight); }
    public static int CompareDivs(long leftTop, long leftBottom, long rightTop, long rightBottom) { checked { return (leftTop * rightBottom).CompareTo(rightTop * leftBottom); } }
}
[DebuggerNonUserCode]
public static partial class CoreExtension
{
    public static V getOrElse<K,V>(this IDictionary<K,V> dict, K key, V fallback) { V ans; if (dict.TryGetValue(key, out ans)) return ans; return fallback; }
    public static IEnumerable<T> each<T>(this IEnumerable<T> stream, Action<T> act) { foreach (var elem in stream) act(elem); return stream; }
    public static IEnumerable<T> SelectElement<T>(this IEnumerable<long> indices, IList<T> lst) { return indices.Select(Convert.ToInt32).Select(i => lst[i]); }
    public static IEnumerable<T> SelectElement<T>(this IList<T> lst, IEnumerable<long> indices) { return indices.Select(Convert.ToInt32).Select(i => lst[i]); }
    public static int int32(this IConvertible val) { return val.ToInt32(null); }
    public static long long64(this IConvertible val) { return val.ToInt64(null); }
    public static IConvertible convert(this IConvertible val) { return val; }
    public static IEnumerable<long> long64(this IEnumerable<int> stream) { return stream.Select(x => (long)x); }
    public static T? optional<T>(this T value) where T : struct { return value; }
    public static IEnumerable<T?> optional<T>(this IEnumerable<T> stream) where T : struct { return stream.Select(optional); }
    public static long skip(this long src, long skipSigned) { return checked(src + skipSigned); }
    public static int? explainSearchIndex(this int rawIndex) { if (rawIndex < 0) return null; return rawIndex; }
    public static T[] sort<T>(this T[] arr, long left, long right) { Array.Sort(arr, left.int32(), CoreLibs.countLength(left, right).int32()); return arr; }
    public static List<T> sort<T>(this List<T> lst) { lst.Sort(); return lst; }
    public static T[] ll_1<T>(this IEnumerable<T> stream) { var l = new List<T>(); l.Add(default(T)); l.AddRange(stream); return l.ToArray(); }
    public static List<T> list<T>(this IEnumerable<T> stream) { return stream.ToList(); }
    public static T collect<T, E>(this IEnumerable<E> stream, T coll) where T : ICollection<E> { foreach (var e in stream) coll.Add(e); return coll; }
    public static string stringify<T>(this T? val, string fallback) where T : struct { return val.HasValue ? val.ToString() : fallback; }
    public static string stringify(this IEnumerable<char> stream) { return new string(stream.ToArray()); }
    public static T poll<T>(this ICollection<T> coll, T remove) { CoreLibs.assert(coll.Remove(remove)); return remove; }
    public static T poll<T>(this LinkedList<T> coll, LinkedListNode<T> node) { coll.Remove(node); return node.Value; }
    public static KeyValuePair<Tk, Tv> poll<Tk, Tv>(this IDictionary<Tk, Tv> dict, Tk key)
    {
        var val = dict[key]; dict.Remove(key); return new KeyValuePair<Tk, Tv>(key, val);
    }
    public static int getUpperBound<T>(this IList<T> list) { return list.Count - 1; }
    public static V computeMemo<K, V>(this IDictionary<K, V> dict, K key, Func<V> calc)
    { V ans; if (dict.TryGetValue(key, out ans)) return ans; return (dict[key] = calc()); }
    //
    public static T? AggregateOrNullable<T>(this IEnumerable<T> stream, Func<T, T, T> merge_CHECKED) where T : struct
    { var it = stream.GetEnumerator(); if (!it.MoveNext()) return null; var res = it.Current; while (it.MoveNext()) res = merge_CHECKED(res, it.Current); return res; }
    public static int GetUpperBound(this System.Collections.IList list) { return list.Count - 1; }
    public static T? elementAtOrNullable<T>(this IList<T> list, int index) where T : struct { if (index < 0 || index >= list.Count) return null; return list[index]; }
    [Conditional("DEBUG")]
    public static void lrAssert(this long left, long right) { { if (!CoreLibs.SLOW) CoreLibs.assert(left <= right); } }
    public static bool betweenIncl(this long val, long left, long right) { left.lrAssert(right); return val >= left && val <= right; }
    public static void swap<T>(this IList<T> list, int i1, int i2) { var tmp = list[i1]; list[i1] = list[i2]; list[i2] = tmp; }
    public static void swap<T>(this IList<T> list, long i1, long i2) { swap(list, i1.int32(), i2.int32()); }
    public static void Shuffle<T>(this IList<T> list) { var rng = new Random(); for (var i = 0; i < list.Count; i++) list.swap(rng.Next(list.Count), rng.Next(list.Count)); }
}
#endregion

Chef and Wedding Arrangements CodeChef Solution in NODEJS

// process.stdin.resume();
// process.stdin.setEncoding('utf8');

function readDOM() {
    return document.querySelector("#exampleinput").nextElementSibling.textContent
}

let CONFIG = {
    getStringFunc: readDOM
};

stdioCPPattern({}, ({ readNum, writeLine }) => {
    // your code goes here
//     debugger;
    let marker = Array(100);

    let tc_count = readNum();
    let nGuests, unitPrice,
        fam = Array(1000),
        optimalCost = Array(1000),
        optValue, backwardCost,
        counter, currentFi;

    while (tc_count--) {
        [nGuests, unitPrice] = [readNum(), readNum()];
        for (let index = 0; index < nGuests; index++) {
            fam[index] = readNum() - 1;
        }


        for (let index = 0; index < nGuests; index++) {
            optValue = 1e7;
            marker.fill(0);
            counter = 0;
            for (let leftIndex = index; leftIndex >= 0; leftIndex--) {
                backwardCost = leftIndex > 0 ? optimalCost[leftIndex - 1] : 0;
                currentFi = fam[leftIndex];
                oldCount = marker[currentFi];
                if (oldCount) {
                    counter++;
                    if (oldCount < 2) counter++;
                }
                marker[currentFi]++;

                optValue = Math.min(optValue, backwardCost + unitPrice + counter);
            }
            optimalCost[index] = optValue;
        }
        writeLine(optimalCost[nGuests - 1]);
    }
});

function stdinReadAll() {
    const fs = require("fs");
    return fs.readFileSync(0).toString();
}
// WARNING!!!
// DO NOT MODIFY THE CODE BELOW
// IT WILL STOP WORKING FOREVERRRRRRRRRRR!!!
function stdioCPPattern({
    getStringFunc = stdinReadAll
}, callbackfn) {
    const aStr = getStringFunc() + "\n";

    let cur = 0;
    const resultList = [];// Array(numberOfLine);

    callbackfn({
        log: console.log,
        readNum() {
            let x = 0, ch = aStr.charCodeAt(cur) - 48;
            while (ch < 0 || 9 < ch) ch = aStr.charCodeAt(++cur) - 48;
            while (0 <= ch && ch <= 9) {
                x = x * 10 + ch;
                ch = aStr.charCodeAt(++cur) - 48;
            }
            return x;
        },
        writeLine(data) {
            resultList.push(`${data}`);
        },
        readStr() {
            throw new Error("Did not implement ):<");
        }
    });
    let prompt = resultList.join("\n");
    if (prompt) console.log(prompt);
}

Chef and Wedding Arrangements CodeChef Solution in GO

package main

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

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
}

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

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n, k := readTwoNums(reader)
		F := readNNums(reader, n)

		fmt.Println(solve(n, k, F))
	}
}

const INF = 1 << 20

func solve(n, k int, F []int) int {
	dp := make([]int, n+1)
	dp[1] = k
	for i := 1; i < n; i++ {
		cnt := make(map[int]int)
		dp[i+1] = INF
		var arg int
		for j := i; j >= 0; j-- {
			cnt[F[j]]++
			if cnt[F[j]] == 2 {
				arg += 2
			} else if cnt[F[j]] > 2 {
				arg++
			}
			dp[i+1] = min(dp[i+1], dp[j]+arg+k)
		}
	}

	return dp[n]
}

func min(a, b int) int {
	if a <= b {
		return a
	}
	return b
}
Chef and Wedding Arrangements CodeChef Solution Review:

In our experience, we suggest you solve this Chef and Wedding Arrangements 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 Chef and Wedding Arrangements CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Chef and Wedding Arrangements 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 *