【Codeforces】1213B – Bad Prices

正文索引 [隐藏]

Problem Description:

Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_{1},a_{2},…,a_{n}, where a_{i} is the price of berPhone on the day i.
Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if n = 6 and a = [3,9,4,6,7,5], then the number of days with a bad price is 3 — these are days 2 (a_{2} = 9), 4 (a_{4} = 6) and 5 (a_{5} = 7).
Print the number of days with a bad price.
You have to answer t independent data sets.

Input Specification:

The first line contains an integer t (1 ≤ t ≤ 10000) — the number of sets of input data in the test. Input data sets must be processed independently, one after another.
Each input data set consists of two lines. The first line contains an integer n (1 ≤ n ≤ 150000) — the number of days. The second line contains n integers a_{1},a_{2},…,a_{n} (1 ≤ a_{i} ≤ 10^{6}), where a_{i} is the price on the i-th day.
It is guaranteed that the sum of n over all data sets in the test does not exceed 150000.

Output Specification:

Print t integers, the j-th of which should be equal to the number of days with a bad price in the j-th input data set.

Sample Input:

5
6
3 9 4 6 7 5
1
1000000
2
2 1
10
31 41 59 26 53 58 97 93 23 84
7
3 2 1 2 3 4 5

Sample Output:

3
1
8
2

解题思路:

这题大意说白了就是一句话判断一个数列中,有多少个数后面存在比它小的数。我第一次用了双重for循环,提交之后Time limit exceeded on test 3啦,然后加了一行ios::sync_with_stdio(false);来取消cin和stdin的同步后 提交还是TLE。。。。。。大佬Aaver苗神说从后往前跑一遍就好了,因为这题换个思维来说不就是从后往前不断更新最小的数,判断前面有几个数比当前最小数要大吗?

AC代码:TLE代码:

#include <bits/stdc++.h>
using namespace std;
#define Up(i,a,b) for(int i = a; i < b; i++)
 
int main()
{
    ios::sync_with_stdio(false);    //取消cin和stdin的同步
    int t;
    cin >> t;
    while(t--)
    {
        int n;
        cin >> n;
        int a[n];
        Up(i,0,n)
        {
            cin >> a[i];
        }
        int cnt = 0;  //统计有多少个数后面的数比该数要小
        Up(i,0,n)
        {
            Up(j,i+1,n)
            {
                if(a[j] < a[i])
                {
                    cnt++;
                    break;
                }
            }
        }
        cout << cnt << endl;
    }
    return 0;
}

AC代码:

#include <bits/stdc++.h>
using namespace std;
#define Up(i,a,b) for(int i = a; i <= b; i++)
#define Down(i,a,b) for(int i = a; i >= b; i--)
int main()
{
    ios::sync_with_stdio(false);   //取消cin和stdin的同步
    int t;
    cin >> t;
    while(t--)
    {
        int n;
        cin >> n;
        int a[n];
        Up(i,0,n-1)
        {
            cin >> a[i];
        }
        int cnt = 0, _ = a[n-1];   //cnt记录前面有多少个数比该数要大,_表示当前最小数
        Down(i,n-1,0)
        {
            _ = min(_,a[i]);
            if(a[i] > _)
            {
                cnt++;
            }
        }
        cout << cnt << endl;
    }
    return 0;
}