📌  相关文章
📜  从数组中选择至少两个元素,使得它们的 GCD 为 1 且成本最小

📅  最后修改于: 2021-10-28 01:37:16             🧑  作者: Mango

给定两个整数数组arr[]cost[]其中cost[i]是选择arr[i]的成本。任务是选择一个至少包含两个元素的子集,使得该子集中所有元素的 GCD 为 1,并且选择这些元素的成本尽可能小,然后打印最小成本。
例子:

方法:将任意两个元素的 GCD 添加到地图中,现在对于每个元素arr[i]使用迄今为止找到的所有 gcd 值(保存在地图中)计算其 gcd 并更新map[gcd] = min(map[gcd] , map[gcd] + cost[i]) 。如果最后, map 不包含gcd = 1 的任何条目,则打印-1否则打印存储的最小成本。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the minimum cost required
int getMinCost(int arr[], int n, int cost[])
{
 
    // Map to store  pair where
    // cost is the cost to get the current gcd
    map mp;
    mp.clear();
    mp[0] = 0;
 
    for (int i = 0; i < n; i++) {
        for (auto it : mp) {
            int gcd = __gcd(arr[i], it.first);
 
            // If current gcd value already exists in map
            if (mp.count(gcd) == 1)
 
                // Update the minimum cost
                // to get the current gcd
                mp[gcd] = min(mp[gcd], it.second + cost[i]);
 
            else
                mp[gcd] = it.second + cost[i];
        }
    }
 
    // If there can be no sub-set such that
    // the gcd of all the elements is 1
    if (mp[1] == 0)
        return -1;
    else
        return mp[1];
}
 
// Driver code
int main()
{
    int arr[] = { 5, 10, 12, 1 };
    int cost[] = { 2, 1, 2, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << getMinCost(arr, n, cost);
    return 0;
}


Java
// Java implementation of the approach
 
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
 
class GFG{
  
// Function to return the minimum cost required
static int getMinCost(int arr[], int n, int cost[])
{
  
    // Map to store  pair where
    // cost is the cost to get the current gcd
    Map mp = new ConcurrentHashMap();
    mp.clear();
    mp.put(0, 0);
  
    for (int i = 0; i < n; i++) {
        for (Map.Entry it : mp.entrySet()){
            int gcd = __gcd(arr[i], it.getKey());
  
            // If current gcd value already exists in map
            if (mp.containsKey(gcd))
  
                // Update the minimum cost
                // to get the current gcd
                mp.put(gcd, Math.min(mp.get(gcd), it.getValue() + cost[i]));
  
            else
                mp.put(gcd,it.getValue() + cost[i]);
        }
    }
  
    // If there can be no sub-set such that
    // the gcd of all the elements is 1
    if (!mp.containsKey(1))
        return -1;
    else
        return mp.get(1);
}
static int __gcd(int a, int b) 
{ 
    return b == 0? a:__gcd(b, a % b);    
}
// Driver code
public static void main(String[] args)
{
    int arr[] = { 5, 10, 12, 1 };
    int cost[] = { 2, 1, 2, 6 };
    int n = arr.length;
  
    System.out.print(getMinCost(arr, n, cost));
}
}
 
// This code is contributed by PrinciRaj1992


Python3
# Python3 implementation of the approach
from math import gcd as __gcd
 
# Function to return the minimum cost required
def getMinCost(arr, n, cost):
 
    # Map to store  pair where
    # cost is the cost to get the current gcd
    mp = dict()
    mp[0] = 0
 
    for i in range(n):
        for it in list(mp):
            gcd = __gcd(arr[i], it)
 
            # If current gcd value
            # already exists in map
            if (gcd in mp):
 
                # Update the minimum cost
                # to get the current gcd
                mp[gcd] = min(mp[gcd],
                              mp[it] + cost[i])
 
            else:
                mp[gcd] = mp[it] + cost[i]
 
    # If there can be no sub-set such that
    # the gcd of all the elements is 1
    if (mp[1] == 0):
        return -1
    else:
        return mp[1]
 
# Driver code
arr = [ 5, 10, 12, 1]
cost = [ 2, 1, 2, 6]
n = len(arr)
 
print(getMinCost(arr, n, cost))
 
# This code is contributed by Mohit Kumar


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
  static int __gcd(int a, int b)  
  {  
    return b == 0? a:__gcd(b, a % b);     
  }
 
  // Function to return the minimum cost required
  static int getMinCost(int[] arr, int n, int[] cost)
  {
 
    // Map to store  pair where
    // cost is the cost to get the current gcd
    Dictionary mp = new Dictionary();
    mp.Add(0, 0);
    for (int i = 0; i < n; i++)
    {
 
      foreach (int it in mp.Keys.ToList())
      {
        int gcd = __gcd(arr[i], it);
 
        // If current gcd value already exists in map
        if(mp.ContainsKey(gcd))
        {
 
          // Update the minimum cost
          // to get the current gcd
          mp[gcd] = Math.Min(mp[gcd], mp[it] + cost[i]);
        }
        else
        {
          mp.Add(gcd, mp[it] + cost[i]);
        }
      } 
    }
 
    // If there can be no sub-set such that
    // the gcd of all the elements is 1
    if (mp[1] == 0)
    {
      return -1;
    }
    else
    {
      return mp[1];
    }       
  }
 
  // Driver code
  static public void Main ()
  {
    int[] arr = { 5, 10, 12, 1 };
    int[] cost = { 2, 1, 2, 6 };
    int n = arr.Length;
    Console.WriteLine(getMinCost(arr, n, cost));
  }
}
 
// This code is contributed by avanitrachhadiya2155


Javascript


输出:
4

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