📌  相关文章
📜  给定操作的范围为[L,R]的数字,该数字具有Kth的最小转换成本为1

📅  最后修改于: 2021-04-28 00:08:33             🧑  作者: Mango

给出三个整数L,RK,其中[L,R]表示元素的范围内,任务是找到在范围要求ķ转换的最小的代价1元素[L,R]。如果两个或更多元素的成本相同,则在其中最小的元素上打印出来。

例子:

天真的方法:最简单的方法是使用递归计算与LR之间的每个元素相关的成本。步骤如下:

  1. 定义一个函数func ,以递归方式计算成本。
  2. 将所有成本要素存储在成对的数组中。
  3. 根据成对的数组对它们进行排序。
  4. 然后从数组中返回第(K-1)索引处的元素。

下面是上述方法的实现:

C++14
// C++14 implementation of
// the above approach
#include 
using namespace std;
 
//Function to calculate the cost
int func(int n)
{
    int count = 0;
 
    // Base case
    if (n == 2 or n == 1)
        return 1;
 
    // Even condtion
    if (n % 2 == 0)
        count = 1 + func(n / 2);
 
    // Odd condtion
    if (n % 2 != 0)
        count = 1 + func(n * 3 + 1);
 
    // Return cost
    return count;
}
 
// Function to find Kth element
void findKthElement(int l, int r, int k)
{
    vector arr;
 
    for(int i = l; i <= r; i++)
        arr.push_back(i);
 
    // Array to store the costs
    vector> result;
 
    for(int i : arr)
        result.push_back({i, func(i)});
 
    // Sort the array based on cost
    sort(result.begin(), result.end());
 
    cout << (result[k - 1][0]);
}
 
// Driver Code
int main()
{
     
    // Given range and6 K
    int l = 12;
    int r = 15;
    int k = 2;
     
    // Function call
    findKthElement(l, r, k);
     
    return 0;
}
 
// This code is contributed by mohit kumar 29


Java
// Java implementation of
// the above approach
import java.util.*;
 
