CodeForces - 863F Almost Permutation

Description

你有一个长度为 \(n\le50\) 数组, 值域为 \([1,n]\) ,但你忘了它长成啥样了。只记得 \(q(q\le 100)\) 个形如 $ (p,l, r,v) $ 的限制。若 \(p=1\) 则表示 \(\forall x\in [l,r],a_x\ge v\) 。若 \(p=2\) 则表示 \(\forall x\in [l,r],a_x\le v\)

\(i\) 的出现次数为 \(cnt(i)\) ,填入数字使得 \(cost=\sum cnt(i)^2\) 最小。

Solution

上一篇题解太水了,这篇稍微好好写一下。

你以为我会重写上一篇吗?naive

费用流。那个二次就建一堆 \(1,3,5,7\cdots\) 的边就行了。

#include<bits/stdc++.h>
using namespace std;

template <class T> void read(T &x) {
	x = 0; bool flag = 0; char ch = getchar(); for (; ch < '0' || ch > '9'; ch = getchar()) flag |= ch == '-';
	for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - 48; flag ? x = ~x + 1 : 0;
}

#define N 150
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define INF 0x3f3f3f3f

int S, T, flow, cost, head[N], tot = 1, dis[N], pre[N];;
struct edge { int u, v, c, w, next; }e[100001];
queue<int> q;
bool inq[N];
inline void insert(int u, int v, int c, int w) { e[++tot].u = u, e[tot].v = v, e[tot].c = c, e[tot].w = w, e[tot].next = head[u], head[u] = tot; }
inline void add(int u, int v, int c, int w) { insert(u, v, c, w), insert(v, u, 0, -w); }
inline bool spfa() {
	rep(i, S, T) dis[i] = INF; dis[S] = 0; q.push(S);
	while (!q.empty()) {
		int u = q.front(); q.pop(); inq[u] = 0;
		for (int i = head[u], v, w; i; i = e[i].next) if (e[i].c > 0 && dis[v = e[i].v] > dis[u] + (w = e[i].w)) {
			dis[v] = dis[u] + w, pre[v] = i;
			if (!inq[v]) q.push(v); inq[v] = 1;
		}
	}
	return dis[T] != INF;
}
inline void mcf() {
	int d = INF;
	for (int i = T; (i ^ S); i = e[pre[i]].u) d = min(d, e[pre[i]].c);
	flow += d;
	for (int i = T; (i ^ S); i = e[pre[i]].u) e[pre[i]].c -= d, e[pre[i] ^ 1].c += d, cost += d * e[pre[i]].w;
}

int L[N], R[N];

int main() {
	int n, q; read(n), read(q);
	memset(L, 0xc0, sizeof L), memset(R, 0x3f, sizeof R);
	T = 2 * n + 1;
	rep(i, 1, n) {
		rep(j, 1, n) add(S, i, 1, j * 2 - 1);
		add(i + n, T, 1, 0);
	}
	while (q--) {
		int op, l, r, v; read(op), read(l), read(r), read(v);
		rep(i, l, r) op == 1 ? L[i] = max(L[i], v) : R[i] = min(R[i], v);
	}
	rep(i, 1, n) rep(j, 1, n) if (i >= L[j] && i <= R[j]) add(i, j + n, 1, 0);
	while (spfa()) mcf();
	printf("%d", flow == n ? cost : -1);
	return 0;
}
posted @ 2018-09-04 19:55  aziint  阅读(171)  评论(0编辑  收藏  举报
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.