📌  相关文章
📜  使一群人坐在一起所需的最小跳跃

📅  最后修改于: 2021-04-29 13:17:52             🧑  作者: Mango

给定长度为N的字符串S ,该字符串由“ x”“。”组成。给定的字符串表示一行座位,其中“ x”“。”分别代表已占用和未占用的座位。任务是最大程度地减少跳跃或跳跃的总数,以使所有乘员坐在一起,即彼此相邻,而在他们之间没有任何空位。

注意:由于跳转的次数可能非常大,因此请以10 9 + 7为模数打印答案。

例子:

方法:想法是使用贪婪方法解决此问题。请注意,将元素向所有人员中的中间元素或中心人员中的中间元素移动总是最佳的。当我们将点移动到中位数时,跳跃次数将始终是最小的。步骤如下:

  • 初始化向量位置以存储在场人员的索引。
  • 找到向量position []的中位数。现在将使所有其他人员坐在该人员周围,因为这将使所需的跳次数最少。
  • 初始化变量ans ,该变量存储所需的最小跳转。
  • 现在,遍历向量position [] ,对于每个索引,找到中值元素并将ans更新为:
  • 完成上述步骤后,将ans的值打印为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
long long int MOD = 1e9 + 7;
 
// Function to find the minimum jumps
// required to make the whole group
// sit adjacently
int minJumps(string seats)
{
    // Store the indexes
    vector position;
 
    // Stores the count of occupants
    int count = 0;
 
    // Length of the string
    int len = seats.length();
 
    // Traverse the seats
    for (int i = 0; i < len; i++) {
 
        // If current place is occupied
        if (seats[i] == 'x') {
 
            // Push the current position
            // in the vector
            position.push_back(i - count);
            count++;
        }
    }
 
    // Base Case:
    if (count == len || count == 0)
        return 0;
 
    // The index of the median element
    int med_index = (count - 1) / 2;
 
    // The value of the median element
    int med_val = position[med_index];
 
    int ans = 0;
 
    // Traverse the position[]
    for (int i = 0;
         i < position.size(); i++) {
 
        // Update the ans
        ans = (ans % MOD
               + abs(position[i]
                     - med_val)
                     % MOD)
              % MOD;
    }
 
    // Return the final count
    return ans % MOD;
}
 
// Driver Code
int main()
{
    // Given arrange of seats
    string S = "....x..xx...x..";
 
    // Function Call
    cout << minJumps(S);
 
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
class GFG{
 
static int MOD = (int)1e9 + 7;
 
// Function to find the minimum
// jumps required to make the
// whole group sit adjacently
static int minJumps(String seats)
{
  // Store the indexes
  Vector position =
                  new Vector<>();
 
  // Stores the count of
  // occupants
  int count = 0;
 
  // Length of the String
  int len = seats.length();
 
  // Traverse the seats
  for (int i = 0; i < len; i++)
  {
    // If current place is occupied
    if (seats.charAt(i) == 'x')
    {
      // Push the current position
      // in the vector
      position.add(i - count);
      count++;
    }
  }
 
  // Base Case:
  if (count == len ||
      count == 0)
    return 0;
 
  // The index of the median
  // element
  int med_index = (count - 1) / 2;
 
  // The value of the median
  // element
  int med_val = position.get(med_index);
 
  int ans = 0;
 
  // Traverse the position[]
  for (int i = 0;
           i < position.size(); i++)
  {
    // Update the ans
    ans = (ans % MOD +
           Math.abs(position.get(i) -
                    med_val) % MOD) % MOD;
  }
 
  // Return the final count
  return ans % MOD;
}
 
// Driver Code
public static void main(String[] args)
{
  // Given arrange of seats
  String S = "....x..xx...x..";
 
  // Function Call
  System.out.print(minJumps(S));
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program for the above approach
MOD = 10**9 + 7
 
# Function to find the minimum jumps
# required to make the whole group
# sit adjacently
def minJumps(seats):
     
    # Store the indexes
    position = []
 
    # Stores the count of occupants
    count = 0
 
    # Length of the string
    lenn = len(seats)
 
    # Traverse the seats
    for i in range(lenn):
 
        # If current place is occupied
        if (seats[i] == 'x'):
 
            # Push the current position
            # in the vector
            position.append(i - count)
            count += 1
 
    # Base Case:
    if (count == lenn or count == 0):
        return 0
 
    # The index of the median element
    med_index = (count - 1) // 2
 
    # The value of the median element
    med_val = position[med_index]
 
    ans = 0
 
    # Traverse the position[]
    for i in range(len(position)):
         
        # Update the ans
        ans = (ans % MOD +
               abs(position[i] - med_val)
               % MOD) % MOD
 
    # Return the final count
    return ans % MOD
 
# Driver Code
if __name__ == '__main__':
     
    # Given arrange of seats
    S = "....x..xx...x.."
 
    # Function Call
    print(minJumps(S))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
static int MOD = (int)1e9 + 7;
 
// Function to find the minimum
// jumps required to make the
// whole group sit adjacently
static int minJumps(String seats)
{
  // Store the indexes
  List position =
       new List();
 
  // Stores the count of
  // occupants
  int count = 0;
 
  // Length of the String
  int len = seats.Length;
 
  // Traverse the seats
  for (int i = 0; i < len; i++)
  {
    // If current place is
    // occupied
    if (seats[i] == 'x')
    {
      // Push the current
      // position in the
      // vector
      position.Add(i - count);
      count++;
    }
  }
 
  // Base Case:
  if (count == len ||
      count == 0)
    return 0;
 
  // The index of the median
  // element
  int med_index = (count - 1) / 2;
 
  // The value of the median
  // element
  int med_val = position[med_index];
 
  int ans = 0;
 
  // Traverse the position[]
  for (int i = 0;
           i < position.Count; i++)
  {
    // Update the ans
    ans = (ans % MOD +
           Math.Abs(position[i] -
           med_val) % MOD) % MOD;
  }
 
  // Return the readonly
  // count
  return ans % MOD;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given arrange of seats
  String S = "....x..xx...x..";
 
  // Function Call
  Console.Write(minJumps(S));
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
5

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