Simple Operations CodeChef Solution

Problem -Simple Operations 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.

Simple Operations CodeChef Solution in C++17

#include <iostream>
#include<bits/stdc++.h>
#define ll long long

using namespace std;

int main() {
	// your code goes here
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	ll t;
	cin>>t;
	while(t--){
	    string s, r;
	    cin>>s>>r;
	    ll n =s.size();
	    ll gapLength = 0, k=0, l=0;
	    bool initial = false;
	    vector<ll> gaps;
	    for(ll i=0; i<n; ++i){
	        if(s[i] == r[i]){
	            if(initial)
	                gapLength++;
	        }
	        else{
	            if(!initial) k++;
	            l++;
	            initial = true;
	            if(gapLength>0){
	                k++;
	                gaps.push_back(gapLength);
	                gapLength = 0;
	            }
	        }
	    }
	    sort(gaps.begin(), gaps.end());
	    ll ans = k*l;
	    for(auto g: gaps){
	        k--;
	        l += g;
	        ans = min(ans, k*l);
	    }
	    
	    cout<<ans<<endl;
	    
	}
	return 0;
}

Simple Operations CodeChef Solution in C++14

#include <iostream>
#include <vector>
#include <set>
#include <iomanip>
#include <algorithm>
#include <functional>
#include <stdio.h>
#include <cmath>
#include <queue>
#include <string>
#include <map>
#include <complex>
#include <stack>
#include <set>

#define FOR(i,n) for(int i=0;i<n;i++)
#define FORE(i,a,b) for(int i=a;i<=b;i++)
#define ll long long int
#define vi vector<int>
#define ii pair<int,int>
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define pll pair<ll,ll>
#define cd complex<double>
#define vv vector

using namespace std;

const int INF = 1e9;
const int MAXN = 1e3+5;

int main(){
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	int t;
	cin >> t;
	while(t--){
		string a;
		string b;
		cin >> a >> b;
		int n = a.size();

		int fst = 0;
		vi all;
		ll mn = 0;
		int k = 0;
		bool badstuffGot = 0;
		FOR(i,n){
			if(a[i] == b[i]){
				if(badstuffGot)fst++;
			}else{
				if(!badstuffGot)k++;
				badstuffGot = 1;
				mn++;

				if(fst > 0){
					k++;
					all.pb(fst);
					fst = 0;
				}
			}
		}
		sort(all.begin(), all.end());
		//cout << all.size() << " " << k << endl;
		ll ans = k*mn;
		for(auto e : all){
			mn += e;
			k--;
			ans = min(ans,mn*k);
		}
		cout << ans << endl;
	}

	return 0;
}

Simple Operations CodeChef Solution in PYTH 3

# cook your dish here
T=int(input())
for i in range(T):
    s=input()
    r=input()
    val=[i for i in range(len(s)) if s[i]!=r[i]]
    a=[val[i+1]-val[i]-1 for i in range(len(val)-1)]
    a.sort()
    k,l=len(val),len(val)
    n=[k*l]
    for i in a:
        k-=1
        l+=i
        n.append(k*l)
    print(min(n))

Simple Operations CodeChef Solution in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#define MAX 1000001

void merge(long long int arr[],long long int l,long long int m,long long int r) 
{ 
    long long int i, j, k; 
    long long int n1 = m - l + 1; 
    long long int n2 =  r - m; 
  
    /* create temp arrays */
    long long int L[n1], R[n2]; 
  
    /* Copy data to temp arrays L[] and R[] */
    for (i = 0; i < n1; i++) 
        L[i] = arr[l + i]; 
    for (j = 0; j < n2; j++) 
        R[j] = arr[m + 1+ j]; 
  
    /* Merge the temp arrays back into arr[l..r]*/
    i = 0; // Initial index of first subarray 
    j = 0; // Initial index of second subarray 
    k = l; // Initial index of merged subarray 
    while (i < n1 && j < n2) 
    { 
        if (L[i] >= R[j]) 
        { 
            arr[k] = L[i]; 
            i++; 
        } 
        else
        { 
            arr[k] = R[j]; 
            j++; 
        } 
        k++; 
    }
    while (i < n1) 
    { 
        arr[k] = L[i]; 
        i++; 
        k++; 
    }
    while (j < n2) 
    { 
        arr[k] = R[j]; 
        j++; 
        k++; 
    } 
} 
void mergeSort(long long int arr[],long long int l,long long int r) 
{ 
    if (l < r) 
    { 
        long long int m = l+(r-l)/2; 
        mergeSort(arr, l, m); 
        mergeSort(arr, m+1, r); 
  
        merge(arr, l, m, r); 
    } 
}



