📌  相关文章
📜  检查数组是否可以仅使用给定索引之间的交换进行排序

📅  最后修改于: 2021-10-25 03:06:22             🧑  作者: Mango

给定一个大小为N的数组arr[]由范围[0, N – 1] 中的不同整数组成,这些整数以随机顺序排列。还给出了几对,其中每对表示可以交换数组元素的索引。允许的掉期数量没有限制。任务是找出是否可以使用这些交换按升序排列数组。如果可能,则打印Yes否则打印No
例子:

方法:给定的问题可以被认为是一个图问题,其中N表示图中节点的总数,每个交换对表示图中的一条无向边。我们必须找出是否可以将输入数组转换为{0, 1, 2, 3, …, N – 1} 的形式
让我们将上面的数组称为 B。现在找出两个数组的所有连接组件,如果至少一个组件的元素不同,则答案为No ,否则答案为Yes
下面是上述方法的实现:

CPP
// C++ implementation of the approach
#include 
using namespace std;
 
// Function that returns true if the array elements
// can be sorted with the given operation
bool canBeSorted(int N, vector a, int P,
vector > vp)
{
 
    // To create the adjacency list of the graph
    vector v[N];
 
    // Boolean array to mark the visited nodes
    bool vis[N] = { false };
 
    // Creating adjacency list for undirected graph
    for (int i = 0; i < P; i++) {
        v[vp[i].first].push_back(vp[i].second);
        v[vp[i].second].push_back(vp[i].first);
    }
 
    for (int i = 0; i < N; i++) {
 
        // If not already visited
        // then apply BFS
        if (!vis[i]) {
            queue q;
            vector v1;
            vector v2;
 
            // Set visited to true
            vis[i] = true;
 
            // Push the node to the queue
            q.push(i);
 
            // While queue is not empty
            while (!q.empty()) {
                int u = q.front();
                v1.push_back(u);
                v2.push_back(a[u]);
                q.pop();
 
                // Check all the adjacent nodes
                for (auto s : v[u]) {
 
                    // If not visited
                    if (!vis[s]) {
 
                        // Set visited to true
                        vis[s] = true;
                        q.push(s);
                    }
                }
            }
            sort(v1.begin(), v1.end());
            sort(v2.begin(), v2.end());
 
            // If the connected component does not
            // contain same elements then return false
            if (v1 != v2)
                return false;
        }
    }
    return true;
}
 
// Driver code
int main()
{
    vector a = { 0, 4, 3, 2, 1, 5 };
    int n = a.size();
    vector > vp = { { 1, 4 }, { 2, 3 } };
    int p = vp.size();
 
    if (canBeSorted(n, a, p, vp))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Java
// Java implementation of the approach
import java.io.*;
import java.util.*;
class GFG
{
   
  // Function that returns true if the array elements
  // can be sorted with the given operation
  static boolean canBeSorted(int N, ArrayList a,
                             int p, ArrayList> vp)
  {
     
    // To create the adjacency list of the graph
    ArrayList> v = new ArrayList>();
    for(int i = 0; i < N; i++)
    {
      v.add(new ArrayList());
    }
     
    // Boolean array to mark the visited nodes
    boolean[] vis = new boolean[N];
 
    // Creating adjacency list for undirected graph
    for (int i = 0; i < p; i++)
    {
      v.get(vp.get(i).get(0)).add(vp.get(i).get(1));
      v.get(vp.get(i).get(1)).add(vp.get(i).get(0));
    }
    for (int i = 0; i < N; i++)
    {
       
      // If not already visited
      // then apply BFS
      if (!vis[i])
      {
        Queue q = new LinkedList<>();
        ArrayList v1 = new ArrayList();
        ArrayList v2 = new ArrayList();
 
        // Set visited to true    
        vis[i] = true;
 
        // Push the node to the queue
        q.add(i);
 
        // While queue is not empty
        while (q.size() > 0)
        {
          int u = q.poll();
          v1.add(u);
          v2.add(a.get(u));
 
          // Check all the adjacent nodes
          for(int s: v.get(u))
          {
             
            // If not visited
            if (!vis[s])
            {
               
              // Set visited to true
              vis[s] = true;
              q.add(s);
            }
          }
 
        }
        Collections.sort(v1);
        Collections.sort(v2);
 
        // If the connected component does not
        // contain same elements then return false
        if(!v1.equals(v2))
        {
          return false;
        }
      }
    }
    return true;
  }
 
  // Driver code
  public static void main (String[] args)
  {
    ArrayList a = new ArrayList(Arrays.asList(0, 4, 3, 2, 1, 5));
    int n = a.size();
    ArrayList> vp = new ArrayList>();
    vp.add(new ArrayList(Arrays.asList(1, 4)));
    vp.add(new ArrayList(Arrays.asList(2, 3)));
    int p = vp.size();
    if (canBeSorted(n, a, p, vp))
    {
      System.out.println("Yes");   
    }
    else
    {
      System.out.println("No");
    }
 
  }
}
 
// This code is contributed by avanitrachhadiya2155


Python3
# Python3 implementation of the approach
from collections import deque as queue
 
# Function that returns true if the array elements
# can be sorted with the given operation
def canBeSorted(N, a, P, vp):
 
    # To create the adjacency list of the graph
    v = [[] for i in range(N)]
 
    # Boolean array to mark the visited nodes
    vis = [False]*N
 
    # Creating adjacency list for undirected graph
    for i in range(P):
        v[vp[i][0]].append(vp[i][1])
        v[vp[i][1]].append(vp[i][0])
 
    for i in range(N):
 
        # If not already visited
        # then apply BFS
        if (not vis[i]):
            q = queue()
            v1 = []
            v2 = []
 
            # Set visited to true
            vis[i] = True
 
            # Push the node to the queue
            q.append(i)
 
            # While queue is not empty
            while (len(q) > 0):
                u = q.popleft()
                v1.append(u)
                v2.append(a[u])
 
                # Check all the adjacent nodes
                for s in v[u]:
 
                    # If not visited
                    if (not vis[s]):
 
                        # Set visited to true
                        vis[s] = True
                        q.append(s)
 
            v1 = sorted(v1)
            v2 = sorted(v2)
 
            # If the connected component does not
            # contain same elements then return false
            if (v1 != v2):
                return False
    return True
 
# Driver code
if __name__ == '__main__':
    a = [0, 4, 3, 2, 1, 5]
    n = len(a)
    vp = [ [ 1, 4 ], [ 2, 3 ] ]
    p = len(vp)
 
    if (canBeSorted(n, a, p, vp)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by mohit kumar 29


Javascript


输出:

Yes

时间复杂度: O(N)
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程