【Rust】競技プログラミングよく使うスニペット

# ■ 標準入出力
```rust
use std::io;
use std::io::prelude::*;
use std::io::{BufReader, BufWriter};

fn main() {
  let mut n: usize = 0;
  let mut w: usize = 0;
  let mut bs: Vec<Vec<i64>> = vec![];
  // let mut writer = writer();
  for (idx, line) in reader().lines().enumerate() {
    let line = line.ok().unwrap();
    // writer.write(line.as_bytes()).unwrap();
    // writer.write("\n".as_bytes()).unwrap();
    let ary = line.trim().split(" ").map(|e| {e.parse::<i64>().ok().unwrap()}).collect::<Vec<i64>>();
    if idx == 0 {
      n = ary[0] as usize;
      w = ary[1] as usize;
    } else {
      bs.push(ary);
      if idx == n {break;}
    }
  }
}

#[allow(dead_code)]
fn reader() -> BufReader<Box<dyn Read>> {
    let read: Box<dyn Read> = Box::new(io::stdin());
    return BufReader::new(read);
}

#[allow(dead_code)]
fn writer() -> BufWriter<Box<dyn Write>> {
    let write: Box<dyn Write> = Box::new(io::stdout());
    return BufWriter::new(write);
}
```

# ■ 初期サイズを指定して配列を作成
```rust
let mut dp: Vec<i64> = vec![default; len];
```

# ■ 文字列 <-> 1文字ずつ 
```rust
let cs: Vec<char> = line.trim().chars().collect::<Vec<char>>();
let s: String = cs.into_iter().collect();
```
# ■ 文字列 -> 数値へのパース
```rust
fn main() {
    let number = "10";
    let int = number.parse::<i32>().ok().unwrap();
    println!("{}", int);
}
```

# ■ 数値比較
```rust
let a = 10;
let b = 20;
let max = a.max(b); // 20
let min = a.min(b); // 10
```
# ■ スペース区切りの文字列を配列にパース
```rust
fn main() {
    let line = "10 20 30 40";
    let ary = line.trim().split(" ").map(|e| {e.parse::<i64>().ok().unwrap()}).collect::<Vec<i64>>()
    println!("{:?}", ary);
}
```

# ■ 余りの演算

```rust
#[allow(dead_code)]
struct ModExpr {
  m: i64
}

#[allow(dead_code)]
impl ModExpr {
  fn new(m: i64) -> Self {
    return ModExpr{m};
  }
  fn add(&self, a: i64, b: i64) -> i64 {
    return (a + b) % self.m;
  }

  fn sub(&self, a: i64, b: i64) -> i64 {
    let sub = (a - b) % self.m;
    return if sub < 0 {sub + self.m} else {sub};
  }

  fn mul(&self, a: i64, b: i64) -> i64 {
    return a * b % self.m;
  }

  fn pow(&self, a: i64, n: i64) -> i64 {
    let mut ret: i64 = 1;
    for _ in 0..n {
      ret = ret * a % self.m;
    }
    return ret;
  }
}
```

# ■ 累積和
```rust
fn main() {
  // 余りの演算を行う
  let me = ModExpr::new(10_i64.pow(9) + 7);
  let add = |a: i64, b: i64| {me.add(a, b)};
  let memo: Vec<i64> = cumulative_sum(&data, Some(&add));

  // 余りの演算を行わない
  let memo: Vec<i64> = cumulative_sum(&data, None);
}

fn cumulative_sum<F>(ary: &[i64], add: Option<&F>) -> Vec<i64>
  where F: Fn(i64, i64) -> i64
{
  let mut ret: Vec<i64> = vec![0; ary.len()];
  let mut sum = 0;
  for (i, &d) in ary.iter().enumerate().rev() {
    sum = if let Some(f) = add { f(sum, d) } else { sum + d };
    ret[i] = sum;
  }
  return ret;
}
```

# ■ UnionFind1
```rust
use std::collections::HashMap;
use std::hash::Hash

#[allow(dead_code)]
struct UnionFind<T: Eq + Hash + Clone> {
  par: HashMap<T, T>,
}

#[allow(dead_code)]
impl<T: Eq + Hash + Clone> UnionFind<T> {
  fn new() -> Self {
    return UnionFind {par: HashMap::new()};
  }

  fn root(&self, k: &T) -> Option<&T> {
    if let Some(v) = self.par.get(k) {
      if *v == *k {
        return Some(v);
      } else {
        return self.root(v);
      };
    } else {
      return None;
    }
  }

  fn root_or_insert(&mut self, k: &T) -> &T {
    if !self.par.contains_key(k) {
      self.par.insert(k.clone(), k.clone());
    }
    return self.root(k).unwrap();
  }

  fn unite(&mut self, a: &T, b: &T) {
    let root_a = self.root_or_insert(a).clone();
    let root_b = self.root_or_insert(b).clone();
    if root_a != root_b {
      self.par.insert(root_a, root_b);
    }
  }

  fn same(&self, a: &T, b: &T) -> bool {
    if let (Some(root_a), Some(root_b)) = (self.root(a), self.root(b)) {
      return *root_a == *root_b;
    } else {
      return false;
    }
  }

  fn group(&self) -> HashMap<T, Vec<T>> {
    let mut group: HashMap<T, Vec<T>> = HashMap::new();
    for (k, _) in self.par.iter() {
      if let Some(root) = self.root(k) {
        if let Some(ks) = group.get_mut(root) {
          ks.push(k.clone());
        } else {
          group.insert(root.clone(), vec![k.clone()]);
        }
      }
    }
    return group;
  }
}
```
# ■ UnionFind2
```rust
fn main() {
  let mut uf = UnionFind::new(10);
  uf.resize(30);
  uf.unite(1, 3);
  uf.unite(1, 4);
  uf.unite(2, 5);
  uf.size(1); // 3
  uf.size(4); // 3
  uf.size(5); // 2
}
```
```rust

#[allow(dead_code)]
struct UnionFind {
  par: Vec<i64>,
}

#[allow(dead_code)]
impl UnionFind {
  fn new(len: usize) -> Self {
    return UnionFind {par: vec![-1; len]};
  }

  fn resize(&mut self, len: usize) {
    self.par.resize(len, -1);
  }

  fn root(&mut self, k: usize) -> usize {
    if self.par.len() <= k { self.resize(k + 1); }
    if self.par[k] < 0 {
      return k;
    } else {
      let root: usize = self.root(self.par[k] as usize);
      self.par[k] = root as i64;
      return root;
     }
  }

  fn unite(&mut self, a: usize, b: usize) {
    let ra = self.root(a);
    let rb = self.root(b);
    if ra != rb {
      if self.par[ra] > self.par[rb] {
        self.par.swap(ra, rb);
      }
      self.par[ra] = self.par[ra] + self.par[rb];
      self.par[rb] = ra as i64;
    }
  }

  fn same(&mut self, a: usize, b: usize) -> bool {
    return self.root(a) == self.root(b);
  }

  fn size(&mut self, k: usize) -> i64 {
    let root = self.root(k);
    return - self.par[root];
  }
}
```