题解-AT4516

· · 题解

简要分析

大小为 x 一定会放在位置 x 上,所以我们可以考虑倒推整个过程

每次从后往前找到第一个满足 a[x]==x 的,将其存到答案中,然后暴力将其后面的所有往前一位

因为是从后往前找到的第一个,所以必然不会影响到之后的答案

如果找不到符合条件的数,那么就输出无解

因为整个过程是倒推的,所以最后答案也要反过来输出

时间复杂度为 O(n^2)

完整代码

#include <bits/stdc++.h>
#define int long long
#define ri register int
#define N 105
using namespace std;
int n, a[N], ans[N];
template <typename T>
inline void read(T &x)
{
    register T f = 0, c = getchar();
    for (; c < 48 || 57 < c; c = getchar())
        if (c == '-')
            f = 1;
    for (x = 0; 48 <= c && c <= 57; c = getchar())
        x = (x << 3) + (x << 1) + (c & 15);
    if (f)
        x = ~(--x);
}
template <typename T>
inline void print(T x)
{
    if (x < 0)
        putchar('-'), x = ~(--x);
    if (x > 9)
        print(x / 10);
    putchar(x % 10 | 48);
}
signed main()
{
    read(n);
    for (ri i = 1; i <= n; ++i)
        read(a[i]);
    for (ri i = n, f; i; --i)
    {
        f = 1;
        for (ri j = i; j && f; --j)
            if (a[j] == j)
                ans[i] = j, f = 0;
        if (f)
        {
            puts("-1");
            return 0;
        }
        for (ri j = ans[i]; j < i; ++j)
            a[j] = a[j + 1];
    }
    for (ri i = 1; i <= n; ++i)
        print(ans[i]), puts("");
    return 0;
}