USACO Bronze 2017 February - Why Did the Cow Cross the Road II

Authors: Benjamin Qi, Danh Ta Chi Thanh

Official Analysis (Java)

Time Complexity: O(N2)\mathcal{O}(N^2), where NN is the number of cows.

Define StartxStart_x and EndxEnd_x to be the indices of the first and last occurrences of cow xx in the input string, respectively. We want to count the number of pairs of cows (i,j)(i,j) such that cow ii enters before cow jj and leaves somewhere between cow jj's entry and exit. In other words, Starti<Startj<Endi<EndjStart_i < Start_j < End_i < End_j.

Since NN is small, we can afford to iterate over all possibilities for ii and jj and check whether the condition above is satisfied in O(N2)\mathcal{O}(N^2) time.

C++

#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
freopen("circlecross.in","r",stdin);
freopen("circlecross.out","w",stdout);
string s; cin >> s;
int Start[26], Exit[26];
//Set all elements of Start and End arrays to -1.

Alternative Implementation

Time Complexity: O(N4)\mathcal{O}(N^4)

Due to the low constraints, we can iterate over all O(N4)\mathcal{O}(N^4) possible pairs of intersecting paths and check whether they represent two cows.

C++

#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
freopen("circlecross.in","r",stdin);
freopen("circlecross.out","w",stdout);
string s; cin >> s;
int ans = 0;
for (int a = 0; a < s.size(); ++a)

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!