poj2289 Jamie's Contact Groups(二分答案+最大流)

老套路了。

#include 
#include 
#include 
#include 
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 2010
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x*f;
}
int n,m,h[N],num=1,lev[N],T=2001,tot=0;
char s[20];
struct edge{
    int to,next,val;
}data[1100000];
inline void add(int x,int y,int val){
    data[++num].to=y;data[num].next=h[x];h[x]=num;data[num].val=val;
    data[++num].to=x;data[num].next=h[y];h[y]=num;data[num].val=0;
}
inline bool bfs(){
    queue<int>q;memset(lev,0,sizeof(lev));
    lev[0]=1;q.push(0);
    while(!q.empty()){
        int x=q.front();q.pop();
        for(int i=h[x];i;i=data[i].next){
            int y=data[i].to;if(lev[y]||!data[i].val) continue;
            lev[y]=lev[x]+1;q.push(y);
        }
    }return lev[T];
}
inline int dinic(int x,int low){
    if(x==T) return low;int tmp=low;
    for(int i=h[x];i;i=data[i].next){
        int y=data[i].to;if(lev[y]!=lev[x]+1||!data[i].val) continue;
        int res=dinic(y,min(tmp,data[i].val));
        if(!res) lev[y]=0;tmp-=res;data[i].val-=res;data[i^1].val+=res;
        if(!tmp) return low;
    }return low-tmp;
}
inline bool jud(int x){
    num=1;int ans=0;
    for(int i=1;i<=m;++i) data[++num].val=x,data[++num].val=0;
    for(int i=1;i<=n;++i) data[++num].val=1,data[++num].val=0;
    while(num1,data[++num].val=0;
    while(bfs()) ans+=dinic(0,inf);
    return ans==n;
}
int main(){
//  freopen("a.in","r",stdin);
    while(1){
        n=read();m=read();if(!n&&!m) break;
        memset(h,0,sizeof(h));num=1;
        for(int i=1;i<=m;++i) add(i+n,T,0);
        for(int i=1;i<=n;++i) add(0,i,1);
        for(int i=1;i<=n;++i){
            scanf("%s",s+1);int x=0;
            while(1){scanf("%d",&x);add(i,n+x+1,1);char op=getchar();if(op=='\n'||op=='\r') break;}
        }int l=n/m,r=n;tot=num;
        while(l<=r){
            int mid=l+r>>1;
            if(jud(mid)) r=mid-1;
            else l=mid+1;
        }printf("%d\n",r+1);
    }return 0;
}

你可能感兴趣的:(二分答案,其他oj,-----网络流-------,最大流)