📜  每个元素返回其初始位置所需的 shuffle 次数

📅  最后修改于: 2021-09-04 08:35:17             🧑  作者: Mango

给定一个整数数组arr[] ,其中包含从1N的整数排列。令K[]为任意数组。数组 arr[i] 中的每个元素表示元素的索引,该元素最初位于数组 K[] 中的位置“i”处。任务是找到需要在 K[] 上执行的 shuffle 次数,以使元素回到初始位置。
注意:假设必须对K[]进行至少 1 次 shuffle(即),必须将最初位于数组K[] 中位置 ‘i’ 的元素放置在索引arr[i] 中对数组 K[] 中的所有元素至少一次。
例子:

朴素的方法:这个问题的朴素的方法是计算每个元素所需的 shuffle 次数。这种方法的时间复杂度为O(N 2 )
有效方法:解决此问题的有效方法是首先计算问题中的循环数。同一循环中的元素具有相同的shuffle次数。例如,在给定的数组 arr[] = {3, 4, 1, 2} 中:

  • 在每次洗牌时,第一个元素总是排在第三位,而第三个元素总是排在第一位。
  • 因此,可以得出结论,这两个元素都在一个循环中。因此,无论数组K[]是什么,对这两个元素进行的 shuffle 次数都是 2。
  • 因此,想法是在数组中找到此类循环的数量并跳过这些元素。

下面是上述方法的实现:

C++
// C++ program to find the number of
// shuffles required for each element
// to return to its initial position
 
#include 
using namespace std;
 
// Function to count the number of
// shuffles required for each element
// to return to its initial position
void countShuffles(int* A, int N)
{
    // Initialize array to store
    // the counts
    int count[N];
 
    // Initialize visited array to
    // check if visited before or not
    bool vis[N];
    memset(vis, false, sizeof(vis));
 
    // Making the array 0-indexed
    for (int i = 0; i < N; i++)
        A[i]--;
 
    for (int i = 0; i < N; i++) {
        if (!vis[i]) {
 
            // Initialize vector to store the
            // elements in the same cycle
            vector cur;
 
            // Initialize variable to store
            // the current element
            int pos = i;
 
            // Count number of shuffles
            // for current element
            while (!vis[pos]) {
 
                // Store the elements in
                // the same cycle
                cur.push_back(pos);
 
                // Mark visited
                vis[pos] = true;
 
                // Make the shuffle
                pos = A[pos];
            }
 
            // Store the result for all the
            // elements in the same cycle
            for (auto el : cur)
                count[el] = cur.size();
        }
    }
 
    // Print the result
    for (int i = 0; i < N; i++)
        cout << count[i] << " ";
    cout << endl;
}
 
// Driver code
int main()
{
    int arr[] = { 4, 6, 2, 1, 5, 3 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    countShuffles(arr, N);
 
    return 0;
}


Java
// Java program to find the number of
// shuffles required for each element
// to return to its initial position
import java.util.*;
 
class GFG {
 
// Function to count the number of
// shuffles required for each element
// to return to its initial position
static void countShuffles(int[] A, int N)
{
     
    // Initialize array to store
    // the counts
    int[] count = new int[N];
 
    // Initialize visited array to
    // check if visited before or not
    boolean[] vis = new boolean[N];
 
    // Making the array 0-indexed
    for(int i = 0; i < N; i++)
       A[i]--;
 
    for(int i = 0; i < N; i++)
    {
       if (!vis[i])
       {
            
           // Initialize vector to store the
           // elements in the same cycle
           Vector cur = new Vector<>(); 
            
           // Initialize variable to store
           // the current element
           int pos = i;
            
           // Count number of shuffles
           // for current element
           while (!vis[pos])
           {
                
               // Store the elements in
               // the same cycle
               cur.add(pos);
                
               // Mark visited
               vis[pos] = true;
                
               // Make the shuffle
               pos = A[pos];
            }
             
            // Store the result for all the
            // elements in the same cycle
            for(int k = 0; k < cur.size(); k++)
               count[cur.get(k)] = cur.size();
       }
    }
     
    // Print the result
    for(int k = 0; k < N; k++)
       System.out.print(count[k] + " ");
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 4, 6, 2, 1, 5, 3 };
    int N = arr.length;
 
    countShuffles(arr, N);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program to find the number of
# shuffles required for each element
# to return to its initial position
 
# Function to count the number of
# shuffles required for each element
# to return to its initial position
def countShuffles(A, N):
 
    # Initialize array to store
    # the counts
    count = [0] * N
 
    # Initialize visited array to
    # check if visited before or not
    vis = [False] * N
 
    # Making the array 0-indexed
    for i in range(N):
        A[i] -= 1
 
    for i in range(N):
        if (not vis[i]):
 
            # Initialize vector to store the
            # elements in the same cycle
            cur = []
 
            # Initialize variable to store
            # the current element
            pos = i
 
            # Count number of shuffles
            # for current element
            while (not vis[pos]):
 
                # Store the elements in
                # the same cycle
                cur.append(pos)
 
                # Mark visited
                vis[pos] = True
 
                # Make the shuffle
                pos = A[pos]
 
            # Store the result for all the
            # elements in the same cycle
            for el in cur:
                count[el] = len(cur)
 
    # Print the result
    for i in range(N):
        print(count[i], end = " ")
    print()
 
# Driver code
if __name__ == "__main__":
     
    arr = [ 4, 6, 2, 1, 5, 3 ]
    N = len(arr)
    countShuffles(arr, N)
     
# This code is contributed by chitranayal


C#
// C# program to find the number of
// shuffles required for each element
// to return to its initial position
using System;
using System.Collections;
 
class GFG{
 
// Function to count the number of
// shuffles required for each element
// to return to its initial position
static void countShuffles(int[] A, int N)
{
     
    // Initialize array to store
    // the counts
    int[] count = new int[N];
 
    // Initialize visited array to
    // check if visited before or not
    bool[] vis = new bool[N];
 
    // Making the array 0-indexed
    for(int i = 0; i < N; i++)
        A[i]--;
 
    for(int i = 0; i < N; i++)
    {
        if (!vis[i])
        {
             
            // Initialize vector to store the
            // elements in the same cycle
            ArrayList cur = new ArrayList();
         
            // Initialize variable to store
            // the current element
            int pos = i;
                 
            // Count number of shuffles
            // for current element
            while (!vis[pos])
            {
                 
                // Store the elements in
                // the same cycle
                cur.Add(pos);
                     
                // Mark visited
                vis[pos] = true;
                     
                // Make the shuffle
                pos = A[pos];
            }
             
            // Store the result for all the
            // elements in the same cycle
            for(int k = 0; k < cur.Count; k++)
                count[(int)cur[k]] = cur.Count;
        }
    }
     
    // Print the result
    for(int k = 0; k < N; k++)
        Console.Write(count[k] + " ");
}
 
// Driver code
public static void Main(string[] args)
{
    int []arr = { 4, 6, 2, 1, 5, 3 };
    int N = arr.Length;
 
    countShuffles(arr, N);
}
}
 
// This code is contributed by rutvik_56


Javascript


输出:
2 3 3 2 1 3

时间复杂度: O(N) ,其中 N 是数组的大小。

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live