Problem
n个老鼠,m个洞,告诉你他们的一维坐标和m个洞的容量限制,问最小总距离。
Solution
用dp[i][j]表示前i个洞,进了前j个老鼠的最小代价
dp[i][j]=min(dp[i-1][k]+Sum[j]-Sum[k])(其中Sum[x]表示前x个老鼠到当前第i个洞的距离总和)
因此我们用单调队列维护dp[i-1][k]-Sum[k]
Notice
要开滚动数组,不然内存不够
Code
#include<deque>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define sqz main
#define ll long long
#define reg register int
#define rep(i, a, b) for (reg i = a; i <= b; i++)
#define per(i, a, b) for (reg i = a; i >= b; i--)
#define travel(i, u) for (reg i = head[u]; i; i = edge[i].next)
const int N = 5000;
const ll INF = 6e12;
const double eps = 1e-6, phi = acos(-1.0);
ll mod(ll a, ll b) {if (a >= b || a < 0) a %= b; if (a < 0) a += b; return a;}
ll read(){ ll x = 0; int zf = 1; char ch; while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
if (ch == '-') zf = -1, ch = getchar(); while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); return x * zf;}
void write(ll y) { if (y < 0) putchar('-'), y = -y; if (y > 9) write(y / 10); putchar(y % 10 + '0');}
int T[N + 5];
ll f[2][N + 5], Sum[N + 5];
deque<int> Q;
struct node
{
int p, c;
}H[N + 5];
int cmp(node X, node Y)
{
return X.p < Y.p;
}
int sqz()
{
int n = read(), m = read();
rep(i, 1, n) T[i] = read();
rep(i, 1, m) H[i].p = read(), H[i].c = read();
sort(T + 1, T + n + 1);
sort(H + 1, H + m + 1, cmp);
int now = 1, pre = 0;
rep(i, 0, n) f[pre][i] = INF;
f[pre][0] = 0;
rep(i, 1, m)
{
rep(j, 1, n) Sum[j] = Sum[j - 1] + abs(T[j] - H[i].p);
Q.clear();
Q.push_back(0);
rep(j, 1, n)
{
while (!Q.empty() && j - Q.front() > H[i].c) Q.pop_front();
while (!Q.empty() && f[pre][j] - Sum[j] <= f[pre][Q.back()] - Sum[Q.back()]) Q.pop_back();
Q.push_back(j);
f[now][j] = f[pre][Q.front()] - Sum[Q.front()] + Sum[j];
}
now ^= 1, pre ^= 1;
}
if (f[pre][n] == INF) puts("-1");
else printf("%I64d\n", f[pre][n]);
}