{ "data": { "question": { "questionId": "2739", "questionFrontendId": "2646", "boundTopicId": null, "title": "Minimize the Total Price of the Trips", "titleSlug": "minimize-the-total-price-of-the-trips", "content": "

There exists an undirected and unrooted tree with n nodes indexed from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

\n\n

Each node has an associated price. You are given an integer array price, where price[i] is the price of the ith node.

\n\n

The price sum of a given path is the sum of the prices of all nodes lying on that path.

\n\n

Additionally, you are given a 2D integer array trips, where trips[i] = [starti, endi] indicates that you start the ith trip from the node starti and travel to the node endi by any path you like.

\n\n

Before performing your first trip, you can choose some non-adjacent nodes and halve the prices.

\n\n

Return the minimum total price sum to perform all the given trips.

\n\n

 

\n

Example 1:

\n\"\"\n
\nInput: n = 4, edges = [[0,1],[1,2],[1,3]], price = [2,2,10,6], trips = [[0,3],[2,1],[2,3]]\nOutput: 23\nExplanation: The diagram above denotes the tree after rooting it at node 2. The first part shows the initial tree and the second part shows the tree after choosing nodes 0, 2, and 3, and making their price half.\nFor the 1st trip, we choose path [0,1,3]. The price sum of that path is 1 + 2 + 3 = 6.\nFor the 2nd trip, we choose path [2,1]. The price sum of that path is 2 + 5 = 7.\nFor the 3rd trip, we choose path [2,1,3]. The price sum of that path is 5 + 2 + 3 = 10.\nThe total price sum of all trips is 6 + 7 + 10 = 23.\nIt can be proven, that 23 is the minimum answer that we can achieve.\n
\n\n

Example 2:

\n\"\"\n
\nInput: n = 2, edges = [[0,1]], price = [2,2], trips = [[0,0]]\nOutput: 1\nExplanation: The diagram above denotes the tree after rooting it at node 0. The first part shows the initial tree and the second part shows the tree after choosing node 0, and making its price half.\nFor the 1st trip, we choose path [0]. The price sum of that path is 1.\nThe total price sum of all trips is 1. It can be proven, that 1 is the minimum answer that we can achieve.\n
\n\n

 

\n

Constraints:

\n\n\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Hard", "likes": 443, "dislikes": 16, "isLiked": null, "similarQuestions": "[]", "exampleTestcases": "4\n[[0,1],[1,2],[1,3]]\n[2,2,10,6]\n[[0,3],[2,1],[2,3]]\n2\n[[0,1]]\n[2,2]\n[[0,0]]", "categoryTitle": "Algorithms", "contributors": [], "topicTags": [ { "name": "Array", "slug": "array", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Dynamic Programming", "slug": "dynamic-programming", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Tree", "slug": "tree", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Depth-First Search", "slug": "depth-first-search", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Graph", "slug": "graph", "translatedName": null, "__typename": "TopicTagNode" } ], "companyTagStats": null, "codeSnippets": [ { "lang": "C++", "langSlug": "cpp", "code": "class Solution {\npublic:\n int minimumTotalPrice(int n, vector>& edges, vector& price, vector>& trips) {\n \n }\n};", "__typename": "CodeSnippetNode" }, { "lang": "Java", "langSlug": "java", "code": "class Solution {\n public int minimumTotalPrice(int n, int[][] edges, int[] price, int[][] trips) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Python", "langSlug": "python", "code": "class Solution(object):\n def minimumTotalPrice(self, n, edges, price, trips):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :type price: List[int]\n :type trips: List[List[int]]\n :rtype: int\n \"\"\"\n ", "__typename": "CodeSnippetNode" }, { "lang": "Python3", "langSlug": "python3", "code": "class Solution:\n def minimumTotalPrice(self, n: int, edges: List[List[int]], price: List[int], trips: List[List[int]]) -> int:\n ", "__typename": "CodeSnippetNode" }, { "lang": "C", "langSlug": "c", "code": "int minimumTotalPrice(int n, int** edges, int edgesSize, int* edgesColSize, int* price, int priceSize, int** trips, int tripsSize, int* tripsColSize){\n\n}", "__typename": "CodeSnippetNode" }, { "lang": "C#", "langSlug": "csharp", "code": "public class Solution {\n public int MinimumTotalPrice(int n, int[][] edges, int[] price, int[][] trips) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "JavaScript", "langSlug": "javascript", "code": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number[]} price\n * @param {number[][]} trips\n * @return {number}\n */\nvar minimumTotalPrice = function(n, edges, price, trips) {\n \n};", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "function minimumTotalPrice(n: number, edges: number[][], price: number[], trips: number[][]): number {\n\n};", "__typename": "CodeSnippetNode" }, { "lang": "PHP", "langSlug": "php", "code": "class Solution {\n\n /**\n * @param Integer $n\n * @param Integer[][] $edges\n * @param Integer[] $price\n * @param Integer[][] $trips\n * @return Integer\n */\n function minimumTotalPrice($n, $edges, $price, $trips) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Swift", "langSlug": "swift", "code": "class Solution {\n func minimumTotalPrice(_ n: Int, _ edges: [[Int]], _ price: [Int], _ trips: [[Int]]) -> Int {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Kotlin", "langSlug": "kotlin", "code": "class Solution {\n fun minimumTotalPrice(n: Int, edges: Array, price: IntArray, trips: Array): Int {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Dart", "langSlug": "dart", "code": "class Solution {\n int minimumTotalPrice(int n, List> edges, List price, List> trips) {\n\n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Go", "langSlug": "golang", "code": "func minimumTotalPrice(n int, edges [][]int, price []int, trips [][]int) int {\n \n}", "__typename": "CodeSnippetNode" }, { "lang": "Ruby", "langSlug": "ruby", "code": "# @param {Integer} n\n# @param {Integer[][]} edges\n# @param {Integer[]} price\n# @param {Integer[][]} trips\n# @return {Integer}\ndef minimum_total_price(n, edges, price, trips)\n \nend", "__typename": "CodeSnippetNode" }, { "lang": "Scala", "langSlug": "scala", "code": "object Solution {\n def minimumTotalPrice(n: Int, edges: Array[Array[Int]], price: Array[Int], trips: Array[Array[Int]]): Int = {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Rust", "langSlug": "rust", "code": "impl Solution {\n pub fn minimum_total_price(n: i32, edges: Vec>, price: Vec, trips: Vec>) -> i32 {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Racket", "langSlug": "racket", "code": "(define/contract (minimum-total-price n edges price trips)\n (-> exact-integer? (listof (listof exact-integer?)) (listof exact-integer?) (listof (listof exact-integer?)) exact-integer?)\n\n )", "__typename": "CodeSnippetNode" }, { "lang": "Erlang", "langSlug": "erlang", "code": "-spec minimum_total_price(N :: integer(), Edges :: [[integer()]], Price :: [integer()], Trips :: [[integer()]]) -> integer().\nminimum_total_price(N, Edges, Price, Trips) ->\n .", "__typename": "CodeSnippetNode" }, { "lang": "Elixir", "langSlug": "elixir", "code": "defmodule Solution do\n @spec minimum_total_price(n :: integer, edges :: [[integer]], price :: [integer], trips :: [[integer]]) :: integer\n def minimum_total_price(n, edges, price, trips) do\n\n end\nend", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"8.5K\", \"totalSubmission\": \"19.3K\", \"totalAcceptedRaw\": 8525, \"totalSubmissionRaw\": 19318, \"acRate\": \"44.1%\"}", "hints": [ "The final answer is the price[i] * freq[i], where freq[i] is the number of times node i was visited during the trip, and price[i] is the final price.", "To find freq[i] we will use dfs or bfs for each trip and update every node on the path start and end.", "Finally, to find the final price[i] we will use dynamic programming on the tree. Let dp(v, 0/1) denote the minimum total price with the node v’s price being halved or not." ], "solution": null, "status": null, "sampleTestCase": "4\n[[0,1],[1,2],[1,3]]\n[2,2,10,6]\n[[0,3],[2,1],[2,3]]", "metaData": "{\n \"name\": \"minimumTotalPrice\",\n \"params\": [\n {\n \"name\": \"n\",\n \"type\": \"integer\"\n },\n {\n \"type\": \"integer[][]\",\n \"name\": \"edges\"\n },\n {\n \"type\": \"integer[]\",\n \"name\": \"price\"\n },\n {\n \"type\": \"integer[][]\",\n \"name\": \"trips\"\n }\n ],\n \"return\": {\n \"type\": \"integer\"\n }\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": true, "envInfo": "{\"cpp\": [\"C++\", \"

Compiled with clang 11 using the latest C++ 20 standard.

\\r\\n\\r\\n

Your code is compiled with level two optimization (-O2). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\"], \"java\": [\"Java\", \"

OpenJDK 17. Java 8 features such as lambda expressions and stream API can be used.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n

Includes Pair class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.

\"], \"python\": [\"Python\", \"

Python 2.7.12.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\\r\\n\\r\\n

Note that Python 2.7 will not be maintained past 2020. For the latest Python, please choose Python3 instead.

\"], \"c\": [\"C\", \"

Compiled with gcc 8.2 using the gnu11 standard.

\\r\\n\\r\\n

Your code is compiled with level one optimization (-O1). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n\\r\\n

For hash table operations, you may use uthash. \\\"uthash.h\\\" is included by default. Below are some examples:

\\r\\n\\r\\n

1. Adding an item to a hash.\\r\\n

\\r\\nstruct hash_entry {\\r\\n    int id;            /* we'll use this field as the key */\\r\\n    char name[10];\\r\\n    UT_hash_handle hh; /* makes this structure hashable */\\r\\n};\\r\\n\\r\\nstruct hash_entry *users = NULL;\\r\\n\\r\\nvoid add_user(struct hash_entry *s) {\\r\\n    HASH_ADD_INT(users, id, s);\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

2. Looking up an item in a hash:\\r\\n

\\r\\nstruct hash_entry *find_user(int user_id) {\\r\\n    struct hash_entry *s;\\r\\n    HASH_FIND_INT(users, &user_id, s);\\r\\n    return s;\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

3. Deleting an item in a hash:\\r\\n

\\r\\nvoid delete_user(struct hash_entry *user) {\\r\\n    HASH_DEL(users, user);  \\r\\n}\\r\\n
\\r\\n

\"], \"csharp\": [\"C#\", \"

C# 10 with .NET 6 runtime

\"], \"javascript\": [\"JavaScript\", \"

Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES6 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\\r\\n\\r\\n

For Priority Queue / Queue data structures, you may use 5.3.0 version of datastructures-js/priority-queue and 4.2.1 version of datastructures-js/queue.

\"], \"ruby\": [\"Ruby\", \"

Ruby 3.1

\\r\\n\\r\\n

Some common data structure implementations are provided in the Algorithms module: https://www.rubydoc.info/github/kanwei/algorithms/Algorithms

\"], \"swift\": [\"Swift\", \"

Swift 5.5.2.

\"], \"golang\": [\"Go\", \"

Go 1.21

\\r\\n

Support https://godoc.org/github.com/emirpasic/gods@v1.18.1 library.

\"], \"python3\": [\"Python3\", \"

Python 3.10.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\"], \"scala\": [\"Scala\", \"

Scala 2.13.7.

\"], \"kotlin\": [\"Kotlin\", \"

Kotlin 1.9.0.

\"], \"rust\": [\"Rust\", \"

Rust 1.58.1

\\r\\n\\r\\n

Supports rand v0.6\\u00a0from crates.io

\"], \"php\": [\"PHP\", \"

PHP 8.1.

\\r\\n

With bcmath module

\"], \"typescript\": [\"Typescript\", \"

TypeScript 5.1.6, Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES2022 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\"], \"racket\": [\"Racket\", \"

Run with Racket 8.3.

\"], \"erlang\": [\"Erlang\", \"Erlang/OTP 25.0\"], \"elixir\": [\"Elixir\", \"Elixir 1.13.4 with Erlang/OTP 25.0\"], \"dart\": [\"Dart\", \"

Dart 2.17.3

\\r\\n\\r\\n

Your code will be run directly without compiling

\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }