Řešení KSP úlohy 33-3-4 Obsazování území https://ksp.mff.cuni.cz/h/ulohy/33/zadani3.html#task-33-3-4
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

293 lines
9.4 KiB

use crate::city;
use crate::db::{LayoutDB, SavedLayout};
use crate::city::{City, House, SIZE};
use itertools::Itertools;
use itertools::iproduct;
use std::collections::{VecDeque, HashMap};
use std::collections::vec_deque::Iter;
struct LeftState<'a> {
layout: &'a SavedLayout,
sorted_houses: Vec<House>,
line: LeftLine
}
struct RightState<'a> {
layout: &'a SavedLayout,
line: RightLine
}
pub struct CompatibilityCache {
map: HashMap<(usize, usize, usize, bool), bool>
}
impl CompatibilityCache {
pub fn new() -> CompatibilityCache {
CompatibilityCache {
map: HashMap::new()
}
}
pub fn is_compatible(&self, left_layout: &SavedLayout, right_layout: &SavedLayout, index: usize, y_axis: bool) -> Option<&bool> {
self.map.get(&(left_layout.id(), right_layout.id(), index, y_axis))
}
pub fn set_compatible(&mut self, left_layout: &SavedLayout, right_layout: &SavedLayout, index: usize, y_axis: bool, compatible: bool) {
self.map.insert((left_layout.id(), right_layout.id(), index, y_axis), compatible);
}
}
pub fn try_combine(city: &City, left_layouts: &Vec<SavedLayout>, right_layouts: &Vec<SavedLayout>, db: &mut LayoutDB, cache: &mut CompatibilityCache, transposed: bool) -> bool {
let mut improved = false;
let mut lefts = Vec::new();
let mut rights = Vec::new();
for left_layout in left_layouts {
// Sorted in reverse so we can remove from the end
let sorted_houses: Vec<_> = left_layout.houses().iter().sorted_by(|h1, h2| h2.x.cmp(&h1.x)).map(|x| *x).collect();
lefts.push(LeftState {
layout: &left_layout,
sorted_houses,
line: LeftLine::new()
});
}
for right_layout in right_layouts {
let mut sorted_houses: Vec<_> = right_layout.houses().iter().sorted_by(|h1, h2| h2.x.cmp(&h1.x)).map(|x| *x).collect();
let mut line = RightLine::new();
// Make sure that we include all houses initially
while let Some(house) = sorted_houses.pop() {
line.add_house(house, &city);
}
rights.push(RightState {
layout: right_layout,
line
});
}
let mut best_price = left_layouts.iter().chain(right_layouts.iter())
.map(|layout| city::get_price(&city, layout.houses()))
.min();
let axis = if transposed { "y" } else { "x" };
// x is the last left coordinate, x+1 is right
for x in 0..SIZE {
eprintln!("Starting {} {}", axis, x);
// Update the lines
for left in lefts.iter_mut() {
while let Some(house) = left.sorted_houses.last() {
if house.x == x {
left.line.add_house(*house, &city);
left.sorted_houses.pop();
} else {
break;
}
}
}
for right_line in rights.iter_mut() {
right_line.line.remove_houses(x, &city);
}
// Check compatibility of lines
if x == 0 {
// Cannot check this due to limitations in the implementation of LeftLine,
// it wouldn't be very interesting anyway.
continue;
}
let pairs = iproduct!(lefts.iter().enumerate(), rights.iter().enumerate())
.filter(|((left_i, _), (right_i, _))| left_i != right_i)
.map(|((left_i, left), (right_i, right))| (left, right, left.line.price + right.line.price, left_i, right_i))
.sorted_by(|(_, _, price1, _, _), (_, _, price2, _, _)| price1.cmp(&price2));
let mut compatibles = 0;
let mut incompatibles = 0;
let mut cache_hits = 0;
for (left, right, price, left_i, right_i) in pairs {
if let Some(min_price) = best_price {
if price >= min_price {
break;
}
}
let compatible = match cache.is_compatible(left.layout, right.layout, x, transposed) {
None => {
let compatible = is_compatible(city, &left.line, &right.line);
cache.set_compatible(left.layout, right.layout, x, transposed, compatible);
compatible
}
Some(compatible) => {
cache_hits += 1;
*compatible
}
};
if compatible {
if best_price.is_none() || price < best_price.unwrap() {
best_price = Some(price);
eprintln!("{} - new best score, cut on {} {}, left {} - right {}, printing", price, axis, x, left_i, right_i);
println!("{} - new best score, cut on {} {}, left {} - right {}", price, axis, x, left_i, right_i);
let mut new_houses: Vec<_> = left.line.houses().copied().chain(right.line.houses().copied()).collect();
if transposed {
new_houses = transpose_layout(&new_houses);
}
println!("{}", new_houses.len());
for house in &new_houses {
println!("{} {}", house.y, house.x);
}
// We only add best results to avoid overfilling the database with similar layouts
db.add_layout(&new_houses, false);
improved = true;
}
compatibles += 1;
// All other pairs would be more expensive
break;
} else {
incompatibles += 1;
}
}
eprintln!("{} incompatibles checked before {} compatible ({} cache hits)", incompatibles, compatibles, cache_hits);
}
improved
}
fn is_compatible(city: &City, left: &LeftLine, right: &RightLine) -> bool {
for y in 0..SIZE {
let max_left_covered_x = left.get_max_covered_x(y);
let min_right_covered_x = right.get_min_covered_x(y);
// This range will often be empty
for x in (max_left_covered_x + 1)..min_right_covered_x {
if city.is_house_xy(x, y) {
return false;
}
}
}
true
}
struct LeftLine {
covers: Vec<usize>,
houses: Vec<House>,
price: u32,
}
struct RightLine {
covers: Vec<usize>,
houses: VecDeque<House>,
price: u32,
}
impl LeftLine {
pub fn new() -> Self {
// XXX: Careful, default of 0 includes covering first vertical line
let covers = vec![0; SIZE];
let houses = Vec::new();
LeftLine { covers, houses, price: 0 }
}
pub fn add_house(&mut self, house: House, city: &City) {
let range_rect = house.range_rectangle();
for y in range_rect.top..=range_rect.bottom {
// Should always be the max variant
self.covers[y] = self.covers[y].max(range_rect.right);
}
self.price += city.get_price(house) as u32;
self.houses.push(house);
}
pub fn get_max_covered_x(&self, y: usize) -> usize {
self.covers[y]
}
pub fn get_side_price(&self) -> u32 {
self.price
}
pub fn houses(&self) -> std::slice::Iter<'_, House> {
self.houses.iter()
}
}
impl RightLine {
pub fn new() -> Self {
let covers = vec![usize::MAX; SIZE];
let houses = VecDeque::new();
RightLine { covers, houses, price: 0 }
}
pub fn add_house(&mut self, house: House, city: &City) {
// Added houses have to always be ordered by x
let range_rect = house.range_rectangle();
for y in range_rect.top..=range_rect.bottom {
self.covers[y] = self.covers[y].min(range_rect.left);
}
self.houses.push_back(house);
self.price += city.get_price(house) as u32
}
pub fn remove_houses(&mut self, x: usize, city: &City) {
// Has to be called with x, x+1, x+2...
while let Some(house) = self.houses.front() {
if house.x == x {
let removed_house = self.houses.pop_front().unwrap();
let removed_rect = removed_house.range_rectangle();
// Remove the now-outdated distances around the removed house
for y in removed_rect.top..=removed_rect.bottom {
self.covers[y] = usize::MAX;
}
// Update distances around the removed house if the area of any houses
// intersects the removed area
for house in &self.houses {
let house_rect = house.range_rectangle();
let y_intersection = if removed_house.y < house.y {
house_rect.top..=removed_rect.bottom
} else {
removed_rect.top..=house_rect.bottom
};
for y in y_intersection {
self.covers[y] = self.covers[y].min(house_rect.left);
}
}
self.price -= city.get_price(removed_house) as u32;
} else {
break;
}
}
}
pub fn get_min_covered_x(&self, y: usize) -> usize {
self.covers[y].min(SIZE)
}
pub fn get_side_price(&self) -> u32 {
self.price
}
pub fn houses(&self) -> Iter<'_, House> {
self.houses.iter()
}
}
pub fn transpose_layout(houses: &Vec<House>) -> Vec<House> {
let mut transposed = Vec::new();
for house in houses {
transposed.push(House::new(house.y, house.x));
}
transposed
}