Official Analysis (Java)

Solution

Explanation

We can calculate the prefix sum array of our IDs to quickly compute whether or not a range of cows has IDs summing to a multiple of 77.

Given a prefix sum array pp, the sum over the range [l,r][l, r] is p[r]p[l1]p[r] - p[l-1]. We must also make sure this sum is a multiple of 77 to be a valid group. These two conditions give us the following:

(p[r]p[l1])0(mod7)p[r]p[l1](mod7)(p[r] - p[l - 1]) \equiv 0 \pmod{7} \Longleftrightarrow p[r] \equiv p[l - 1] \pmod{7}

Thus, we can simplify the solution to finding the largest difference between two indices where their prefix sums are equivalent mod 77.

Additionally, because the prefix sum at ii is defined by

p[i]%7=(a[i]+p[i1])%7,p[i]\%7 = \left(a[i]+p[i-1]\right)\%7,

we can find the prefix mod 77 when precomputing to avoid large numbers.

In order to find the largest consecutive group, we try to find the largest distance between two equal prefixes. We can have a list that stores the first occurrence of each remainder. Everytime we see a remainder again, we calculate the distance between the current index and the first occurrence of the remainder.

Implementation

Time Complexity: O(N)\mathcal{O}(N)

C++

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int MOD = 7;
int main() {
freopen("div7.in", "r", stdin);

Java

import java.io.*;
import java.util.*;
public final class Div7 {
private static final int MOD = 7;
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
BufferedReader read = new BufferedReader(new FileReader("div7.in"));
int cowNum = Integer.parseInt(read.readLine());

Python

MOD = 7
with open("div7.in") as read:
cows = [int(read.readline()) for _ in range(int(read.readline()))]
best_photo = 0
# first_occ[i] stores the index of the first time a prefix sum % 7 == i
first_occ = [-1 for _ in range(MOD)]
first_occ[0] = 0

Video Solution

By Project Starcoder

Video Solution Code

C++

#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main() {
ifstream cin("div7.in");
ofstream cout("div7.out");
ll N;

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!