class GFG{
 
// Function to calculate the cost
static int func(int n)
{
    int count = 0;
 
    // Base case
    if (n == 2 || n == 1)
        return 1;
 
    // Even condtion
    if (n % 2 == 0)
        count = 1 + func(n / 2);
 
    // Odd condtion
    if (n % 2 != 0)
        count = 1 + func(n * 3 + 1);
 
    // Return cost
    return count;
}
 
// Function to find Kth element
static void findKthElement(int l, int r, int k)
{
    ArrayList arr = new ArrayList<>();
 
    for(int i = l; i <= r; i++)
        arr.add(i);
 
    // Array to store the costs
    ArrayList> result = new ArrayList<>();
 
    for(int i : arr)
        result.add(Arrays.asList(i, func(i)));
 
    // Sort the array based on cost
    Collections.sort(result, (s1, s2) -> s1.get(1) -
                                         s2.get(1));
 
    System.out.println(result.get(k - 1).get(0));
}
 
// Driver code
public static void main (String[] args)
{
     
    // Given range and6 K
    int l = 12;
    int r = 15;
    int k = 2;
     
    // Function call
    findKthElement(l, r, k);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 implementation of
# the above approach
 
# Function to calculate the cost
def func(n):
    count = 0
     
    # Base case
    if n == 2 or n == 1:
        return 1
     
    # Even condtion
    if n % 2 == 0:  
        count = 1 + func(n//2)
 
    # Odd condtion
    if n % 2 != 0: 
        count = 1 + func(n * 3 + 1)
 
    # Return cost 
    return count
 
# Function to find Kth element
def findKthElement(l, r, k):
    arr = list(range(l, r + 1))
 
    # Array to store the costs
    result = []
    for i in arr:
        result.append([i, func(i)])
 
    # Sort the array based on cost
    result.sort()
    print(result[k-1][0])
 
# Driver Code
 
# Given range and K
l = 12
r = 15
k = 2
 
# Function Call
findKthElement(l, r, k)


C#
// C# implementation of
// the above approach
using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG{
 
// Function to calculate the cost
static int func(int n)
{
    int count = 0;
     
    // Base case
    if (n == 2 || n == 1)
        return 1;
 
    // Even condtion
    if (n % 2 == 0)
        count = 1 + func(n / 2);
 
    // Odd condtion
    if (n % 2 != 0)
        count = 1 + func(n * 3 + 1);
 
    // Return cost
    return count;
}
 
// Function to find Kth element
static void findKthElement(int l, int r, int k)
{
    List arr = new List();
 
    for(int i = l; i <= r; i++)
        arr.Add(i);
 
    // Array to store the costs
    Dictionary result = new Dictionary();
    foreach(int i in arr)
    {
        result.Add(i, func(i));
    }
     
    // Sort the array based on cost
    var myList = result.ToList();
     
    myList.Sort((pair1, pair2) => pair1.Value.CompareTo(
        pair2.Value));
 
    Console.WriteLine(myList[1].Key);
}
 
// Driver code
public static void Main(String[] args)
{
     
    // Given range and6 K
    int l = 12;
    int r = 15;
    int k = 2;
     
    // Function call
    findKthElement(l, r, k);
}
}
 
// This code is contributed by aashish1995


C++
// C++ implementation of the above approach
#include 
using namespace std;
 
// Function to calculate the cost
int func(int n, int dp[])
{
    int count = 0;
 
    // Base case
    if (n == 2 || n == 1)
        return 1;
 
    if (dp[n] != -1)
        return dp[n];
 
    // Even condtion
    if (n % 2 == 0)
        count = 1 + func(n / 2, dp);
 
    // Odd condition
    if (n % 2 != 0)
        count = 1 + func(n * 3 + 1, dp);
 
    // Store the result
    dp[n] = count;
    return dp[n];
}
 
// Function to find Kth element
void findKthElement(int l, int r, int k)
{
 
    // Array to store the results
    vector > result;
 
    // Define DP array
    int dp[r + 1] = {0};
    dp[1] = 1;
    dp[2] = 1;
 
    for(int i = l; i <= r; i++)
        result.push_back({i, func(i, dp)});
 
    // Sort the array based on cost
    sort(result.begin(), result.end());
     
    cout << (result[k - 1].first);
}
 
// Driver code
int main()
{
     
    // Given range and K
    int l = 12;
    int r = 15;
    int k = 2;
 
    // Function call
    findKthElement(l, r, k);
}
 
// This code is contributed by grand_master


Java
// Java implementation of
// the above approach
import java.util.*;
class GFG{
     
static class Pair implements Comparable
{
  int start,end;
   
  Pair(int s, int e)
  {
    start = s;
    end = e;
  }
 
  public int compareTo(Pair p)
  {
    return this.start - p.start;
  }
}
 
// Function to calculate
// the cost
static int func(int n,
                int dp[])
{
  int count = 0;
 
  // Base case
  if (n == 2 ||
      n == 1)
    return 1;
 
  if (dp[n] != -1)
    return dp[n];
 
  // Even condtion
  if (n % 2 == 0)
    count = 1 + func(n / 2, dp);
 
  // Odd condition
  if (n % 2 != 0)
    count = 1 + func(n * 3 +
                     1, dp);
 
  // Store the result
  dp[n] = count;
  return dp[n];
}
 
// Function to find Kth element
static void findKthElement(int l,
                           int r,
                           int k)
{
  // Array to store the
  // results
  Vector result =
         new Vector<>();
 
  // Define DP array
  int []dp = new int[r + 1];
  dp[1] = 1;
  dp[2] = 1;
 
  for(int i = l; i <= r; i++)
    result.add(new Pair(i,
               func(i, dp)));
 
  // Sort the array based
  // on cost
  Collections.sort(result);
 
  System.out.print(
  result.get(k - 1).start);
}
 
// Driver code
public static void main(String[] args)
{   
  // Given range and K
  int l = 12;
  int r = 15;
  int k = 2;
 
  // Function call
  findKthElement(l, r, k);
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 implementation of the above approach
# Function to calculate the cost
def func(n, dp):
    count = 0
 
    # Base case
    if n == 2 or n == 1:
        return 1
    if n in dp:
      return dp[n] 
 
    # Even condtion
    if n % 2 == 0: 
        count = 1 + func(n//2, dp)
 
    # Odd condition
    if n % 2 != 0:  
        count = 1 + func(n * 3 + 1, dp)
 
    # Store the result
    dp[n]= count
    return dp[n]
 
# Function to find Kth element
def findKthElement(l, r, k):
    arr = list(range(l, r + 1))
 
    # Array to store the results
    result = []
 
    # Define DP array
    dp ={1:1, 2:1}
 
    for i in arr:
        result.append([i, func(i, dp)])
 
    # Sort the array based on cost
    result.sort()
    print(result[k-1][0])
 
# Given range and K
l = 12
r = 15
k = 2
 
# Function Call
findKthElement(l, r, k)


C#
// C# implementation of
// the above approach
using System;
using System.Collections;
 
class GFG{
     
class Pair
{
   public int start,end;
    
  public Pair(int s, int e)
  {
    start = s;
    end = e;
  }
}
 
class sortHelper : IComparer
{
   int IComparer.Compare(object a, object b)
   {
      Pair first=(Pair)a;
      Pair second=(Pair)b;
         
      return first.start - second.start;
   }
}
      
  
// Function to calculate
// the cost
static int func(int n, int []dp)
{
  int count = 0;
  
  // Base case
  if (n == 2 || n == 1)
    return 1;
  
  if (dp[n] != -1)
    return dp[n];
  
  // Even condtion
  if (n % 2 == 0)
    count = 1 + func(n / 2, dp);
  
  // Odd condition
  if (n % 2 != 0)
    count = 1 + func(n * 3 +
                     1, dp);
  
  // Store the result
  dp[n] = count;
  return dp[n];
}
  
// Function to find Kth element
static void findKthElement(int l,
                           int r,
                           int k)
{
  // Array to store the
  // results
  ArrayList result =
         new ArrayList();
  
  // Define DP array
  int []dp = new int[r + 1];
  dp[1] = 1;
  dp[2] = 1;
  
  for(int i = l; i <= r; i++)
    result.Add(new Pair(i,
               func(i, dp)));
  
  // Sort the array based
  // on cost
  result.Sort(new sortHelper());
  
  Console.Write(((Pair)result[k - 1]).start);
}
  
// Driver code
public static void Main(string[] args)
{   
  // Given range and K
  int l = 12;
  int r = 15;
  int k = 2;
  
  // Function call
  findKthElement(l, r, k);
}
}
 
// This code is contributed by rutvik_56


输出:
13

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

高效的方法:可以通过使用动态编程来优化上述方法。步骤如下:

  • 为避免重新计算重叠的子问题,请初始化dp []数组,以存储遇到的每个子问题的最低成本,达到1。
  • 更新dp []表的重复关系为:
  • 将所有计算出的成本存储在成对的阵列中
  • 根据成对的数组对它们进行排序。
  • 然后从数组中返回第(K – 1)索引处的元素。

下面是上述方法的实现:

C++

// C++ implementation of the above approach
#include 
using namespace std;
 
// Function to calculate the cost
int func(int n, int dp[])
{
    int count = 0;
 
    // Base case
    if (n == 2 || n == 1)
        return 1;
 
    if (dp[n] != -1)
        return dp[n];
 
    // Even condtion
    if (n % 2 == 0)
        count = 1 + func(n / 2, dp);
 
    // Odd condition
    if (n % 2 != 0)
        count = 1 + func(n * 3 + 1, dp);
 
    // Store the result
    dp[n] = count;
    return dp[n];
}
 
// Function to find Kth element
void findKthElement(int l, int r, int k)
{
 
    // Array to store the results
    vector > result;
 
    // Define DP array
    int dp[r + 1] = {0};
    dp[1] = 1;
    dp[2] = 1;
 
    for(int i = l; i <= r; i++)
        result.push_back({i, func(i, dp)});
 
    // Sort the array based on cost
    sort(result.begin(), result.end());
     
    cout << (result[k - 1].first);
}
 
// Driver code
int main()
{
     
    // Given range and K
    int l = 12;
    int r = 15;
    int k = 2;
 
    // Function call
    findKthElement(l, r, k);
}
 
// This code is contributed by grand_master

Java

// Java implementation of
// the above approach
import java.util.*;
class GFG{
     
static class Pair implements Comparable
{
  int start,end;
   
  Pair(int s, int e)
  {
    start = s;
    end = e;
  }
 
  public int compareTo(Pair p)
  {
    return this.start - p.start;
  }
}
 
// Function to calculate
// the cost
static int func(int n,
                int dp[])
{
  int count = 0;
 
  // Base case
  if (n == 2 ||
      n == 1)
    return 1;
 
  if (dp[n] != -1)
    return dp[n];
 
  // Even condtion
  if (n % 2 == 0)
    count = 1 + func(n / 2, dp);
 
  // Odd condition
  if (n % 2 != 0)
    count = 1 + func(n * 3 +
                     1, dp);
 
  // Store the result
  dp[n] = count;
  return dp[n];
}
 
// Function to find Kth element
static void findKthElement(int l,
                           int r,
                           int k)
{
  // Array to store the
  // results
  Vector result =
         new Vector<>();
 
  // Define DP array
  int []dp = new int[r + 1];
  dp[1] = 1;
  dp[2] = 1;
 
  for(int i = l; i <= r; i++)
    result.add(new Pair(i,
               func(i, dp)));
 
  // Sort the array based
  // on cost
  Collections.sort(result);
 
  System.out.print(
  result.get(k - 1).start);
}
 
// Driver code
public static void main(String[] args)
{   
  // Given range and K
  int l = 12;
  int r = 15;
  int k = 2;
 
  // Function call
  findKthElement(l, r, k);
}
}
 
// This code is contributed by gauravrajput1

Python3

# Python3 implementation of the above approach
# Function to calculate the cost
def func(n, dp):
    count = 0
 
    # Base case
    if n == 2 or n == 1:
        return 1
    if n in dp:
      return dp[n] 
 
    # Even condtion
    if n % 2 == 0: 
        count = 1 + func(n//2, dp)
 
    # Odd condition
    if n % 2 != 0:  
        count = 1 + func(n * 3 + 1, dp)
 
    # Store the result
    dp[n]= count
    return dp[n]
 
# Function to find Kth element
def findKthElement(l, r, k):
    arr = list(range(l, r + 1))
 
    # Array to store the results
    result = []
 
    # Define DP array
    dp ={1:1, 2:1}
 
    for i in arr:
        result.append([i, func(i, dp)])
 
    # Sort the array based on cost
    result.sort()
    print(result[k-1][0])
 
# Given range and K
l = 12
r = 15
k = 2
 
# Function Call
findKthElement(l, r, k)

C#

// C# implementation of
// the above approach
using System;
using System.Collections;
 
class GFG{
     
class Pair
{
   public int start,end;
    
  public Pair(int s, int e)
  {
    start = s;
    end = e;
  }
}
 
class sortHelper : IComparer
{
   int IComparer.Compare(object a, object b)
   {
      Pair first=(Pair)a;
      Pair second=(Pair)b;
         
      return first.start - second.start;
   }
}
      
  
// Function to calculate
// the cost
static int func(int n, int []dp)
{
  int count = 0;
  
  // Base case
  if (n == 2 || n == 1)
    return 1;
  
  if (dp[n] != -1)
    return dp[n];
  
  // Even condtion
  if (n % 2 == 0)
    count = 1 + func(n / 2, dp);
  
  // Odd condition
  if (n % 2 != 0)
    count = 1 + func(n * 3 +
                     1, dp);
  
  // Store the result
  dp[n] = count;
  return dp[n];
}
  
// Function to find Kth element
static void findKthElement(int l,
                           int r,
                           int k)
{
  // Array to store the
  // results
  ArrayList result =
         new ArrayList();
  
  // Define DP array
  int []dp = new int[r + 1];
  dp[1] = 1;
  dp[2] = 1;
  
  for(int i = l; i <= r; i++)
    result.Add(new Pair(i,
               func(i, dp)));
  
  // Sort the array based
  // on cost
  result.Sort(new sortHelper());
  
  Console.Write(((Pair)result[k - 1]).start);
}
  
// Driver code
public static void Main(string[] args)
{   
  // Given range and K
  int l = 12;
  int r = 15;
  int k = 2;
  
  // Function call
  findKthElement(l, r, k);
}
}
 
// This code is contributed by rutvik_56
输出:
13

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