USACO 2016 January Contest, Silver Problem 2. Subsequences Summing to Sevens

原题下载

USACO2016-JAN-S2

答案

(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();
	}
}
翰林国际教育资讯二维码