Created
April 11, 2023 12:51
-
-
Save attgm/d0033f5cca8919e9c4fd1ccbc4a782fc to your computer and use it in GitHub Desktop.
Alternative code to solve 'G - Longest Pat' in Educational DP Contest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use proconio::input; | |
use proconio::marker::Usize1; | |
use std::collections::VecDeque; | |
struct Node { | |
id: usize, | |
neighbors: Vec<usize>, | |
lengths: Vec<(usize, i64)> | |
} | |
impl Node { | |
fn add_path(&mut self, src: usize, length: i64) -> bool { | |
match self.lengths.iter().position(|(s, _)| *s == src) { | |
Some(pos) => { | |
let (_, l) = self.lengths[pos]; | |
if l < length { | |
self.lengths[pos] = (src, length); | |
return true; | |
} | |
}, | |
None => { | |
self.lengths.push((src, length)); | |
return true; | |
} | |
} | |
return false; | |
} | |
} | |
struct Message { | |
to: usize, | |
src: usize, | |
length: i64 | |
} | |
fn main(){ | |
input!( | |
n: usize, m: usize, | |
links: [(Usize1, Usize1); m] | |
); | |
let mut node_pool = Vec::with_capacity(n); | |
for i in 0..n { | |
node_pool.push(Node{id:i, neighbors:Vec::new(), lengths:Vec::new()}); | |
} | |
let mut message_queue: VecDeque<Message> = VecDeque::with_capacity(n); | |
for (src, dst) in &links { | |
node_pool[*src].neighbors.push(*dst); | |
message_queue.push_back(Message{to:*dst, src:*src, length:1}); | |
} | |
loop { | |
if let Some(message) = message_queue.pop_front() { | |
if message.src == message.to { println!{"Loop detection at {} length {}", message.src, message.length}; break;} | |
if node_pool[message.to].add_path(message.src, message.length) == true { | |
for neighbor in &(node_pool[message.to].neighbors) { | |
message_queue.push_back(Message{to:*neighbor, src:message.src, length:message.length + 1}); | |
} | |
} | |
} else { | |
break; | |
} | |
} | |
let mut results: Vec<(usize, usize, i64)> = Vec::with_capacity(n); | |
for node in &node_pool { | |
if let Some((src, length)) = node.lengths.iter().max_by(|a,b| a.1.cmp(&b.1)) { | |
results.push((*src + 1, node.id + 1, *length)); | |
} | |
} | |
println!("{:?}", results.iter().max_by(|a,b| a.2.cmp(&b.2)).unwrap()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment