原题下载
答案
(Analysis by Nick Wu)
In this problem, we have a list of numbers. We want to find a sublist of numbers where the sum of the numbers is divisible by 7.
Define a prefix of a list to be the first K numbers of the list. Note that any sublist of numbers can be obtained by taking some prefix of the original list and removing a smaller prefix of the list. Note furthermore that if you take the sums of the two prefixes, they have the same remainder when divided by 7.
Therefore, for every prefix, we can compute the sum of the numbers in the prefix modulo 7, and keep track of the shortest and longest prefixes that when summed are equivalent to xx modulo 7 for 0<x<7. The answer is then the maximum difference between the lengths of the shortest and longest prefixes over all x.
Here is my Java code demonstrating this.
import java.io.*;
import java.util.*;
public class div7 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("div7.in"));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("div7.out")));
int n = Integer.parseInt(br.readLine());
int[] first = new int[7];
int[] last = new int[7];
Arrays.fill(first, Integer.MAX_VALUE);
first[0] = 0;
int currPref = 0;
for(int i = 1; i <= n; i++) {
currPref += Integer.parseInt(br.readLine());
currPref %= 7;
first[currPref] = Math.min(first[currPref], i);
last[currPref] = i;
}
int ret = 0;
for(int i = 0; i < 7; i++) {
if(first[i] <= n) {
ret = Math.max(ret, last[i] - first[i]);
}
}
pw.println(ret);
pw.close();
}
}
以上就是关于【USACO 2016 January Contest, Silver Problem 2. Subsequences Summing to Sevens】的解答,如需了解学校/赛事/课程动态,可至翰林教育官网获取更多信息。
往期文章阅读推荐:
2027赛季USAAIO人工智能奥赛开放报名!冲刺MIT入场资格!
USACO计算机奥赛如何认证成绩?2026赛季黄金铂金组“定时开赛”规则详解!

© 2026. All Rights Reserved. 沪ICP备2023009024号-1