传送门
题目描述
有 n n n个座位,有些座位被人占了,现在需要他们挪动座位,需要的最短时间为多少
分析
比较裸的最小费用最大流
我们将源点和每一个被占了的座位连接,流量为1,费用为0,每一个没被占的座位和汇点连接,流量为1,费用为0,每两个座位之间连一条边,流量为
n
n
n,费用为1,跑
E
K
EK
EK即可
代码
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10,M = N * 2;
const ll mod = 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a) {
char c = getchar(); T x = 0, f = 1; while (!isdigit(c)) {if (c == '-')f = -1; c = getchar();}
while (isdigit(c)) {x = (x << 1) + (x << 3) + c - '0'; c = getchar();} a = f * x;
}
int gcd(int a, int b) {return (b > 0) ? gcd(b, a % b) : a;}
int h[N],ne[M],e[M],w[M],f[M],idx;
int n,m,S,T;
int q[N],d[N],pre[N],incf[N];
bool st[N];
int a[N];
void add(int a,int b,int c,int d){
ne[idx] = h[a],e[idx] = b,f[idx] = c,w[idx] = d,h[a] = idx++;
ne[idx] = h[b],e[idx] = a,f[idx] = 0,w[idx] = -d,h[b] = idx++;
}
bool spfa(){
int hh = 0,tt = 1;
memset(d,0x3f,sizeof d);
memset(incf,0,sizeof incf);
q[0] = S,d[S] = 0,incf[S] = INF;
while(hh != tt){
int t = q[hh++];
if(hh == N) hh = 0;
st[t] = false;
for(int i = h[t];~i;i = ne[i]){
int ver = e[i];
if(f[i] && d[ver] > d[t] + w[i]){
pre[ver] = i;
d[ver] = d[t] + w[i];
incf[ver] = min(f[i],incf[t]);
if(!st[ver]){
q[tt++] = ver;
if(tt == N) tt = 0;
st[ver] = true;
}
}
}
}
return incf[T] > 0;
}
void EK(int &flow,int &cost){
flow = cost = 0;
while(spfa()){
int t = incf[T];
flow += t,cost += t * d[T];
for(int i = T;i != S;i = e[pre[i] ^ 1]){
f[pre[i]] -= t;
f[pre[i] ^ 1] += t;
}
}
}
int main() {
read(n);
memset(h,-1,sizeof h);
S = 0,T = N - 1;
for(int i = 1;i <= n;i++) {
read(a[i]);
if(a[i] == 1) add(S,i,1,0);
else add(i,T,1,0);
if(i == 1) continue;
add(i - 1,i,n,1);
add(i,i - 1,n,1);
}
int flow,cost;
EK(flow,cost);
di(cost);
return 0;
}
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/