首页 > 代码库 > 2014 BNU 邀请赛B题(枚举)

2014 BNU 邀请赛B题(枚举)

Beautiful Garden

题意:x轴上放了一些树,现在要移动一些树使得所有树都等间距,问最少要移动多少棵
思路:枚举,枚举第一棵树,和另一棵树,以及中间有多少树,这样就能知道等差数列的首项和公差,然后再循环一边计算出答案,保存最小值
代码:

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
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;
}