Chef Likes Good Sequences CodeChef Solution

Problem -Chef Likes Good Sequences 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 Likes Good Sequences CodeChef Solution in C++17

#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace chrono;
using namespace __gnu_pbds;

#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> //find_by_order,order_of_key
#define int               long long
#define pb                push_back
#define ppb               pop_back
#define pf                push_front
#define ppf               pop_front
#define fr               first
#define sc                second
#define all(x)            (x).begin(),(x).end()
#define uniq(v)           (v).erase(unique(all(v)),(v).end())
#define sz(x)             (int)((x).size())
#define pii               pair<int,int>
#define rep(i,a,b)        for(int i=a;i<b;i++)
#define mem1(a)           memset(a,-1,sizeof(a))
#define mem0(a)           memset(a,0,sizeof(a))
#define ppc               __builtin_popcount
#define ppcll             __builtin_popcountll


template<typename T> istream &operator>>(istream &input, vector<T> &v) {for (auto &it : v) input >> it; return input;}
template<typename T> ostream &operator<<(ostream &output, vector<T> &v) {for (auto &it : v) output << it << " "; return output;}
template<typename T, typename T1>T amax(T &a, T1 b) {if (b > a)a = b; return a;}
template<typename T, typename T1>T amin(T &a, T1 b) {if (b < a)a = b; return a;}

const int32_t M = 1e9 + 7;
const int32_t MM = 998244353;
const int N = 1e6 + 7;
const int INF = 1e17;
const int dx[4] {1, 0, -1, 0}, dy[4] {0, 1, 0, -1};

#ifndef ONLINE_JUDGE
#include "debug.h"
#else 
#define debug(x)
#endif

void Solve() {
    int n,q;
    cin >> n >> q;
    vector<int> v(n);
    cin >> v;
    int tot_cnt = 1;
    for(int i = 1;i<n;i++){
        if(v[i] != v[i-1]) tot_cnt++;
    }
    for(int i = 0;i < q;i++){
        int idx,x;
        cin >> idx >> x;
        --idx;
        int cnt = 0;
        if(n == 1){
            cout << 1 <<'\n';
            continue;
        }
        if(idx==0){
            if(v[idx] != v[idx + 1]) cnt++;
        }
        else if(idx != 0 and idx == n-1){
            if(v[idx] != v[idx - 1]) cnt++;
        }
        else{
            if(v[idx] != v[idx + 1]) cnt++;
            if(v[idx] != v[idx - 1]) cnt++;
        }
        tot_cnt-=cnt;
        cnt = 0;
        v[idx] = x;
        if(idx==0){
            if(v[idx] != v[idx + 1]) cnt++;
        }
        else if(idx != 0 and idx == n-1){
            if(v[idx] != v[idx - 1]) cnt++;
        }
        else{
            if(v[idx] != v[idx + 1]) cnt++;
            if(v[idx] != v[idx - 1]) cnt++;
        }
        tot_cnt+=cnt;
        cout << tot_cnt <<'\n';
    }
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
#ifndef ONLINE_JUDGE
    freopen("Error.txt", "w", stderr);
#endif
    int t = 1;
    cin >> t;
    while (t--) {
        Solve();
    }
    return 0;
}

Chef Likes Good Sequences CodeChef Solution in C++14

#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);

//   /freopen("alimagde.in","r",stdin);

    ll t;
    cin>>t;
    while(t--)
    {

        ll n,m;
        cin>>n>>m;
        vector<ll>v;
        ll a,x,y;
        for(ll i=1; i<=n; i++) cin>>a,v.push_back(a);
        ll ans=1;
        for(ll i = 1 ; i<n; i++)
        {
            if(v[i]!=v[i-1])
                ans++;
        }
        for(ll i=0; i<m; i++)
        {
            cin>>x>>y;
            x--;
            ll cur=1;
            if(x+1<n and v[x]!=v[x+1])
                cur++;
            if(x-1>=0 and v[x]!=v[x-1])
                cur++;

            ll now=1;
            v[x]=y;
            if(x+1<n and v[x]!=v[x+1])
                now++;
            if(x-1>=0 and v[x]!=v[x-1])
                now++;
            ans-=cur;
            ans+=now;
            cout<<ans<<'\n';
        }

    }
}