int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		char S[MAX];
		char R[MAX];
		scanf("%s",S);
		char ch = getchar();
		scanf("%s",R);
		ch = getchar();
		long long int len = strlen(S);


		long long int mismatch[len];
		long long int match[len];

		long long int match_index=0,mis_index=0;
		int first = 0;
		long long int size=0;
		int matching = 1;

		for(long long int i=0;i<len;i++)
		{
			if(S[i]==R[i]&&first==0)
				continue;
			else if(S[i]==R[i]&&first==1)
			{
				if(matching)
					size++;
				else
				{
					matching=1;
					mismatch[mis_index++] = size;
					size=1;
				}

			}
			else if(S[i]!=R[i])
			{
				//first = 1;
				if(!matching)
					size++;
				else
				{
					matching=0;
					if(first==0)
					{
						first=1;
						size++;
					}
					else
					{
						match[match_index++] = size;
						size=1;
					}
				}
			}
		}

		if(!matching)
			mismatch[mis_index++] = size;

		/*printf("Printing Match :\n");
		for(int i=0;i<match_index;i++)
		{
			printf("%d\t",match[i]);
		}
		printf("\n");
		printf("Printing Mismatch :\n");
		for(int i=0;i<mis_index;i++)
		{
			printf("%d\t",mismatch[i]);
		}*/

		mergeSort(match,0,match_index-1);

		long long int sum = 0;

		for(int i=0;i<match_index;i++)
		{
			sum = sum + match[i];
		}
	
		for(int i=0;i<mis_index;i++)
		{
			sum = sum + mismatch[i];
		}

		long long int min_cost = sum;
		long long int curr_cost;
		long long int costIndex = 0;

		for(long long int i=0;i<match_index;i++)
		{
			sum = sum-match[i];
			curr_cost = (i+2)*(sum);
			if(curr_cost<min_cost)
				min_cost = curr_cost;
		}

		printf("%lld\n",min_cost);

	}
}

Simple Operations CodeChef Solution in JAVA



import java.util.*;

//import sun.util.resources.cldr.ext.CurrencyNames_en_TT;

import java.io.*;
class Codechef {

	static FastScanner scr=new FastScanner();
//	static Scanner scr=new Scanner(System.in);
	 static PrintStream out=new PrintStream(System.out);
	 static StringBuilder sb=new StringBuilder();
	 static  class FastScanner {
		 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
	 	String next() {
	 		while (!st.hasMoreTokens())
	 			try {
	 				st=new StringTokenizer(br.readLine());
	 			} catch (IOException e) {
	 				e.printStackTrace();
	 			}
	 			return st.nextToken();
		} long gcd(long a,long b){
			if(b==0) {
				return a;
			}
				
			return gcd(b,a%b);
		}
		int gcd(int a,int b) {
			if(a*b==0) {
				return a+b;
			}
			return gcd(b,a%b);
		}
	 	 long modPow(long base,long exp) {
			if(exp==0) {
				return 1;
			}
			if(exp%2==0) {
				long res=(modPow(base,exp/2));
				return (res*res);
			}
			return (base*modPow(base,exp-1));
		}
	 	long []reverse(long[] count){
			long b[]=new long[count.length];
			int index=0;
			for(int i=count.length-1;i>=0;i--) {
				b[index++]=count[i];
			}
			return b;
		}
	 	int []reverse(int[] count){
			int b[]=new int[count.length];
			int index=0;
			for(int i=count.length-1;i>=0;i--) {
				b[index++]=count[i];
			}
			return b;
		}
		int nextInt() {
			return Integer.parseInt(next());
		}
		long getMax(long a[],int n) {
			long max=Long.MIN_VALUE;
			for(int i=0;i<n;i++) {
				max=Math.max(a[i], max);
			}
				return max;
		}
		long[] readLongArray(int n) {
			long  [] a=new long  [n];
			for (int i=0; i<n; i++) a[i]=nextLong();
			return a;
		}int[] readArray(int n) {
			int  [] a=new int  [n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}
		long nextLong() {
			return Long.parseLong(next());
		}
		 boolean isPrime(long n)  {
	          if(n < 2) return false;
	          if(n == 2 || n == 3) return true;
	          if(n%2 == 0 || n%3 == 0) return false;
	          long sqrtN = (long)Math.sqrt(n)+1;
	          for(long i = 6L; i <= sqrtN; i += 6) {
	              if(n%(i-1) == 0 || n%(i+1) == 0) return false;
	          }
	          return true;
	      }
		 int sum(int a[]) {
			 int s=0;
			 for(int i=0;i<a.length;i++)s+=a[i];
			 return s;
		 }
		 long sum(long a[]) {
			 long s=0;
			 for(int i=0;i<a.length;i++)s+=a[i];
			 return s;
		 }
		
	}

	 static class triplet{
		 int x;
		 int y;
		 int z;
		triplet(int x,int y,int z){
			this.x=x;
			this.y=y;
			this.z=z;
		}
	} 
	 static class pair{
			int x;
			int y;
			pair( int x,int y){
				this.x=x;
				this.y=y;
			}
	 }
	 static Solve s=new Solve();
	 public static  void main(String []args) {
		int t=scr.nextInt();
		while(t-->0) {
			s.solve();
		}
		out.println(sb);
	}
	static class Solve {
		
