fn main() { let n: usize = read(); assert!(n % 2 == 0); let mut nums: Vec = read_vec(); for p in old_maid(&mut nums) { print!("{} ", p); } print!("\n"); } fn old_maid(nums: &mut[usize]) -> Vec { assert_eq!(nums.len() % 2, 0); let n = nums.len(); let mut rev = vec![usize::MAX; n]; for p in nums.iter_mut() { *p = *p - 1; } for (i, p) in nums.iter().enumerate() { rev[*p] = i; } let mut ret = Vec::new(); let mut min = 0; for _ in 0..n / 2 { while rev[min] >= nums.len() - 1 { min += 1; assert!(min < nums.len()); } let mut n_idx = rev[min] + 1; while nums[n_idx] >= rev.len() || rev[nums[n_idx]] >= nums.len() { n_idx += 1; assert!(n_idx < nums.len()); } let next = nums[n_idx]; rev[min] = usize::MAX; rev[next] = usize::MAX; while rev.last().is_some_and(|i| *i == usize::MAX) { rev.pop(); } ret.push(min + 1); ret.push(next + 1); } ret } fn read() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn read_vec() -> Vec { read::() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect() } fn read_vec2(n: u32) -> Vec> { (0..n).map(|_| read_vec()).collect() } #[cfg(test)] mod test { use super::old_maid; #[test] fn test() { assert_eq!(old_maid(&mut vec![3, 2, 4, 1]), vec![2, 4, 3, 1]); assert_eq!(old_maid(&mut vec![4,6,3,2,8,5,7,1]), vec![2,8,3,5,4,6,7,1]); } }