您的位置:首页 > 其它

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

2017-04-10 20:36 387 查看
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=1500;
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=0;i<n;++i) G[i].clear();
edges.clear();
}

void AddEdge(int from,int to,int cap)
{
edges.push_back( Edge(from,to,cap,0) );
edges.push_back( Edge(to,from,0,0) );
m=edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}

bool BFS()
{
queue<int> Q;
memset(vis,0,sizeof(vis));
vis[s]=true;
d[s]=0;
Q.push(s);
while(!Q.empty())
{
int x=Q.front(); Q.pop();
for(int i=0;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]+1;
Q.push(e.to);
}
}
}
return vis[t];
}

int DFS(int x,int a)
{
if(x==t || a==0) return a;
int flow=0, f;
for(int &i=cur[x];i<G[x].size();++i)
{
Edge &e=edges[G[x][i]];
if(d[e.to]==d[x]+1 && (f=DFS(e.to,min(a,e.cap-e.flow) ) )>0)
{
e.flow +=f;
edges[G[x][i]^1].flow -=f;
flow +=f;
a -=f;
if(a==0) break;
}
}
return flow;
}

int Maxflow(int s,int t)
{
this->s=s; this->t=t;
int flow=0;
while(BFS())
{
memset(cur,0,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,0,sizeof(num));
for(int i=1;i<=n;i++)
{
int count=0;
for(int j=m-1;j>=0;--j)
{
int p;
scanf("%d",&p);
if(p) count |= 1<<j;
}
++num[count];
}

src=(1<<m)+m;
dst=(1<<m)+1+m;
DC.init((1<<m)+2+m);
for(int i=0;i<(1<<m);++i)
if(num[i])
{
DC.AddEdge(src,i,num[i]);
for(int j=0;j<m;++j)if(i&(1<<j))
DC.AddEdge(i,(1<<m)+j,INF);
}
for(int i=0;i<m;++i)
{
int p;
scanf("%d",&p);
DC.AddEdge((1<<m)+i,dst,p);
}

printf("%s\n",DC.Maxflow(src,dst)==n?"YES":"NO");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: