{"id":34762,"date":"2024-11-01T09:31:43","date_gmt":"2024-11-01T09:31:43","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=34762"},"modified":"2024-11-01T11:26:39","modified_gmt":"2024-11-01T11:26:39","slug":"swift-coding-test-course-segment-tree","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/34762\/","title":{"rendered":"Swift Coding Test Course, Segment Tree"},"content":{"rendered":"<p>Hello! In this lecture, we will take a closer look at the segment tree, which is one of the data structures. The segment tree is a powerful data structure that can efficiently handle interval queries, especially useful for calculating the range sum, range minimum, and range maximum of an array. In this text, we will explore the basic concepts of segment trees, how to implement them, and solve problems that are frequently asked in practice.<\/p>\n<h2>1. What is a Segment Tree?<\/h2>\n<p>A segment tree is a powerful tool for efficiently managing the interval information of an array. Typically, when the size of the array is N, a segment tree uses approximately 2 * 2<sup>\u2308log\u2082(N)\u2309<\/sup> memory space. This is due to the use of a complete binary tree structure. Fundamentally, the segment tree can perform the following two operations efficiently:<\/p>\n<ul>\n<li>Interval Query: Quickly retrieve information about a specific interval.<\/li>\n<li>Update: Rapidly update the interval information affected after changing a specific element of the array.<\/li>\n<\/ul>\n<h2>2. Structure of the Segment Tree<\/h2>\n<p>The segment tree is made up of nodes, each representing a specific interval. For example, there is a root node that manages the interval from index 0 to N-1 of the array, and this node divides the array into two halves through two child nodes. By continuously dividing the array in this manner, each node holds the information of a specific interval.<\/p>\n<h3>2.1 Node Definition<\/h3>\n<p>Each node contains the following information:<\/p>\n<ul>\n<li><strong>Start Index (start)<\/strong>: The starting point of the interval<\/li>\n<li><strong>End Index (end)<\/strong>: The ending point of the interval<\/li>\n<li><strong>Value (value)<\/strong>: A variable to store the information of the interval (e.g., sum, minimum value, etc.)<\/li>\n<\/ul>\n<h2>3. Creating and Querying the Segment Tree<\/h2>\n<p>To implement a segment tree, we first need to build the tree. For this, we use a method that recursively creates segment tree nodes based on the input array. As a simple example, let&#8217;s create a segment tree for range sums.<\/p>\n<pre>\n<code>\n\/\/ Swift Code\nclass SegmentTree {\n    var tree: [Int] \/\/ Array to store the segment tree\n    var n: Int \/\/ Size of the array\n\n    init(_ data: [Int]) {\n        self.n = data.count\n        self.tree = Array(repeating: 0, count: 4 * n) \/\/ Initialize the tree array\n        buildTree(data: data, node: 1, start: 0, end: n - 1)\n    }\n\n    \/\/ Build the segment tree using the interval of the array\n    func buildTree(data: [Int], node: Int, start: Int, end: Int) {\n        if start == end {\n            tree[node] = data[start] \/\/ Store value in leaf node\n        } else {\n            let mid = (start + end) \/ 2\n            buildTree(data: data, node: 2 * node, start: start, end: mid) \/\/ Left subtree\n            buildTree(data: data, node: 2 * node + 1, start: mid + 1, end: end) \/\/ Right subtree\n            tree[node] = tree[2 * node] + tree[2 * node + 1] \/\/ Update parent node value\n        }\n    }\n}\n<\/code>\n<\/pre>\n<h2>4. Processing Segment Tree Queries<\/h2>\n<p>The segment tree now needs to add a feature to calculate range sums. To handle range sum queries, we will add the following function:<\/p>\n<pre>\n<code>\n\/\/ Function to calculate the sum of a given interval\nfunc query(node: Int, start: Int, end: Int, l: Int, r: Int) -> Int {\n    if r < start || end < l { \/\/ If intervals do not overlap\n        return 0 \/\/ Default value\n    }\n    if l <= start &#038;&#038; end <= r { \/\/ If the interval is completely contained\n        return tree[node]\n    }\n    let mid = (start + end) \/ 2\n    let leftSum = query(node: 2 * node, start: start, end: mid, l: l, r: r) \/\/ Query left subtree\n    let rightSum = query(node: 2 * node + 1, start: mid + 1, end: end, l: l, r: r) \/\/ Query right subtree\n    return leftSum + rightSum \/\/ Sum the results\n}\n<\/code>\n<\/pre>\n<h2>5. Updating the Segment Tree<\/h2>\n<p>We will also add a function to update the elements of the array. When changing a specific index of the array, here\u2019s how we can quickly update the information in the segment tree:<\/p>\n<pre>\n<code>\n\/\/ Function to update a specific index of the array\nfunc update(node: Int, start: Int, end: Int, idx: Int, value: Int) {\n    if start == end { \/\/ Reached leaf node\n        tree[node] = value \/\/ Update the node\n    } else {\n        let mid = (start + end) \/ 2\n        if start <= idx &#038;&#038; idx <= mid {\n            update(node: 2 * node, start: start, end: mid, idx: idx, value: value) \/\/ Update left subtree\n        } else {\n            update(node: 2 * node + 1, start: mid + 1, end: end, idx: idx, value: value) \/\/ Update right subtree\n        }\n        tree[node] = tree[2 * node] + tree[2 * node + 1] \/\/ Update parent node value\n    }\n}\n<\/code>\n<\/pre>\n<h2>6. Example of a Practical Problem<\/h2>\n<p>Now that we have looked at the basic structure of the segment tree and how to perform queries and updates, let's tackle a problem that is frequently asked in practice. The problem is as follows:<\/p>\n<h3>Problem Description<\/h3>\n<p>Given an array, answer the following questions:<\/p>\n<ol>\n<li>Calculate the sum of the interval [L, R].<\/li>\n<li>Update the value of index I to V.<\/li>\n<\/ol>\n<h3>Input Format<\/h3>\n<pre>\nN (array size)\narr[0], arr[1], ..., arr[N-1]\nQ (number of queries)\nEach query is given in the following format:\n1 L R (range sum query)\n2 I V (update query)\n<\/pre>\n<h3>Output Format<\/h3>\n<pre>\nOutput for each range sum query\n<\/pre>\n<h3>Example<\/h3>\n<pre>\n5\n1 2 3 4 5\n3\n1 1 3\n2 2 10\n1 1 3\n<\/pre>\n<pre>\nExample Output\n6\n<\/pre>\n<h2>7. Problem-Solving Process<\/h2>\n<ol>\n<li>Build a segment tree for the input array.<\/li>\n<li>Depending on the query type, call the query() function for range queries and the update() function for update queries.<\/li>\n<li>Print the results.<\/li>\n<\/ol>\n<pre>\n<code>\n\/\/ Main function to solve the problem\nimport Foundation\n\nfunc main() {\n    \/\/ Input processing\n    let n = Int(readLine()!)!\n    let arr = readLine()!.split(separator: \" \").map { Int($0)! }\n    let q = Int(readLine()!)!\n\n    \/\/ Build the segment tree\n    let segmentTree = SegmentTree(arr)\n\n    \/\/ Process queries\n    for _ in 0..<q {\n        let input = readLine()!.split(separator: \" \").map { String($0) }\n        if input[0] == \"1\" { \/\/ Range sum query\n            let l = Int(input[1])!\n            let r = Int(input[2])!\n            let sum = segmentTree.query(node: 1, start: 0, end: n - 1, l: l, r: r)\n            print(sum)\n        } else { \/\/ Update query\n            let idx = Int(input[1])!\n            let value = Int(input[2])!\n            segmentTree.update(node: 1, start: 0, end: n - 1, idx: idx, value: value)\n        }\n    }\n}\n<\/code>\n<\/pre>\n<h2>8. Conclusion<\/h2>\n<p>Through this lecture on segment trees, we learned the importance of data structures and how to utilize them. Segment trees can be effectively used for various interval query problems. We hope you will enhance your skills in applying segment trees through more practice problems. Thank you!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello! In this lecture, we will take a closer look at the segment tree, which is one of the data structures. The segment tree is a powerful data structure that can efficiently handle interval queries, especially useful for calculating the range sum, range minimum, and range maximum of an array. In this text, we will &hellip; <a href=\"https:\/\/atmokpo.com\/w\/34762\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Swift Coding Test Course, Segment Tree&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[129],"tags":[],"class_list":["post-34762","post","type-post","status-publish","format-standard","hentry","category-swift-coding-test"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Swift Coding Test Course, Segment Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/34762\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Swift Coding Test Course, Segment Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"Hello! In this lecture, we will take a closer look at the segment tree, which is one of the data structures. The segment tree is a powerful data structure that can efficiently handle interval queries, especially useful for calculating the range sum, range minimum, and range maximum of an array. In this text, we will &hellip; \ub354 \ubcf4\uae30 &quot;Swift Coding Test Course, Segment Tree&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/34762\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:31:43+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:26:39+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"2\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/34762\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34762\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Swift Coding Test Course, Segment Tree\",\"datePublished\":\"2024-11-01T09:31:43+00:00\",\"dateModified\":\"2024-11-01T11:26:39+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34762\/\"},\"wordCount\":540,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Swift Coding Test\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/34762\/\",\"url\":\"https:\/\/atmokpo.com\/w\/34762\/\",\"name\":\"Swift Coding Test Course, Segment Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:31:43+00:00\",\"dateModified\":\"2024-11-01T11:26:39+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34762\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/34762\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/34762\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Swift Coding Test Course, Segment Tree\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Swift Coding Test Course, Segment Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/34762\/","og_locale":"ko_KR","og_type":"article","og_title":"Swift Coding Test Course, Segment Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"Hello! In this lecture, we will take a closer look at the segment tree, which is one of the data structures. The segment tree is a powerful data structure that can efficiently handle interval queries, especially useful for calculating the range sum, range minimum, and range maximum of an array. In this text, we will &hellip; \ub354 \ubcf4\uae30 \"Swift Coding Test Course, Segment Tree\"","og_url":"https:\/\/atmokpo.com\/w\/34762\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:31:43+00:00","article_modified_time":"2024-11-01T11:26:39+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"2\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/34762\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/34762\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Swift Coding Test Course, Segment Tree","datePublished":"2024-11-01T09:31:43+00:00","dateModified":"2024-11-01T11:26:39+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/34762\/"},"wordCount":540,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Swift Coding Test"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/34762\/","url":"https:\/\/atmokpo.com\/w\/34762\/","name":"Swift Coding Test Course, Segment Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:31:43+00:00","dateModified":"2024-11-01T11:26:39+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/34762\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/34762\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/34762\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Swift Coding Test Course, Segment Tree"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34762","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=34762"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34762\/revisions"}],"predecessor-version":[{"id":34763,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34762\/revisions\/34763"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=34762"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=34762"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=34762"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}