Submission

Status:
[PPPPPPPPPP][PPPPT]

Score: 10

User: jxkrpn

Problemset: ขนมของเซ้น143 (v.ยาก)

Language: c

Time: 0.233 second

Submitted On: 2024-10-02 12:48:23

#include <stdio.h>

long long int my_abs(long long int x) {
    return x < 0 ? -x : x;  // Custom absolute value function
}

int main() {
    long long int n, total_sum, half_sum, group_a_sum, min_diff;

    // Input the number of snack bags
    scanf("%lld", &n);

    // Calculate the total sum of all numbers from 1 to n
    total_sum = (n * (n + 1)) / 2;

    // Find the sum closest to half the total sum
    half_sum = total_sum / 2;

    // We can derive x directly using integer arithmetic
    long long int x = 0;
    
    // Find x such that (x * (x + 1)) / 2 is close to half_sum
    while ((x * (x + 1)) / 2 < half_sum) {
        x++;
    }
    
    // Calculate the sum for group A using x
    group_a_sum = (x * (x + 1)) / 2;

    // Calculate the minimal difference by checking the difference with both x and x-1
    long long int group_b_sum = total_sum - group_a_sum;
    min_diff = my_abs(group_a_sum - group_b_sum);

    // Also check the previous number (x - 1) to see if we get a better result
    if (x > 1) {
        long long int group_a_sum_prev = ((x - 1) * x) / 2;
        long long int group_b_sum_prev = total_sum - group_a_sum_prev;
        long long int diff_prev = my_abs(group_a_sum_prev - group_b_sum_prev);

        // Output the smallest difference
        if (diff_prev < min_diff) {
            min_diff = diff_prev;
        }
    }

    printf("%lld\n", min_diff);

    return 0;
}