POJ 2289 Jamie's Contact Groups

时间:2020-12-09 03:01:55

二分答案+网络最大流

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std; int N,M;
const int maxn = + ;
const int INF = 0x7FFFFFFF;
struct Edge
{
int from, to, cap, flow;
Edge(int u, int v, int c, int f) :from(u), to(v), cap(c), flow(f){}
};
vector<Edge>edges;
vector<int>G[maxn];
bool vis[maxn];
int d[maxn];
int cur[maxn];
int n, m, s, t;
int U[maxn*],V[maxn*];
int tot;
int T[maxn];
char ss[maxn]; void init()
{
for(int i = ; i < maxn; i++) G[i].clear();
edges.clear();
tot=;
memset(T,,sizeof T);
} void AddEdge(int from, int to, int cap)
{
edges.push_back(Edge(from, to, cap, ));
edges.push_back(Edge(to, from, , ));
int w = edges.size();
G[from].push_back(w - );
G[to].push_back(w - );
} bool BFS()
{
memset(vis, , sizeof(vis));
queue<int>Q;
Q.push(s);
d[s] = ;
vis[s] = ;
while (!Q.empty())
{
int x = Q.front();
Q.pop();
for (int i = ; i<G[x].size(); i++)
{
Edge e = edges[G[x][i]];
if (!vis[e.to] && e.cap>e.flow)
{
vis[e.to] = ;
d[e.to] = d[x] + ;
Q.push(e.to);
}
}
}
return vis[t];
} int DFS(int x, int a)
{
if (x == t || a == )
return a;
int flow = , f;
for (int &i = cur[x]; i<G[x].size(); i++)
{
Edge e = edges[G[x][i]];
if (d[x]+ == d[e.to]&&(f=DFS(e.to,min(a,e.cap-e.flow)))>)
{
edges[G[x][i]].flow+=f;
edges[G[x][i] ^ ].flow-=f;
flow+=f;
a-=f;
if(a==) break;
}
}
if(!flow) d[x] = -;
return flow;
} int dinic(int s, int t)
{
int flow = ;
while (BFS())
{
memset(cur, , sizeof(cur));
flow += DFS(s, INF);
}
return flow;
} void Input()
{
int SS;
for(int i=;i<=N;i++)
{
gets(ss);
for(int ii=;ss[ii];ii++)
if(ss[ii]==' ')
{SS=ii;break;}
int num=;
for(int ii=SS+;;ii++)
{
if(ss[ii]>=''&&ss[ii]<='') num=num*+ss[ii]-'';
if(ss[ii]==' '||ss[ii]=='\0')
{
U[tot]=i;V[tot]=N+num+;tot++;
T[num]++;
num=;
}
if(ss[ii]=='\0') break;
}
}
} void Solve()
{
int Ma=-INF;
for(int i=;i<M;i++) if(T[i]>Ma) Ma=T[i];
int Min=,Max=Ma;
int Mid=(Min+Max)/;
s=;t=N+M+;
while()
{
for(int i = ; i < maxn; i++) G[i].clear();
edges.clear();
for(int i=;i<=N;i++) AddEdge(s,i,);
for(int i=;i<tot;i++) AddEdge(U[i],V[i],INF);
for(int i=N+;i<=N+M;i++) AddEdge(i,t,Mid);
if(dinic(s,t)<N)
{
Min=Mid+;
Mid=(Min+Max)/;
}
else
{
Max=Mid;
Mid=(Min+Max)/;
}
if(Min==Max) break;
}
printf("%d\n",Min);
} int main()
{
while(~scanf("%d%d",&N,&M))
{
if(!N&&!M) break;
scanf("\n");
init();
Input();
Solve();
}
return ;
}