Please subscribe to the official Codeforces channel in Telegram via the link https://t.me/codeforces_official. ×
FOCUS-ASTU-TECH-COMMUNITY-CONTEST-2 Editorial
Difference between en2 and en3, changed 6 character(s)
#[contest:682771]↵
↵
Hello everyone!↵
↵
Welcome to the editorial for our mashup contest. We selected a mix of implementation, strings, greedy, and two-pointer problems. The goal was to strengthen logical thinking and problem-solving skills without getting bogged down in complex data structures.↵
↵
Below you will find hints, tutorials, and solutions for each problem. We used spoiler tags to keep things clean. Try to solve it yourself before clicking!↵
↵
Happy coding!↵
↵
## Problem-A:[problem:682771A]↵
**Tags:** `Implementation` `Simulation`<br>↵
**Difficulty:** ⭐️ (Very Easy) ↵
↵
This is a classic implementation problem that tests your ability to observe patterns in a sequence.↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Goal↵
We are given `n` magnets, each represented as:↵
↵
- "10" → minus-plus  ↵
- "01" → plus-minus  ↵
↵
Magnets are placed one after another in a row.↵
↵
---↵
↵
#### Key Idea↵
- If two adjacent magnets are the same → they stick together → same group  ↵
- If they are different → they repel → new group  ↵
↵
---↵
↵
#### What is a Group?↵
A group is formed when magnets are connected (same pattern continues).↵
↵
So we need to count the number of times the pattern changes.↵
↵
---↵
↵
#### Input Constraints↵
$$1 \le n \le 100000$$  ↵
↵
</spoiler>↵
↵
<spoiler summary="Hint">↵
↵
- Start with 1 group (because at least one magnet exists).  ↵
- Compare each magnet with the previous one.  ↵
- Every time they are different, increase the group count.  ↵
↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
↵
Since the constraints are large (`n` up to 100000), we need an efficient approach. Fortunately, we only need a single pass through the magnets.↵
↵
### Step-by-Step Logic↵
1. Initialize: We start with `groups = 1` since at least one magnet forms a group.  ↵
2. Traverse: Loop through the magnets starting from the second one.  ↵
3. Compare: For each magnet, compare it with the previous one.  ↵
   if magnets[i] != magnets[i &mdash; 1]  ↵
4. Update: If they are different, increment `groups` by 1.  ↵
5. Result: After processing all magnets, `groups` is the answer.  ↵
↵
---↵
↵
### Why this works↵
Each time the pattern changes:↵
"10" → "01" OR "01" → "10"  ↵
a new group is formed.↵
↵
---↵
↵
### Example Walkthrough↵
↵
Input:↵
4  ↵
01  ↵
01  ↵
10  ↵
10  ↵
↵
Process:↵
Start → groups = 1  ↵
01 → 01 → same  ↵
01 → 10 → different → groups = 2  ↵
10 → 10 → same  ↵
↵
Final Answer = 2  ↵
↵
---↵
↵
### Common Mistake↵
Forgetting to initialize `groups = 1`.  ↵
If you start from 0, your answer will always be wrong.↵
↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
n = int(input())↵
↵
magnets = [input().strip() for _ in range(n)]↵
↵
groups = 1↵
↵
for i in range(1, n):↵
    if magnets[i] != magnets[i - 1]:↵
        groups += 1↵
↵
print(groups)↵
~~~~~↵
↵
### Optimized Version↵
↵
~~~~~↵
n = int(input())↵
↵
prev = input().strip()↵
groups = 1↵
↵
for _ in range(n - 1):↵
    curr = input().strip()↵
    if curr != prev:↵
        groups += 1↵
    prev = curr↵
