結果

問題 No.5020 Averaging
ユーザー tipstar0125tipstar0125
提出日時 2024-02-26 18:43:05
言語 Rust
(1.77.0 + proconio)
結果
AC  
実行時間 884 ms / 1,000 ms
コード長 10,846 bytes
コンパイル時間 2,124 ms
コンパイル使用メモリ 206,464 KB
実行使用メモリ 110,236 KB
スコア 39,717,700
最終ジャッジ日時 2024-02-26 18:43:55
合計ジャッジ時間 48,563 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
純コード判定しない問題か言語
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 870 ms
110,236 KB
testcase_01 AC 884 ms
104,860 KB
testcase_02 AC 877 ms
110,108 KB
testcase_03 AC 866 ms
104,224 KB
testcase_04 AC 870 ms
109,980 KB
testcase_05 AC 870 ms
105,244 KB
testcase_06 AC 866 ms
109,340 KB
testcase_07 AC 868 ms
109,212 KB
testcase_08 AC 805 ms
11,608 KB
testcase_09 AC 869 ms
107,804 KB
testcase_10 AC 865 ms
104,224 KB
testcase_11 AC 869 ms
107,420 KB
testcase_12 AC 871 ms
106,140 KB
testcase_13 AC 864 ms
109,852 KB
testcase_14 AC 870 ms
104,988 KB
testcase_15 AC 865 ms
108,188 KB
testcase_16 AC 866 ms
105,372 KB
testcase_17 AC 802 ms
6,676 KB
testcase_18 AC 869 ms
108,956 KB
testcase_19 AC 867 ms
109,212 KB
testcase_20 AC 867 ms
107,804 KB
testcase_21 AC 873 ms
104,224 KB
testcase_22 AC 867 ms
107,804 KB
testcase_23 AC 870 ms
104,224 KB
testcase_24 AC 868 ms
107,420 KB
testcase_25 AC 868 ms
104,224 KB
testcase_26 AC 865 ms
104,224 KB
testcase_27 AC 865 ms
109,468 KB
testcase_28 AC 870 ms
104,224 KB
testcase_29 AC 883 ms
108,060 KB
testcase_30 AC 880 ms
108,828 KB
testcase_31 AC 868 ms
107,548 KB
testcase_32 AC 863 ms
108,828 KB
testcase_33 AC 867 ms
104,604 KB
testcase_34 AC 866 ms
109,212 KB
testcase_35 AC 866 ms
105,244 KB
testcase_36 AC 856 ms
105,628 KB
testcase_37 AC 868 ms
104,348 KB
testcase_38 AC 867 ms
109,468 KB
testcase_39 AC 869 ms
105,884 KB
testcase_40 AC 871 ms
109,468 KB
testcase_41 AC 863 ms
107,676 KB
testcase_42 AC 869 ms
110,236 KB
testcase_43 AC 865 ms
105,756 KB
testcase_44 AC 866 ms
109,596 KB
testcase_45 AC 819 ms
31,512 KB
testcase_46 AC 866 ms
108,828 KB
testcase_47 AC 867 ms
105,756 KB
testcase_48 AC 804 ms
8,760 KB
testcase_49 AC 869 ms
106,652 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#![allow(non_snake_case)]
#![allow(unused_imports)]
#![allow(unused_macros)]
#![allow(clippy::needless_range_loop)]
#![allow(clippy::comparison_chain)]
#![allow(clippy::nonminimal_bool)]
#![allow(clippy::neg_multiply)]
#![allow(dead_code)]
use std::cmp::Reverse;
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};

use crate::rnd::gen_range;

const TARGET: isize = 5e17 as isize;
const TURN_MAX: usize = 50;

#[derive(Default)]
struct Solver {}
impl Solver {
    fn solve(&mut self) {
        let start = std::time::Instant::now();
        #[cfg(feature = "local")]
        {
            let seed = 1;
            eprintln!("Seed: {seed}");
            rnd::init(seed);
        }

        let time_keeper = TimeKeeper::new(0.8);

        input! {
            N: usize,
            AB: [(isize, isize); N]
        }

        let mut order = (1..N).collect::<Vec<usize>>();
        let mut used = HashSet::new();
        used.insert(order.clone());
        let mut best_order = order.clone();
        let (mut best_score, _) = play(&AB, &order);
        let mut iterations = 0;
        let mut temp = 2.0;
        let cool_rate = 0.9;

        'outer: while !time_keeper.isTimeOver() {
            iterations += 1;
            let mut i;
            let mut j;
            loop {
                if time_keeper.isTimeOver() {
                    break 'outer;
                }
                i = rnd::gen_range(0, N - 1);
                j = rnd::gen_range(0, N - 1);
                if i == j {
                    continue;
                }
                order.swap(i, j);
                if used.contains(&order) {
                    order.swap(i, j);
                } else {
                    used.insert(order.clone());
                    break;
                }
            }
            let (score, _) = play(&AB, &order);
            if score > best_score
                || rnd::gen_float() < ((score as f64 - best_score as f64) / temp).exp()
            {
                best_score = score;
                best_order = order.clone();
            } else {
                order.swap(i, j);
            }
            temp *= cool_rate;
        }

