Cho một mảng a [] chứa N số nguyên, thử thách là in k hoán vị khác nhau của các chỉ số sao cho các giá trị tại các chỉ số đó tạo thành một dãy không giảm. In -1 nếu không thể.
Ví dụ
Input: arr[] = {2,5,6,2,2,2,2}, k = 4
Output:
0 3 4 5 6 1 2
3 0 4 5 6 1 2
0 3 4 5 6 1 2
3 0 4 5 6 1 2 Sắp xếp mảng đã cho và theo dõi các chỉ số ban đầu của mỗi phần tử. Điều đó mang lại một hoán vị bắt buộc. Bây giờ nếu bất kỳ 2 phần tử liên tục nào bằng nhau thì chúng có thể được đổi chỗ để có được một hoán vị khác. Tương tự, hoán vị thứ ba có thể được tạo.
Thuật toán
START
Step 1 -> Declare Function void indice(int n, pair<int, int> array[])
Loop For int i=0 and i<n and i++
Print array[i].second
End
Step 2 -> Declare Function void permutation(int n, int a[], int k)
Use STL pair<int, int> arr[n]
Loop for int i=0 and i<n and i++
Set arr[i].first = a[i]
Set arr[i].second = i
End
Call sort(arr, arr + n)
Declare int count to 1
Loop For int i=1 and i<n and i++
IF (arr[i].first == arr[i - 1].first)
Increment count by 1
End
End
IF count < k
Return -1
End
Loop For int i = 0 and i < k – 1 and i++
Call indice(n, arr)
Loop For int j = 1 and j < n and j++
IF arr[j].first == arr[j - 1].first
Call swap(arr[j], arr[j - 1])
Break
End
End
End
Call indice(n, arr)
Step 3 -> In main()
Declare array a[]={2,5,6,2,2,2,2}
Declare int n= sizeof(a)/sizeof(a[0])
Declare int k=4
Call permutation(n,a,k)
STOP Ví dụ
#include <bits/stdc++.h>
using namespace std;
void indice(int n, pair<int, int> array[]){
for (int i = 0; i < n; i++)
cout << array[i].second << " ";
cout << endl;
}
void permutation(int n, int a[], int k){
pair<int, int> arr[n];
for (int i = 0; i < n; i++){
arr[i].first = a[i];
arr[i].second = i;
}
sort(arr, arr + n);
int count = 1;
for (int i = 1; i < n; i++)
if (arr[i].first == arr[i - 1].first)
count++;
if (count < k){
cout << "-1";
return;
}
for (int i = 0; i < k - 1; i++){
indice(n, arr);
for (int j = 1; j < n; j++){
if (arr[j].first == arr[j - 1].first){
swap(arr[j], arr[j - 1]);
break;
}
}
}
indice(n, arr);
}
int main(){
int a[] ={2,5,6,2,2,2,2};
int n = sizeof(a) / sizeof(a[0]);
int k = 4;
permutation(n, a, k);
return 0;
} Đầu ra
nếu chúng ta chạy chương trình trên thì nó sẽ tạo ra kết quả sau
0 3 4 5 6 1 2 3 0 4 5 6 1 2 0 3 4 5 6 1 2 3 0 4 5 6 1 2