Chef Likes Good Sequences CodeChef Solution in PYTH 3

# cook your dish here
tc = int(input())

while tc > 0:
    n,q = map(int,input().split())
    arr = [int(i) for i in input().split()]
    currlen = 1
    i = 1
    while i<n:
        if arr[i] != arr[i-1]:
            currlen += 1
        else:
            while i<n and arr[i] == arr[i-1]:
                i += 1
            if i<n:
                currlen += 1
        i += 1
    while q>0:
        x,y = map(int,input().split())
        if arr[x-1] == y:
            print(currlen)
        else:
            p = ne = 0
            p += 1 if (x-1)>0 and arr[x-1] != arr[x-2] else 0
            p +=1 if (x-1)<(n-1) and arr[x-1] != arr[x] else 0
            arr[x-1] = y
            ne += 1 if (x-1)>0 and arr[x-1] != arr[x-2] else 0
            ne += 1 if (x-1)<(n-1) and arr[x-1] != arr[x] else 0
            currlen = currlen - p + ne
            print(currlen)
            
        q -= 1
    tc -= 1

Chef Likes Good Sequences CodeChef Solution in C

#include<stdio.h>
#include<stdlib.h>
typedef long long int ll;
int main()
{
    int t,i;
    scanf("%d",&t);
    for(i=0;i<t;i++)
    {
        ll n,q,*arr,j,x,y,count=1;
        scanf("%lld%lld",&n,&q);
        arr=(ll *)malloc(n*sizeof(ll));
        for(j=0;j<n;j++)
        {
            scanf("%lld",&arr[j]);
            if(j!=0)
            {
                if(arr[j]!=arr[j-1])
                {
                    count++;                //count initial length of subsequence;
                }
            }
        }
        for(j=0;j<q;j++)
        {
            scanf("%lld%lld",&x,&y);
            if(y==arr[x-1])                 //there is no change in the array after introducing y at x;
            {
                printf("%lld\n",count);
                continue;
            }
            else
            {
                if(arr[x-1]==arr[x-2] && arr[x-1]==arr[x])  //both neighbours are equal to arr[x] ,  
                {                                            // comes in same segment, then,
                    if(y!=arr[x-1])                          //middle is different and divide one segment
                    {                                        // into three of different elements
                        count+=2;
                    }
                }
                else if(arr[x-1]==arr[x-2] && arr[x-1]!=arr[x])  // arr[x] is identical to its left neighbour
                {                                                // means two segment , divide it into three. 
                    if(y!=arr[x-1] && y!=arr[x])
                    {
                        count++;
                    }
                }
                else if(arr[x-1]!=arr[x-2] && arr[x-1]==arr[x]) // arr[x] is identical to its right neighbour.
                {
                    if(y!=arr[x-1] && y!=arr[x-2])
                    {
                        count++;
                    }
                }
                else if(arr[x-1]!=arr[x-2] && arr[x-1]!=arr[x])  // when arr[x] is different from its neighbour
                {                                               
                    if(y==arr[x-2] && y==arr[x])
                    {
                        count-=2;
                    }
                    else if(y==arr[x-2] && y!=arr[x])
                    {
                        count--;
                    }
                    else if(y==arr[x] && y!=arr[x-2])
                    {
                        count--;
                    }
                }
                arr[x-1]=y;     // change the array after every query
                 printf("%lld\n",count);
            }
           
        }
    }
    return 0;
}

Chef Likes Good Sequences CodeChef Solution in JAVA

