题解:
题目让我们求type(l,r)/(r-l+1)的最小,显然可以用01分数规划,来二分求最小答案。所以我们从左往右移动端点,来统计种类。线段树来维护type(l,r)+l*mid的值。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 7;
const double eps = 1e-7;
double sum[N];
int lazy[N];
int pre[60007];
int a[60007];
int n;
void build(int l, int r, int rt, double mi) {
lazy[rt] = 0; //初始种类数为零
if (l == r) {
sum[rt] = l * mi; // l*mid
return;
}
int mid = (l + r) >> 1;
build(l, mid, rt << 1, mi);
build(mid + 1, r, rt << 1 | 1, mi);
sum[rt] = min(sum[rt<<1], sum[rt<<1|1]);
}
void pushdown(int rt) {
lazy[rt << 1] += lazy[rt];
lazy[rt << 1|1] += lazy[rt];
sum[rt << 1] += lazy[rt];
sum[rt << 1|1] += lazy[rt];
lazy[rt] = 0;
}
void update(int l, int r, int rt, int L, int R) {
if (L <= l && r <= R) {
sum[rt] += 1;
lazy[rt] += 1;
return;
}
if (lazy[rt]) pushdown(rt);
int mid = (l + r) >> 1;
if (L <= mid) update(l, mid, rt<<1, L, R);
if (R > mid) update(mid+1, r, rt<<1|1, L, R);
sum[rt] = min(sum[rt<<1], sum[rt<<1|1]);
}
double query(int l, int r, int rt, int L, int R) {
if (L <= l && r <= R) {
return sum[rt];
}
if (lazy[rt]) pushdown(rt);
int mid = (l + r) >> 1;
double tmp = 1e9;
if (L <= mid) tmp = min(tmp, query(l, mid, rt<<1, L, R));
if (R > mid) tmp = min(tmp, query(mid+1, r, rt<<1|1, L, R));
return tmp;
}
int check(double mid) {
build(1, n, 1, mid);
memset(pre, 0, sizeof(pre));
for (int i = 1; i <= n; ++i) {
update(1, n, 1, pre[a[i]]+1, i);
if (query(1, n, 1, 1, i) - mid*(i+1) < eps) return 1;
pre[a[i]] = i;
}
return 0;
}
int main() {
int t;
scanf ("%d", &t);
while (t--) {
scanf ("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf ("%d", &a[i]);
}
double l = 0, r = 1;
while (r - l > eps) {
double mid = (l + r)/2.0;
if (check(mid)) r = mid;
else l = mid;
}
printf ("%0.5f\n", l);
}
return 0;
}