1. 程式人生 > >[luogu4005]小Y和地鐵【搜索+樹狀數組】

[luogu4005]小Y和地鐵【搜索+樹狀數組】

www. memset bre pri ref pro sizeof 樹狀 main

傳送門:https://www.luogu.org/problemnew/show/P4005


最簡單的暴力拿最高的分,二進制爆搜。

#include <bits/stdc++.h>
#define ll long long
#define ms(a, b) memset(a, b, sizeof(a))
#define inf 0x3f3f3f3f
#define N 55
using namespace std;
template <typename T>
inline void read(T &x) {
    x = 0; T fl = 1;
    char ch = 0;
    while (ch < '0' || ch > '9') {
        if (ch == '-') fl = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    x *= fl;
}
struct BIT {
    #define lowbit(x) (x&-x)
    int tr[N], n;
    void init(int M) {
        n = M;
        memset(tr, 0, sizeof(tr));
    }
    void add(int x, int val) {
        for (; x <= n; x += lowbit(x)) tr[x] += val;
    }
    int sum(int x) {
        int res = 0;
        for (; x; x -= lowbit(x)) res += tr[x];
        return res;
    }
    int query(int l, int r) {
        return sum(r) - sum(l - 1);
    }
}up, down;
int tot, ans, n;
int l[N], r[N], a[N];
void dfs(int st, int sum) {
    if (st > tot) {
        ans = min(ans, sum);
        return;
    }
    if (sum > ans) return;
    int a1 = min(up.query(l[st], r[st]), down.query(l[st], n) + up.query(r[st], n));
    up.add(r[st], 1);
    dfs(st + 1, sum + a1);
    up.add(r[st], -1);
    int a2 = min(down.query(l[st], r[st]), up.query(l[st], n) + down.query(r[st], n));
    down.add(r[st], 1);
    dfs(st + 1, sum + a2);
    down.add(r[st], -1);
}
int main() {
    int cas; read(cas);
    while (cas --) {
        read(n); 
        ans = inf;
        for (int i = 1; i <= n; i ++) read(a[i]);
        tot = 0;
        for (int i = 1; i <= n; i ++) {
            for (int j = i + 2; j <= n; j ++) {
                if (a[i] == a[j]) {
                    l[++ tot] = i;
                    r[tot] = j;
                    break;
                }
            }
        }
        up.init(n); down.init(n);
        dfs(1, 0);
        printf("%d\n", ans);
    }
    return 0;
}

[luogu4005]小Y和地鐵【搜索+樹狀數組】