使用C++编写代码,找到具有K个逆序对的排列数量

2023年 8月 30日 49.9k 0

使用C++编写代码,找到具有K个逆序对的排列数量

在数组中,如果 a[i] > a[j] 且 i

Input: N = 4, K = 1
Output: 3
Explanation: Permutation of the first N numbers in total : 1234, 1243, 1324 and 2134. With 1 inversion we have 1243, 1324 and 2134.

Input : N = 3, K = 2
Output : 3
Explanation: Permutation of the first N numbers in total : 123, 132, 213, 231, 312, and 321 with 2 inversions we have 231, 312 and 321.

登录后复制

求解的方法

我们可以采用蛮力法,首先找到前N个数的所有排列,然后检查所有的反转是否相等是否K。如果是,则增加结果计数器。

高效方法

在这种方法中,我们有前 N 个自然数的 N 位。该数字的所有排列都是在其他地方计算的,我们从中寻找 K 个排列。为了找到它,我们将在所有排列中插入下一个数字 Nth(最大),并在添加该数字后查找反转计数等于 K 的数字应计入我们的结果中。采用没有 (K – 3) 个反转的 (N – 1) 个数字的排列,我们将在最后一个索引的第三个索引处移动新数字。反转次数为 K,find_permutations(N-1, K-3) 将是我们的答案。相同的逻辑可以用于其他反转,我们将得到上述递归作为最终答案。

输入

#include
using namespace std;
const int X = 100;
int a = 0;
int arr[X][X];
// recursive function
int find_permutations (int N_numbers, int K_inversion){
if (N_numbers == 0){
return 0; // return 0 when N becomes 0
}
if (K_inversion == 0)
return 1; // return 1 when K becomes 1
if (arr[N_numbers][K_inversion] != 0)
return arr[N_numbers][K_inversion];
int result = 0;
for (int i = 0; i N; // taking input from user
cin >> K;
cout

相关文章

如何删除WordPress中的所有评论
检查WordPress服务器磁盘使用情况的7种简便方法(查找大文件和数据)
如何更改WordPress常量FS_METHOD
如何为区块编辑器、Elementor等构建WordPress文章模板
如何彻底地删除WordPress主题及相关内容
如何使用WordPress搭建一个内网

发布评论