📜  找到给定步骤的 Alpha 分数(使用 BST)

📅  最后修改于: 2021-09-03 04:12:13             🧑  作者: Mango

给定一个由N 个数字组成的数组A[] ,表示写在N步上的值,任务是找到爬上所有楼梯的总行程的 alpha 分数。由于答案可能非常大,打印答案模10 9 + 7

例子:

天真的方法:
解决问题的最简单的方法是遍历数组中的每个元素,并计算之前索引处存在的小于当前元素的所有元素的总和,以计算当前楼梯Alpha Score对于计算的每个总和,更新total_sum (总行程的 Alpha 分数)。最后,打印total_sum作为整个旅程的 Alpha 分数。

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

有效的方法:
上述方法可以使用二叉搜索树进行优化。请按照以下步骤操作:

  • 对给定的数组进行排序
  • 从排序的数组构造一个 BST。
  • 递归遍历BST并按照以下步骤操作:
    • 遍历左子树。
    • 当前节点的值添加到sum (当前楼梯的 Alpha 分数)并更新total_sum (到目前为止旅程的 Alpha 分数)。
    • 遍历右子树。
  • 完全遍历 BST 后,打印total_sum

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include
using namespace std;
 
static long sum = 0, total_sum = 0;
static long mod = 1000000007;
 
// Structure of a node
struct Node
{
    Node *left, *right;
    int data;
     
    Node(int x)
    {
        data = x;
        left = NULL;
        right = NULL;
    }
};
 
// Function to calculate and return
// the Alpha Score of the journey
long getAlphaScore(Node* node)
{
     
    // Traverse left subtree
    if (node->left != NULL)
        getAlphaScore(node->left);
 
    // Calculate the alpha score
    // of the current step
    sum = (sum + node->data) % mod;
 
    // Update alpha score of
    // the journey
    total_sum = (total_sum + sum) % mod;
 
    // Traverse right subtree
    if (node->right != NULL)
        getAlphaScore(node->right);
 
    // Return
    return total_sum;
}
 
// Function to construct a BST
// from the sorted array arr[]
Node* constructBST(int arr[], int start,
                   int end, Node* root)
{
    if (start > end)
        return NULL;
 
    int mid = (start + end) / 2;
 
    // Insert root
    if (root == NULL)
        root = new Node(arr[mid]);
 
    // Construct left subtree
    root->left = constructBST(arr, start,
                              mid - 1, root->left);
 
    // Construct right subtree
    root->right = constructBST(arr, mid + 1, end,
                               root->right);
 
    // Return root
    return root;
}
 
// Driver Code
int main()
{
    int arr[] = { 10, 11, 12 };
    int length = 3;
     
    // Sort the array
    sort(arr, arr + length);
     
    Node *root = NULL;
     
    // Construct BST from the sorted array
    root = constructBST(arr, 0, length - 1, root);
     
    cout << (getAlphaScore(root));
}
 
// This code is contributed by mohit kumar 29


Java
// Java Program to implement
// the above approach
import java.lang.*;
import java.util.*;
 
// Structure of a node
class Node {
    Node left, right;
    int data;
    public Node(int data)
    {
        this.data = data;
        left = null;
        right = null;
    }
}
 
class AlphaScore {
 
    Node root;
 
    AlphaScore() { root = null; }
 
    static long sum = 0, total_sum = 0;
    static long mod = 1000000007;
 
    // Function to calculate and return
    // the Alpha Score of the journey
    public static long getAlphaScore(Node node)
    {
        // Traverse left subtree
        if (node.left != null)
            getAlphaScore(node.left);
 
        // Calculate the alpha score
        // of the current step
        sum = (sum + node.data) % mod;
 
        // Update alpha score of
        // the journey
        total_sum = (total_sum + sum) % mod;
 
        // Traverse right subtree
        if (node.right != null)
            getAlphaScore(node.right);
 
        // Return
        return total_sum;
    }
 
