思路:
首先把数组离散化,然后观察可以发现,在最优解中最终没有被移动过的那些数字一定是连续的,那么找到最长的连续的数字长度即可。
实现:
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int N = 300005; 4 int a[N], l[N], r[N]; 5 int main() 6 { 7 int q; cin >> q; 8 while (q--) 9 { 10 int n; cin >> n; 11 for (int i = 0; i < n; i++) cin >> a[i]; 12 vector<int> v(a, a + n); 13 sort(v.begin(), v.end()); 14 v.erase(unique(v.begin(), v.end()), v.end()); 15 for (int i = 0; i < n; i++) 16 { 17 a[i] = lower_bound(v.begin(), v.end(), a[i]) - v.begin() + 1; 18 } 19 int m = v.size(); 20 for (int i = 1; i <= m; i++) { l[i] = n + 1; r[i] = 0; } 21 for (int i = 0; i < n; i++) 22 { 23 l[a[i]] = min(l[a[i]], i + 1); 24 r[a[i]] = max(r[a[i]], i + 1); 25 } 26 int ans = m - 1, tmp = 1; 27 for (int i = m - 1; i >= 1; i--) 28 { 29 if (r[i] < l[i + 1]) tmp++; 30 else tmp = 1; 31 ans = min(ans, m - tmp); 32 } 33 cout << ans << endl; 34 } 35 return 0; 36 }