📌  相关文章
📜  重新排列数组使得没有元素超过其相邻元素的总和的成本

📅  最后修改于: 2021-10-26 06:49:20             🧑  作者: Mango

给定一个由N 个唯一整数组成的数组arr[] ,任务是找到将它们排列成圆形排列的成本,以使每个元素都小于或等于其相邻元素的总和。

如果这种安排是不可能的,则打印-1
例子:

方法:该问题可以使用贪心方法解决。这个想法是将元素的原始索引存储在一个哈希图中,然后对数组进行排序。现在检查给定的条件是否满足。如果发现为真,则通过将当前索引和先前索引之间的差异相加来计算成本。否则,打印-1
下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Function to check if given elements
// can be arranged such that sum of
// its neighbours is strictly greater
void Arrange(int arr[], int n)
{
    // Initialize the total cost
    int cost = 0;
 
    // Storing the original index of
    // elements in a hashmap
    unordered_map index;
 
    for (int i = 0; i < n; i++) {
        index[arr[i]] = i;
    }
 
    // Sort the given array
    sort(arr, arr + n);
 
    // Check if a given condition
    // is satisfies or not
    for (int i = 0; i < n; i++) {
 
        // First number
        if (i == 0) {
            if (arr[i] > arr[i + 1]
                             + arr[n - 1]) {
                cout << "-1";
                return;
            }
            else {
 
                // Add the cost to overall cost
                cost += abs(index[arr[i]] - i);
            }
        }
 
        // Last number
        else if (i == n - 1) {
            if (arr[i] > arr[i - 1]
                             + arr[0]) {
                cout << "-1";
                return;
            }
            else {
 
                // Add the cost to
                // overall cost
                cost += abs(index[arr[i]] - i);
            }
        }
 
        else {
            if (arr[i] > arr[i - 1]
                             + arr[i + 1]) {
                cout << "-1";
                return;
            }
            else {
 
                // Add the cost to
                // overall cost
                cost += abs(index[arr[i]] - i);
            }
        }
    }
 
    // Printing the cost
    cout << cost;
    return;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 2, 4, 5, 1, 3 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    Arrange(arr, N);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to check if given elements
// can be arranged such that sum of
// its neighbors is strictly greater
static void Arrange(int arr[], int n)
{
     
    // Initialize the total cost
    int cost = 0;
 
    // Storing the original index of
    // elements in a hashmap
    HashMap index = new HashMap();
 
    for(int i = 0; i < n; i++)
    {
        index.put(arr[i], i);
    }
 
    // Sort the given array
    Arrays.sort(arr);
 
    // Check if a given condition
    // is satisfies or not
    for(int i = 0; i < n; i++)
    {
 
        // First number
        if (i == 0)
        {
            if (arr[i] > arr[i + 1] +
                         arr[n - 1])
            {
                System.out.print("-1");
                return;
            }
            else
            {
                 
                // Add the cost to overall cost
                cost += Math.abs(index.get(arr[i]) - i);
            }
        }
 
        // Last number
        else if (i == n - 1)
        {
            if (arr[i] > arr[i - 1] +
                arr[0])
            {
                System.out.print("-1");
                return;
            }
            else
            {
                 
                // Add the cost to
                // overall cost
                cost += Math.abs(index.get(arr[i]) - i);
            }
        }
 
        else
        {
            if (arr[i] > arr[i - 1] +
                         arr[i + 1])
            {
                System.out.print("-1");
                return;
            }
            else
            {
 
                // Add the cost to
                // overall cost
                cost += Math.abs(index.get(arr[i]) - i);
            }
        }
    }
 
    // Printing the cost
    System.out.print(cost);
    return;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array
    int arr[] = { 2, 4, 5, 1, 3 };
 
    int N = arr.length;
 
    // Function call
    Arrange(arr, N);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to implement
# the above approach
 
# Function to check if given elements
# can be arranged such that sum of
# its neighbours is strictly greater
def Arrange(arr, n):
 
    # Initialize the total cost
    cost = 0
 
    # Storing the original index of
    # elements in a hashmap
    index = {}
 
    for i in range(n):
        index[arr[i]] = i
 
    # Sort the given array
    arr.sort()
 
    # Check if a given condition
    # is satisfies or not
    for i in range(n):
 
        # First number
        if(i == 0):
            if(arr[i] > arr[i + 1] + arr[-1]):
                print("-1")
                return
            else:
                 
                # Add the cost to overall cost
                cost += abs(index[arr[i]] - i)
 
        # Last number
        elif(i == n - 1):
            if(arr[i] > arr[i - 1] + arr[0]):
                print("-1")
                return
            else:
                 
                # Add the cost to
                # overall cost
                cost += abs(index[arr[i]] - i)
 
        else:
             
            if(arr[i] > arr[i - 1] + arr[i + 1]):
                print("-1")
                return
            else:
                 
                # Add the cost to
                # overall cost
                cost += abs(index[arr[i]] - i)
 
    # Printing the cost
    print(cost)
    return
 
# Driver Code
 
# Given array
arr = [ 2, 4, 5, 1, 3 ]
 
N = len(arr)
 
# Function call
Arrange(arr, N)
 
# This code is contributed by Shivam Singh


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to check if given elements
// can be arranged such that sum of
// its neighbors is strictly greater
static void Arrange(int []arr, int n)
{
     
    // Initialize the total cost
    int cost = 0;
 
    // Storing the original index of
    // elements in a hashmap
    Dictionary index = new Dictionary();
 
    for(int i = 0; i < n; i++)
    {
        index.Add(arr[i], i);
    }
 
    // Sort the given array
    Array.Sort(arr);
 
    // Check if a given condition
    // is satisfies or not
    for(int i = 0; i < n; i++)
    {
 
        // First number
        if (i == 0)
        {
            if (arr[i] > arr[i + 1] +
                         arr[n - 1])
            {
                Console.Write("-1");
                return;
            }
            else
            {
                 
                // Add the cost to overall cost
                cost += Math.Abs(index[arr[i]] - i);
            }
        }
 
        // Last number
        else if (i == n - 1)
        {
            if (arr[i] > arr[i - 1] +
                arr[0])
            {
                Console.Write("-1");
                return;
            }
            else
            {
                 
                // Add the cost to
                // overall cost
                cost += Math.Abs(index[arr[i]] - i);
            }
        }
 
        else
        {
            if (arr[i] > arr[i - 1] +
                         arr[i + 1])
            {
                Console.Write("-1");
                return;
            }
            else
            {
 
                // Add the cost to
                // overall cost
                cost += Math.Abs(index[arr[i]] - i);
            }
        }
    }
 
    // Printing the cost
    Console.Write(cost);
    return;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array
    int []arr = { 2, 4, 5, 1, 3 };
 
    int N = arr.Length;
 
    // Function call
    Arrange(arr, N);
}
}
 
// This code is contributed by shikhasingrajput


Javascript


输出:

10

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

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