洛谷P3153[CQOI2009]跳舞
思路:
拆点+二分+最大流:
将男生,女生都拆成两个点,喜欢的点和不喜欢的点,二分答案
a
n
s
ans
ans。
S
S
S向男生的喜欢点连边,权值为
a
n
s
ans
ans;
男生喜欢的点向男生不喜欢的点连边,权值为
k
k
k;
女生不喜欢的点向女生喜欢的点连边,权值为
k
k
k;
女生喜欢的点向
T
T
T连边,权值为
a
n
s
ans
ans;
男生喜欢和不喜欢的点分别向女生喜欢不喜欢的点连边,权值为
1
1
1。
然后判断跑出来的值是否等于
a
n
s
∗
n
ans*n
ans∗n。
代码:
#include<bits/stdc++.h>
#define pii pair<int,int>
#define int long long
#define cl(x,y) memset(x,y,sizeof(x))
#define ct cerr<<"Time elapsed:"<<1.0*clock()/CLOCKS_PER_SEC<<"s.\n";
const int N=5e5+210;
const int M=1e2+10;
const int mod=1e9+7;
const int inf=0x3f3f3f3f;
const int minn=0xc0c0c0c0;
using namespace std;
struct edge
{
int u,v,w;
}maze[N<<1];
int len=1,head[N]={0};
int dep[N];//深度
void add(int u,int v,int w)
{
maze[++len]={head[u],v,w};
head[u]=len;
}
void inc(int u,int v,int w)
{
add(u,v,w);
add(v,u,0);
}
int dfs(int u,int f,int t)
{
int ans=0,i;
if(u==t)
return f;
for(i=head[u];i && f;i=maze[i].u)
{
int v=maze[i].v,w=maze[i].w;
if(dep[v]==dep[u]+1 && w)//符合深度关系且能流
{
int sum=dfs(v,min(f,w),t);
maze[i].w-=sum;
maze[i^1].w+=sum;
f-=sum;
ans+=sum;
}
}
if(!ans)
dep[u]=-2;
return ans;
}
int bfs(int s,int t)
{
queue<int> q;
cl(dep,0);
dep[s]=1;//源点深度为1
q.push(s);
while(!q.empty())
{
int u=q.front(),i;
q.pop();
for(i=head[u];i;i=maze[i].u)
{
int v=maze[i].v,w=maze[i].w;
if(w && !dep[v])//有深度且能流
{
dep[v]=dep[u]+1;
q.push(v);
}
}
}
return dep[t];
}
int dinic(int s,int t)
{
int ans=0;
while(bfs(s,t))
ans+=dfs(s,inf,t);
return ans;
}
char a[M][M];
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int n,k,i,j;
cin>>n>>k;
for(i=1;i<=n;i++)
cin>>a[i]+1;
int s=0,t=4*n+1;
int l=0,r=100,ans;
while(l<=r)
{
len=1;
cl(head,0);
int mid=(l+r)/2;
for(i=1;i<=n;i++)
inc(s,i,mid);
for(i=1;i<=n;i++)
inc(i+3*n,t,mid);
for(i=1;i<=n;i++)
inc(i,i+n,k);
for(i=1;i<=n;i++)
inc(i+2*n,i+3*n,k);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(a[i][j]=='Y')
inc(i,j+3*n,1);
else
inc(i+n,j+2*n,1);
if(dinic(s,t)==mid*n)
{
l=mid+1;
ans=mid;
}
else
r=mid-1;
}
cout<<ans<<endl;
return 0;
}