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

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →