Problem:
Problem H: Eleven Lover

Edward Leven loves multiples of eleven very much. When he sees a number, he always tries
to find consecutive subsequences (or substrings) forming multiples of eleven. He calls such
subsequences as 11-sequences. For example, he can find an 11-sequence 781 in a number 17819.

He thinks a number which has many 11-sequences is a good number. He would like to find out
a very good number. As the first step, he wants an easy way to count how many 11-sequences
are there in a given number. Even for him, counting them from a big number is not easy.
Fortunately, one of his friends, you, is a brilliant programmer. He asks you to write a program
to count the number of 11-sequences. Note that an 11-sequence must be a positive number
without leading zeros.

Input

The input is a sequence of lines each of which contains a number consisting of less than or equal
to 80000 digits.

The end of the input is indicated by a line containing a single zero, which should not be processed.

Output

For each input number, output a line containing the number of 11-sequences.

You can assume the answer fits in a 32-bit signed integer.

Sample Input

17819
1111
11011
1234567891011121314151617181920
0

Output for the Sample Input

1
4
4
38

Solution in JAVA (judge verdict: Memory Limit Exceeded)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;

/**
 * Eleven Lover
 */
public class Main {

	static String line;
	static Map<Long, Integer> cache;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		//String line;

		cache = new HashMap<>();

		while ((line = br.readLine()) != null && !line.isEmpty()) {

			if (line.equals("0")) break;
			line += "_";

			int count = 0;
			for (int i = 0; i < line.length() - 2; i++) {
				for (int j = i + 2; j < line.length(); j++) {
					if (line.charAt(i) == '0') continue;
					//
					long mod = 0;
					if (j - i > 18) {
						mod = mod11(i, j);
					} else {
						mod = num(i, j, 0) % 11;
					}
					if (mod == 0) count++;
				}
			}
			System.out.println(count);
		} //end while
	} //end main

	static long mod11(int i, int j) {

		int mod = 0;
		for (; i < j; i += 17) {
			long _num = 0;
			if (i + 17 < j) {
				_num = num(i, i + 17, mod);
			} else {
				_num = num(i, j, mod);
			}
			if (cache.containsKey(_num)) {
				mod = cache.get(_num);
			} else {
				mod = (int) (_num % 11);
				cache.put(_num, mod);
			}
		}
		return mod;
	}

	static long num(int i, int j, int s) {
		long l = s;
		for (; i < j; i++) {
			l *= 10;
			l += line.charAt(i) - '0';
		}
		return l;
	}

}