#[allow(unused_macros)] macro_rules! debug { ($($a:expr),* $(,)*) => { #[cfg(debug_assertions)] eprintln!(concat!($("| ", stringify!($a), "={:?} "),*, "|"), $(&$a),*); }; } fn main() { let Input { n, s } = Input::read(std::io::stdin().lock()); let mut dp: Vec> = vec![vec![(0, 0, 0); n + 1]; n + 1]; // dp[i][j].0: s[i..j] の末尾に on を付け足したときの pon 数 // dp[i][j].1: s[i..j] の末尾に n を付け足したときの pon 数 // dp[i][j].2: s[i..j] の pon 数 // 0 <= i <= j <= n を満たす (i, j) を走査 for j in 0..=n { for i in (0..=j).rev() { // s[i..j] を見るとき, // 0 <= k <= l < j を満たす s[k..l] と // i < k <= l <= j を満たす s[k..l] は // 全て既に見ている if i < j { match s[j - 1] { 'p' => chmax(1, &mut dp[i][j].0), 'o' => chmax(dp[i][j - 1].0, &mut dp[i][j].1), 'n' => chmax(dp[i][j - 1].1, &mut dp[i][j].2), _ => unreachable!(), } } for k in 0..i { chmax(dp[k][i].0 + dp[i][j].2, &mut dp[k][j].0); chmax(dp[k][i].1 + dp[i][j].2, &mut dp[k][j].1); chmax(dp[k][i].2 + dp[i][j].2, &mut dp[k][j].2); } } } /* for row in &dp { eprintln!("{}", row.iter().map(|x| format!("{:?}", x)).collect::>().join(" ")); } */ let mut ans = None; for i in 0..n { let former = dp[0][i].2; let latter = dp[i][n].2; if former > 0 && latter > 0 { ans = ans.max(Some(former + latter - 2)); } } println!("{}", ans.unwrap_or(-1)); } fn chmax(x: T, y: &mut T) { if &x > y { *y = x; } } struct Input { n: usize, s: Vec, } impl Input { fn read(mut input: T) -> Input { let n = { let mut buffer = String::new(); input.read_line(&mut buffer).unwrap(); match &split(&buffer).unwrap()[..] { [n] => n.parse().unwrap(), _ => panic!("input format error: N"), } }; let s = { let mut buffer = String::new(); input.read_line(&mut buffer).unwrap(); let split = split(&buffer).unwrap(); assert_eq!(split.len(), 1, "input format error: S"); split[0].chars().collect::>() }; assert!(matches!(n, 1..=500)); assert_eq!(n, s.len()); Input { n: n, s: s } } } fn split(s: &str) -> Option> { enum State { Word(usize), Space, End, } let mut state = State::Word(0); let mut ret = Vec::new(); for (i, c) in s.char_indices() { let prev = match state { State::End => return None, State::Word(i) => i, State::Space => { state = State::Word(i); i } }; if c == ' ' || c == '\n' { ret.push(&s[prev..i]); state = if c == ' ' { State::Space } else { State::End }; } } matches!(state, State::End).then(|| ret) } #[test] fn test_split() { assert_eq!(split("word\n"), Some(vec!["word"])); assert_eq!( split("many words separated\n"), Some(vec!["many", "words", "separated"]) ); assert_eq!( split(" extra spaces \n"), Some(vec!["", "extra", "", "spaces", ""]) ); assert_eq!(split("no line feed"), None); assert_eq!(split("extra characters\nafter line feed"), None); }