Charges CodeChef Solution

Problem -Charges 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.
<<Previous CodeChef Problem Next Codechef Problem>>

Charges CodeChef Solution in C++17

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

int main() {
	// your code goes here
	int t;cin>>t;
	while(t--){
	    int n,k;cin>>n>>k;
	    string s;cin>>s;
	   // vector<int>v;
	   // for(int i=0;i<k;i++){
	   //     int a;cin>>a;v.push_back(a);
	   // }
	    int ans=0;
	    for(int i=0;i<n-1;i++){
	        if(s[i]!=s[i+1])ans++;
	        else ans+=2;
	    }
	    int x=0;
	    while(x<k){
	        int a;cin>>a;a--;
	        x++;
	        if(n==1){
	           cout<<0<<endl;continue;
	        }
	        if(a==0){
	            if(s[a]!=s[a+1])ans+=1;
	            else ans-=1;
	            s[a]=='1'?(s[a]='0'):(s[a]='1');
	        }
	        else if(a==n-1){
	            if(s[a]!=s[a-1])ans+=1;
	            else ans-=1;
	            s[a]=='1'?(s[a]='0'):(s[a]='1');
	        }
	        else{
	           if (s[a]!=s[a-1]  &&  s[a]!=s[a+1])ans+=2;
	           else if(s[a]==s[a+1] && s[a]==s[a-1])ans-=2;
	           else ans+=0;
	            s[a]=='1'?(s[a]='0'):(s[a]='1');
	        }
	        cout<<ans<<endl;
	    }
	    
	    
	    
	}
	return 0;
}

Charges CodeChef Solution in C++14

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

void findCharges(string S, int K, vector<int>& vec){
    
    int totdist = 0;
    for(int i=0; i<S.length()-1; i++){
        if(S[i] == S[i+1])
            totdist += 2;
        else
            totdist += 1;
    }
    
    for(int i=0; i<vec.size(); i++){
        
        int net = 0;
        if((vec[i] - 2) >= 0){
            if(S[vec[i] - 1] == S[vec[i] - 2])
                net -= 1;
            else
                net += 1;
        }
        
        if(vec[i] < S.length()){
            if(S[vec[i] - 1] == S[vec[i]])
                net -= 1;
            else
                net += 1;
        }
        
        totdist += net;
        cout<<totdist<<endl;
        if(S[vec[i] - 1] == '0')
            S[vec[i] - 1] = '1';
        else
            S[vec[i] - 1] = '0';
        
    }
    
}

int main() {
	
	int T;
	cin>>T;
	for(int i=0; i<T; i++){
	    
	    int N, K;
	    cin>>N>>K;
	    string S;
	    cin>>S;
	    vector<int> vec(K);
	    for(int j=0; j<K; j++)
	        cin>>vec[j];
	    findCharges(S, K, vec);
	}
	
	
	return 0;
}

Charges CodeChef Solution in PYTH 3

for _ in range(int(input())):
    n,k = map(int,input().split())
    s = input()
    q = list(map(int,input().split()))
    base,spaces = s[0],0
    for i in range(1,n):
        if s[i] == base:spaces+=2
        else:spaces+=1
        base = s[i]
    for i in q:
        if s[i-1]=="1":s = s[:i-1]+"0"+s[i:]
        else:s = s[:i-1]+"1"+s[i:]
        if i-1>0:
            if s[i-2] == s[i-1]:spaces+=1
            else:spaces-=1
        if i-1<n-1:
            if s[i] == s[i-1]:spaces+=1
            else:spaces-=1
        print(spaces)

Charges CodeChef Solution in C

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

int main()
{
    short int t;
    scanf("%hd",&t);
    for(int i=0;i<=t-1;i++)
    {
        int n,k,sum=0;
        scanf("%d %d",&n,&k);
        char *s=malloc(n*sizeof(char));
        scanf("%s",s);
        for(int j=1;j<=n-1;j++)
        {
            if(s[j]==s[j-1])
                sum=sum+2;
            else
                sum=sum+1;
        }
       
        for(int j=0;j<=k-1;j++)
        {
            int pos;
            scanf("%d",&pos);
           
           
           if (pos!=n)
           {
               if(s[pos-1]==s[pos])
               sum--;
               else
               sum++;
           }
           if(pos!=1)
           {
               if(s[pos-1]==s[pos-2])
               sum--;
               else
               sum++;
           }
            if(s[pos-1]=='0')
             s[pos-1]='1';
            else
             s[pos-1]='0';
           
           printf("%d\n",sum);
        }
        printf("\n");
    }

}

Charges 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
{
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		Scanner sc=new Scanner(System.in);
		int t=sc.nextInt();
		while(t-->0){
		    int n=sc.nextInt();
		    int k=sc.nextInt();
		    String str=sc.next();
		    char arr[]=str.toCharArray();
		    int sum=0;
		    for(int j=0;j<n-1;j++){
		        
		        if(arr[j]==arr[j+1])
		        sum=sum+2;
		        else
		        sum=sum+1;
		    }
		    for(int j=0;j<k;j++){
		       int a=sc.nextInt()-1;
		       if(a>0){
		           if(arr[a]==arr[a-1])
		           sum=sum-1;
		           else
		           sum=sum+1;
		       }
		       if(a<n-1)
		          if(arr[a]==arr[a+1])
		          sum=sum-1;
		          else
		          sum=sum+1;
		          System.out.println(sum);
		          if(arr[a]=='1')
		          arr[a]='0';
		          else
		          arr[a]='1';
		       
		    }
		    
		}
	}
}

