无法直接构造最大流来解决这个问题,因为题目要求每首舞曲都需要n对男女进行跳舞。
答案又满足单调性,这启发我们二分答案,判断是否满流验证答案。
假设舞曲数目为x时满足条件,那么每个男生和女生都需要跳x次舞。 连边(s,男i,x), (女i,t,x)来进行限制。
同时要求每个男生最多可以和k个不喜欢的女生跳舞,女生同样。那么把男生和女生拆成两个点,分别表示和喜欢的人跳舞,和不喜欢的人跳舞。
那么连边(男i,男i',k),(女i',女i,k)来进行限制。
同样的一对男女只准跳一次。那么将边容量设为1即可限制。构图完毕后跑最大流就行了。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# include <cstdio> # include <cstring> # include <cstdlib> # include <iostream> # include <vector> # include <queue> # include <stack> # include <map> # include <set> # include <cmath> # include <algorithm> using namespace std; # define lowbit(x) ((x)&(-x)) # define pi 3.1415926535 # define eps 1e-9 # define MOD 100000007 # define INF 1000000000 # define mem(a,b) memset(a,b,sizeof(a)) # define FOR(i,a,n) for(int i=a; i<=n; ++i) # define FO(i,a,n) for(int i=a; i<n; ++i) # define bug puts("H"); # define lch p<<1,l,mid # define rch p<<1|1,mid+1,r # define mp make_pair # define pb push_back typedef pair<int,int> PII; typedef vector<int> VI; # pragma comment(linker, "/STACK:1024000000,1024000000") typedef long long LL; int Scan() { int res=0, flag=0; char ch; if((ch=getchar())=='-') flag=1; else if(ch>='0'&&ch<='9') res=ch-'0'; while((ch=getchar())>='0'&&ch<='9') res=res*10+(ch-'0'); return flag?-res:res; } void Out(int a) { if(a<0) {putchar('-'); a=-a;} if(a>=10) Out(a/10); putchar(a%10+'0'); } const int N=55; //Code begin... char str[N][N]; struct Edge{int p, next, w;}edge[N*N*10]; int head[N*5], cnt=2, s, t, n, k, vis[N*5]; queue<int>Q; void add_edge(int u, int v, int w){ edge[cnt].p=v; edge[cnt].w=w; edge[cnt].next=head[u]; head[u]=cnt++; edge[cnt].p=u; edge[cnt].w=0; edge[cnt].next=head[v]; head[v]=cnt++; } int bfs() { int i, v; mem(vis,-1); vis[s]=0; Q.push(s); while (!Q.empty()) { v=Q.front(); Q.pop(); for (i=head[v]; i; i=edge[i].next) { if (edge[i].w>0 && vis[edge[i].p]==-1) { vis[edge[i].p]=vis[v] + 1; Q.push(edge[i].p); } } } return vis[t]!=-1; } int dfs(int x, int low) { int i, a, temp=low; if (x==t) return low; for (i=head[x]; i; i=edge[i].next) { if (edge[i].w>0 && vis[edge[i].p]==vis[x]+1){ a=dfs(edge[i].p,min(edge[i].w,temp)); temp-=a; edge[i].w-=a; edge[i^1].w += a; if (temp==0) break; } } if (temp==low) vis[x]=-1; return low-temp; } bool check(int x){ mem(head,0); cnt=2; s=0, t=4*n+1; FOR(i,1,n) add_edge(s,i,x), add_edge(3*n+i,t,x), add_edge(i,n+i,k), add_edge(2*n+i,3*n+i,k); FOR(i,1,n) FOR(j,1,n) { if (str[i][j]=='Y') add_edge(i,3*n+j,1); else add_edge(n+i,2*n+j,1); } int temp, sum=0; while (bfs()) while (temp=dfs(s,INF)) sum+=temp; return sum==x*n; } int main () { scanf("%d%d",&n,&k); FOR(i,1,n) scanf("%s",str[i]+1); int l=0, r=n+1, mid; while (l<r) { mid=(l+r)>>1; if (l==mid) break; if (check(mid)) l=mid; else r=mid; } printf("%d ",l); return 0; }