luoguP4005 小 Y 和地铁
题目描述
Solution
#include<bits/stdc++.h> using namespace std; inline int read() { int f = 1,x = 0; char ch; do { ch = getchar(); if(ch == '-')f = -1; }while(ch<'0'||ch>'9'); do { x = (x<<3) + (x<<1) + ch - '0'; ch = getchar(); }while(ch>='0'&&ch<='9'); return f*x; } const int MAXN = 44 + 10; int T; int n; int a[MAXN]; int l[MAXN],r[MAXN],num; int ans; int c_up[MAXN],c_down[MAXN]; inline int lowbit(int x) { return x&(-x); } inline void add1(int x,int t) { while(x<=n) { c_up[x] += t; x+=lowbit(x); } } inline void add2(int x,int t) { while(x<=n) { c_down[x] += t; x += lowbit(x); } } inline int Ask1(int x) { int res = 0; while(x) { res += c_up[x]; x -=lowbit(x); } return res; } inline int Ask2(int x) { int res = 0; while(x) { res += c_down[x]; x -= lowbit(x); } return res; } inline int query1(int l,int r) { return Ask1(r) - Ask1(l-1); } inline int query2(int l,int r) { return Ask2(r) - Ask2(l-1); } inline void dfs(int x,int sum) { if(sum >= ans) return; if(x > num) { ans = min(ans ,sum); return; } add1(r[x],1); dfs(x+1,sum+min(query1(l[x],r[x]-1),query2(l[x],n)+query1(r[x]+1,n))); add1(r[x],-1); add2(r[x],1); dfs(x+1,sum+min(query2(l[x],r[x]-1),query2(r[x]+1,n)+query1(l[x],n))); add2(r[x],-1); } int main() { T = read(); while(T--) { ans = 1<<30;num=0; memset(c_up,0,sizeof(c_up)); memset(c_down,0,sizeof(c_down)); n = read(); for(int i=1;i<=n;i++) a[i] = read(); for(int i=1;i<=n;i++) for(int j=i+1;j<=n;j++) if(a[i] == a[j]) {l[++num] = i,r[num] = j;break;} dfs(1,0); printf("%d ",ans); } }