Description
小凸和小方是好朋友,小方给小凸一个N*M(N<=M)的矩阵A,要求小秃从其中选出N个数,其中任意两个数字不能在同一行或同一列,现小凸想知道选出来的N个数中第K大的数字的最小值是多少。
1<=K<=N<=M<=250,1<=矩阵元素<=10^9
来自 https://www.lydsy.com/JudgeOnline/problem.php?id=4443
Solution
第k大可以是第n-k+1小,那么二分答案把不大于mid的点行列连边,若最大匹配数>n-k+1就可行,否则扩大二分下界
Code
#include <stdio.h>
#include <string.h>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
#define fill(x,t) memset(x,t,sizeof(x))
const int N=200005;
const int E=800005;
const int L=505;
struct edge {int x,y,next;} e[E];
int rc[L][L];
int ls[N],edCnt;
int vis[N],link[N];
void add_edge(int x,int y) {
e[++edCnt]=(edge) {x,y,ls[x]}; ls[x]=edCnt;
e[++edCnt]=(edge) {y,x,ls[y]}; ls[y]=edCnt;
}
bool find(int x,int id) {
for (int i=ls[x];i;i=e[i].next) {
if (vis[e[i].y]==id) continue;
vis[e[i].y]=id;
if (find(link[e[i].y],id)||!link[e[i].y]) {
link[e[i].y]=x;
return true;
}
}
return false;
}
int hungary(int n) {
fill(link,0);
fill(vis,0);
int ret=0;
rep(i,1,n) ret+=find(i,i);
return ret;
}
void build_graph(int n,int m,int lim) {
fill(ls,0); edCnt=0;
rep(i,1,n) rep(j,1,m) if (rc[i][j]<=lim) add_edge(i,j+n);
}
int main(void) {
int n,m,k; scanf("%d%d%d",&n,&m,&k); k=n-k+1;
rep(i,1,n) rep(j,1,m) scanf("%d",&rc[i][j]);
int ans=0;
for (int l=0,r=1000000000;l<=r;) {
int mid=(l+r)>>1;
build_graph(n,m,mid);
int ret=hungary(n);
if (ret>=k) r=mid-1,ans=mid;
else l=mid+1;
}
printf("%d\n", ans);
return 0;
}