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

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →