Team Formation


Problem Statement :


For an upcoming programming contest, Roy is forming some teams from the students of his university. A team can have any number of contestants.

Roy knows the skill level of each contestant. To make the teams work as a unit, he forms the teams based on some rules. Each of the team members must have a unique skill level for the team. If a member's skill level is  where , there exists another team member whose skill level is . Note that a contestant can write buggy code and thus can have a negative skill level.

The more contestants on the team, the more problems they can attempt at a time so Roy wants to form teams such that the smallest team is as large as possible.


Input Format

The first line contains an integer , the number of test cases.

Each of the next  lines contains a string of space-separated integers,  followed by  integers , a list of the contestants' skill levels.


Output Format

For each test case, print the size of largest possible smallest team on a separate line.



Solution :



title-img


                            Solution in C :

In  C :





#include<stdio.h>
void merge(int a[],int low,int p,int high)
{
	int n,m,i,j,k,c[100000];
	n=p-low+1;
	m=high-p;
	if(n>0 || m>0)
	{
		i=low;
		j=p+1;
		k=low;
		//printf("%d %d\n",n,m);
		while(i<=p && j<=high)
		{
			while(a[i]<=a[j] && i<=p && j<=high)
			{
				c[k++]=a[i++];
			}
			while(a[i]>=a[j] && i<=p && j<=high)
			{
				c[k++]=a[j++];
			}
		}
		if(i<=p)
		{
			while(i<=p)
			{
				c[k++]=a[i++];
			}
		}
		if(j<=high)
		{
			while(j<=high)
			{
				c[k++]=a[j++];
			}
		}
		for(i=low;i<=high;i++)
		{
			a[i]=c[i];
			//printf("%d ",a[i]);
		}
		//printf("\n");
	}
	else
	{
		return;
	}
}
void mergesort(int a[],int low,int high)
{
	int p,i;
	if(high>low)
	{
		p=(low+high)/2;
		mergesort(a,low,p);
		mergesort(a,p+1,high);
		//printf("here is the %d %d %d\n",low,p,high);
		merge(a,low,p,high);
	}
	else
	{
		return;
	}
}
int main()
{
	int a[100000],i,n,b[100010],precount,count,j,k,counter,t,t1=0,min;
	scanf("%d",&t);
	while(t1<t)
	{
	scanf("%d",&n);
	for(i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
	}
	mergesort(a,0,n-1);

	precount=0;
	count=0;
	j=-1;
	for(i=0;i<n+10;i++)
	{
        b[i]=0;
	}
	i=0;
	while(i<n-1)
	{
        if(a[i]==a[i+1])
        {
            count++;
        }
        else
        {
            count++;
            if(count<=precount)
            {
                k=j;
            }
            else // count>precount
            {
                j+=count-precount;
                k=j;
            }
            counter=0;
            while(counter<count)
            {
                b[k--]++;
                counter++;
            }
            precount=count;
            count=0;
            if(a[i]!=(a[i+1]-1))
            {
                precount=0;
            }
        }
        i++;
	}

	for(i=0;i<=j;i++)
	{
        //printf("%d %d\n",i,b[i]);
	}
	//printf("after\n");
	if(n>1)
	{
        if(a[n-2]==a[n-1])
        {
            count++;
            if(count<=precount)
            {
                k=j;
            }
            else // count>precount
            {
                j+=count-precount;
                k=j;
            }
            counter=0;
            while(counter<count)
            {
                b[k--]++;
                counter++;
            }
        }
        else if(a[n-2]==a[n-1]-1)
        {
            b[j]++;
        }
        else
        {
            b[++j]++;
        }
    }
    min=1000000000;
	for(i=0;i<=j;i++)
	{
        //printf("%d %d\n",i,b[i]);
        if(min>b[i])
        {
            min=b[i];
        }
	}
    if(n==0)
    {
        min=0;    
    }
	if(n==1)
	{
        min=1;
	}
	printf("%d\n",min);
	t1++;
	}
	return 0;
}
                        


                        Solution in C++ :

In  C++  :






#include <cstdio>
#include <set>
#include <algorithm>
using namespace std;

const int NMAX = 100010;

int T, N, V[NMAX], Ans;
multiset<pair<int,int> > S;

