当前位置: 代码迷 >> 综合 >> poj 2289 二分图多重匹配
  详细解决方案

poj 2289 二分图多重匹配

热度:5   发布时间:2023-11-18 03:42:37.0

                                                                                                                  题目链接点击打开链接

Jamie's Contact Groups
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 8121   Accepted: 2723

Description

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

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.

Output

For each test case, output a line containing a single integer, the size of the largest contact group.

Sample Input

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

Sample Output

2
2

Source

Shanghai 2004

题目大意:将n个联系人分配到m个组,然后找到一个最小的limit值值得该二分图可以完全匹配

这道题要用二分搜索,否则会超时,然后再套上二分搜索模板就可以解决

#include<iostream>
#include<string.h>
#include<string>
#include<stdio.h>
using namespace std;
int n,m;
int map[1010][510];
bool check[510];
int cnt[510];
int cy[510][1010];
int y;
int limit;
string str;
bool dfs(int x)
{for(int j=0;j<m;j++){if(map[x][j]&&!check[j]){check[j]=true;if(cnt[j]<limit){cy[j][++cnt[j]]=x;return true;}for(int k=1;k<=cnt[j];k++){if(dfs(cy[j][k])){cy[j][k]=x;return true;}}}}return false;
}
bool solve()
{memset(cnt,0,sizeof(cnt));for(int i=0;i<n;i++){memset(check,false,sizeof(check));if(!dfs(i))return false;}return true;
}
int main()
{while(cin>>n>>m){if(n==0&&m==0)break;memset(map,0,sizeof(map));for(int i=0;i<n;i++){cin>>str;while(getchar()!='\n'){cin>>y;map[i][y]=1;}}int left=0;int right=n;while(left<right){limit=(left+right)/2;if(solve())right=limit;elseleft=limit+1;}cout<<left<<endl;}return 0;
}