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

📅  最后修改于: 2021-04-17 18:19:20             🧑  作者: Mango

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

例子:

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

  • 初始化一对vector > ,例如v,以存储元素对及其各自的位置。
  • 遍历数组arr []并将对{arr [i],i}推入向量v中。
  • 初始化两个变量,例如ans = 0last = 0,以存储所需的总成本和最后访问的元素的索引。
  • 按升序对向量对进行排序。
  • 遍历向量v并将ans增加abs(v [i] .second-last)最后更新为last = arr [i] .second。
  • 完成上述步骤后,将获得的答案打印为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)