题目描述:
给出 n*m 个数
每一行和每一列只能选一个数,求能选出最小的第K个数是什么
题目分析:
先二分K
S -> 每一行 cap=1
每一列 -> T cap=1
a[i][j]<=mid i->j+n cap=inf
然后判定即可
题目链接:
Ac 代码:
#include <cstdio>
#include <iostream>
#include <queue>
#include <cstring>
#define il inline
using namespace std;
const int inf=0x7fffffff;
const int maxm=260*260;
int head[1100],to[maxm*2],cap[maxm*2],net[maxm*2],deep[1100],cnt=1;
il void add(int x,int y,int c){cnt++,to[cnt]=y,cap[cnt]=c,net[cnt]=head[x],head[x]=cnt;}
queue <int> dl;
int n,m,k,num[251][251];
il bool BFS(int s,int t)
{
while(!dl.empty()) dl.pop();
memset(deep,-1,sizeof(deep));
dl.push(s),deep[s]=0;
while(!dl.empty())
{
int x=dl.front();dl.pop();
for(int i=head[x];i;i=net[i])
if(cap[i]>0&&deep[to[i]]==-1)
dl.push(to[i]),deep[to[i]]=deep[x]+1;
}
return deep[t]==-1?0:1;
}
int dfs(int now,int flow,int t)
{
if(now==t) return flow;
int w,used=0;
for(int i=head[now];i;i=net[i])
{
int v=to[i];
if(deep[v]==deep[now]+1&&cap[i])
{
w=dfs(v,min(flow-used,cap[i]),t);
cap[i]-=w;
cap[i^1]+=w;
used+=w;
if(used==flow) return flow;
}
}
if(!used) deep[now]=-1;
return used;
}
il int dinic(int s,int t)
{
int maxflow=0;
while(BFS(s,t)) maxflow+=dfs(s,inf,t);
return maxflow;
}
inline void adx(int x,int y,int cax)
{
add(x,y,cax),add(y,x,0);
}
il bool check(int mid)
{
//printf("%d\n",mid);
memset(head,0,sizeof(head));
cnt=1;
int s=0,t=n+m+10;
for(int i=1;i<=n;i++)
adx(s,i,1);
for(int j=1;j<=m;j++)
adx(j+n,t,1);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(num[i][j]<=mid) adx(i,j+n,inf);
return dinic(s,t)>=n-k+1;
}
int main()
{
scanf("%d%d%d",&n,&m,&k);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
scanf("%d",&num[i][j]);
int l=0,r=1e9+1;
while(l<=r)
{
int mid=(l+r)>>1;
//printf("%d\n",check(mid));
if(check(mid)) r=mid-1;
else l=mid+1;
}
printf("%d\n",l);
return 0;
}