Explanation
Let denote the position of cow in array and denote the position of cow in array (where arrays and represent the two sides of the road). Observe that two cows and will cross if and .
We can use the above fact to compute the initial number of crossings. Using an Order Statistics Tree, we can initially store all . To obtain the number of cows that cross with cow , we can erase all such that and query for the number of elements in the tree that are less than . To optimize erasing, we can loop from to and erase each before each query.
To handle cyclic shifts, we only care about moving the first cow to the last position. All other crossings will hold constant. Consider shifting array to the left:
- To detach existing crossings from , we must subtract because we know for all positions such that , is attached to some position such that .
- Now, becomes . The number of new crossings is because we know for all positions such that , is attached to some position such that .
Our answer is the minimum crossings out of all cyclic shifts. Note that we may have to consider shifting as well.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>#include <ext/pb_ds/assoc_container.hpp>using namespace std;using namespace __gnu_pbds;using ll = long long;template <typename T>using ordered_set =tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!