		int MAX=Integer.MAX_VALUE;
		int MIN=Integer.MIN_VALUE;
		ArrayList<Integer>list[];
		long time[];
		boolean visited[];
		void solve() {
			char c[]=scr.next().toCharArray();
			char t[]=scr.next().toCharArray();
			int n=c.length;
			
			long ans=0;
			long cnt=0;
			long count=0;
			int total=0;
			boolean first=true;
			ArrayList<Long>a=new ArrayList<>();
			for(int i=0;i<n;i++) {
				if(c[i]==t[i]) {
					cnt++;
				}else {
					if(cnt!=0 && first==false) {
						a.add(cnt);
					}
					first=false;
					cnt=0;
					total++;
				}
			}
			Collections.sort(a);
			ans=total*(a.size()+1);
//			out.println(total);
			for(int i=0;i<a.size();i++) {
				long ele=(total+a.get(i))*(a.size()-i);
				total+=a.get(i);
				ans=Math.min(ele, ans);
			}
			out.println(ans);
		}
	}
}








Simple Operations CodeChef Solution in PYPY 3

#prevent copy clone duplicate
#Code Protector
# ()..() ()..()
import math
import os,sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

import math
for _ in range(int(input())):
    s=input()
    r=input()
    n=len(s)
    res=[]
    cl,fl=0,0
    z=0
    for i in range(n):
        if s[i]!=r[i]:
            if cl>0 and fl>0:
                res.append(cl)
                z+=cl
            cl=0
            fl=1
            z+=1
            continue
        cl+=1
    n=z
    res.sort(reverse=True)
    for i in range(len(res)):
        n-=res[i]
        z=min(z,(i+2)*n)
    print(z)

Simple Operations CodeChef Solution in PYTH

# cook your code here
t = int(raw_input())
for i in range(t):
	S = raw_input().strip()
	R = raw_input().strip()
	sz = len(S)
	p = 0
	while (p < sz) and (S[p] == R[p]):
		p += 1
	# endwhile
	if p == sz:
		r = 0
	else:
		q = sz-1
		while S[q] == R[q]:
			q -= 1
		# endwhile
		r = q+1-p
		s = 0
		c = 0
		ch = 1
		L = []
		for k in range(p,q+1):
			if S[k] == R[k]:
				if ch == 0:
					c += 1
				else:
					ch = 0
					c = 1
				# endif
			else:
				if ch == 0:
					ch = 1
					L.append(c)
					s += c
				# endif
			# endif
		# endfor k
		L.sort()
		L.reverse()
		sz = len(L)
		c = r-s
		mx = r/c -1
		mx = min(mx,sz)
		nc = r
		z = 1
		for k in range(mx):
			z += 1
			nc -= L[k]
			pr = z*nc
			if pr < r:
				r = pr
			# endif
		# endfor k
	# endif
	print r
# endfor i

Simple Operations CodeChef Solution in C#

using System;
using System.Collections.Generic;
using System.Linq;

public class Practice
{
    public static void Main()
    {
        var t = int.Parse(Console.ReadLine());
        for (int tt = 0; tt < t; ++tt)
        {
            var s = Console.ReadLine();
            var r = Console.ReadLine();
            var ss = 0; while (ss < s.Length && s[ss] == r[ss]) ++ss;
            if (ss == s.Length)
            {
                Console.WriteLine(0); continue;
            }

            var ee = s.Length - 1; while (s[ee] == r[ee]) --ee;
            int l0 = ee - ss + 1, best = l0, l = 0, cnt = 0;

            var map = new Dictionary<int, int>();
            while(++ss <= ee)
            {
                if (s[ss] == r[ss]) ++cnt;
                else if (cnt > 0)
                {
                    int oc; map.TryGetValue(cnt, out oc);
                    map[cnt] = oc + 1;
                    cnt = 0;
                }
            }

            var lst = map.Select(kvp => Tuple.Create(kvp.Key, kvp.Value)).ToList();
            lst.Sort();
            
            cnt = 2;
            while (lst.Count > 0 && cnt*cnt < best)
            {
                var it = lst[lst.Count - 1];
                l += it.Item1;
                var i2 = it.Item2 - 1;
                if (i2 > 0) lst[lst.Count - 1] = Tuple.Create(it.Item1, i2);
                else lst.RemoveAt(lst.Count - 1);
                var candidate = (l0 - l) * cnt;
                if (candidate < best) best = candidate;
                ++cnt;
            }
            Console.WriteLine(best);
        }
    }
}

Simple Operations CodeChef Solution in GO

package main

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

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--
		S, _ := reader.ReadString('\n')
		R, _ := reader.ReadString('\n')

		fmt.Println(solve(S, R))
	}
}

func solve(S, R string) int {
	n := len(S)

	var gaps []int

	prev := -1

	var l int

	for i := 0; i < n; i++ {
		if S[i] == R[i] {
			continue
		}
		l++
		// S[i] != R[i]
		if prev < 0 {
			prev = i
			continue
		}
		gaps = append(gaps, i-prev-1)
		prev = i
	}
	if l == 0 {
		return 0
	}

	k := l
	res := int64(l) * int64(k)

	sort.Ints(gaps)

	for i := 0; i < len(gaps); i++ {
		cur := gaps[i]

		l += cur
		k--

		res = min(res, int64(k)*int64(l))
	}

	return int(res)
}

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

In our experience, we suggest you solve this Simple Operations 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 Simple Operations CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Simple Operations 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 *