题解:P1428 小鱼比可爱

· · 题解

P1428 小鱼比可爱【题解】

第一眼先看数据范围,n \le 100,考虑直接 O(n^{2}) 双重循环暴力。

我们先遍历每条鱼,然后再遍历这条鱼左边的所有鱼,用一个 cnt 变量统计在这条鱼左边的所有可爱值小于这条鱼的鱼的数量,然后在遍历下一条鱼之前输出 cnt 就可以啦!!!

AC Code:

#include <bits/stdc++.h>
using namespace std;
const int N = 100 + 5;
int n, a[N];

inline int read(){      // 快读,用于加速读入,可用cin代替
    int f = 1, x = 0;
    char c = getchar();
    while(c < '0' || c > '9'){if(c == '-') f = -1; c = getchar();}
    while('0' <= c && c <= '9') x = (x << 3) + (x << 1) + (int)(c - '0'), c = getchar();
    return x * f;
}

int main(){
    n = read();
    for(int i = 1; i <= n; i++) a[i] = read();
    for(int i = 1; i <= n; i++){       // 遍历每条鱼
        int cnt = 0;      // 计数变量(答案)
        for(int j = 1; j < i; j++) if(a[j] < a[i]) cnt++;      // 遍历在第i条鱼左边的所有鱼,如果可爱值比第i条鱼小,cnt++
        cout << cnt << ' ';      // 由于以后的答案都跟这个答案没有关系,可以直接输出
    }
    cout << "\n";
    return 0;
}