20241212 finished.

This commit is contained in:
jackfiled 2024-12-12 18:08:04 +08:00
parent f711d3f4d6
commit 441384ffbd
2 changed files with 76 additions and 0 deletions

View File

@ -364,3 +364,5 @@ mod p1812_determine_color_of_a_chessboard_square;
mod p935_knight_dialer; mod p935_knight_dialer;
mod p2717_semi_ordered_permutation; mod p2717_semi_ordered_permutation;
mod p2931_maximum_spending_after_buying_items;

View File

@ -0,0 +1,74 @@
/**
* [2931] Maximum Spending After Buying Items
*/
pub struct Solution {}
// submission codes start here
use std::cmp::Ordering;
use std::collections::BinaryHeap;
#[derive(Debug, PartialEq, Eq)]
struct Item {
price: i64,
shop: usize,
pos: usize,
}
impl Ord for Item {
fn cmp(&self, other: &Self) -> Ordering {
other.price.cmp(&self.price)
}
}
impl PartialOrd for Item {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Solution {
pub fn max_spending(values: Vec<Vec<i32>>) -> i64 {
let (m, n) = (values.len(), values[0].len());
let mut heap = BinaryHeap::with_capacity(values.len());
let mut result = 0;
for i in 0..m {
heap.push(Item {
price: values[i][n - 1] as i64,
shop: i,
pos: n - 1,
});
}
let mut day = 1;
while let Some(top) = heap.pop() {
result += top.price * day;
day += 1;
if top.pos > 0 {
heap.push(Item {
price: values[top.shop][top.pos - 1] as i64,
shop: top.shop,
pos: top.pos - 1,
})
}
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2931() {
assert_eq!(
285,
Solution::max_spending(vec![vec![8, 5, 2], vec![6, 4, 1], vec![9, 7, 3]])
);
}
}