Solution 1
Explanation
Due to the low constraints, we can iterate over all possible pairs of intersecting paths and check whether they represent two cows.
Implementation
Time Complexity:
with open("circlecross.in") as read:crossings = read.readline().strip()crossing_pairs = 0# Iterate through all characters of the stringfor a in range(len(crossings)):for b in range(a + 1, len(crossings)):for c in range(b + 1, len(crossings)):for d in range(c + 1, len(crossings)):"""
Solution 2
Explanation
Define and to be the indices of the first and last occurrences of cow in the input string, respectively. We want to count the number of pairs of cows such that cow enters before cow and leaves somewhere between cow 's entry and exit. This condition can be formulated as the inequality .
Since is small, we can afford to iterate over all possibilities for and and check whether the above condition is satisfied.
Implementation
Time Complexity: , where is the number of cows.
with open("circlecross.in") as read:crossings = read.readline().strip()start = [-1 for _ in range(26)]end = [-1 for _ in range(26)]for v, c in enumerate(crossings):c_id = ord(c) - ord("A")if start[c_id] == -1:start[c_id] = velse:
Solution 3
Explanation
For every cow , we check which cows have exactly one entry/exit point between cow 's entry and exit point. Notice that for each of these cows , we know that they must cross , so we add the pair to a hash set containing all crossings. We must take care to not store both and in the set, as that would result in overcounting.
Our final answer is the length of the hash set with all the pairs.
Implementation
Time Complexity: , where is the length of FJ's string.
with open("circlecross.in") as read:crossings = read.readline().strip()# Equivalent to the start array in Solution 2first_found = [-1 for _ in range(26)]found_crossings = set()for i in range(len(crossings)):c_id = ord(crossings[i]) - ord("A")if first_found[c_id] == -1:# Mark the entry point of this cow
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!