Preparing for the Blue Bridge Cup Day2: Branching Structures

image.png

Today, I followed the plan and worked on Luogu's 【Introduction 2: Branching Structures】. I thought it would go smoothly after yesterday's foundation, but halfway through, I found that with too many nested conditional judgments, the logic easily became messy. Plus, some problems disguised as branching structures were actually testing loop simulation, which was indeed a bit brain-draining. I decided to strategically abandon the remaining few long problems and tackle them tomorrow.

Let me briefly organize a few syntax blind spots and logical pitfalls that tripped me up today.

1. Backfired by My Own One-Liner Code (P5714 Obesity Problem)

To be lazy, I wanted to write multi-branch judgments in one line using the ternary operator.
The flawed code logic at the time was like this:
print(f'{'Underweight'if BMI<18.5 else ... str(BMI)+"\nOverweight"}')

It directly threw a syntax error. Upon careful investigation, I found two misconceptions.
First was quote conflict. Both the outer and inner layers used single quotes, causing Python to think the string ended prematurely.
Second was over-reliance on f-strings. I thought any variable must be wrapped in an outermost f"{}". Actually, the ternary operator itself evaluates to a result that can be directly placed into print. For branches that truly need variable concatenation, a separate f-string can be used.

The corrected approach is much clearer in logic and has no extra parentheses or quote wrapping:

m, h = map(float, input().split())
bmi = m / (h ** 2)

# Leveraging the natural exclusivity of multi-branching, subsequent conditions don't need to write bmi >= 18.5
print("Underweight" if bmi < 18.5 else "Normal" if bmi < 24 else f"{bmi:g}\nOverweight")

2. The Magical Formatting Symbol :g

In the code for the obesity problem above, there's another pitfall for Python users. The problem requires outputting with six significant digits and removing trailing zeros. This actually caters to C++ users' default output rules. Using str(bmi) for conversion makes it hard to control digits and trailing zeros.

After checking the documentation, I found there's also a :g usage in f-strings. g stands for general format; it can automatically strip useless trailing zeros and retain significant digits. Simply writing f"{bmi:g}" perfectly solves this output constraint.

3. Write Loops Honestly, Don't Force Formulas (P1424 Little Fish's Voyage)

This problem calculates the total swimming distance of a little fish across weeks. At first, I stubbornly tried to derive a mathematical formula, using division to calculate how many full weeks passed and then the remaining days. Due to too many edge cases, it became increasingly messy.

I changed my approach. For problems with small data volumes like this, the safest method is brute-force simulation, which computers excel at. Just write a for loop to simulate day by day: add 250 to the mileage as long as it's not Saturday or Sunday. After Sunday, reset the weekday directly back to 1.

x, n = map(int, input().split())
total_distance = 0

for _ in range(n):
    if x != 6 and x != 7:
        total_distance += 250
    x += 1
    if x == 8:
        x = 1

print(total_distance)

This is called trading computational power for brainpower. Sometimes algorithm problems don't require deliberately deriving profound mathematical formulas.

4. Sorting Three-Digit Numbers

The sorting problem can be solved using list.sort(), or you can use bubble sort logic. Also, I remember another pitfall: list.sort() has no return value; it modifies the original list directly. In one problem, I assigned it to a variable, causing incorrect results no matter how many times I ran it.

Bubble sort idea: Starting from the first element of the array, compare adjacent two numbers. If the left number is larger than the right one, swap them. Keep comparing and moving forward like this until reaching the last element; this process needs to run n-1 passes.

5. Trigonometric Functions

This problem requires using math.gcd(num1, num2) to find the greatest common divisor of two numbers because the problem asks for fraction reduction—finding the GCD of numerator and denominator. Also, using / results in a float with .0, so when reducing fractions by dividing numerator and denominator by the GCD, use // (integer division).

My brain is exhausted for today, so I'll stop here.