<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

302. BHTML 1.0
Time limit per test: 0.25 second(s)
Memory limit: 65536 kilobytes
input: standard
output: standard



The hypertext markup language BHTML 1.0 has only two paired tags. They are UP /UP and DOWN /DOWN. The UP /UP tag capitalizes all letters inside its body (between an open tag and a close one), and DOWN /DOWN makes all inside the body letters lowercase. You are given the text consisting of latin letters and tags. Your task is to write the text right as it will be shown in the Bernet Explorer browser window. Tags in the text are arranged correctly, i.e. they form correct bracket sequence. If a letter lays inside several tags, its case is defined by the most inner tag.

Input
The input contains the string S with the text. The length of the string is a natural number not exceeding 1000. Tags are always written in uppercase.

Output
Write to the output text after the processing.

Example(s)
sample input
sample output
Thi<UP>sIs<DOWN>EaSY</DOWN>Pr<UP>O</UP>ble</UP>m 
ThiSISeasyPROBLEm

<|response|>
1. Abridged Problem Statement  
You are given a string S (|S| ≤ 1000) that contains only Latin letters and correctly nested tags `<UP>...</UP>` and `<DOWN>...</DOWN>`.  
- `<UP>…</UP>` makes all letters in its body uppercase.  
- `<DOWN>…</DOWN>` makes all letters in its body lowercase.  
When tags nest, the innermost tag’s rule takes effect.  
Output the rendered text with all tags removed.

2. Key Observations  
- Tags form a correct bracket sequence, so every opening tag has a matching closing tag.  
- We can process S in one left-to-right scan, maintaining a stack of active modes (`UP` or `DOWN`).  
- On seeing `<UP>` or `<DOWN>`, push the corresponding mode. On seeing `</UP>` or `</DOWN>`, pop the mode.  
- For each regular letter, if the stack is nonempty, apply the top mode; otherwise leave it unchanged.  
- Checking for tags and character processing both take O(1) per step, so overall O(n) time and O(n) extra space for the stack and output.

3. Full Solution Approach  
1. Initialize an empty stack `modeStack` and an output buffer `result`.  
2. Scan the input string `S` with an index `i` from 0 to `S.size()-1`.  
   - If `S` starting at `i` matches `<UP>`, push `UP` onto `modeStack`, advance `i` by 4.  
   - Else if it matches `</UP>`, pop `modeStack`, advance `i` by 5.  
   - Else if it matches `<DOWN>`, push `DOWN`, advance `i` by 6.  
   - Else if it matches `</DOWN>`, pop `modeStack`, advance `i` by 7.  
   - Otherwise `S[i]` is a normal letter:  
     • If `modeStack` is empty, append `S[i]` as is.  
     • If top is `UP`, append `toupper(S[i])`.  
     • If top is `DOWN`, append `tolower(S[i])`.  
     Then advance `i` by 1.  
3. After the loop, `result` holds the final text. Print it.

4. C++ Implementation with Detailed Comments  
```cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    string S;
    // The input string has no spaces: only letters and tags.
    cin >> S;

    int n = S.size();
    vector<int> modeStack;  
    // We'll encode UP as +1, DOWN as -1.

    string result;
    result.reserve(n);

    int i = 0;
    while (i < n) {
        // Check for "<UP>"
        if (i + 4 <= n && S.compare(i, 4, "<UP>") == 0) {
            modeStack.push_back(+1);
            i += 4;
        }
        // Check for "</UP>"
        else if (i + 5 <= n && S.compare(i, 5, "</UP>") == 0) {
            if (!modeStack.empty()) modeStack.pop_back();
            i += 5;
        }
        // Check for "<DOWN>"
        else if (i + 6 <= n && S.compare(i, 6, "<DOWN>") == 0) {
            modeStack.push_back(-1);
            i += 6;
        }
        // Check for "</DOWN>"
        else if (i + 7 <= n && S.compare(i, 7, "</DOWN>") == 0) {
            if (!modeStack.empty()) modeStack.pop_back();
            i += 7;
        }
        else {
            // Normal letter
            char c = S[i];
            if (modeStack.empty()) {
                result.push_back(c);
            } else if (modeStack.back() == +1) {
                // Convert to uppercase
                result.push_back(static_cast<char>(toupper(static_cast<unsigned char>(c))));
            } else { // modeStack.back() == -1
                // Convert to lowercase
                result.push_back(static_cast<char>(tolower(static_cast<unsigned char>(c))));
            }
            i++;
        }
    }

    // Output the rendered text without any tags
    cout << result << "\n";
    return 0;
}
```

5. Python Implementation with Detailed Comments  
```python
import sys

def render_bhtml(s):
    """
    Render the BHTML string s according to <UP> and <DOWN> tags.
    Returns the final text with all tags removed.
    """
    i = 0
    n = len(s)
    mode_stack = []   # will store "UP" or "DOWN"
    output = []

    while i < n:
        # Detect opening <UP>
        if s.startswith("<UP>", i):
            mode_stack.append("UP")
            i += 4
        # Detect closing </UP>
        elif s.startswith("</UP>", i):
            mode_stack.pop()
            i += 5
        # Detect opening <DOWN>
        elif s.startswith("<DOWN>", i):
            mode_stack.append("DOWN")
            i += 6
        # Detect closing </DOWN>
        elif s.startswith("</DOWN>", i):
            mode_stack.pop()
            i += 7
        else:
            # Regular character
            c = s[i]
            if not mode_stack:
                output.append(c)
            elif mode_stack[-1] == "UP":
                output.append(c.upper())
            else:  # mode_stack[-1] == "DOWN"
                output.append(c.lower())
            i += 1

    return "".join(output)

if __name__ == "__main__":
    data = sys.stdin.read().strip()
    # Process and print the rendered text
    print(render_bhtml(data))
```

Explanation of the main steps:  
- We never store tags in the output buffer.  
- We use a stack to remember which case-conversion is active.  
- On each ordinary character, we apply `str.upper()` or `str.lower()` (or leave it) based on the top of the stack.  
- Since each character and each tag is scanned exactly once, overall complexity is O(n).