题目链接:https://vjudge.net/problem/SPOJ-Coconuts
题意:N 个城堡守卫正在就非洲的燕子能否搬运椰子而进行投票。每个人都有自己的看法,但是为了避免跟自己的朋友持相反意见,他们 时常会投相反的票。现在给出每个人的初始看法以及朋友关系,求在某种投票方案下, 违背自己意愿的票数与持不同意见的朋友对数的总和最小。 (2 <= N <= 300,1 <= M <= N(N-1)/2)
解法:和spoj 839比较类似,S和原来为0的点连边,t和原来为1的点,原来的边(u,v)->大的多个addedge(u,v,1),addedge(v,u,1),求最小割就可以了,我们再来考虑一下最小割的意义,割边如果是与s或者t相连,那么表示这个点变色,如果不是,表示两边的颜色都不变
#include <bits/stdc++.h>
using namespace std;
const int maxn = 410;
const int maxm = 500010;
const int inf = 0x3f3f3f3f;
struct G
{
int v, cap, next;
G() {}
G(int v, int cap, int next) : v(v), cap(cap), next(next) {}
} E[maxm];
int p[maxn], T;
int d[maxn], temp_p[maxn], qw[maxn]; //d顶点到源点的距离标号,temp_p当前狐优化,qw队列
void init()
{
memset(p, -1, sizeof(p));
T = 0;
}
void add(int u, int v, int cap)
{
E[T] = G(v, cap, p[u]);
p[u] = T++;
E[T] = G(u, 0, p[v]);
p[v] = T++;
}
bool bfs(int st, int en, int n)
{
int i, u, v, head, tail;
for(i = 0; i <= n; i++) d[i] = -1;
head = tail = 0;
d[st] = 0;
qw[tail] = st;
while(head <= tail)
{
u = qw[head++];
for(i = p[u]; i + 1; i = E[i].next)
{
v = E[i].v;
if(d[v] == -1 && E[i].cap > 0)
{
d[v] = d[u] + 1;
qw[++tail] = v;
}
}
}
return (d[en] != -1);
}
int dfs(int u, int en, int f)
{
if(u == en || f == 0) return f;
int flow = 0, temp;
for(; temp_p[u] + 1; temp_p[u] = E[temp_p[u]].next)
{
G& e = E[temp_p[u]];
if(d[u] + 1 == d[e.v])
{
temp = dfs(e.v, en, min(f, e.cap));
if(temp > 0)
{
e.cap -= temp;
E[temp_p[u] ^ 1].cap += temp;
flow += temp;
f -= temp;
if(f == 0) break;
}
}
}
return flow;
}
int dinic(int st, int en, int n)
{
int i, ans = 0;
while(bfs(st, en, n))
{
for(i = 0; i <= n; i++) temp_p[i] = p[i];
ans += dfs(st, en, inf);
}
return ans;
}
int main(){
int n, m;
while(~scanf("%d%d", &n,&m)){
if(n==0&&m==0) break;
int x, s = 0, t = n+1;
init();
for(int i=1; i<=n; i++){
scanf("%d", &x);
if(x==0) add(s, i, 1);
else add(i, t, 1);
}
for(int i=1; i<=m; i++){
int x, y;
scanf("%d %d", &x,&y);
add(x, y, 1);
add(y, x, 1);
}
int ans = dinic(s, t, t+1);
printf("%d\n", ans);
}
}