[SCOI2015]小凸玩矩阵
Description
小凸和小方是好朋友,小方给小凸一个N*M(N<=M)的矩阵A,要求小秃从其中选出N个数,其中任意两个数字不能在同一行或同一列,现小凸想知道选出来的N个数中第K大的数字的最小值是多少。
Input
第一行给出三个整数N,M,K
接下来N行,每行M个数字,用来描述这个矩阵
Output
如题
Sample Input
3 4 2
1 5 6 6
8 3 4 3
6 8 6 3
Sample Output
3
HINT
1<=K<=N<=M<=250,1<=矩阵元素<=10^9
求第\(k\)大不如求第\(n-k+1\)小,我们考虑二分答案,对于所有点权小于二分出的值的点,将其所在行向所在列连一条流量为1的边,源点向所有行连一条流量为1的边,所有列向汇点连一条流量为1的边,如果最大流\(\geqslant n-k+1\),则下调二分上界,否则上调二分下界
/*program from Wolfycz*/
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 0x7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
inline char gc(){
static char buf[1000000],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
}
inline int frd(){
int x=0,f=1; char ch=gc();
for (;ch<'0'||ch>'9';ch=gc()) if (ch=='-') f=-1;
for (;ch>='0'&&ch<='9';ch=gc()) x=(x<<3)+(x<<1)+ch-'0';
return x*f;
}
inline int read(){
int x=0,f=1; char ch=getchar();
for (;ch<'0'||ch>'9';ch=getchar()) if (ch=='-') f=-1;
for (;ch>='0'&&ch<='9';ch=getchar()) x=(x<<3)+(x<<1)+ch-'0';
return x*f;
}
inline void print(int x){
if (x<0) putchar('-'),x=-x;
if (x>9) print(x/10);
putchar(x%10+'0');
}
const int N=2.5e2,M=7e4;
int pre[(M<<1)+10],now[(N<<1)+10],child[(M<<1)+10],val[(M<<1)+10];
int v[N+10][N+10],h[(N<<1)+10],deep[(N<<1)+10];
int n,m,k,S,T,tot;
void join(int x,int y,int z){pre[++tot]=now[x],now[x]=tot,child[tot]=y,val[tot]=z;}
void insert(int x,int y,int z){join(x,y,z),join(y,x,0);}
bool bfs(){
int head=1,tail=1;
memset(deep,255,sizeof(deep));
deep[h[head]=S]=0;
for (;head<=tail;head++){
int Now=h[head];
for (int p=now[Now],son=child[p];p;p=pre[p],son=child[p]){
if (!~deep[son]&&val[p]){
deep[h[++tail]=son]=deep[Now]+1;
if (son==T) return 1;
}
}
}
return 0;
}
int dfs(int x,int v){
if (x==T) return v;
int res=0;
for (int p=now[x],son=child[p];p;p=pre[p],son=child[p]){
if (deep[son]>deep[x]&&val[p]){
int t=dfs(son,min(v,val[p]));
val[p]-=t,v-=t;
val[p^1]+=t,res+=t;
if (!v) break;
}
}
if (!res) deep[x]=-1;
return res;
}
bool check(int limit){
memset(now,0,sizeof(now)),tot=1;
int Ans=0;
for (int i=1;i<=n;i++) insert(S,i,1);
for (int i=1;i<=m;i++) insert(i+n,T,1);
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
if (v[i][j]<=limit)
insert(i,j+n,1);
while (bfs()) Ans+=dfs(S,inf);
return Ans>=k;
}
int main(){
n=read(),m=read(),k=n-read()+1,S=n+m+1,T=S+1;
for (int i=1;i<=n;i++) for (int j=1;j<=m;j++) v[i][j]=read();
int l=1,r=1e9;
while (l<=r){
int mid=(l+r)>>1;
if (check(mid)) r=mid-1;
else l=mid+1;
}
printf("%d\n",l);
return 0;
}