洛谷$P$1402 酒店之王 网络流

时间:2024-08-22 23:06:56

正解:网络流

解题报告:

传送门!

一看就很网络流昂,,,于是现在的问题就变成怎么建图了$QwQ$

首先如果只有一个要求,那就直接按要求建图然后跑个最大流就好.

现在变成,有两个要求,必须同时满足,考虑怎么解决?

考虑拆点,把人拆成两个点,分别连食物和酒店,然后跑个最大流,做完了$QwQ$

$over$

对了这题有三倍经验,,,讨论区有分享$QwQ$

#include<bits/stdc++.h>
using namespace std;
#define il inline
#define lf double
#define gc getchar()
#define t(i) edge[i].to
#define n(i) edge[i].nxt
#define w(i) edge[i].wei
#define ri register int
#define rb register bool
#define rc register char
#define rp(i,x,y) for(ri i=x;i<=y;++i)
#define my(i,x,y) for(ri i=x;i>=y;--i)
#define e(i,x) for(ri i=head[x];~i;i=edge[i].nxt) const int N=+,M=N*,inf=1e9;
int head[M],ed_cnt=-,n,p,q,S,T,cur[M],nod_cnt,dep[M];
struct ed{int to,nxt,wei;}edge[M<<]; il int read()
{
ri x=;rb y=;rc ch=gc;
while(ch!='-' && (ch>'' || ch<''))ch=gc;
if(ch=='-')ch=gc,y=;
while(ch>='' && ch<='')x=(x<<)+(x<<)+(ch^''),ch=gc;
return y?x:-x;
}
il void ad(ri x,ri y,ri z){edge[++ed_cnt]=(ed){x,head[y],z};head[y]=ed_cnt;edge[++ed_cnt]=(ed){y,head[x],};head[x]=ed_cnt;}
il bool bfs()
{
queue<int>Q;Q.push(S);memset(dep,,sizeof(dep));dep[S]=;
while(!Q.empty()){ri nw=Q.front();Q.pop();e(i,nw)if(w(i) && !dep[t(i)])dep[t(i)]=dep[nw]+,Q.push(t(i));}
return dep[T];
}
il int dfs(ri nw,ri flow)
{
if(nw==T || !flow)return flow;ri ret=;
for(ri &i=cur[nw];~i;i=n(i))if(w(i) && dep[t(i)]==dep[nw]+){ri tmp=dfs(t(i),min(flow,w(i)));flow-=tmp,w(i)-=tmp,ret+=tmp,w(i^)+=tmp;}
return ret;
}
il int dinic(){ri ret=;while(bfs()){rp(i,S,T)cur[i]=head[i];while(int d=dfs(S,inf))ret+=d;}return ret;} int main()
{
memset(head,-,sizeof(head));n=read();p=read();q=read();
S=;T=p+q+(n<<)+;rp(i,,p)ad(i,S,);rp(i,,n)ad(i+p+n,i+p,);rp(i,,q)ad(T,i+p+(n<<),);
rp(i,,n)rp(j,,p){ri tmp=read();if(tmp)ad(i+p,j,);}rp(i,,n)rp(j,,q){ri tmp=read();if(tmp)ad(j+p+(n<<),i+p+n,);}
printf("%d\n",dinic());
return ;
}