AtCoder Beginner Contest 277 D

https://atcoder.jp/contests/abc277/tasks/abc277_d

Aをソートして、グループ化します。あとは最初と最後がくっつくかですね。

// Takahashi's Solitaire
#![allow(non_snake_case)]

fn read<T: std::str::FromStr>() -> T {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).ok();
    line.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>().split_whitespace()
            .map(|e| e.parse().ok().unwrap()).collect()
}

fn read_input() -> (usize, Vec<usize>) {
    let v: Vec<usize> = read_vec();
    let _N = v[0];
    let M = v[1];
    let A = read_vec();
    (M, A)
}

fn make_regions(A: &Vec<usize>, M: usize) -> Vec<(usize, usize, usize)> {
    let mut B = A.clone();
    B.sort();
    
    let mut regions = Vec::<(usize, usize, usize)>::new();
    let mut first: usize = M;
    let mut last: usize = 0;
    let mut s: usize = 0;
    for &a in B.iter() {
        if first == M {     // start
            first = a;
            s = a;
        }
        else if a == last - 1 || a == last {
            s += a;
        }
        else {
            regions.push((first, last, s));
            first = a;
            s = a;
        }
        last = a + 1;
    }
    regions.push((first, last, s));
    let (first1, last1, s1) = regions.first().unwrap();
    let (first2, last2, s2) = regions.last().unwrap();
    if *first1 == 0 && *last2 == M && regions.len() > 1 {
        regions[0] = (*first2, *last1, s1 + s2);
        regions.pop();
    }
    regions
}

fn f(M: usize, A: Vec<usize>) -> usize {
    let regions = make_regions(&A, M);
    let max_sum = regions.iter().map(|(_, _, s)| s).max().unwrap();
    A.iter().sum::<usize>() - max_sum
}

fn main() {
    let v = read_input();
    println!("{}", f(v.0, v.1))
}