给定前N个自然数的排列{P 1 ,P 2 ,P 3 ,….. P N ) 。任务是检查是否有可能通过交换任意两个数字来增加排列。如果已经按升序排列,则什么也不做。
例子:
Input: a[] = {5, 2, 3, 4, 1}
Output: Yes
Swap 1 and 5
Input: a[] = {1, 2, 3, 4, 5}
Output: Yes
Already in increasing order
Input: a[] = {5, 2, 1, 4, 3}
Output: No
方法:设K为P 1 ≠i (基于1的索引)的位置i的数量。如果K = 0 ,则答案为“是”,因为排列可以保持原样。如果K = 2 ,则答案也为“是” :交换两个放错位置的元素。 (注意,如果将任何元素放置在错误的位置,永远不可能使K = 1 ,原本应该放置在该位置的元素也必须放错位置。)如果K> 2,则答案为否:一次交换只能影响两个元素,因此最多只能校正两个错位。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function that returns true if it is
// possible to make the permutation
// increasing by swapping any two numbers
bool isPossible(int a[], int n)
{
// To count misplaced elements
int k = 0;
// Count all misplaced elements
for (int i = 0; i < n; i++) {
if (a[i] != i + 1)
k++;
}
// If possible
if (k <= 2)
return true;
return false;
}
// Driver code
int main()
{
int a[] = { 5, 2, 3, 4, 1 };
int n = sizeof(a) / sizeof(a[0]);
if (isPossible(a, n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function that returns true if it is
// possible to make the permutation
// increasing by swapping any two numbers
static boolean isPossible(int a[], int n)
{
// To count misplaced elements
int k = 0;
// Count all misplaced elements
for (int i = 0; i < n; i++)
{
if (a[i] != i + 1)
k++;
}
// If possible
if (k <= 2)
return true;
return false;
}
// Driver code
public static void main(String[] args)
{
int a[] = { 5, 2, 3, 4, 1 };
int n = a.length;
if (isPossible(a, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Code_Mech
Python3
# Python3 implementation of the approach
# Function that returns true if it is
# possible to make the permutation
# increasing by swapping any two numbers
def isPossible(a, n) :
# To count misplaced elements
k = 0;
# Count all misplaced elements
for i in range(n) :
if (a[i] != i + 1) :
k += 1;
# If possible
if (k <= 2) :
return True;
return False;
# Driver code
if __name__ == "__main__" :
a = [5, 2, 3, 4, 1 ];
n = len(a);
if (isPossible(a, n)) :
print("Yes");
else :
print("No");
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function that returns true if it is
// possible to make the permutation
// increasing by swapping any two numbers
static Boolean isPossible(int []a, int n)
{
// To count misplaced elements
int k = 0;
// Count all misplaced elements
for (int i = 0; i < n; i++)
{
if (a[i] != i + 1)
k++;
}
// If possible
if (k <= 2)
return true;
return false;
}
// Driver code
public static void Main(String[] args)
{
int []a = { 5, 2, 3, 4, 1 };
int n = a.Length;
if (isPossible(a, n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by 29AjayKumar
Javascript
输出:
Yes