1669 Jamie's Contact Groups
題面:
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. Input
分析及思路:
典型的二分圖多重匹配問題,注意每個聯絡人只需要知道編號就行,不需要名字,建圖後跑二分圖最大匹配即可,由於要求最大值的最小化,可以用二分答案的方法優化時間複雜度。 AC程式碼:
#include<iostream>
#include<sstream>
#include<cstring>
#define rep(i,x,n) for(int i=x;i<n;i++)
#define per(i,x,n) for(int i=n-1;i>=x;i--)
using namespace std;
//head
const int maxn=1006;
int n,m,nx,ny,r,l,limit,vis[maxn],mp[maxn][maxn],cy[maxn][maxn],vcy[maxn];
bool findpath(int x)
{
rep(i,0,m)
{
if(mp[x][i]&&vis[i]==0)
{
vis[i]=1;
if(vcy[i]<limit)
{
cy[i][vcy[i]++]=x;
return 1;
}
rep(j,0,vcy[i])
{
if(findpath(cy[i][j]))
{
cy[i][j]=x;
return 1;
}
}
}
}
return 0;
}
bool match()
{
memset(vcy,0,sizeof(vcy));
rep(i,0,n)
{
memset(vis,0,sizeof(vis));
if(!findpath(i))return 0;
}
return 1;
}
int main()
{
char str[20];int tmp;char q;
while(scanf("%d%d",&n,&m),m+n)
{
memset(mp,0,sizeof(mp));
if(n==0&&m==0)break;
rep(i,0,n)
{
scanf("%s",str);
while(1)
{
scanf("%d%c",&tmp,&q);
mp[i][tmp]=1;
if(q == '\n')
break;
}
}
l=1,r=n;
while(l<r)
{
limit=(l+r)/2;
if(match())r=limit;
else l=limit+1;
}
printf("%d\n",r);
}
return 0;
}