Skip to content

Commit 5778202

Browse files
committed
1057
1 parent 86d984f commit 5778202

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,7 @@ mod prob_1000;
326326
mod prob_1002;
327327
mod prob_1003;
328328
mod prob_1007;
329+
mod prob_1057;
329330
mod prob_1059;
330331
mod prob_1092;
331332
mod prob_1109;

src/prob_1057.rs

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
use std::collections::BinaryHeap;
2+
use std::cmp::Ordering;
3+
4+
#[derive(Eq, PartialEq)]
5+
struct Elem(i32, usize, usize);
6+
7+
impl Ord for Elem {
8+
fn cmp(&self, other: &Self) -> Ordering {
9+
if self.0 == other.0 {
10+
if self.1 == other.1 {
11+
other.2.cmp(&self.2)
12+
} else {
13+
other.1.cmp(&self.1)
14+
}
15+
} else {
16+
other.0.cmp(&self.0)
17+
}
18+
}
19+
}
20+
21+
impl PartialOrd for Elem {
22+
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
23+
Some(self.cmp(other))
24+
}
25+
}
26+
27+
impl Solution {
28+
pub fn assign_bikes(workers: Vec<Vec<i32>>, bikes: Vec<Vec<i32>>) -> Vec<i32> {
29+
let n = workers.len();
30+
if n == 0 {
31+
return vec![];
32+
}
33+
let m = bikes.len();
34+
if m == 0 {
35+
return vec![];
36+
}
37+
let mut hp = BinaryHeap::new();
38+
for i in 0..n {
39+
for j in 0..m {
40+
let d = Self::abs(workers[i][0]-bikes[j][0]) + Self::abs(workers[i][1]-bikes[j][1]);
41+
hp.push(Elem(d, i, j));
42+
}
43+
}
44+
let mut ans = vec![0; n];
45+
let mut used_w = vec![false; n];
46+
let mut used_b = vec![false; m];
47+
let mut count = 0;
48+
while let Some(Elem(d, i, j)) = hp.pop() {
49+
if used_w[i] || used_b[j] {continue;}
50+
ans[i] = j as i32;
51+
used_w[i] = true;
52+
used_b[j] = true;
53+
count += 1;
54+
if count == n {
55+
break;
56+
}
57+
}
58+
ans
59+
}
60+
#[inline]
61+
fn abs(x: i32) -> i32 {
62+
if x >= 0 {x} else {-x}
63+
}
64+
}
65+
66+
struct Solution;
67+
68+
#[cfg(test)]
69+
mod tests {
70+
use super::Solution;
71+
72+
#[test]
73+
fn test_assign_bikes() {
74+
let test_cases = vec![
75+
(
76+
vec![[664,994],[3,425],[599,913],[220,352],[145,348],[604,428],[519,183],[732,148]],
77+
vec![[611,698],[113,338],[579,770],[276,588],[948,679],[731,525],[925,877],[182,281],[39,299]],
78+
vec![0,8,2,7,1,5,3,4],
79+
),
80+
(vec![[0,0],[2,1]], vec![[1,2],[3,3]], vec![1,0]),
81+
(vec![[0,0],[1,1],[2,0]], vec![[1,0],[2,2],[2,1]], vec![0,2,1]),
82+
];
83+
for (workers, bikes, expect) in test_cases {
84+
assert_eq!(Solution::assign_bikes(
85+
workers.iter().map(|v| vec![v[0], v[1]]).collect(),
86+
bikes.iter().map(|v| vec![v[0], v[1]]).collect()
87+
), expect, "workers: {:?}, bikes: {:?}", workers, bikes);
88+
}
89+
}
90+
}

0 commit comments

Comments
 (0)