        let (score, idx) = play(&AB, &best_order);
        let mut operations = vec![];
        for i in 0..=idx {
            operations.push((0, best_order[i]));
        }
        output(&operations);
        eprintln!("score: {}", score);
        eprintln!("Iterations: {}", iterations);

        #[allow(unused_mut, unused_assignments)]
        let mut elapsed_time = start.elapsed().as_micros() as f64 * 1e-6;
        #[cfg(feature = "local")]
        {
            eprintln!("Local Mode");
            elapsed_time *= 0.55;
        }
        eprintln!("Elapsed: {}", (elapsed_time * 1000.0) as usize);
    }
}

fn play(AB: &[(isize, isize)], order: &[usize]) -> (usize, usize) {
    let N = AB.len();
    let mut now = AB[0];
    let mut best_score = calc_score(now);
    let mut best_idx = 0;
    for i in 0..N - 1 {
        let ret = op(now, AB[order[i]]);
        now = ret;
        let score = calc_score(now);
        if score > best_score {
            best_score = score;
            best_idx = i;
        }
    }
    (best_score, best_idx)
}

fn op(u: (isize, isize), v: (isize, isize)) -> (isize, isize) {
    ((u.0 + v.0) / 2, (u.1 + v.1) / 2)
}

fn calc_score(ab: (isize, isize)) -> usize {
    let v1 = (ab.0 - TARGET).abs();
    let v2 = (ab.1 - TARGET).abs();
    let mx = max!(v1, v2) as f64;
    let score = 2e6 - 1e5 * (mx + 1.0).log10();
    score.floor() as usize
}

fn output(operations: &[(usize, usize)]) {
    println!("{}", operations.len());
    for &(a, b) in operations.iter() {
        println!("{} {}", a + 1, b + 1);
    }
}

#[macro_export]
macro_rules! max {
    ($x: expr) => ($x);
    ($x: expr, $( $y: expr ),+) => {
        std::cmp::max($x, max!($( $y ),+))
    }
}
#[macro_export]
macro_rules! min {
    ($x: expr) => ($x);
    ($x: expr, $( $y: expr ),+) => {
        std::cmp::min($x, min!($( $y ),+))
    }
}

fn main() {
    std::thread::Builder::new()
        .stack_size(128 * 1024 * 1024)
        .spawn(|| Solver::default().solve())
        .unwrap()
        .join()
        .unwrap();
}

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

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

#[macro_export]
macro_rules! input {
    () => {};
    (mut $var:ident: $t:tt, $($rest:tt)*) => {
        let mut $var = __input_inner!($t);
        input!($($rest)*)
    };
    ($var:ident: $t:tt, $($rest:tt)*) => {
        let $var = __input_inner!($t);
        input!($($rest)*)
    };
    (mut $var:ident: $t:tt) => {
        let mut $var = __input_inner!($t);
    };
    ($var:ident: $t:tt) => {
        let $var = __input_inner!($t);
    };
}

#[macro_export]
macro_rules! __input_inner {
    (($($t:tt),*)) => {
        ($(__input_inner!($t)),*)
    };
    ([$t:tt; $n:expr]) => {
        (0..$n).map(|_| __input_inner!($t)).collect::<Vec<_>>()
    };
    ([$t:tt]) => {{
        let n = __input_inner!(usize);
        (0..n).map(|_| __input_inner!($t)).collect::<Vec<_>>()
    }};
    (chars) => {
        __input_inner!(String).chars().collect::<Vec<_>>()
    };
    (bytes) => {
        __input_inner!(String).into_bytes()
    };
    (usize1) => {
        __input_inner!(usize) - 1
    };
    ($t:ty) => {
        $crate::read::<$t>()
    };
}

#[macro_export]
macro_rules! println {
    () => {
        $crate::write(|w| {
            use std::io::Write;
            std::writeln!(w).unwrap()
        })
    };
    ($($arg:tt)*) => {
        $crate::write(|w| {
            use std::io::Write;
            std::writeln!(w, $($arg)*).unwrap()
        })
    };
}

#[macro_export]
macro_rules! print {
    ($($arg:tt)*) => {
        $crate::write(|w| {
            use std::io::Write;
            std::write!(w, $($arg)*).unwrap()
        })
    };
}

#[macro_export]
macro_rules! flush {
    () => {
        $crate::write(|w| {
            use std::io::Write;
            w.flush().unwrap()
        })
    };
}

pub fn read<T>() -> T
where
    T: std::str::FromStr,
    T::Err: std::fmt::Debug,
{
    use std::cell::RefCell;
    use std::io::*;

    thread_local! {
        pub static STDIN: RefCell<StdinLock<'static>> = RefCell::new(stdin().lock());
    }

    STDIN.with(|r| {
        let mut r = r.borrow_mut();
        let mut s = vec![];
        loop {
            let buf = r.fill_buf().unwrap();
            if buf.is_empty() {
                break;
            }
            if let Some(i) = buf.iter().position(u8::is_ascii_whitespace) {
                s.extend_from_slice(&buf[..i]);
                r.consume(i + 1);
                if !s.is_empty() {
                    break;
                }
            } else {
                s.extend_from_slice(buf);
                let n = buf.len();
                r.consume(n);
            }
        }
        std::str::from_utf8(&s).unwrap().parse().unwrap()
    })
}

pub fn write<F>(f: F)
where
    F: FnOnce(&mut std::io::BufWriter<std::io::StdoutLock>),
{
    use std::cell::RefCell;
    use std::io::*;

    thread_local! {
        pub static STDOUT: RefCell<BufWriter<StdoutLock<'static>>> =
            RefCell::new(BufWriter::new(stdout().lock()));
    }

    STDOUT.with(|w| f(&mut w.borrow_mut()))
}

// trait Bound<T> {
//     fn lower_bound(&self, x: &T) -> usize;
//     fn upper_bound(&self, x: &T) -> usize;
// }

// impl<T: PartialOrd> Bound<T> for [T] {
//     fn lower_bound(&self, x: &T) -> usize {
//         let (mut low, mut high) = (0, self.len());
//         while low + 1 < high {
//             let mid = (low + high) / 2;
//             if self[mid] < *x {
//                 low = mid;
//             } else {
//                 high = mid;
//             }
//         }
//         if self[low] < *x {
//             low + 1
//         } else {
//             low
//         }
//     }

//     fn upper_bound(&self, x: &T) -> usize {
//         let (mut low, mut high) = (0, self.len());
//         while low + 1 < high {
//             let mid = (low + high) / 2;
//             if self[mid] <= *x {
//                 low = mid;
//             } else {
//                 high = mid;
//             }
//         }
//         if self[low] <= *x {
//             low + 1
//         } else {
//             low
//         }
//     }
// }

mod rnd {
    static mut S: usize = 0;
    static MAX: usize = 1e9 as usize;

    #[inline]
    pub fn init(seed: usize) {
        unsafe {
            if seed == 0 {
                let t = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_secs() as usize;
                S = t
            } else {
                S = seed;
            }
        }
    }
    #[inline]
    pub fn gen() -> usize {
        unsafe {
            if S == 0 {
                init(0);
            }
            S ^= S << 7;
            S ^= S >> 9;
            S
        }
    }
    #[inline]
    pub fn gen_range(a: usize, b: usize) -> usize {
        gen() % (b - a) + a
    }
    #[inline]
    pub fn gen_bool() -> bool {
        gen() & 1 == 1
    }
    #[inline]
    pub fn gen_range_isize(a: usize) -> isize {
        let mut x = (gen() % a) as isize;
        if gen_bool() {
            x *= -1;
        }
        x
    }
    #[inline]
    pub fn gen_range_neg_wrapping(a: usize) -> usize {
        let mut x = gen() % a;
        if gen_bool() {
            x = x.wrapping_neg();
        }
        x
    }
    #[inline]
    pub fn gen_float() -> f64 {
        ((gen() % MAX) as f64) / MAX as f64
    }
}

#[derive(Debug, Clone)]
struct TimeKeeper {
    start_time: std::time::Instant,
    time_threshold: f64,
}

impl TimeKeeper {
    fn new(time_threshold: f64) -> Self {
        TimeKeeper {
            start_time: std::time::Instant::now(),
            time_threshold,
        }
    }
    #[inline]
    fn isTimeOver(&self) -> bool {
        let elapsed_time = self.start_time.elapsed().as_nanos() as f64 * 1e-9;
        #[cfg(feature = "local")]
        {
            elapsed_time * 0.55 >= self.time_threshold
        }
        #[cfg(not(feature = "local"))]
        {
            elapsed_time >= self.time_threshold
        }
    }
    #[inline]
    fn get_time(&self) -> f64 {
        let elapsed_time = self.start_time.elapsed().as_nanos() as f64 * 1e-9;
        #[cfg(feature = "local")]
        {
            elapsed_time * 0.55
        }
        #[cfg(not(feature = "local"))]
        {
            elapsed_time
        }
    }
}
0