From b61adf6b31e06680745735819e3abf57999edf47 Mon Sep 17 00:00:00 2001 From: hit-lu Date: Fri, 8 Aug 2025 23:12:31 +0800 Subject: [PATCH] add segment tree with example 3479 --- segment-tree/3479 fruits-into-baskets-III.cpp | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 segment-tree/3479 fruits-into-baskets-III.cpp diff --git a/segment-tree/3479 fruits-into-baskets-III.cpp b/segment-tree/3479 fruits-into-baskets-III.cpp new file mode 100644 index 0000000..8aaf6ea --- /dev/null +++ b/segment-tree/3479 fruits-into-baskets-III.cpp @@ -0,0 +1,63 @@ +/* You are given two arrays of integers, fruits and baskets, each of length n, where fruits[i] represents the quantity of the ith type of fruit, and baskets[j] represents the capacity of the jth basket. + + From left to right, place the fruits according to these rules: + + 1.Each fruit type must be placed in the leftmost available basket with a capacity greater than or equal to the quantity of that fruit type. + 2.Each basket can hold only one type of fruit. + 3.If a fruit type cannot be placed in any basket, it remains unplaced. + + Return the number of fruit types that remain unplaced after all possible allocations are made. +*/ +class SegmentTree { +private: + vector segVal; + void maintain(int node) { + segVal[node] = max(segVal[node * 2], segVal[node * 2 + 1]); + } + void build(const vector& vec, int node, int left, int right) { + if (left == right) { + segVal[node] = vec[left]; + return; + } + int mid = (left + right) / 2; + build(vec, node * 2, left, mid); + build(vec, node * 2 + 1, mid + 1, right); + maintain(node); + } +public: + SegmentTree(const vector& vec) { + size_t n = vec.size(); + segVal.resize(2 << std::bit_width(n - 1)); + build(vec, 1, 0, n - 1); + } + int findFirstAndUpdate(int node, int left, int right, int val) { + if (segVal[node] < val) { + return -1; // not found; + } + if (left == right) { + segVal[node] = -1; // update state + return left; + } + int mid = (left + right) / 2; + int idx = findFirstAndUpdate(node * 2, left, mid, val); + if (idx < 0) { + idx = findFirstAndUpdate(node * 2 + 1, mid + 1, right, val); + } + maintain(node); + return idx; + } +}; + +class Solution { +public: + int numOfUnplacedFruits(vector& fruits, vector& baskets) { + SegmentTree t(baskets); + int n = baskets.size(), ans = 0; + for (int x : fruits) { + if (t.findFirstAndUpdate(1, 0, n - 1, x) < 0) { + ans++; + } + } + return ans; + } +};