Olympiad in Informatics

[Fortuna OJ] Running Laps — Solution

Main Idea

So godlike.

The idea behind this problem is really clever. The answer is easy to see; it is

\[ ans = \lfloor \sum_{i=1}^{n} \frac{L*C*speed[i]}{maxSpeed*C} \rfloor \]

Simplifying gives:

\[ ans = \lfloor \sum_{i=1}^{n} \frac{L*speed[i]}{maxSpeed} \rfloor \]

If we sum up the real numbers inside the brackets, we get some nasty errors that only ever show up on a computer, so we can consider taking the floor of each term separately and then summing. Here is a little trick: for two numbers,

\[ \lfloor a - b \rfloor = \begin{cases} \lfloor a \rfloor - \lfloor b \rfloor, a的小数部分 \leq b的小数部分 \\ \lfloor a \rfloor - \lfloor b \rfloor - 1, a的小数部分>b的小数部分 \end{cases} \]

When checking the fractional parts, we can turn the comparison between fractional parts into a comparison between remainders. The answer subtracts that 1 from the floor by default, and then we use a Fenwick tree to add back the floor terms that were wrongly subtracted.

Code

// FOJ2930.cpp
#include <bits/stdc++.h>
#define ll long long
#define lowbit(p) (p & -p)
using namespace std;
const ll MAX_N = 1e5 + 200;
ll n, l, c, spd[MAX_N], mxspd, f[MAX_N], tree[1000100];
void update(int num)
{
    num++;
    while (num <= mxspd)
        tree[num] += 1, num += lowbit(num);
}
ll sum(int num)
{
    num++;
    ll ans = 0;
    while (num)
        ans += tree[num], num -= lowbit(num);
    return ans;
}
int main()
{
    scanf("%lld%lld%lld", &n, &l, &c);
    for (int i = 1; i <= n; i++)
        scanf("%lld", &spd[i]);
    sort(spd + 1, spd + 1 + n), mxspd = spd[n];
    for (int i = 1; i <= n; i++)
        f[i] = (l * spd[i]) / mxspd;
    update((l * spd[1]) % mxspd);
    ll prefix = f[1], ans = 0;
    for (int i = 2; i <= n; i++)
    {
        prefix += f[i];
        ans += i * f[i] - prefix - i;
        update((l * spd[i]) % mxspd);
        ans += sum((l * spd[i]) % mxspd);
    }
    printf("%lld", ans);
    return 0;
}