Charges CodeChef Solution in PYPY 3

T = int(input())

for _ in range(T):
    N, K = map(int, input().split())
    S = list(input())
    Q = list(map(int, input().split()))
    
    d = 0
    
    for i in range(1, N):
        if S[i] == S[i-1]:
            d += 2
        else:
            d += 1
    
    for i in Q:
        i = i-1
        if S[i] == '0':
            S[i] = '1'
        else:
            S[i] = '0'
            
            
        if i+1 < N:
            if S[i+1] == S[i]:
                d += 1
            else:
                d -= 1
        if i-1 >= 0:
            if S[i-1] == S[i]:
                d += 1
            else:
                d -= 1
                
                
        print(d)
                

Charges 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])
	S = raw_input().strip()
	A = [0]
	for x in S:
		if x == '0':
			A.append(0)
		else:
			A.append(1)
		# endif
	# endfor x
	tot = 0
	for k in range(1,N):
		tot += (2 - abs(A[k]-A[k+1]))
	# endfor k
	st = raw_input().split()
	for x in st:
		p = int(x)
		if p > 1:
			tot -= (2 - abs(A[p]-A[p-1]))
		# endif
		if p < N:
			tot -= (2 - abs(A[p]-A[p+1]))
		# endif
		A[p] = 1-A[p]
		if p > 1:
			tot += (2 - abs(A[p]-A[p-1]))
		# endif
		if p < N:
			tot += (2 - abs(A[p]-A[p+1]))
		# endif
		print tot
	# endfor x
# endfor i

Charges CodeChef Solution in C#

using System;

public class Test
{
	public static void Main()
	{
		// your code goes here
		
		int test = Convert.ToInt32(Console.ReadLine());
		
		for(int i=1; i<=test; i++)
		{
		    int[] qus = Array.ConvertAll(Console.ReadLine().Split(), item => Convert.ToInt32(item));
		    
		    string charges = Console.ReadLine();
		    
		     string[] chargesArray = new string[qus[0]];
		     
		     int count =0;
		     
		     foreach(var num in charges)
		     {
		         chargesArray[count] = num.ToString();
		         count++;
		     }
		    
		    
		      int[] positions = Array.ConvertAll(Console.ReadLine().Split(), item => Convert.ToInt32(item));
		    //Calculate intial distance
		    
		    long distance = 0;
		    
		    for(int j=0 ; j< qus[0] -1; j++)
		    {
		        if(chargesArray[j] == chargesArray[j+1])
		            distance +=2;
		        else
		            distance +=1;
		        
		    }
		    
		    //Now calculating changes
		    
		    for(int j=0; j< positions.Length; j++)
		    {
		        int pos = positions[j] -1;
		        
		        chargesArray[pos] = chargesArray[pos] == "0"? "1" : "0";
		        
		        //Checking for the right side
		        
		        if(pos < qus[0] -1 )
		        {
		            if (chargesArray[pos +1] == chargesArray[pos] )
		                distance+=1;
		            else
		        
		             distance-=1;
		             
		        
		            
		        }
		        
		        
		        if(pos > 0 )
		        {
		            if(chargesArray[pos -1] == chargesArray[pos])
		                 distance+=1;
		            else
		        
		             distance-=1;
		             
		        
		            
		        }
		        
		        
		      
		        
		        Console.WriteLine(distance);
		    }
		}
	}

}

Charges 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, m := readTwoNums(reader)
		S, _ := reader.ReadBytes('\n')
		Q := readNNums(reader, m)
		res := solve(n, m, S, Q)
		for _, ans := range res {
			buf.WriteString(fmt.Sprintf("%d\n", ans))
		}
	}

	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
}

func solve(n, m int, S []byte, Q []int) []int {
	var tot int

	for i := 1; i < n; i++ {
		if S[i] != S[i-1] {
			tot++
		} else {
			tot += 2
		}
	}

	update := func(i int, mul int) {
		if i+1 < n {
			if S[i] != S[i+1] {
				// only one
				tot += mul
			} else {
				tot += 2 * mul
			}
		}
		if i > 0 {
			if S[i] != S[i-1] {
				tot += mul
			} else {
				tot += 2 * mul
			}
		}
	}

	res := make([]int, m)

	for i := 0; i < m; i++ {
		j := Q[i] - 1
		update(j, -1)
		if S[j] == '1' {
			S[j] = '0'
		} else {
			S[j] = '1'
		}
		update(j, 1)
		res[i] = tot
	}

	return res
}
Charges CodeChef Solution Review:

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

Find on CodeChef

Conclusion:

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