/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 328.0 KiB
#2 Accepted 1ms 396.0 KiB
#3 Accepted 36ms 464.0 KiB
#4 Accepted 148ms 464.0 KiB
#5 Time Exceeded ≥1045ms ≥476.0 KiB
#6 Time Exceeded ≥1020ms ≥500.0 KiB

Code

use std::io::{self, BufRead};

fn main() {
    let stdin = io::stdin();
    let mut input = stdin.lock().lines();

    let t: usize = input.next().unwrap().unwrap().trim().parse().unwrap();  // Read number of test cases
    for _ in 0..t {
        let mut first_line = input.next().unwrap().unwrap();
        let mut first_line_split = first_line.split_whitespace();
        
        let n: usize = first_line_split.next().unwrap().parse().unwrap();  // Read n
        let k: usize = first_line_split.next().unwrap().parse().unwrap();  // Read k

        let s: String = input.next().unwrap().unwrap();  // Read the string s
        let mut p = s.clone();  // Copy the string s to p
        let mut ans: i64 = 0;
        let mut temp = k;
        let mut cnt_a: i64 = s.chars().filter(|&c| c == 'A').count() as i64;

        // Track occurrences of 'A' counts
        let mut occ_a = Vec::new();

        // Handle the '?' characters from the back and decrement temp accordingly
        for i in (0..n).rev() {
            if temp == 0 {
                break;
            }
            if s.chars().nth(i).unwrap() == 'A' {
                cnt_a -= 1;
            }
            if s.chars().nth(i).unwrap() == '?' {
                p.replace_range(i..i+1, "B");
                temp -= 1;
                occ_a.push(cnt_a);
            }
        }

        // Count 'B's in modified string p
        let mut cnt_b: i64 = p.chars().filter(|&c| c == 'B').count() as i64;
        let mut temp_b = cnt_b;

        // Calculate the initial answer
        for (i, ch) in p.chars().enumerate() {
            if ch == 'B' {
                temp_b -= 1;
            }
            if s.chars().nth(i).unwrap() == 'A' {
                ans += temp_b;
            }
        }

        let mut answer = ans;
        let mut pos: i64 = occ_a.len() as i64 - 1;
        let mut new_a = 0;

        // Update the answer by adjusting for '?' characters
        for (i, ch) in s.chars().enumerate() {
            if cnt_b == 0 || pos < 0 {
                break;
            }
            if ch == 'B' {
                cnt_b -= 1;
            }
            if ch == '?' {
                ans -= occ_a[pos as usize];
                cnt_b -= 1;
                pos -= 1;
                ans += cnt_b;
                ans -= new_a;
                new_a += 1;
            }
            answer = answer.max(ans);
        }

        println!("{}", answer);
    }
}

Information

Submit By
Type
Submission
Problem
P1110 Subsequence of AB
Language
Rust 2021 (Rust 1.75.0)
Submit At
2024-10-21 09:55:53
Judged At
2024-11-11 02:36:15
Judged By
Score
7
Total Time
≥1045ms
Peak Memory
≥500.0 KiB