HDU 2689 sort it-from lanshui_Yang

Source: Internet
Author: User

Problem Description
You want to processe a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. Then how many times it need.
For example, 1 2 3 5 4, we only need one operation: swap 5 and 4.

 

Input
The input consists of a number of test cases. each case consists of two lines: the first line contains a positive integer n (n <= 1000); the next line contains a permutation of the n integers from 1 to n.


Output
For each case, output the minimum times need to sort it in ascending order on a single line.


Sample Input
3
1 2 3
4
4 3 2 1

Sample Output
0
6. Give you a number of n, and then 1 ~ A permutation of n, allowing you to find the number of reverse orders in this arrangement. Solution: You can use a tree array to solve this problem. The tree array has three purposes: 1. Single Point update, interval SUM 2, Interval Update, single point sum 3, and reverse order number. The idea of Reverse Order is relatively simple. Please refer to the code

# Include <iostream> # include <cstring> # include <string> # include <cstdio> # include <cmath> # include <algorithm> # include <queue> using namespace std; const int MAXN = 1e5 + 7; int C [MAXN]; int n; int lowbit (int x) {return x &-x;} int sum (int x) {int sumt = 0; while (x> 0) {sumt + = C [x]; x-= lowbit (x);} return sumt;} void add (int x, int d) {while (x <= n) {C [x] + = d; x + = lowbit (x) ;}} int main () {whi Le (scanf ("% d", & n )! = EOF) {int I; int ans = 0; memset (C, 0, sizeof (C); for (I = 1; I <= n; I ++) {int a; scanf ("% d", & a); add (a, 1); // This is the essence of the entire program, please understand ans + = I-sum (a); // count the number of reverse orders} printf ("% d \ n", ans);} return 0 ;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.