📌  相关文章
📜  每个元素返回到其初始位置所需的随机播放次数

📅  最后修改于: 2021-05-14 02:20:21             🧑  作者: Mango

给定一个整数数组arr [] ,该数组包含从1N的整数排列。令K []为任意数组。数组arr [i]中的每个元素都代表该元素的索引,该元素最初位于数组K []中的位置“ i”。任务是找到需要在K []上执行以将元素返回到初始位置的随机播放次数。

注意:假定必须在K []上进行至少1次混洗(即,最初位于数组K []中的位置“ i”的元素必须放置在索引arr [i]中)对于数组K []中的所有元素至少一次。

例子:

幼稚的方法:针对此问题的幼稚的方法是计算每个元素所需的随机播放次数。该方法的时间复杂度为O(N 2 )

高效方法:解决此问题的有效方法是首先计算问题中的循环数。同一周期中的元素具有相同数量的混洗。例如,在给定数组arr [] = {3,4,1,2}中:

  • 每次洗牌时,第一个元素始终排在第三位,第三个元素始终排在第一位。
  • 因此,可以得出结论,两个要素都处于循环中。因此,与数组K []无关,这两个元素所采用的混洗次数为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


输出:
2 3 3 2 1 3

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