9.1 Exercises compartment restructuring solution to a problem

Written for: Luo Gu P1116

Title Description

Next to an old train station there is a bridge, a deck can be rotated around the center of the river piers level. A station workers found the length of the bridge can accommodate up to two cars, if the rotation of the bridge \ (180 \) degrees, the two adjacent compartments can exchange positions, this method can rearrange the order of the compartment. He is responsible for using the bridge will stop cabin by cabin number in ascending order. After he retired, the railway station decided to automate this work, one important task is to compile a program, enter the initial carriage order to calculate the minimum number of steps will be able to sort by carriage.

Input Format

A total of two lines.
The first line is the total number of passenger compartment \ (N (≤ 10000) \) .
The second row is a \ (N \) different number indicates the initial order of the cabin.

Output Format

An integer, the minimum number of rotations.

Sample input

4
4 3 2 1

Sample Output

6

problem analysis

This question is actually a bubble sort of simulation questions, use thought bubble sort, find each adjacent pair of the left is greater than the right, exchanged them, plus a coincidence.
Or ask us directly for reverse it - that is: Find the number of array in reverse order of the number of reverse is our answer.
Bubble sort codes are as follows:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010;
int n, a[maxn], cnt;
int main() {
    cin >> n;
    for (int i = 0; i < n; i ++) cin >> a[i];
    for (int i = 1; i < n; i ++) {
        for (int j = 0; j < n-i; j ++) {
            if (a[j] > a[j+1]) {
                cnt ++;
                swap(a[j], a[j+1]);
            }
        }
    }
    cout << cnt << endl;
    return 0;
}

Reverse of the code to achieve the following method:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010;
int n, a[maxn], cnt;
int main() {
    cin >> n;
    for (int i = 0; i < n; i ++) cin >> a[i];
    for (int i = 0; i < n; i ++)
        for (int j = i+1; j < n; j ++)
            if (a[i] > a[j])
                cnt ++;
    cout << cnt << endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/zifeiynoip/p/11482980.html
9.1