版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pengwill97/article/details/82823515
题意
幼儿园里有n个小朋友打算通过投票来决定睡不睡午觉。对他们来说,这个问题并不是很重要,于是他们决定发扬谦让精神。虽然每个人都有自己的主见,但是为了照顾一下自己朋友的想法,他们也可以投和自己本来意愿相反的票。我们定义一次投票的冲突数为好朋友之间发生冲突的总数加上和所有和自己本来意愿发生冲突的人数。 我们的问题就是,每位小朋友应该怎样投票,才能使冲突数最小?
题解
第i个小朋友偏好1,则S连i,容量为1。
第i个小朋友偏好0,则i连T,容量为1。
第i个小朋友和第j个小朋友为好朋友关系,则i和j互相连接,容量为1.
跑最小割,即为答案。
代码
//
// Created by pengwill on 2018/9/23.
//
#include <bits/stdc++.h>
using namespace std;
const int nmax = 100000;
const int INF = 0x3f3f3f3f;
typedef int valtype;
struct Dinic {
int head[nmax], cur[nmax];
valtype d[nmax];
bool vis[nmax];
int tot, n, s, t, front, tail;
int qqq[nmax];
struct edge {
int nxt, to;
valtype cap, flow;
} e[nmax<<1];
void init(int n) {
this->n = n;
memset(head, -1, sizeof head);
memset(e,0,sizeof e);
this->tot = 0;
}
int add_edge(int u, int v, valtype c) {
int temp = tot;
e[tot].to = v, e[tot].cap = c, e[tot].flow = 0;
e[tot].nxt = head[u];
head[u] = tot++;
e[tot].to = u, e[tot].cap = c, e[tot].flow = c;
e[tot].nxt = head[v];
head[v] = tot++;
return temp;
}
bool BFS() {
for(int i = 0; i <= n; ++i) vis[i] = false;
front = tail = 0;
vis[s] = true; d[s] = 0;
qqq[tail++] = s;
while (front < tail) {
int u = qqq[front++];
for (int i = head[u]; i != -1; i = e[i].nxt) {
int v = e[i].to;
if (!vis[v] && e[i].cap > e[i].flow) {
vis[v] = true;
d[v] = d[u] + 1;
qqq[tail++] = v;
}
}
}
return vis[t];
}
valtype DFS(int x, valtype a) {
if (x == t || a == 0) return a;
valtype Flow = 0, f;
for (int& i = cur[x]; i != -1; i = e[i].nxt) {
int v = e[i].to;
if (d[v] == d[x] + 1 && (f = DFS(v, min(a, e[i].cap - e[i].flow))) > 0) {
Flow += f;
e[i].flow += f;
e[i ^ 1].flow -= f;
a -= f;
if (a == 0) break;
}
}
return Flow;
}
valtype Maxflow(int s, int t) {
this->s = s, this->t = t;
valtype Flow = 0;
while (BFS()) {
for (int i = 0; i <= n; i++) cur[i] = head[i];
Flow += DFS(s,INF);
}
return Flow;
}
} dinic;
int n, m;
int main() {
scanf("%d %d", &n, &m);
int tmp;
int s = 0, t = n + 1;
dinic.init(t);
for(int i = 1; i <= n; ++i) {
scanf("%d", &tmp);
if(tmp == 1) {
dinic.add_edge(s, i, 1);
} else {
dinic.add_edge(i, t ,1);
}
}
for(int i = 1; i <= m; ++i) {
int u, v;
scanf("%d %d", &u, &v);
dinic.add_edge(u, v, 1);
dinic.add_edge(v, u, 1);
}
int ans = dinic.Maxflow(s, t);
printf("%d\n", ans);
return 0;
}