# BZOJ 1934洛谷2057善意的投票题解

BZ链接

# include<iostream>
# include<cstdio>
# include<algorithm>
# include<cstring>
# include<cmath>
# include<queue>
using namespace std;
const int inf = 0x3f3f3f3f;
const int mn = 310;
int head[mn],edge_max=1;
struct edge{int to,next,flow;
};
edge e[mn*mn*2];
int n,m;
void add_edge(int x,int y,int z)
{
e[++edge_max].to=y;
e[edge_max].next=head[x];
e[edge_max].flow=z;
head[x]=edge_max;
}
void add(int x,int y,int z)
{
add_edge(x,y,z);
add_edge(y,x,0);
}
queue<int> q;
int deep[mn];
bool bfs(int x,int y)
{
memset(deep,0,sizeof(deep));
q.push(x);
deep[x]=1;
while(!q.empty())
{
int u=q.front();
q.pop();
for(int i=head[u];i;i=e[i].next)
{
if(e[i].flow>0 && deep[e[i].to]==0)
{
deep[e[i].to]=deep[u]+1;
q.push(e[i].to);
}
}
}
return deep[y]!=0;
}
int dfs(int x,int cost,int y)
{
if(x==y) return cost;
for(int i=head[x];i;i=e[i].next)
{
if(deep[e[i].to]==deep[x]+1 && e[i].flow>0)
{
int di=dfs(e[i].to,min(cost,e[i].flow),y);
if(di>0)
{
e[i].flow-=di;
e[i^1].flow+=di;
return di;
}
}
}
return 0;
}
int dinic(int x,int y)
{
int ans=0;
while(bfs(x,y))
{
//    printf("ssss\n");
while(int k=dfs(x,inf,y))
ans+=k;
//    printf("%d\n",ans);
}
return ans;
}
int main()
{
int st,en,x,y;
scanf("%d%d",&n,&m);
st=n+1,en=n+2;
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
if(x) {
add(st,i,1);
//printf("%d %d\n",st,i);
}
else add(i,en,1);
}
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
add(x,y,1),add(y,x,1);
}
printf("%d",dinic(st,en));
return 0;
}

posted @ 2018-07-21 16:50  logeadd  阅读(128)  评论(0编辑  收藏  举报