A sequence is given. You can move it cyclically (that is, move the following section to the Front) and ask the smallest number of backward orders that can be moved. Reverse Order can be used for sorting, and the complexity is O (nlogn). However, if you perform this operation once every time you move it, it will definitely time out. Online question solutions can be used and implemented, after thinking for a long time, I finally found that "the next line contains a permutation of the n integers from 0 to n-1", the hookan guys, these numbers are actually from 0 to n-1. In this way, we can deduce that the reverse order of the series will change regularly for every moving bit, it is related to it and it is a large number of Reverse Order Number pairs will be reduced, in fact, it is the number of a smaller number than the sequential sorting, in fact, it is its own value; it is a larger number than the decimal number in reverse order. So you just need to sort it once, find the current number of reverse orders, and then simulate the number of reverse orders that will be generated after the loop, and obtain the minimum value. Code:
/* * Author: illuz <iilluzen@gmail.com> * Blog: http://blog.csdn.net/hcbbt * File: hdu1394.cpp * Lauguage: C/C++ * Create Date: 2013-08-30 10:28:05 * Descripton: hdu1394, Minimum Inversion Number, partitation, simutation */ #include <cstdio> #include <cstring> #include <algorithm> using namespace std; #define rep(i, n) for (int i = 0; i < (n); i++) #define repu(i, a, b) for (int i = (a); i < (b); i++) const int MAXN = 5100; int n, a[MAXN], b[MAXN], t[MAXN]; int cnt, Min, sum; void mergeSort(int* A, int x, int y) { if (y - x <= 1) return; int m = x + (y - x) / 2; mergeSort(A, x, m); mergeSort(A, m, y); int p = x, q = m, i = x; while (p < m || q < y) if (q >= y || (p < m && A[p] <= A[q])) t[i++] = A[p++]; else t[i++] = A[q++], cnt += m - p; repu(i, x, y) A[i] = t[i]; } int main() { while (scanf("%d", &n) != EOF) { rep(i, n) scanf("%d", &a[i]); int Min = 0xffffff; memcpy(b, a, sizeof(a)); cnt = 0; mergeSort(a, 0, n); sum = Min = cnt; rep(i, n) { sum = sum - b[i] + (n - 1 - b[i]); Min = min(Min, sum); } printf("%d\n", Min); } return 0; }