今天我们来看看洛谷P1003的Rust解法。 先上AC代码:
use std::io::stdin;
#[derive(Debug, Clone)]
struct Point {
pub x: i32,
pub y: i32
}
struct Rect {
pub bottom_left: Point,
pub top_right: Point,
}
impl Point {
fn new(x: i32, y: i32) -> Self {
Self {
x, y
}
}
}
impl Rect {
fn new(bottom_left: &Point, top_right: &Point) -> Self {
Self {
bottom_left: bottom_left.clone(),
top_right: top_right.clone(),
}
}
}
fn read_numbers_in_line() -> Vec<i32> {
let mut buffer = String::new();
stdin().read_line(&mut buffer).unwrap();
buffer.split(" ").filter_map(|x| {
x.trim().parse::<i32>().ok()
}).collect()
}
fn main() {
let n = read_numbers_in_line()[0];
let mut rects: Vec<Rect> = vec![];
for _i in 0..n {
let ns = read_numbers_in_line();
rects.push(Rect::new(
&Point::new(ns[0], ns[1]),
&Point::new(ns[0] + ns[2], ns[1] + ns[3]),
))
}
let input_ptr = read_numbers_in_line();
let query = Point::new(input_ptr[0], input_ptr[1]);
let x = query.x;
let y = query.y;
for counter in (0..=(n-1)).rev() {
if rects[counter as usize].top_right.x >= x && rects[counter as usize].top_right.y >= y && rects[counter as usize].bottom_left.x <= x && rects[counter as usize].bottom_left.y <= y {
println!("{}", counter + 1);
return;
}
}
println!("-1");
}
这是一道简单的模拟题,从后往前模拟即可。一旦找到了地毯,直接return,没什么好说的。不过这里呢用到了Rust结构体:Rust当中结构体可以具有方法(写在impl里),其生命就是多个字段用逗号隔开,花括号结尾没有分号(这是我最喜欢的一点):
struct Rect {
pub bottom_left: Point,
pub top_right: Point,
}根据习惯,我们常常会声明一个new函数来构造一个新的struct。当然,rust的struct声明远不止于此。我们还可以有unit struct:
struct AUnitStruct;这使它表现的像一个Unit类型一样,比如,unit struct具有一个实例就是它本身,所以
AUnitStruct的类型就是AUnitStruct,就像单例一样(只不过没有字段)。Rust结构体还可以用来实现约束。格外提一下,约束也是Rust当中一个非常强大的功能,你甚至可以用它来扩展各种类型,比如给String加一个自定义的XXX方法就是可以写成:
trait MyStringExt {
pub fn xxx(&self) {
// Go here
}
}
impl MyStringExt for String {}这样,你就可以在String上调用xxx方法了。你不需要自己重写一个String!