結果

問題 No.3 ビットすごろく
ユーザー cra77756176
提出日時 2022-11-17 23:19:44
言語 Rust
(1.83.0 + proconio)
結果
AC  
実行時間 596 ms / 5,000 ms
コード長 1,275 bytes
コンパイル時間 13,669 ms
コンパイル使用メモリ 379,332 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-09-19 09:26:10
合計ジャッジ時間 20,717 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

use std::{
    collections::HashSet,
    io::{self, BufRead},
};

fn main() {
    io::stdin().lock().lines().for_each(|l| {
        let goal = l.unwrap().parse::<usize>().unwrap();
        if goal == 1 {
            println!("1");
            return;
        }

        let pop_counts = (0..=goal)
            .map(|n| n.count_ones() as usize)
            .collect::<Vec<_>>();

        let mut positions = HashSet::new();
        positions.insert(1);
        let mut reached = positions.clone();

        for i in 2.. {
            let mut new_positions = HashSet::new();
            for p in &positions {
                let left = p - pop_counts[*p];
                if left >= 1 {
                    new_positions.insert(left);
                }
                let right = p + pop_counts[*p];
                if right <= goal {
                    new_positions.insert(right);
                }
            }

            if new_positions.contains(&goal) {
                println!("{}", i);
                break;
            } else if new_positions.iter().all(|p| reached.contains(p)) {
                println!("-1");
                break;
            }

            positions = new_positions.clone();
            reached.extend(new_positions);
        }
    });
}
0