use std::cell::RefCell;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::fmt::Debug;
use std::io::{BufRead, Write};
use std::str::FromStr;
thread_local! {
static READ_ITEM_BUF: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) }
}
fn fill_until_whitespace(input: &mut impl BufRead, buf: &mut Vec<u8>) {
buf.clear();
loop {
let mut chunk = input
.fill_buf()
.expect("EOF or error before encountering whitespace");
let skipped_white = if buf.is_empty() {
let before_skipped = chunk.len();
chunk = chunk.trim_ascii_start();
before_skipped - chunk.len()
} else {
0
};
let white_pos = chunk
.iter()
.position(|b| (*b as char).is_ascii_whitespace());
let found = white_pos.is_some();
let white_pos = white_pos.unwrap_or(chunk.len());
buf.extend_from_slice(&chunk[..white_pos]);
input.consume(skipped_white + white_pos);
if found {
return;
}
}
}
fn read_item<T>(input: &mut impl BufRead) -> T
where
T: FromStr,
T::Err: Debug,
{
READ_ITEM_BUF.with_borrow_mut(|buf| {
fill_until_whitespace(input, buf);
T::from_str(std::str::from_utf8(buf).expect("not a utf-8 string")).expect("failed to parse")
})
}
struct Vertex {
distance: u32,
edges: Vec<Edge>,
}
struct Edge {
target: usize,
cost: u32,
}
fn parse_graph(input: &mut impl BufRead) -> Vec<Vertex> {
let num_cities: usize = read_item(input);
let num_connections: usize = read_item(input);
let mut graph: Vec<Vertex> = std::iter::repeat_with(|| Vertex {
distance: u32::MAX,
edges: Vec::new(),
})
.take(num_cities)
.collect();
for _ in 0..num_connections {
let a: usize = read_item(input);
let b: usize = read_item(input);
let cost: u32 = read_item(input);
graph[a - 1].edges.push(Edge {
target: b - 1,
cost,
});
graph[b - 1].edges.push(Edge {
target: a - 1,
cost,
});
}
graph
}
fn send_bits(num: u32, bits: u32, output: &mut impl Write) {
debug_assert!(num < (1 << bits));
// eprintln!(" sending {} bits, {}", bits, num);
for shift in 0..bits {
let b = (num >> shift) & 1;
writeln!(output, "+ {}", b).unwrap();
}
output.flush().unwrap();
}
fn receive_bits(bits: u32, input: &mut impl BufRead, output: &mut impl Write) -> u32 {
let mut num = 0;
// eprintln!(" receiving {} bits", bits);
for shift in 0..bits {
writeln!(output, "?").unwrap();
output.flush().unwrap();
let b: char = read_item(input);
let b = if b == '1' { 1 } else { 0 };
num |= b << shift;
}
num
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)]
struct NextVertex {
distance: Reverse<u32>,
vertex: usize,
}
fn negotiate_next_vertex(
next_vertex: NextVertex,
baseline_cost: u32,
dominant: bool,
input: &mut impl BufRead,
output: &mut impl Write,
) -> NextVertex {
let NextVertex { distance, vertex } = next_vertex;
let distance = distance.0;
send_bits(distance - baseline_cost, 9, output);
let remote_distance = receive_bits(9, input, output) + baseline_cost;
if (distance, !dominant) < (remote_distance, dominant) {
// Our distance is lower or we won the tie break
send_bits(vertex as u32, 11, output);
NextVertex {
distance: Reverse(distance),
vertex,
}
} else {
let remote_vertex = receive_bits(11, input, output);
NextVertex {
distance: Reverse(remote_distance),
vertex: remote_vertex as usize,
}
}
}
fn main() {
let mut stdin = std::io::stdin().lock();
let mode: String = read_item(&mut stdin);
// eprintln!("mode: {}", mode);
assert!(mode == "Algosia" || mode == "Bajtek");
let is_algosia = mode == "Algosia";
let mut graph = parse_graph(&mut stdin);
let mut queue = BinaryHeap::new();
queue.push(NextVertex {
distance: Reverse(0),
vertex: 0,
});
let mut stdout = std::io::stdout().lock();
let mut countdown = graph.len();
let mut baseline_cost = 0;
while countdown > 0 {
let proposed_next_vertex = match queue.pop() {
Some(nv) => {
if graph[nv.vertex].distance <= nv.distance.0 {
// eprintln!("{mode}({countdown}): discarding {}", nv.vertex);
continue;
}
nv
}
None => NextVertex {
distance: Reverse(baseline_cost + (1 << 9) - 1),
vertex: usize::MAX,
},
};
// eprintln!(
// "{mode}({countdown}): negotiating {:?}",
// proposed_next_vertex
// );
let next_vertex = negotiate_next_vertex(
proposed_next_vertex,
baseline_cost,
is_algosia,
&mut stdin,
&mut stdout,
);
let won_negotiation = next_vertex == proposed_next_vertex;
// eprintln!(
// "{mode}({countdown}): negotiation result: {:?} (won: {})",
// next_vertex, won_negotiation,
// );
if !won_negotiation && proposed_next_vertex.vertex != usize::MAX {
queue.push(proposed_next_vertex);
}
debug_assert_eq!(graph[next_vertex.vertex].distance, u32::MAX);
graph[next_vertex.vertex].distance = next_vertex.distance.0;
for edge in graph[next_vertex.vertex].edges.iter() {
queue.push(NextVertex {
distance: Reverse(next_vertex.distance.0 + edge.cost),
vertex: edge.target,
});
}
baseline_cost = next_vertex.distance.0;
countdown -= 1;
}
if is_algosia {
write!(stdout, "!").unwrap();
for vertex in graph.iter() {
write!(stdout, " {}", vertex.distance).unwrap();
}
writeln!(stdout).unwrap();
stdout.flush().unwrap();
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | use std::cell::RefCell; use std::cmp::Reverse; use std::collections::BinaryHeap; use std::fmt::Debug; use std::io::{BufRead, Write}; use std::str::FromStr; thread_local! { static READ_ITEM_BUF: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) } } fn fill_until_whitespace(input: &mut impl BufRead, buf: &mut Vec<u8>) { buf.clear(); loop { let mut chunk = input .fill_buf() .expect("EOF or error before encountering whitespace"); let skipped_white = if buf.is_empty() { let before_skipped = chunk.len(); chunk = chunk.trim_ascii_start(); before_skipped - chunk.len() } else { 0 }; let white_pos = chunk .iter() .position(|b| (*b as char).is_ascii_whitespace()); let found = white_pos.is_some(); let white_pos = white_pos.unwrap_or(chunk.len()); buf.extend_from_slice(&chunk[..white_pos]); input.consume(skipped_white + white_pos); if found { return; } } } fn read_item<T>(input: &mut impl BufRead) -> T where T: FromStr, T::Err: Debug, { READ_ITEM_BUF.with_borrow_mut(|buf| { fill_until_whitespace(input, buf); T::from_str(std::str::from_utf8(buf).expect("not a utf-8 string")).expect("failed to parse") }) } struct Vertex { distance: u32, edges: Vec<Edge>, } struct Edge { target: usize, cost: u32, } fn parse_graph(input: &mut impl BufRead) -> Vec<Vertex> { let num_cities: usize = read_item(input); let num_connections: usize = read_item(input); let mut graph: Vec<Vertex> = std::iter::repeat_with(|| Vertex { distance: u32::MAX, edges: Vec::new(), }) .take(num_cities) .collect(); for _ in 0..num_connections { let a: usize = read_item(input); let b: usize = read_item(input); let cost: u32 = read_item(input); graph[a - 1].edges.push(Edge { target: b - 1, cost, }); graph[b - 1].edges.push(Edge { target: a - 1, cost, }); } graph } fn send_bits(num: u32, bits: u32, output: &mut impl Write) { debug_assert!(num < (1 << bits)); // eprintln!(" sending {} bits, {}", bits, num); for shift in 0..bits { let b = (num >> shift) & 1; writeln!(output, "+ {}", b).unwrap(); } output.flush().unwrap(); } fn receive_bits(bits: u32, input: &mut impl BufRead, output: &mut impl Write) -> u32 { let mut num = 0; // eprintln!(" receiving {} bits", bits); for shift in 0..bits { writeln!(output, "?").unwrap(); output.flush().unwrap(); let b: char = read_item(input); let b = if b == '1' { 1 } else { 0 }; num |= b << shift; } num } #[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)] struct NextVertex { distance: Reverse<u32>, vertex: usize, } fn negotiate_next_vertex( next_vertex: NextVertex, baseline_cost: u32, dominant: bool, input: &mut impl BufRead, output: &mut impl Write, ) -> NextVertex { let NextVertex { distance, vertex } = next_vertex; let distance = distance.0; send_bits(distance - baseline_cost, 9, output); let remote_distance = receive_bits(9, input, output) + baseline_cost; if (distance, !dominant) < (remote_distance, dominant) { // Our distance is lower or we won the tie break send_bits(vertex as u32, 11, output); NextVertex { distance: Reverse(distance), vertex, } } else { let remote_vertex = receive_bits(11, input, output); NextVertex { distance: Reverse(remote_distance), vertex: remote_vertex as usize, } } } fn main() { let mut stdin = std::io::stdin().lock(); let mode: String = read_item(&mut stdin); // eprintln!("mode: {}", mode); assert!(mode == "Algosia" || mode == "Bajtek"); let is_algosia = mode == "Algosia"; let mut graph = parse_graph(&mut stdin); let mut queue = BinaryHeap::new(); queue.push(NextVertex { distance: Reverse(0), vertex: 0, }); let mut stdout = std::io::stdout().lock(); let mut countdown = graph.len(); let mut baseline_cost = 0; while countdown > 0 { let proposed_next_vertex = match queue.pop() { Some(nv) => { if graph[nv.vertex].distance <= nv.distance.0 { // eprintln!("{mode}({countdown}): discarding {}", nv.vertex); continue; } nv } None => NextVertex { distance: Reverse(baseline_cost + (1 << 9) - 1), vertex: usize::MAX, }, }; // eprintln!( // "{mode}({countdown}): negotiating {:?}", // proposed_next_vertex // ); let next_vertex = negotiate_next_vertex( proposed_next_vertex, baseline_cost, is_algosia, &mut stdin, &mut stdout, ); let won_negotiation = next_vertex == proposed_next_vertex; // eprintln!( // "{mode}({countdown}): negotiation result: {:?} (won: {})", // next_vertex, won_negotiation, // ); if !won_negotiation && proposed_next_vertex.vertex != usize::MAX { queue.push(proposed_next_vertex); } debug_assert_eq!(graph[next_vertex.vertex].distance, u32::MAX); graph[next_vertex.vertex].distance = next_vertex.distance.0; for edge in graph[next_vertex.vertex].edges.iter() { queue.push(NextVertex { distance: Reverse(next_vertex.distance.0 + edge.cost), vertex: edge.target, }); } baseline_cost = next_vertex.distance.0; countdown -= 1; } if is_algosia { write!(stdout, "!").unwrap(); for vertex in graph.iter() { write!(stdout, " {}", vertex.distance).unwrap(); } writeln!(stdout).unwrap(); stdout.flush().unwrap(); } } |
English