int main()
{
   // freopen("c.in", "r", stdin);
  //  freopen("c.out", "w", stdout);

    scanf("%i", &T);
    for(; T; T --)
    {
        scanf("%i", &N);
        for(int i = 1; i <= N; ++ i)
            scanf("%i", &V[i]);

        sort(V + 1, V + N + 1);

        S.clear();
        S.insert(make_pair(V[1] - 1, 0));
        Ans = 0x3f3f3f3f;

        for(int i = 1; i <= N; ++ i)
        {
            while(!S.empty() && S.begin() -> first < V[i] - 1)
            {
                Ans = min(Ans, S.begin() -> second);
                S.erase(S.begin());
            }

            if(S.empty())
                S.insert(make_pair(V[i], 1));
            else
            {
                if(S.begin() -> first == V[i])
                    S.insert(make_pair(V[i], 1));
                else
                {
                    int Nr = S.begin() -> second;
                    S.erase(S.begin());
                    S.insert(make_pair(V[i], Nr + 1));
                }
            }
        }

        while(!S.empty())
        {
            Ans = min(Ans, S.begin() -> second);
            S.erase(S.begin());
        }

        printf("%i\n", Ans);
    }
}
                    


                        Solution in Java :

in   Java :







import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Queue;

public class Solution {
	static InputStream is;
	static PrintWriter out;
	static String INPUT = "";
	
	static void solve()
	{
		for(int T = ni();T >= 1;T--){
			int n = ni();
			int[] a = na(n);
			if(n == 0){
				out.println(0);
				continue;
			}
			Arrays.sort(a);
			Queue<Integer> q = new ArrayDeque<Integer>();
			int f = 0;
			int prev = -1999999999;
			int min = 1999999999;
			for(int i = 0;i < n;){
				int j = i;
				for(;j < n && a[i] == a[j];j++);
				int cf = j-i;
				if(prev+1 < a[i]){
					for(int k = 0;k < f;k++){
						min = Math.min(min, prev-q.poll()+1);
					}
					for(int k = 0;k < cf;k++){
						q.add(a[i]);
					}
				}else{
					if(cf > f){
						for(int k = f;k < cf;k++){
							q.add(a[i]);
						}
					}else{
						for(int k = cf;k < f;k++){
							min = Math.min(min, a[i]-q.poll());
						}
					}
				}
				prev = a[i];
				f = cf;
				i = j;
			}
			for(int k = 0;k < f;k++){
				min = Math.min(min, prev-q.poll()+1);
			}
			out.println(min);
		}
	}
	
	public static void main(String[] args) throws Exception
	{
		long S = System.currentTimeMillis();
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);
		
		solve();
		out.flush();
		long G = System.currentTimeMillis();
		tr(G-S+"ms");
	}
	
	private static boolean eof()
	{
		if(lenbuf == -1)return true;
		int lptr = ptrbuf;
		while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
		
		try {
			is.mark(1000);
			while(true){
				int b = is.read();
				if(b == -1){
					is.reset();
					return true;
				}else if(!isSpaceChar(b)){
					is.reset();
					return false;
				}
			}
		} catch (IOException e) {
			return true;
		}
	}
	
	private static byte[] inbuf = new byte[1024];
	static int lenbuf = 0, ptrbuf = 0;
	
	private static int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}
	
	private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
	
	private static double nd() { return Double.parseDouble(ns()); }
	private static char nc() { return (char)skip(); }
	
	private static String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}
	
	private static char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}
	
	private static char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}
	
	private static int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}
	
	private static int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}
		
		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}
	
	private static long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}
		
		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}
	
	private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}
                    


                        Solution in Python : 
                            
In  Python3 :






import collections
import itertools

def answer(skills):
    if not skills:
        return 0

    finished_team_lengths = []
    current_team_starts = collections.deque()

    def go(s, c):
        while len(current_team_starts) < c:
            current_team_starts.append(s)
        while len(current_team_starts) > c:
            finished_team_lengths.append(s - current_team_starts.popleft())

    last_s = skills[0] - 1
    for s, g in itertools.groupby(skills):
        if s > last_s + 1:
            go(last_s + 1, 0)
        go(s, sum(1 for _ in g))
        last_s = s
    go(last_s + 1, 0)

    return min(finished_team_lengths)

t = int(input())
for i in range(t):
    print(answer(sorted(map(int, input().split()[1:]))))
                    


View More Similar Problems

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →