首先二分一个答案,然后将男孩和女孩都拆为2个点,源点s向男孩1连一条容量为二分值的边,女孩2向汇点连一条容量为二分值的边,男孩1向男孩2连容量为k的边,男孩1向喜欢的女孩1连容量为1的边,男孩2向不喜欢的女孩2连一条容量为1的边,女孩2向女孩1连一条容量为k的边,若最大流 >= n * 二分值,说明可行。
代码:
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 500 + 10;
const int maxm = 300000;
struct Edge
{
int pos,c;
int next;
}E[maxm];
int head[maxn];
int dis[maxn],gap[maxn],pre[maxn],cur[maxn];
bool flag[maxn][maxn];
int s,t,NE,nodenum;
int n,m,k;
int T;
bool che;
void init()
{
freopen("hust1024.in","r",stdin);
freopen("hust1024.out","w",stdout);
}
inline void checkmin(int &a,int b)
{
if(a == -1 || a > b)a = b;
}
void add(int u,int v,int c)
{
E[NE].pos = v;E[NE].c = c;
E[NE].next = head[u];head[u] = NE++;
E[NE].pos = u;E[NE].c = 0;
E[NE].next = head[v];head[v] = NE++;
}
int sap()
{
memset(dis,0,sizeof(dis));
memset(gap,0,sizeof(gap));
for(int i = s;i <= t;i++)cur[i] = head[i];
int u = pre[s] = s,maxflow = 0,aug = -1;
gap[0] = nodenum;
while(dis[s] < nodenum)
{
loop: for(int &i = cur[u];i != -1;i = E[i].next)
{
int v = E[i].pos;
if(E[i].c && dis[u] == dis[v] + 1)
{
checkmin(aug,E[i].c);
pre[v] = u;
u = v;
if(v == t)
{
maxflow += aug;
for(u = pre[u];v != s;v = u,u = pre[u])
{
E[cur[u]].c -= aug;
E[cur[u]^1].c += aug;
}
aug = -1;
}
goto loop;
}
}
int mind = nodenum;
for(int i = head[u];i != -1;i = E[i].next)
{
int v = E[i].pos;
if(E[i].c && (mind > dis[v]))
{
cur[u] = i;
mind = dis[v];
}
}
if((--gap[dis[u]]) == 0)break;
gap[dis[u] = mind + 1]++;
u = pre[u];
}
return maxflow;
}
bool check(int p)
{
memset(E,0,sizeof(E));
memset(head,-1,sizeof(head));
for(int i = 1;i <= n;i++)
{
add(s,i,p);
add(i,i + n,k);
for(int j = 1;j <= n;j++)
{
if(flag[i][j])add(i,j + 2 * n,1);
else add(i + n,j + 3 * n,1);
}
add(i + 3 * n,i + 2 * n,k);
add(i + 2 * n,t,p);
}
if(sap() >= n * p)return true;
else return false;
}
void solve()
{
int l = 0,r = n;
while(l <= r)
{
int m = (l + r) >> 1;
if(check(m))l = m + 1;
else r = m - 1;
}
printf("%d\n",r);
}
void readdata()
{
scanf("%d",&T);
while(T--)
{
memset(flag,false,sizeof(flag));
che = false;
scanf("%d%d%d",&n,&m,&k);
s = 0,t = n * 4 + 1,NE = 0;
nodenum = t + 1;
for(int i = 1;i <= m;i++)
{
int a,b;
scanf("%d%d",&a,&b);
flag[a][b] = true;
}
solve();
}
}
int main()
{
init();
readdata();
return 0;
}