/* package codechef; // don't place package name! */

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
{
    static class Reader {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;
  
        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }
  
        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(
                new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }
  
        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1) {
                if (c == '\n') {
                    if (cnt != 0) {
                        break;
                    }
                    else {
                        continue;
                    }
                }
                buf[cnt++] = (byte)c;
            }
            return new String(buf, 0, cnt);
        }
  
        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
  
            if (neg)
                return -ret;
            return ret;
        }
  
        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }
  
        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
  
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
  
            if (c == '.') {
                while ((c = read()) >= '0' && c <= '9') {
                    ret += (c - '0') / (div *= 10);
                }
            }
  
            if (neg)
                return -ret;
            return ret;
        }
  
        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0,
                                 BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }
  
        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }
  
        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		Reader sc =new Reader();
        int t = sc.nextInt();
        while(t-->0)
       {
            int n = sc.nextInt();
            int q = sc.nextInt();
            int arr[] = new int[n+2];
            int ans=0;
            for(int i=1;i<=n;i++){
                arr[i] =sc.nextInt();
                ans = arr[i]==arr[i-1] ? ans : ans+1;
            }
            StringBuilder sb = new StringBuilder();
            while( q-- > 0){
                int x= sc.nextInt();
                int y = sc.nextInt();
                
                if(arr[x] != y){
                    // 2 2 3 -> 2 3 3 same, 2 4 3 +1
                    if(arr[x]!=arr[x-1])
                        ans--;
                    if(arr[x]!=arr[x+1])
                        ans--;
                    if(y!=arr[x-1])
                        ans++;
                    if(y!=arr[x+1])
                        ans++;
                        
                    arr[x] = y;
                }
                sb.append(ans+"\n");
            }
            System.out.print(sb.toString());
       }
	}
}

Chef Likes Good Sequences CodeChef Solution in PYPY 3

import sys
#from collections import deque
#from functools import *
#from fractions import Fraction as f
from copy import *
from bisect import *	
#from heapq import *
from math import gcd,ceil,sqrt
from itertools import permutations as prm,product
 
def eprint(*args):
    print(*args, file=sys.stderr)
zz=1
 
#sys.setrecursionlimit(10**6)
if zz:
	input=sys.stdin.readline
else:	
	sys.stdin=open('input.txt', 'r')
	sys.stdout=open('all.txt','w')
di=[[-1,0],[1,0],[0,1],[0,-1]]

def string(s):
	return "".join(s)
def fori(n):
	return [fi() for i in range(n)]	
def inc(d,c,x=1):
	d[c]=d[c]+x if c in d else x
def bo(i):
	return ord(i)-ord('A')	
def li():
	return [int(xx) for xx in input().split()]
def fli():
	return [float(x) for x in input().split()]	
def comp(a,b):
	if(a>b):
		return 2
	return 2 if a==b else 0		
def gi():	
	return [xx for xx in input().split()]
def cil(n,m):
	return n//m+int(n%m>0)	
def fi():
	return int(input())
def pro(a): 
	return reduce(lambda a,b:a*b,a)		
def swap(a,i,j): 
	a[i],a[j]=a[j],a[i]	
def si():
	return list(input().rstrip())	
def mi():
	return 	map(int,input().split())			
def gh():
	sys.stdout.flush()
def isvalid(i,j,n,m):
	return 0<=i<n and 0<=j<m 
def bo(i):
	return ord(i)-ord('a')	
def graph(n,m):
	for i in range(m):
		x,y=mi()
		a[x].append(y)
		a[y].append(x)



t=fi()
							 		
while t>0:
	t-=1
	n,q=mi()
	a=li()
	ans=0
	for i in range(n):
		if i==0:
			ans+=1
		elif a[i]!=a[i-1]:
			ans+=1	
	for i in range(q):
		x,val=mi()
		x-=1
		if a[x]==val:
			print(ans)
			continue
		else:
			if x>0 and a[x-1]==val:
				ans-=1
			if x<n-1 and a[x+1]==val:
				ans-=1
			if x>0 and a[x-1]==a[x]:
				ans+=1
			if x<n-1 and a[x+1]==a[x]:
				ans+=1
			print(ans)
			a[x]=val	

Chef Likes Good Sequences CodeChef Solution in PYTH

t = int(raw_input())
for i in range(t):
	st = raw_input().split()
	N = int(st[0])
	Q = int(st[1])
	st = raw_input().split()
	A = [-1]
	for x in st:
		n = int(x)
		A.append(n)
	# endfor x
	tot = 0
	for k in range(1,N+1):
		if A[k] <> A[k-1]:
			tot += 1
		# endif
	# endfor k
	A.append(-1)
	for k in range(Q):
		st = raw_input().split()
		x = int(st[0])
		y = int(st[1])
		if A[x] <> y:
			if A[x] <> A[x-1]:
				tot -= 1
			# endif
			if A[x] <> A[x+1]:
				tot -= 1
			# endif
			A[x] = y
			if A[x] <> A[x-1]:
				tot += 1
			# endif
			if A[x] <> A[x+1]:
				tot += 1
			# endif
		# endif
		print tot
	# endfor k
