102762: [AtCoder]ABC276 C - Previous Permutation

Memory Limit:256 MB Time Limit:2 S
Judge Style:Text Compare Creator:
Submit:5 Solved:0

Description

Score : $300$ points

Problem Statement

You are given a permutation $P = (P_1, \dots, P_N)$ of $(1, \dots, N)$, where $(P_1, \dots, P_N) \neq (1, \dots, N)$.

Assume that $P$ is the $K$-th lexicographically smallest among all permutations of $(1 \dots, N)$. Find the $(K-1)$-th lexicographically smallest permutation.

What are permutations?

A permutation of $(1, \dots, N)$ is an arrangement of $(1, \dots, N)$ into a sequence.

What is lexicographical order?

For sequences of length $N$, $A = (A_1, \dots, A_N)$ and $B = (B_1, \dots, B_N)$, $A$ is said to be strictly lexicographically smaller than $B$ if and only if there is an integer $1 \leq i \leq N$ that satisfies both of the following.

  • $(A_{1},\ldots,A_{i-1}) = (B_1,\ldots,B_{i-1}).$
  • $A_i < B_i$.

Constraints

  • $2 \leq N \leq 100$
  • $1 \leq P_i \leq N \, (1 \leq i \leq N)$
  • $P_i \neq P_j \, (i \neq j)$
  • $(P_1, \dots, P_N) \neq (1, \dots, N)$
  • All values in the input are integers.

Input

The input is given from Standard Input in the following format:

$N$
$P_1$ $\ldots$ $P_N$

Output

Let $Q = (Q_1, \dots, Q_N)$ be the sought permutation. Print $Q_1, \dots, Q_N$ in a single line in this order, separated by spaces.


Sample Input 1

3
3 1 2

Sample Output 1

2 3 1

Here are the permutations of $(1, 2, 3)$ in ascending lexicographical order.

  • $(1, 2, 3)$
  • $(1, 3, 2)$
  • $(2, 1, 3)$
  • $(2, 3, 1)$
  • $(3, 1, 2)$
  • $(3, 2, 1)$

Therefore, $P = (3, 1, 2)$ is the fifth smallest, so the sought permutation, which is the fourth smallest $(5 - 1 = 4)$, is $(2, 3, 1)$.


Sample Input 2

10
9 8 6 5 10 3 1 2 4 7

Sample Output 2

9 8 6 5 10 2 7 4 3 1

Input

题意翻译

给出 1 到 $N$ 的一个排列(保证不是字典序最小的排列),求它按照字典序的上一个排列。

Output

分数:300分

问题描述

给定一个排列 $P = (P_1, \dots, P_N)$,其中 $(P_1, \dots, P_N) \neq (1, \dots, N)$。

假设 $P$ 是所有 $(1 \dots, N)$ 的排列中字典序第 $K$ 小的排列。找出字典序第 $(K-1)$ 小的排列。

什么是排列?

一个 $(1, \dots, N)$ 的 排列 是将 $(1, \dots, N)$ 排列成一个序列。

什么是字典序?

对于长度为 $N$ 的序列 $A = (A_1, \dots, A_N)$ 和 $B = (B_1, \dots, B_N)$,当且仅当满足以下两个条件时,称 $A$ 是 $B$ 的 严格字典序小于 的。

  • $(A_{1},\ldots,A_{i-1}) = (B_1,\ldots,B_{i-1}).$
  • $A_i < B_i$。

约束条件

  • $2 \leq N \leq 100$
  • $1 \leq P_i \leq N \, (1 \leq i \leq N)$
  • $P_i \neq P_j \, (i \neq j)$
  • $(P_1, \dots, P_N) \neq (1, \dots, N)$
  • 输入中的所有值都是整数。

输入

输入从标准输入按以下格式给出:

$N$
$P_1$ $\ldots$ $P_N$

输出

设 $Q = (Q_1, \dots, Q_N)$ 是所需的排列。按顺序在一行中打印 $Q_1, \dots, Q_N$,用空格分隔。


样例输入 1

3
3 1 2

样例输出 1

2 3 1

以下是 $(1, 2, 3)$ 的排列按字典序递增顺序排列:

  • $(1, 2, 3)$
  • $(1, 3, 2)$
  • $(2, 1, 3)$
  • $(2, 3, 1)$
  • $(3, 1, 2)$
  • $(3, 2, 1)$

因此,$P = (3, 1, 2)$ 是第五小的排列,所以所需的排列,即第四小的 $(5 - 1 = 4)$,是 $(2, 3, 1)$。


样例输入 2

10
9 8 6 5 10 3 1 2 4 7

样例输出 2

9 8 6 5 10 2 7 4 3 1

加入题单

算法标签: