Jamie is a very popular girl and has quite a lot of friends, so she always keeps a very long contact list in her cell phone. The contact list has become so long that it often takes a long time for her to browse through the whole
list to find a friend's number. As Jamie's best friend and a programming genius, you suggest that she group the contact list and minimize the size of the largest group, so that it will be easier for her to search for a friend's number among the groups. Jamie
takes your advice and gives you her entire contact list containing her friends' names, the number of groups she wishes to have and what groups every friend could belong to. Your task is to write a program that takes the list and organizes it into groups such
that each friend appears in only one of those groups and the size of the largest group is minimized.
There will be at most 20 test cases. Ease case starts with a line containing two integers N and M. where N is the length of the contact list and M is the number of groups. N lines then follow. Each line contains a friend's name
and the groups the friend could belong to. You can assume N is no more than 1000 and M is no more than 500. The names will contain alphabet letters only and will be no longer than 15 characters. No two friends have the same name. The group label is an integer
between 0 and M - 1. After the last test case, there is a single line `0 0' that terminates the input.
For each test case, output a line containing a single integer, the size of the largest contact group.
3 2 John 0 1 Rose 1 Mary 1 5 4 ACM 1 2 3 ICPC 0 1 Asian 0 2 3 Regional 1 2 ShangHai 0 2 0 0
2 2
题意:有n个人 m个组 求所有情况中最大组的最小值
解 :二分答案 ,设limit 为正确解
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
using namespace std;
int n,m,limit;
string s;
vector<int>g[1050];//每个人可以分为哪几组
int cnt[1050];//每一组人数
int a[1050][555];//每一组的人
int v[1050];//每个人是否已经有组
int dfs(int u)
{
int N=g[u].size();
for(int i=0;i<N;i++)
{
int p=g[u][i];
if(v[p]) continue;
v[p]=1;
if(cnt[p]<limit)//组未满把这个人加入组
{
a[p][cnt[p]++]=u;
return 1;
}
else
{
for(int j=0;j<cnt[p];j++)//组满员,是否有组员可以换到别的租
{
if(dfs(a[p][j]))
{
a[p][j]=u;
return 1;
}
}
}
}
return 0;
}
int hh()
{
memset(cnt,0,sizeof(cnt));
for(int i=1;i<=n;i++)
{
memset(v,0,sizeof(v));
if(!dfs(i)) return 0;
}
return 1;
}
int main()
{
while(~scanf("%d%d",&n,&m)&&n+m)
{
int d;
for(int i=1;i<=n;i++)
{
cin>>s;
while(getchar()!='\n')
{
scanf("%d",&d);
g[i].push_back(d);
}
}
int l=0,r=n;
while(l<r)//二分
{
limit=(l+r)/2;
if(hh())
r=limit;
else
l=limit+1;
}
printf("%d\n",r);
for(int i=1;i<=n;i++)
g[i].clear();
}
}