↵
print(groups)↵
~~~~~↵
↵
### Complexity:↵
- Time: O(n)  ↵
- Space: O(n) (or O(1) optimized)↵
↵
</spoiler>↵
↵
## Problem-B:[problem:682771B]↵
**Tags:** `Implementation` `Strings`<br>↵
**Difficulty:** ⭐️ (Very Easy) ↵
↵
This is a very simple counting problem.↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Goal↵
We are given:↵
- Number of games `n`↵
- A string `s` of length `n`↵
↵
Each character represents the winner:↵
- 'A' → Anton wins  ↵
- 'D' → Danik wins  ↵
↵
---↵
↵
#### Task↵
- Count how many times Anton wins  ↵
- Count how many times Danik wins  ↵
↵
Then:↵
- If Anton > Danik → print "Anton"  ↵
- If Danik > Anton → print "Danik"  ↵
- If equal → print "Friendship"  ↵
↵
</spoiler>↵
↵
<spoiler summary="Hint">↵
↵
- Just count characters in the string  ↵
- You can use:↵
  - a loop  ↵
  - or built-in count()  ↵
↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
↵
This problem is straightforward.↵
↵
### Step-by-Step Logic↵
1. Read integer `n`  ↵
2. Read string `s`  ↵
3. Count:↵
   - number of 'A'↵
   - number of 'D'  ↵
4. Compare the counts:↵
   - If A > D → Anton wins  ↵
   - If D > A → Danik wins  ↵
   - Else → Friendship  ↵
↵
---↵
↵
### Example↵
↵
Input:↵
6  ↵
ADAAAA  ↵
↵
Count:↵
A = 5  ↵
D = 1  ↵
↵
Answer: Anton  ↵
↵
---↵
↵
### Why this works↵
We only need to compare frequencies of characters.↵
↵
---↵
↵
### Complexity↵
- Time: O(n)  ↵
- Space: O(1)  ↵
↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
n = int(input())↵
s = input().strip()↵
↵
anton = s.count('A')↵
danik = s.count('D')↵
↵
if anton > danik:↵
    print("Anton")↵
elif danik > anton:↵
    print("Danik")↵
else:↵
    print("Friendship")↵
~~~~~↵
↵
</spoiler>↵
↵
## Problem-C:[problem:682771C]↵
**Tags:** `Brute Force` `Implementation` `Strings` `Two Pointers`<br>↵
**Difficulty:** ⭐️⭐️ (Easy-Medium) ↵
↵
This is a clever implementation problem that requires careful observation and use of the two-pointer technique.↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Goal↵
We are given a binary string `s` of length `n`.↵
↵
We can perform exactly one operation:↵
- Choose a segment `[l, r]`↵
- Flip all bits in that segment:↵
  &mdash; '0' → '1'↵
  &mdash; '1' → '0'↵
↵
---↵
↵
#### Task↵
Determine if it is possible to make the string a palindrome after exactly one inversion.↵
↵
---↵
↵
#### Key Observation↵
A palindrome means:↵
s[i] == s[n &mdash; i &mdash; 1]↵
↵
So we only care about mismatched pairs.↵
↵
</spoiler>↵
↵
<spoiler summary="Hint 1">↵
↵
Use two pointers:↵
- l = 0↵
- r = n &mdash; 1↵
↵
Compare characters while moving inward.↵
↵
</spoiler>↵
↵
<spoiler summary="Hint 2">↵
↵
Count positions where:↵
s[l] != s[r]↵
↵
These are mismatches we must fix.↵
↵
</spoiler>↵
↵
<spoiler summary="Hint 3 (Important)">↵
↵
- If mismatches are continuous → one segment can fix them ✅  ↵
- If mismatches are separated → impossible ❌  ↵
↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
↵
### Step-by-Step Logic↵
↵
1. Use two pointers:↵
   l = 0, r = n &mdash; 1  ↵
↵
2. Move inward and store mismatch indices  ↵
↵
3. If no mismatches:↵
   Already palindrome → still possible (flip whole or middle)  ↵
↵
4. Otherwise:↵
   Let:↵
   L = first mismatch  ↵
   R = last mismatch  ↵