# endfor i

Chef Likes Good Sequences CodeChef Solution in C#

using System;
using System.Text;

public class Test
{
	public static void Main()
	{
	    int test = int.Parse(Console.ReadLine());
	    StringBuilder sb = new StringBuilder();
	    for(int i=0;i<test;++i){
	        string[] values = Console.ReadLine().Split(' ');
	        int n = int.Parse(values[0]);
	        int q = int.Parse(values[1]);
	        int[] arr = new int[n+2];
	        arr[0] = -1;
	        arr[n+1] = -1;
	        values = Console.ReadLine().Split(' ');
	        for(int j=1;j<=n;++j){
	            arr[j] = int.Parse(values[j-1]);
	        }
	        long totalCount = 2;
	        for(int j=1;j<=n;++j){
	            if(arr[j-1] != arr[j]){
	                totalCount++;
	            }
	        }
	        for(int j=0;j<q;++j){
	            values = Console.ReadLine().Split(' ');
	            int index = int.Parse(values[0]);
	            int valueAtIndex = int.Parse(values[1]);
	            if(arr[index] == valueAtIndex){
	                sb.Append((totalCount-2)+"\n");
	            }
	            else{
                    if(arr[index-1] == arr[index+1] && arr[index] == arr[index-1]
                        && arr[index] == arr[index+1]){
                        totalCount+=2;
                    }
                    else if(arr[index] == arr[index+1] && valueAtIndex != arr[index-1]){
                        totalCount+=1;
                    }
                    else if(arr[index] == arr[index-1] && valueAtIndex != arr[index+1]){
                        totalCount+=1;
                    }
                    if(valueAtIndex == arr[index-1] && arr[index] != arr[index+1]){
                        totalCount -= 1;
                    }
                    if(valueAtIndex == arr[index+1] && arr[index] != arr[index-1]){
                        totalCount -= 1;
                    }
	                arr[index] = valueAtIndex;
	                sb.Append((totalCount-2)+"\n");
	            }
	        }
	    }
	    Console.WriteLine(sb.ToString());
	}
}

Chef Likes Good Sequences CodeChef Solution in GO

package main

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

const N = 100010

var arr [N]int
var bak [N]int

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

	tc := readNum(reader)
	var buf bytes.Buffer
	for tc > 0 {
		tc--
		n, q := readTwoNums(reader)
		A := readNNums(reader, n)
		solver := NewSolver(n, A)
		for q > 0 {
			q--
			x, y := readTwoNums(reader)
			res := solver.Update(x, y)
			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 := bak[: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
}

type Solver struct {
	arr []int
	cur int
	n   int
}

func NewSolver(n int, A []int) Solver {
	var ans = 2
	arr := make([]int, n+2)
	copy(arr[1:], A)
	arr[0] = -1
	arr[n+1] = -1

	for i := 1; i <= n; i++ {
		if arr[i] != arr[i-1] {
			ans++
		}
	}

	return Solver{arr, ans, n}
}

func max(a, b int) int {
	if a >= b {
		return a
	}
	return b
}

func (solver *Solver) Update(x int, y int) int {
	arr := solver.arr
	cur := solver.cur

	if arr[x] == y {
		// no change
		return cur - 2
	}

	if arr[x] == arr[x-1] && arr[x] == arr[x+1] {
		cur += 2
	} else if (arr[x] != arr[x-1]) && (arr[x] == arr[x+1]) {
		cur++
		if y == arr[x-1] {
			cur--
		}
	} else if arr[x] == arr[x-1] && arr[x] != arr[x+1] {
		cur++
		if y == arr[x+1] {
			cur--
		}
	} else {
		// arr[x] != arr[x-1] && arr[x] != arr[x+1]
		if y == arr[x-1] {
			cur--
		}
		if y == arr[x+1] {
			cur--
		}
	}

	arr[x] = y

	solver.cur = cur
	return cur - 2
}
Chef Likes Good Sequences CodeChef Solution Review:

In our experience, we suggest you solve this Chef Likes Good Sequences 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 Likes Good Sequences CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Chef Likes Good Sequences 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 *