📌  相关文章
📜  计算按递增顺序访问所有数组元素的成本

📅  最后修改于: 2021-09-03 14:33:11             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[] ,如果从索引i移动到索引j的成本是绝对差,则任务是从0开始,按升序查找访问所有数组元素的总成本在ij之间。

例子:

方法:这个想法是使用对向量进行排序的概念。请按照以下步骤解决问题:

  • 初始化一对vector > ,比如v,来存储元素对和它们各自的位置。
  • 遍历数组arr[]并将{arr[i], i}对推入向量v 中。
  • 初始化两个变量,比如ans = 0last = 0,以存储所需的总成本和最后访问元素的索引。
  • 按升序对成对的向量进行排序。
  • 遍历向量v并通过abs(v[i].second – last)增加ans最后更新作为最后=常用3 [I]。第二。
  • 完成上述步骤后,将得到的答案打印为ans。

下面是上述方法的实现:

C++
// C++ implementation of the above approach
#include 
using namespace std;
 
// Function to calculate total
// cost of visiting array
// elements in increasing order
int calculateDistance(int arr[], int N)
{
    // Stores the pair of element
    // and their positions
    vector > v;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++)
 
        // Push the pair {arr[i], i} in v
        v.push_back({ arr[i], i });
 
    // Sort the vector in ascending order.
    sort(v.begin(), v.end());
 
    // Stores the total cost
    int ans = 0;
 
    // Stores the index of last element visited
    int last = 0;
 
    // Traverse the vector v
    for (auto j : v) {
 
        // Increment ans
        ans += abs(j.second - last);
 
        // Assign
        last = j.second;
    }
 
    // Return ans
    return ans;
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 3, 2, 5, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << calculateDistance(arr, N);
}


Java
// java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
  // Pair class
  static class Pair {
 
    int first;
    int second;
 
    Pair(int first, int second)
    {
      this.first = first;
      this.second = second;
    }
  }
 
  // Function to calculate total
  // cost of visiting array
  // elements in increasing order
  static int calculateDistance(int arr[], int N)
  {
    // Stores the pair of element
    // and their positions
    Pair v[] = new Pair[N];
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++)
 
      // Push the pair {arr[i], i} in v
      v[i] = new Pair(arr[i], i);
 
    // Sort the vector in ascending order.
    Arrays.sort(v, (p1, p2) -> {
      if (p1.first != p2.first)
        return p1.first - p2.first;
      return p1.second - p2.second;
    });
 
    // Stores the total cost
    int ans = 0;
 
    // Stores the index of last element visited
    int last = 0;
 
    // Traverse the vector v
    for (Pair j : v) {
 
      // Increment ans
      ans += Math.abs(j.second - last);
 
      // Assign
      last = j.second;
    }
 
    // Return ans
    return ans;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[] = { 4, 3, 2, 5, 1 };
    int N = arr.length;
 
    // Function call
    System.out.println(calculateDistance(arr, N));
  }
}
 
// This code is contributed by Kingash.


Python3
# Python3 implementation of the above approach
 
# Function to calculate total
# cost of visiting array
# elements in increasing order
def calculateDistance(arr, N):
 
    # Stores the pair of element
    # and their positions
    v = []
 
    # Traverse the array arr[]
    for i in range(N):
 
        # Push the pair {arr[i], i} in v
        v.append([arr[i], i])
 
    # Sort the vector in ascending order.
    v.sort()
 
    # Stores the total cost
    ans = 0
 
    # Stores the index of last element visited
    last = 0
 
    # Traverse the vector v
    for j in v:
 
        # Increment ans
        ans += abs(j[1] - last)
 
        # Assign
        last = j[1]
 
    # Return ans
    return ans
 
# Driver Code
if __name__ == "__main__" :
 
    arr = [ 4, 3, 2, 5, 1 ]
    N = len(arr)
     
    print(calculateDistance(arr, N))
     
# This code is contributed by AnkThon


输出:
11

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live