↵
5. Flip the segment covering mismatches and check if it becomes palindrome  ↵
↵
---↵
↵
### Why this works↵
Flipping one segment can only fix mismatches if they are inside one continuous range.↵
↵
---↵
↵
### Example↵
↵
Input:↵
10010  ↵
↵
Mismatches occur in a continuous segment → can fix → Yes  ↵
↵
---↵
↵
### Complexity↵
Time: O(n)  ↵
Space: O(1)  ↵
↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
def solve():↵
    t = int(input())↵
    ↵
    for _ in range(t):↵
        n = int(input())↵
        s = input().strip()↵
        ↵
        l, r = 0, n - 1↵
        ↵
        # 1. Skip matching pairs from the outside↵
        while l < r and s[l] == s[r]:↵
            l += 1↵
            r -= 1↵
            ↵
        # Already a palindrome↵
        if l >= r:↵
            print("Yes")↵
            continue↵
            ↵
        # 2. Skip all consecutive mismatched pairs↵
        while l < r and s[l] != s[r]:↵
            l += 1↵
            r -= 1↵
            ↵
        # 3. Remaining pairs must all match↵
        while l < r and s[l] == s[r]:↵
            l += 1↵
            r -= 1↵
            ↵
        # If we met/crossed in the middle, mismatches were contiguous → valid↵
        print("Yes" if l >= r else "No")↵
↵
if __name__ == "__main__":↵
    solve()↵
~~~~~↵
↵
</spoiler>↵
↵
## Problem-D:[problem:682771D]↵
**Tags:** `Greedy` `Sorting` `Two Pointers`<br>↵
**Difficulty:** ⭐️⭐️ (Easy-Medium) ↵
↵
This is a classic greedy optimization problem that combines sorting with a two-pointer traversal to maximize savings.↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Goal↵
We are given `n` products with prices and `k` discount vouchers.↵
Each voucher `b[j]` allows us to buy `b[j]` products, but we only pay for the `b[j] - 1` most expensive ones (the cheapest in the group is free).↵
↵
---↵
↵
#### Task↵
Minimize the total cost to buy all `n` products using the vouchers optimally.↵
↵
---↵
↵
#### Key Observation↵
To maximize savings, we want the **cheapest possible items to be free**.↵
By grouping expensive items together, the "free" item in each group will be as cheap as possible relative to that block, saving us the most money.↵
↵
</spoiler>↵
↵
<spoiler summary="Hint 1">↵
↵
Sort the prices in ascending order and the vouchers in ascending order.↵
↵
</spoiler>↵
↵
<spoiler summary="Hint 2">↵
↵
Process vouchers from smallest to largest, applying them to the most expensive remaining items (right end of the array).↵
↵
</spoiler>↵
↵
<spoiler summary="Hint 3 (Important)">↵
↵
Use a pointer `right` starting at `n-1`.↵
For each voucher `v`, the free item is at index `right - v + 1`.↵
Subtract it from the total cost and move `right` left by `v`.↵
↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
↵
### Step-by-Step Logic↵
↵
1. Sort prices `a` ascending, vouchers `b` ascending  ↵
2. Start with `total = sum(a)`  ↵
3. Initialize `right = n - 1` (most expensive item)  ↵
4. For each voucher `v` in `b`:↵
   - Check if enough items remain: `right - v + 1 >= 0`↵
   - The item at `a[right - v + 1]` is the cheapest in the current group → make it free↵
   - `total -= a[right - v + 1]`↵
   - `right -= v`↵
5. Print the minimized total cost  ↵
↵
---↵
↵
### Why this works↵
Sorting ensures we always pick the optimal group boundaries. Applying vouchers from the expensive end guarantees that the free item in each group is the smallest possible within that block, maximizing overall savings.↵
↵
---↵
↵
### Example↵
Input: `a = [2, 3, 7, 9, 18]`, `b = [1, 1, 3]`↵
- Voucher 1: covers `[18]` → free: 18↵
- Voucher 1: covers `[9]` → free: 9↵
- Voucher 3: covers `[2, 3, 7]` → free: 2↵
Total saved: 18 + 9 + 2 = 29 → Pay: 3 + 7 = 10↵
↵
---↵
↵
### Complexity↵
Time: O(n log n + k log k)  ↵
Space: O(1) extra  ↵
↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
def solve():↵
    t = int(input())↵
