題意:x軸上放了一些樹,現在要移動一些樹使得所有樹都等間距,問最少要移動多少棵
思路:枚舉,枚舉第一棵樹,和另一棵樹,以及中間有多少樹,這樣就能知道等差數列的首項和公差,然後再循環一邊計算出答案,保存最小值
代碼:
#include
#include
#include
#include
using namespace std;
#define INF 0x3f3f3f3f
int t, n;
double x[45];
const double eps = 1e-9;
int solve() {
if (n == 1) return 0;
int ans = INF;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = 1; k < n; k++) {
int count = 0;
double d = (x[j] - x[i]) / k;
double a1 = x[i] - d;
int jj = 0;
for (int ii = 0; ii < n; ii++) {
a1 += d;
while (x[jj] < a1 && jj < n) jj++;
if (jj == n) break;
if (fabs(a1 - x[jj]) < eps) {
count++;
jj++;
}
}
ans = min(ans, n - count);
}
}
}
return ans;
}
int main() {
int cas = 0;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%lf", &x[i]);
sort(x, x + n);
printf("Case #%d: %d\n", ++cas, solve());
}
return 0;
}