    // Function to construct a BST
    // from the sorted array arr[]
    public static Node constructBST(int[] arr, int start,
                                    int end, Node root)
    {
        if (start > end)
            return null;
 
        int mid = (start + end) / 2;
 
        // Insert root
        if (root == null)
            root = new Node(arr[mid]);
 
        // Construct left subtree
        root.left
            = constructBST(arr, start, mid - 1, root.left);
 
        // Construct right subtree
        root.right
            = constructBST(arr, mid + 1, end, root.right);
 
        // Return root
        return root;
    }
 
    // Driver Code
    public static void main(String args[])
    {
 
        int arr[] = { 10, 11, 12 };
        int length = arr.length;
 
        // Sort the array
        Arrays.sort(arr);
 
        Node root = null;
 
        // Construct BST from the sorted array
        root = constructBST(arr, 0, length - 1, root);
 
        System.out.println(getAlphaScore(root));
    }
}


Python3
# Python3 program to implement
# the above approach
 
# Structure of a node
class Node:
    def __init__(self, data):
         
        self.data = data
        self.left = None
        self.right = None
         
sum = 0
total_sum = 0
mod = 1000000007
     
# Function to calculate and return
# the Alpha Score of the journey
def getAlphaScore(node):
     
    global sum
    global total_sum
     
    # Traverse left subtree
    if node.left != None:
        getAlphaScore(node.left)
         
    # Calculate the alpha score
    # of the current step
    sum = (sum + node.data) % mod
     
    # Update alpha score of
    # the journey
    total_sum = (total_sum + sum) % mod
     
    # Traverse right subtree
    if node.right != None:
        getAlphaScore(node.right)
         
    # Return
    return total_sum
 
# Function to construct a BST
# from the sorted array arr[]
def constructBST(arr, start, end, root):
     
    if start > end:
        return None
     
    mid = (start + end) // 2
     
    # Insert root
    if root == None:
        root = Node(arr[mid])
         
    # Construct left subtree
    root.left = constructBST(arr, start,
                             mid - 1,
                             root.left)
     
    # Construct right subtree
    root.right = constructBST(arr, mid + 1,
                              end, root.right)
     
    # Return root
    return root
 
# Driver code
arr = [ 10, 11, 12 ]
length = len(arr)
 
# Sort the array
arr.sort()
 
root = None
 
# Construct BST from the sorted array
root = constructBST(arr, 0, length - 1, root)
 
print(getAlphaScore(root))
 
# This code is contributed by Shivam Singh


C#
// C# program to implement
// the above approach
using System;
 
// Structure of a node
class Node
{
    public Node left, right;
    public int data;
    public Node(int data)
    {
        this.data = data;
        left = null;
        right = null;
    }
}
 
class AlphaScore{
 
Node root;
 
AlphaScore(){root = null;}
 
static long sum = 0, total_sum = 0;
static long mod = 1000000007;
 
// Function to calculate and return
// the Alpha Score of the journey
static long getAlphaScore(Node node)
{
     
    // Traverse left subtree
    if (node.left != null)
        getAlphaScore(node.left);
 
    // Calculate the alpha score
    // of the current step
    sum = (sum + node.data) % mod;
 
    // Update alpha score of
    // the journey
    total_sum = (total_sum + sum) % mod;
 
    // Traverse right subtree
    if (node.right != null)
        getAlphaScore(node.right);
 
    // Return
    return total_sum;
}
 
// Function to construct a BST
// from the sorted array []arr
static Node constructBST(int[] arr, int start,
                         int end, Node root)
{
    if (start > end)
        return null;
 
    int mid = (start + end) / 2;
 
    // Insert root
    if (root == null)
        root = new Node(arr[mid]);
 
    // Construct left subtree
    root.left = constructBST(arr, start,
                             mid - 1, root.left);
 
    // Construct right subtree
    root.right = constructBST(arr, mid + 1,
                              end, root.right);
 
    // Return root
    return root;
}
 
// Driver Code
public static void Main(String []args)
{
 
    int []arr = { 10, 11, 12 };
    int length = arr.Length;
 
    // Sort the array
    Array.Sort(arr);
 
    Node root = null;
 
    // Construct BST from the sorted array
    root = constructBST(arr, 0, length - 1, root);
 
    Console.WriteLine(getAlphaScore(root));
}
}
 
// This is code contributed by PrinciRaj1992


输出:
64





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

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