最大流+二分答案,其实可以用贪心做但是……练习下网络流
代码中init是会WA的,请勿乱用读入优化
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<algorithm> #include<bitset> #define LL long long #define fo(i,a,b) for(int i=a;i<=b;i++) #define efo(i,x) for(int i=last[x];i!=0;i=e[i].next) using namespace std; inline LL read() { LL d=0,f=1;char s=getchar(); while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();} while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();} return d*f; } #define N 1005 #define inf 500 struct edge { int f,y,next; }e[500005]; int last[N*2],ne=1; int a[N*2][N*2]={0}; int n,m; void add(int x,int y,int f) { e[++ne].f=f;e[ne].y=y;e[ne].next=last[x];last[x]=ne; } void add2(int u,int v,int w) { add(u,v,w);add(v,u,0); } void build(int ans) { fo(i,1,n) { add2(0,i,ans); add2(i,i+inf,m); add2(n+i+inf,n+i,m); add2(n+i,2*inf+1,ans); fo(j,1,n) { if(a[i][j])add2(i,n+j,1); else add2(i+inf,n+j+inf,1); } } } int q[500005],level[2*N]; bool bfs(int s,int tt) { memset(level,0,sizeof(level)); level[s]=1; int h=0,t=1;q[1]=s; while(h<t) { int now=q[++h]; if(now==tt)return 1; efo(i,now) if(e[i].f&&level[e[i].y]==0) { q[++t]=e[i].y; level[e[i].y]=level[now]+1; } } return 0; } int dfs(int k,int maxf,int t) { if(t==k)return maxf; int ret=0,f; efo(i,k) if(e[i].f&&level[e[i].y]==level[k]+1) { f=dfs(e[i].y,min(maxf-ret,e[i].f),t); e[i].f-=f; e[i^1].f+=f; ret+=f; if(ret==maxf)return ret; } return ret; } int dinic() { int ans=0,s=0,t=2*inf+1; while(bfs(s,t))ans+=dfs(s,inf*inf,t); return ans; } bool judge(int ans) { memset(e,0,sizeof(e)); memset(last,0,sizeof(last)); ne=1; build(ans); int anss=dinic(); // cout<<ans<<' '<<anss<<endl; if(ans*n<=anss)return 1; else return 0; } void ini() { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) { char ch[51]; scanf("%s",ch); for(int j=1;j<=n;j++) if(ch[j-1]=='Y')a[i][j]=1; } } void init() { n=read(),m=read(); fo(i,1,n) { fo(j,1,n) { char s=getchar(); if(s=='Y')a[i][j]=1; } getchar(); } } int main() { init(); int l=0,r=50; while(l<r) { int mid=(l+r)>>1; if(judge(mid)) { if(l==mid)break; l=mid; } else r=mid; } cout<<l<<endl; return 0; }