[BZOJ1934][Shoi2007]Vote 善意的投票(最小割)

来源:互联网 发布:网络学历 编辑:程序博客网 时间:2024/05/21 09:17

题目描述

传送门

题解

首先拆点xiyi,建立源点和汇点。如果i投0,s->xi,否则,yi->t,如果一对好朋友ij,如果投的相同就不用连边,否则如果i投0,j投1,那么xi->yj。
最小割即为答案。
最小割需要割边使源汇不连通,相当于所有人的意见统一。存在一个冲突相当于把相应的边割掉。

代码

#include<iostream>#include<cstring>#include<cstdio>#include<queue>using namespace std;const int max_n=3e2+5;const int max_N=max_n*2+5;const int max_m=9e4+5;const int max_e=max_m*2;const int INF=1e9;int n,m,N,x,y,maxflow;int tot,point[max_N],next[max_e],v[max_e],remain[max_e];int vote[max_N],deep[max_N],cur[max_N];queue <int> q;inline void addedge(int x,int y,int cap){    ++tot; next[tot]=point[x]; point[x]=tot; v[tot]=y; remain[tot]=cap;    ++tot; next[tot]=point[y]; point[y]=tot; v[tot]=x; remain[tot]=0;}inline bool bfs(int s,int t){    memset(deep,0x7f,sizeof(deep)); deep[s]=0;    for (int i=1;i<=N;++i) cur[i]=point[i];    while (!q.empty()) q.pop(); q.push(s);    while (!q.empty()){        int now=q.front(); q.pop();        for (int i=point[now];i!=-1;i=next[i])          if (deep[v[i]]>INF&&remain[i]){            deep[v[i]]=deep[now]+1;            q.push(v[i]);          }    }    return deep[t]<INF;}inline int dfs(int now,int t,int limit){    if (now==t||!limit) return limit;    int flow=0,f;    for (int i=cur[now];i!=-1;i=next[i]){        cur[now]=i;        if (deep[v[i]]==deep[now]+1&&(f=dfs(v[i],t,min(remain[i],limit)))){            flow+=f;            limit-=f;            remain[i]-=f;            remain[i^1]+=f;            if (!limit) break;        }    }    return flow;}inline void dinic(int s,int t){    while (bfs(s,t)) maxflow+=dfs(s,t,INF);}int main(){    tot=-1;    memset(point,-1,sizeof(point));    memset(next,-1,sizeof(next));    scanf("%d%d",&n,&m);N=n*2+2;    for (int i=1;i<=n;++i){        scanf("%d",&vote[i]);        if (!vote[i]) addedge(1,1+i,1);        else addedge(1+n+i,N,1);    }    for (int i=1;i<=m;++i){        scanf("%d%d",&x,&y);        if (vote[x]==vote[y]) continue;        if (!vote[x]) addedge(1+x,1+n+y,1);        else addedge(1+y,1+n+x,1);    }    dinic(1,N);    printf("%d\n",maxflow);}
0 0
原创粉丝点击