↵
    for _ in range(t):↵
        n, k = map(int, input().split())↵
        a = list(map(int, input().split()))↵
        b = list(map(int, input().split()))↵
↵
        a.sort()  # sort prices ascending↵
        b.sort()  # sort vouchers ascending↵
↵
        total = sum(a)↵
        right = n - 1  # pointer at most expensive item↵
↵
        for voucher in b:↵
            # check if group fits in remaining items↵
            if right - voucher + 1 < 0:↵
                break↵
            # cheapest item in current group becomes free↵
            total -= a[right - voucher + 1]↵
            right -= voucher  # move pointer left↵
↵
        print(total)↵
↵
if __name__ == "__main__":↵
    solve()↵
~~~~~↵
↵
</spoiler>↵
↵
## Problem-E:[problem:BrokenKeyboard]↵
**Tags:** `Brute Force` `Strings` `Two Pointers`<br>↵
**Difficulty:** ⭐️⭐️ (Easy-Medium) ↵
↵
This is a classic two pointers (grouping) problem where we process consecutive characters and use parity (odd/even length) to determine valid keys.↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Goal↵
We are given a string `s` formed after pressing keys on a keyboard.↵
↵
Each key behaves in one of two ways:↵
- Working → prints 1 character↵
- Broken → prints 2 characters↵
↵
---↵
↵
#### Task↵
Determine which characters are guaranteed to be from working keys.↵
↵
---↵
↵
#### Key Observation↵
- Working key → produces odd-length groups (1, 3, 5, …)↵
- Broken key → produces even-length groups (2, 4, …)↵
↵
If a character appears in any odd-length group, it must be working.↵
↵
</spoiler>↵
↵
<spoiler summary="Hint 1">↵
↵
Use two pointers `i` and `j` to group consecutive identical characters.↵
↵
</spoiler>↵
↵
<spoiler summary="Hint 2">↵
↵
For each group, compute its length using `j - i`.↵
↵
</spoiler>↵
↵
<spoiler summary="Hint 3 (Important)">↵
↵
If the group length is odd, mark that character as working.↵
↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
↵
### Step-by-Step Logic↵
↵
1. Read integer `t` (number of test cases).↵
2. For each string `s`:↵
   - Initialize empty set `good`.↵
   - Traverse using pointer `i`.↵
3. For each position:↵
   - Set `j = i`.↵
   - Move `j` forward while characters are the same.↵
   - Compute group length = `j - i`.↵
   - If length is odd, add character to `good`.↵
4. Move `i = j` and continue.↵
5. Output sorted characters in `good`.↵
↵
---↵
↵
### Why this works↵
Each key behaves consistently:↵
- Working → always contributes 1 character↵
- Broken → always contributes 2 characters↵
↵
Thus, only odd-length segments prove a key is working.↵
↵
---↵
↵
### Example↵
Input: `cbddbb`↵
↵
Groups:↵
- `c` → length 1↵
- `b` → length 1↵
- `dd` → length 2↵
- `bb` → length 2↵
↵
Output: `bc`↵
↵
---↵
↵
### Complexity↵
Time: O(n)  ↵
Space: O(1)↵
↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
def solve():↵
    t = int(input())↵
    ↵
    for _ in range(t):↵
        s = input().strip()↵
        good = set()↵
        i = 0↵
        n = len(s)↵
        ↵
        while i < n:↵
            j = i↵
            ↵
            while j < n and s[j] == s[i]:↵
                j += 1↵
            ↵
            if (j - i) % 2 == 1:↵
                good.add(s[i])↵
            ↵
            i = j↵
        ↵
        print(''.join(sorted(good)))↵
↵
if __name__ == "__main__":↵
    solve()↵
