HDU 3605 Escape(状态压缩+最大流)

时间:2023-03-08 19:02:43

http://acm.hdu.edu.cn/showproblem.php?pid=3605

题意:

有n个人和m个星球,每个人可以去某些星球和不可以去某些星球,并且每个星球有最大居住人数,判断是否所有人都能去这m个星球之中。

思路:

这道题建图是关键,因为n的数量很大,如果直接将源点和人相连,是会超时的,因为m≤10,所以每个人的选择可以用二进制来存储,这样最多也就1<<m-1种状态,相同的就可以放在一起处理了。

 #include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
using namespace std; const int maxn=;
const int INF=0x3f3f3f3f; struct Edge
{
int from,to,cap,flow;
Edge(int u,int v,int w,int f):from(u),to(v),cap(w),flow(f){}
}; struct Dinic
{
int n,m,s,t;
vector<Edge> edges;
vector<int> G[maxn];
bool vis[maxn];
int cur[maxn];
int d[maxn]; void init(int n)
{
this->n=n;
for(int i=;i<n;++i) G[i].clear();
edges.clear();
} void AddEdge(int from,int to,int cap)
{
edges.push_back( Edge(from,to,cap,) );
edges.push_back( Edge(to,from,,) );
m=edges.size();
G[from].push_back(m-);
G[to].push_back(m-);
} bool BFS()
{
queue<int> Q;
memset(vis,,sizeof(vis));
vis[s]=true;
d[s]=;
Q.push(s);
while(!Q.empty())
{
int x=Q.front(); Q.pop();
for(int i=;i<G[x].size();++i)
{
Edge& e=edges[G[x][i]];
if(!vis[e.to] && e.cap>e.flow)
{
vis[e.to]=true;
d[e.to]=d[x]+;
Q.push(e.to);
}
}
}
return vis[t];
} int DFS(int x,int a)
{
if(x==t || a==) return a;
int flow=, f;
for(int &i=cur[x];i<G[x].size();++i)
{
Edge &e=edges[G[x][i]];
if(d[e.to]==d[x]+ && (f=DFS(e.to,min(a,e.cap-e.flow) ) )>)
{
e.flow +=f;
edges[G[x][i]^].flow -=f;
flow +=f;
a -=f;
if(a==) break;
}
}
return flow;
} int Maxflow(int s,int t)
{
this->s=s; this->t=t;
int flow=;
while(BFS())
{
memset(cur,,sizeof(cur));
flow +=DFS(s,INF);
}
return flow;
}
}DC; int n,m;
int num[maxn];
int src,dst; int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(num,,sizeof(num));
for(int i=;i<=n;i++)
{
int count=;
for(int j=m-;j>=;--j)
{
int p;
scanf("%d",&p);
if(p) count |= <<j;
}
++num[count];
} src=(<<m)+m;
dst=(<<m)++m;
DC.init((<<m)++m);
for(int i=;i<(<<m);++i)
if(num[i])
{
DC.AddEdge(src,i,num[i]);
for(int j=;j<m;++j)if(i&(<<j))
DC.AddEdge(i,(<<m)+j,INF);
}
for(int i=;i<m;++i)
{
int p;
scanf("%d",&p);
DC.AddEdge((<<m)+i,dst,p);
} printf("%s\n",DC.Maxflow(src,dst)==n?"YES":"NO");
}
return ;
}