Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 6898 | Accepted: 2260 |
Description
Input
Output
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
题意:有N个人和M个小组,要求每一个人只能属于一个小组,现在已经给出每个人可以归属的小组编号(从0到M-1)。设所有小组中人数的 最多的小组所拥有的人数为IT,现在让你求最小的IT。
思路:二分枚举 + 最大流,枚举所有小组中人数最多的小组所拥有的人数,对当前枚举的mid值。建图如下:
1,超级源点到每个人引一条边,容量为1,表示一个人只能属于一个小组;
2,每个人向他所属的小组建边,容量为1;
3,所有小组向超级汇点建边,容量为mid。
最后跑一遍最大流,判断是否满流,若满流向左区间查找,反之向右区间查找。
AC代码:
#include
#include
#include
#include
#include
#include
#define MAXN 1600
#define MAXM 1200000+10
#define INF 0x3f3f3f3f
using namespace std;
struct Edge
{
int from, to, cap, flow, next;
};
Edge edge[MAXM], Redge[MAXM];
int head[MAXN], edgenum, Rhead[MAXN], Redgenum;
int dist[MAXN], cur[MAXN];
bool vis[MAXN];
int source, sink;//超级源点 超级汇点
int N, M;
void init()
{
edgenum = 0;
memset(head, -1, sizeof(head));
}
void addEdge(int u, int v, int w)
{
Edge E1 = {u, v, w, 0, head[u]};
edge[edgenum] = E1;
head[u] = edgenum++;
Edge E2 = {v, u, 0, 0, head[v]};
edge[edgenum] = E2;
head[v] = edgenum++;
}
void getMap()
{
source = 0, sink = N+M+1;
char str[20];
for(int i = 1; i <= N; i++)
{
addEdge(source, i, 1);//源点向每个人 建边 容量为1
scanf("%s", str);
int a;
while(getchar() != '\n')
{
scanf("%d", &a);
addEdge(i, a + N + 1, 1);//每个人向 所属小组建边
}
}
}
bool BFS(int s, int t)
{
queue Q;
memset(dist, -1, sizeof(dist));
memset(vis, false, sizeof(vis));
dist[s] = 0;
vis[s] = true;
Q.push(s);
while(!Q.empty())
{
int u = Q.front();
Q.pop();
for(int i = head[u]; i != -1; i = edge[i].next)
{
Edge E = edge[i];
if(!vis[E.to] && E.cap > E.flow)
{
dist[E.to] = dist[u] + 1;
vis[E.to] = true;
if(E.to == t) return true;
Q.push(E.to);
}
}
}
return false;
}
int DFS(int x, int a, int t)
{
if(x == t || a == 0) return a;
int flow = 0, f;
for(int &i = cur[x]; i != -1; i = edge[i].next)
{
Edge &E = edge[i];
if(dist[E.to] == dist[x] + 1 && (f = DFS(E.to, min(a, E.cap-E.flow), t)) > 0)
{
edge[i].flow += f;
edge[i^1].flow -= f;
flow += f;
a -= f;
if(a == 0) break;
}
}
return flow;
}
int Maxflow(int s, int t)
{
int flow = 0;
while(BFS(s, t))
{
memcpy(cur, head, sizeof(head));
flow += DFS(s, INF, t);
}
return flow;
}
int main()
{
while(scanf("%d%d", &N, &M), N||M)
{
init();
getMap();
memcpy(Rhead, head, sizeof(head));
memcpy(Redge, edge, sizeof(edge));
Redgenum = edgenum;
int left = 0, right = N, ans = N;
while(right >= left)
{
int mid = (left + right) >> 1;
memcpy(edge, Redge, sizeof(Redge));//copy 数组
memcpy(head, Rhead, sizeof(Rhead));
edgenum = Redgenum;
for(int i = 1; i <= M; i++)//枚举枚举都要建边
addEdge(i + N, sink, mid);
if(Maxflow(source, sink) == N)//判断是否满流
{
ans = min(ans, mid);
right = mid - 1;
}
else
left = mid + 1;
}
printf("%d\n", ans);
}
return 0;
}