~~~~~↵
↵
</spoiler>↵
↵
## Problem-F:[problem:682771F]↵
**Tags:** `DP` `Sliding Window` `Two Pointers`<br>↵
**Difficulty:** ⭐️⭐️⭐️ (Medium) ↵
↵
This is a classic optimization problem that efficiently finds the longest valid subsegment using a sliding window approach.↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Goal↵
We are given a binary array `a` of length `n` and an integer `k`.↵
We can flip at most `k` zeros to ones.↵
↵
---↵
↵
#### Task↵
Maximize the length of the longest consecutive subsegment consisting only of ones after the flips.↵
Output the maximum length and the final modified array.↵
↵
---↵
↵
#### Key Observation↵
Finding the longest subsegment of ones with at most `k` flips is equivalent to finding the longest subarray that contains **at most `k` zeros**.↵
Flipping those zeros turns the entire window into ones.↵
↵
</spoiler>↵
↵
<spoiler summary="Hint 1">↵
↵
Use two pointers `left` and `right` to maintain a sliding window.↵
↵
</spoiler>↵
↵
<spoiler summary="Hint 2">↵
↵
Expand `right` to include elements. Keep a counter of zeros inside the current window.↵
↵
</spoiler>↵
↵
<spoiler summary="Hint 3 (Important)">↵
↵
If zeros exceed `k`, shrink the window from `left` until the constraint is satisfied.↵
Track the boundaries of the longest valid window found.↵
↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
↵
### Step-by-Step Logic↵
↵
1. Initialize `left = 0`, `zeros = 0`, and variables to store the best window (`best_len`, `best_l`, `best_r`)  ↵
2. Iterate `right` from `0` to `n-1`:↵
   - If `a[right]` is `0`, increment `zeros`↵
   - While `zeros > k`, shrink from left: decrement `zeros` if `a[left]` is `0`, then increment `left`↵
   - If current window length > `best_len`, update best boundaries↵
3. After scanning, flip all elements in `a[best_l...best_r]` to `1`↵
4. Print `best_len` and the modified array  ↵
↵
---↵
↵
### Why this works↵
The sliding window guarantees that every considered subarray satisfies the `≤ k` zeros constraint.↵
Since both pointers only move forward, we evaluate all optimal candidates in linear time.↵
The longest valid window directly corresponds to the maximum possible consecutive ones.↵
↵
---↵
↵
### Example↵
Input: `a = [1, 0, 0, 1, 1, 0, 1]`, `k = 1`  ↵
- Window expands until it contains 2 zeros → shrink left until valid  ↵
- Longest valid window found: indices `3..6` → `[1, 1, 0, 1]` (length 4, 1 zero)  ↵
- Flip zero at index 5 → array becomes `1 0 0 1 1 1 1`  ↵
↵
---↵
↵
### Complexity↵
Time: O(n)  ↵
Space: O(1) extra  ↵
↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
def solve():↵
    n, k = map(int, input().split())↵
    a = list(map(int, input().split()))↵
    ↵
    left = 0↵
    zeros = 0↵
    best_len = 0↵
    best_l = 0↵
    best_r = -1↵
    ↵
    for right in range(n):↵
        # expand window: count zeros↵
        if a[right] == 0:↵
            zeros += 1↵
        ↵
        # shrink window if zeros exceed k↵
        while zeros > k:↵
            if a[left] == 0:↵
                zeros -= 1↵
            left += 1↵
        ↵
        # update best window found so far↵
        if right - left + 1 > best_len:↵
            best_len = right - left + 1↵
            best_l = left↵
            best_r = right↵
    ↵
    # flip zeros in the best window to ones↵
    for i in range(best_l, best_r + 1):↵
        a[i] = 1↵
    ↵
    print(best_len)↵
    print(' '.join(map(str, a)))↵
↵
if __name__ == "__main__":↵
    solve()↵
~~~~~↵
↵
</spoiler>↵
↵

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en4 English gemechualemu 2026-04-06 14:39:48 21 Tiny change: ':[problem:BrokenKeyboard]\n**Tags:' -> ':[problem:682771E]\n**Tags:'
en3 English gemechualemu 2026-04-06 12:05:10 6 (published)
en2 English gemechualemu 2026-04-06 12:04:45 39386
en1 English gemechualemu 2026-04-02 08:46:36 22800 Initial revision (saved to drafts)