UVA1260 LA4843 Sales【逆序数】

Mr. Cooper, the CEO of CozyWalk Co., receives a report of daily sales every day since the company has been established. Starting from the second day since its establishment, on receiving the report, he compares it with each of the previous reports in order to calculate the number of previous days whose sales amounts are less than or equal to it. After obtaining the number of such days, he writes it in a list.
    This problem can be stated more formally as follows. Let A = (a1, a2, . . . , an) denote the list of daily sales amounts. And let B = (b1, b2, . . . , bn−1) be another integer list maintained by Mr. Cooper, each value representing the number of such previous days. On the i-th day (2 ≤ i ≤ n), he calculates bi−1, the number of ak’s such that ak ≤ ai (1 ≤ k < i).
    For example, suppose that A = (20, 43, 57, 43, 20). For the fourth day’s sales amount, a4 = 43, the number of previous days whose sales amounts are less than or equal to it is 2 since a1 ≤ a4, a2 ≤ a4, and a3 > a4. Therefore, b3 = 2. Similarly, b1, b2, and b4 can be obtained and it results in B = (1, 2, 2, 1).
    Given an array of size n for the list of daily sales amounts, write a program that prints the sum of the n − 1 integers in the list B.
Input
Your program is to read the input from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case starts with a line containing an integer n (2 ≤ n ≤ 1, 000), which represents the size of the list A . In the following line, n integers are given, each represents the daily sales amounts ai (1 ≤ ai ≤ 5, 000 and 1 ≤ i ≤ n) for the test case.
Output
Your program is to write to standard output. For each test case, print the sum of the n − 1 integers in the list B which is obtained from the list A.
    The following shows sample input and output for two test cases.
Sample Input
2
5
38 111 102 111 177
8
276 284 103 439 452 276 452 398
Sample Output
9
20

问题链接 UVA1260 LA4843 Sales
问题简述:(略)
问题分析:计算逆序数问题,数据量少的话,可以简单算一下,时间复杂度为O(N2)。也可以用基于归并排序的思想来实现,时间复杂度是O(NlogN)。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA1260 LA4843 Sales */

#include <bits/stdc++.h>

using namespace std;

const int N = 1000;
int a[N];

int main()
{
    int t, n;
    scanf("%d", &t);
    while (t--) {
        scanf("%d", &n);
        for (int i = 0; i < n; i++) scanf("%d", &a[i]);

        int cnt = 0;
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                if (a[i] <= a[j]) cnt++;

        printf("%d\n", cnt);
    }

    return 0;
}
上一篇:数据分析案例_电子游戏的销售情况


下一篇:BZOJ1607 轻拍牛头