Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Connecting Soldiers CodeChef Solution

Problem -Connecting Soldiers 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.

Connecting Soldiers CodeChef Solution in C++14

#include <bits/stdc++.h>
using namespace std;
int find_min (int n)
{
 int st, ed;
 
 if (n == 0)
  return 0;
 else
 {
  if (n%2==1)
   st = ed = n/2;
  else
  {
   st = n/2 - 1;
   ed = n/2;
  }
  return ((n+1) + find_min(st) + find_min(ed));
 }
}
 
int main ()
{
 int  m, n, mn, mx;
 int t;cin>>t;
 
 while(t--){
  cin>>n>>m;
  
  mn = find_min(n);
  mx = n* (n + 3) / 2;
  
  if (m < mn)
   cout<<"-1"<<endl;
  else if (m > mx)
   cout<<(m - mx)<<endl;
  else
   cout<<"0"<<endl;
 }
 
 return 0;}

Connecting Soldiers CodeChef Solution in PYTH 3

def min_length(k):
    if(k==0):
        return 0
    if(k==1):
       return 2
    else:
        return k+1+min_length((k-1)//2)+min_length((k-1)-(k-1)//2)
        
t=int(input())
for i in range(t):
    n,m=[int(x) for x in input().split()]
    if(m<min_length(n)):
        print(-1)
    elif(m>n*(n+3)/2):
        print(m-(n*(n+3)//2))
    else:
        print(0)

Connecting Soldiers CodeChef Solution in C

#include <stdio.h>

int fun(int n)
{
    int a,b;
    
    if(n==0)
    {
        return 0;
    }
    
    else if(n & 1)
    {
        a=b=n/2;
    }
    
    else
    {
        a=n/2;
        b=n/2-1;
    }
    
    return (n+1 +fun(a)+fun(b));
}

int main(void)
{
	int t;
	scanf("%d",&t);
	
	while(t--)
	{
	    int n,m;
	    scanf("%d %d",&n,&m);
	    
	    
	    int min=fun(n);
	    
	    int max=n*(n+3)/2;
	    
        if (m< min)
            printf ("-1\n");
        
        else if (m > max)
            printf ("%d\n", (m - max));
        
        else
            printf ("0\n");
	        
	}
	return 0;
}

Connecting Soldiers CodeChef Solution in JAVA

import java.io.*;
import java.util.*;
class NOKIA {
	static class FastReader{
		BufferedReader br; StringTokenizer st;
		public FastReader(){
			br=new BufferedReader(new InputStreamReader(System.in)); }
		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()); }
	}
	public static void main(String[] args) {
		FastReader in=new FastReader();
		PrintWriter out=new PrintWriter(System.out);
		int t=in.nextInt();
		while(t-->0) {
			int n=in.nextInt(),
				m=in.nextInt(),
				mi=min(n),
				ma=(n+2)*(n+1)/2-1;
			out.println(m<mi?-1:m>ma?m-ma:0);
		} out.close();
	}
	private static int min(int n) {
		return n==0?0: n==1?2: n+1 + min(n/2) + min((n-1)/2);
	}
}

Connecting Soldiers CodeChef Solution in PYPY 3

def min_length(k):
    if(k==0):
        return 0
    if(k==1):
       return 2
    else:
        return k+1+min_length((k-1)//2)+min_length((k-1)-(k-1)//2)
        
t=int(input())
for i in range(t):
    n,m=[int(x) for x in input().split()]
    if(m<min_length(n)):
        print(-1)
    elif(m>n*(n+3)/2):
        print(m-(n*(n+3)//2))
    else:
        print(0)

Connecting Soldiers CodeChef Solution in PYTH

def findMin(n):
    if n==0:
        return 0
    if n==1:
        return 2
    if n%2==0:
        mid = n/2
    else:
        mid = (n+1)/2
    length = 0
    length = (n+1)+findMin(mid-1)+findMin(n-mid)
    return length

t= int(raw_input().strip())
n,m = [],[]
for ti in range(t):
    ni,mi = map(int,raw_input().strip().split(' '))
    n.append(ni)
    m.append(mi)

for index, ni in enumerate(n):
    min = findMin(ni)
    max = ni*(ni+3)/2
    if m[index] < min:
        print(-1)
        continue
    if m[index] >= min and m[index] <=max:
        print(0)
    else:
        print(m[index]-max)
    
    

        

Connecting Soldiers CodeChef Solution in C#

using System;

public class Test
{
    private static int max_len(int first,int last)
    {
        if(last-first<=1)
        {
            return 0;
        }
        else
        {
            int pos=first+1;
           
           
          return (last-pos+1)+max_len(pos,last);
        }
    }
    private static int min_len(int first,int last)
    {
        
        if(last-first<=1)
        {
            return 0;
        }else if(last-first==2){return 2;}
        else
        {
            
           int mid=0;
           if((1+last)%2==0)
           {
               mid=((1+last)/2);
              
               return (mid-first)+(last-mid)+min_len(0,mid)+min_len(0,last-mid);
           }
           else{
                mid=((1+last-1)/2);
                
                return (mid-first)+(last-mid)+min_len(0,mid)+min_len(0,last-mid);
           }
          
           
        }
    }
    
    
    
	public static void Main()
	{
	   	 int tests=int.Parse(Console.ReadLine());
	   	 for(int i=0;i<tests;i++)
	   	 {
	   	     string input=Console.ReadLine();
	   	     string[] inputs=input.Split(' ');
	   	     int n=int.Parse(inputs[0]);
	   	     int wire=int.Parse(inputs[1]);
	   	     int min=0;
	   	     int max=0;
	   	     min=min_len(0,n+1);
	   	     max=max_len(0,n+1);
	   	    if(min>wire)
	   	     {
	   	        Console.WriteLine("-1");
	   	     }
	   	     else if(min<=wire && max>wire)
	   	     {
	   	         Console.WriteLine("0");
	   	     }
	   	     else if(max<=wire)
	   	     {
	   	          Console.WriteLine(wire-max);
	   	     }
	   	 }
	}
}

Connecting Soldiers CodeChef Solution in NODEJS

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

let input_stdin = "";
let input = "";
let input_currentline = 0;

function readLine() {
    return input[input_currentline++];
}

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input = input_stdin.split("\n");
    main();
});

// your code goes here
function main() {
    const T=parseInt(readLine());
    for(let k = 0; k < T; k++) {
        const firstLine = readLine();
        const N = parseInt(firstLine.split(" ")[0]);
        const M = parseInt(firstLine.split(" ")[1]);
        
        let m1 = min(N);
        let m2 = ((N + 1) * (N + 2) ) / 2 - 1;
        if (m1 <= M && M <= m2) {
            console.log(0);
        }
        else if (m2 < M) {
            console.log(M-m2);
        }
        else {
            console.log(-1);
        }
        /*for (let i = 0; i <= N; i++) {
            console.log(M - (N + 1) - left(i, i - 1, M - (i) - (N + 1 - i)) - left(i, N - i, M - (i) - (N + 1 - i)) );
        }*/


    }
}

function min(N, memo) {
    memo = memo || {};
    if (memo[N]) {
        return memo[N];
    }
    if (N===1) {
        memo[N] = 2
        return memo[N];
    }
    if (N < 1) {
        memo[N] = 0
        return memo[N];
    }
    else {
        memo[N] = N + 1 + min(Math.floor((N - 1) / 2)) + min(Math.ceil((N - 1) / 2));
        return memo[N];
    }
}


function left(i,N,M) {
    if (N == 1) {
        console.log(`left(${i},${N},${M}): ${M >= 2 ? M - 2 : NaN}`);
        return M >= 2 ? M - 2 : NaN;
    }
     if (N == 0) {
        console.log(`left(${i},${N},${M}): 0`);
        return 0;
    }

    let minLeft;
    for (let i = 1; i <= N; i++) {
        let l1 = left(i, i - 1, M - (i) - (N + 1 - i))
        let l2 = left(i, N - i, M - (i) - (N + 1 - i))
        let current = M - (N + 1) - l1 -l2;
        if ( (l1 * l2 >= 0 && current < minLeft) || !minLeft ) {
            minLeft = current;
        }
    }
    console.log(`left(${i},${N},${M}): ${minLeft}`);
    return minLeft
}

Connecting Soldiers CodeChef Solution in GO

package main

import (
	"fmt"
)

func minVal(a, b int) int {
	if a <= b {
		return a
	}
	return b
}

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

func maxV(arr []int) (max int) {
	max = arr[0]
	for _, val := range arr {
		if val > max {
			max = val
		}
	}
	return max
}

var max [31]int
var min [31]int

func preCalculate() {
	for i := 0; i <= 30; i++ {
		max[i] = i * (i + 3) / 2
	}
	min[0] = 0
	min[1] = 2
	min[2] = 5
	for i := 3; i < 31; i++ {
		min[i] = min[i/2] + min[i-(i/2)-1] + i + 1
	}
	// fmt.Println(min, max)
}

func main() {
	var t int
	fmt.Scan(&t)
	preCalculate()
	for qt := 0; qt < t; qt++ {
		var n, m int
		fmt.Scan(&n, &m)
		if min[n] > m {
			fmt.Println(-1)
		} else if max[n] < m {
			fmt.Println(m - max[n])
		} else {
			fmt.Println(0)
		}
	}
}
Connecting Soldiers CodeChef Solution Review:

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

Find on CodeChef

Conclusion:

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