LUOGU P4251 [SCOI2015]小凸玩矩阵
解题思路
二分图匹配,首先二分一个答案,然后对于权值小于这个答案的,行向列连边,然后跑最大匹配,如果最大匹配数>n-k,说明权值比它小的也一定可以满足答案,就缩小边界,时间复杂度O(nmlog(nm))
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdlib>
using namespace std;
const int MAXN = 255;
inline int rd(){
int x=0,f=1;char ch=getchar();
while(!isdigit(ch)) {f=ch=='-'?0:1;ch=getchar();}
while(isdigit(ch)) {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
return f?x:-x;
}
int n,m,k,w[MAXN*MAXN];
int a[MAXN][MAXN],tot,ans,now;
int head[MAXN*MAXN],cnt;
int vis[MAXN*MAXN],num,match[MAXN*MAXN];
int to[MAXN*MAXN<<1],nxt[MAXN*MAXN<<1];
inline void add(int bg,int ed){
to[++cnt]=ed,nxt[cnt]=head[bg],head[bg]=cnt;
}
bool dfs(int x){
for(register int i=head[x];i;i=nxt[i]){
int u=to[i];
if(vis[u]!=num){
vis[u]=num;
if(!match[u] || dfs(match[u])){
match[u]=x;
return true;
}
}
}
return false;
}
inline bool check(int Mid){
memset(head,0,sizeof(head));
memset(match,0,sizeof(match));
ans=cnt=0;
for(register int i=1;i<=n;i++)
for(register int j=1;j<=m;j++)
if(a[i][j]<=Mid) add(i,j);
for(register int i=1;i<=n;i++){
num++;
if(dfs(i)) ans++;
}
if(ans>n-k) return true;
return false;
}
int main(){
n=rd(),m=rd(),k=rd();
for(register int i=1;i<=n;i++)
for(register int j=1;j<=m;j++){
a[i][j]=rd();
w[++tot]=a[i][j];
}
sort(w+1,w+1+tot);
int l=1,r=tot,mid;
while(l<=r){
mid=l+r>>1;
if(check(w[mid])) {
now=mid;
r=mid-1;
}
else l=mid+1;
}cout<<w[now]<<endl;
return 0;
}