【网络流专题6】 公平分配问题
Ahead
11.1.2018
例题
UVALive 3231
二分+网络流
对源点到每一个工作建1的边,工作向机器建1的边,机器向汇点建k的边。 二分枚举k 如果醉倒流能到达m则r=mid 否则l=mid+1
代码
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int s = 100000,t = 100001;
const int N = 200000,inf = 0x3f3f3f3f;
int n,m;
int to[N<<1],nxt[N<<1],last[N],w[N<<1],len=1;
inline void ins(int x,int y,int c)
{
to[++len]=y,nxt[len]=last[x],w[len]=c,last[x]=len;
}
int h[N];
bool vis[N];
bool bfs()
{
memset(h,0,sizeof(h));
queue <int> q;
vis[s]=1;
q.push(s);
h[s]=1;
while(!q.empty())
{
int x = q.front();
q.pop();
vis[x]=0;
for(int k=last[x]; k; k=nxt[k])
{
int y=to[k];
if(w[k] && !h[y])
{
h[y] = h[x] + 1 ;
if(!vis[y])
{
vis[y]=1;
q.push(y);
}
}
}
}
return h[t]!=0;
}
int dfs(int x,int flow)
{
if(x==t) return flow;
int res=flow;
for(int k=last[x]; k; k=nxt[k])
{
int y=to[k];
if(w[k] && h[y] == h[x]+1)
{
int t = dfs(y,min(w[k],res));
w[k]-=t;
w[k^1]+=t;
res-=t;
if(res==0) break;
}
}
if(res==flow) h[x]=0;
return flow-res;
}
inline int dinic()
{
int maxflow=0;
while(bfs())
{
int tmp = dfs(s,inf);
while(tmp)
{
maxflow += tmp;
tmp = dfs(s,inf);
}
}
return maxflow;
}
inline void _clear()
{
len=1;
memset(last,0,sizeof(last));
}
int st;
bool check(int x)
{
for(int i=2; i<=st; i+=2) w[i]=1,w[i^1]=0;
for(int i=st+1; i<=len; i+=2) w[i]=x,w[i^1]=0;
int tmp = dinic();
if(tmp<m) return false ;
else return true;
}
int main()
{
int T,x,y;
scanf("%d",&T);
while(T--)
{
_clear();
scanf("%d%d",&n,&m);
for(int i=1; i<=m; ++i) ins(s,i,1),ins(i,s,0);
for(int i=1; i<=m; ++i)
{
scanf("%d%d",&x,&y);
ins(i,m+x,1),ins(m+x,i,0);
ins(i,m+y,1),ins(m+y,i,0);
}
st=len;
for(int i=1; i<=n; ++i) ins(m+i,t,1),ins(t,m+i,0);
int l=1,r=m;
while(l<r)
{
int mid=(l+r)>>1;
if(check(mid)) r=mid;
else l=mid+1;
}
printf("%d\n",l);
}
return 0;
}