B21968,"import java.util.*; import java.io.*; public class recycled_numbers { public static void main(String[]a) throws Exception{ Scanner f = new Scanner(new File(a[0])); int result=0; int A,B; String n,m; HashSet s=new HashSet(); int T=f.nextInt(); //T total case count for (int t=1; t<=T;t++){//for each case t s.clear(); result=0; //reset A=f.nextInt();B=f.nextInt(); //get values for next case if (A==B)result=0;//remove case not meeting problem limits else{ for(int i=A;i<=B;i++){//for each int in range n=Integer.toString(i); m=new String(n); //System.out.println(n); for (int j=1;j= d.length) jj -= d.length; n = n * 10 + (d[jj] - '0'); } if (n >= a && n < m && !mask[n]) { ++ans; mask[n] = true; r[c++] = n; } } } for (int i = 0; i < c; ++i) { mask[r[i]] = false; } } println(""Case #"" + cs + "": "" + ans); //System.out.println(cs); } System.out.println(""time: "" + (System.currentTimeMillis() - tm)); exit(); } void in(String name) throws IOException { if (name.equals(""__std"")) { in = new BufferedReader(new InputStreamReader(System.in)); } else { in = new BufferedReader(new FileReader(name)); } } void out(String name) throws IOException { if (name.equals(""__std"")) { out = new PrintWriter(System.out); } else { out = new PrintWriter(name); } } void exit() { out.close(); System.exit(0); } int readInt() throws IOException { return Integer.parseInt(readToken()); } long readLong() throws IOException { return Long.parseLong(readToken()); } double readDouble() throws IOException { return Double.parseDouble(readToken()); } String readLine() throws IOException { st = null; return in.readLine(); } String readToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } boolean eof() throws IOException { return !in.ready(); } void print(String format, Object ... args) { out.println(new Formatter(Locale.US).format(format, args)); } void println(String format, Object ... args) { out.println(new Formatter(Locale.US).format(format, args)); } void print(Object value) { out.print(value); } void println(Object value) { out.println(value); } void println() { out.println(); } StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) throws IOException { new C().solve(); } } " B21270,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; public class CopyOfCopyOfMain { static int ndigits(int n) { return (int) (Math.log10(n) + 1); } static int rot(int n, int dig) { return (int) ((n % 10) * Math.pow(10, dig - 1)) + (int) (n / 10); } public static void main(String[] args) throws FileNotFoundException { String file = ""C-large""; Scanner in = new Scanner(new File(file + "".in"")); PrintWriter out = new PrintWriter(new File(file + "".out"")); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int A = in.nextInt(); int B = in.nextInt(); int c = 0; int[] list = new int[ndigits(B)]; numbers: for (int i = A; i <= B; i++) { int digs = ndigits(i); int rot = i; int pairs = 0; Arrays.fill(list, -1); list[0] = i; digits: for (int j = 1; j <= digs + 1; j++) { rot = rot(rot, digs); if(rot < i) continue; if (A <= rot && rot <= B) { for (int k = 0; k < j; k++) { if (list[k] == rot) { continue digits; } } pairs++; list[j] = rot; } } //c += pairs * (pairs + 1) / 2; c += pairs ; // c+=digs; } out.println(""Case #"" + t + "": "" + c); } in.close(); out.close(); } } " B20006,"import java.io.*; import java.math.BigInteger; import java.util.*; import org.jfree.data.function.PowerFunction2D; public class r2a { Map numMap = new HashMap(); int output = 0; /** * @param args */ public static void main(String[] args) { r2a mk = new r2a(); try { FileInputStream fstream = new FileInputStream(""d:/cjinput.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String str; int i = 0; while ((str = br.readLine()) != null) { int begin=0,end = 0; i++; if (i == 1) continue; mk.numMap = new HashMap(); StringTokenizer strTok = new StringTokenizer(str, "" ""); while (strTok.hasMoreTokens()) { begin = Integer.parseInt(((String) strTok.nextToken())); end = Integer.parseInt(((String) strTok.nextToken())); } mk.evaluate(i, begin, end); } in.close(); } catch (Exception e) { System.err.println(e); } } private void evaluate(int rowNum, int begin, int end) { output=0; for (int i = begin; i<= end; i++) { if(numMap.containsKey(Integer.valueOf(i))) continue; List l = getPairElems(i); if (l.size() > 0) { Iterator itr = l.iterator(); int ctr = 0; ArrayList tempList = new ArrayList(); while (itr.hasNext()) { int next = ((Integer)itr.next()).intValue(); if (next <= end && next > i) { numMap.put(Integer.valueOf(next), i); tempList.add(next); ctr++; } } ctr = getCounter(ctr+1,2); /* if (tempList.size() > 0 || ctr > 0) System.out.println(""DD: "" + i + "": "" + tempList +"" ; ctr = "" + ctr);*/ output = output + ctr; } } String outputStr = ""Case #"" + (rowNum -1) + "": "" + output; System.out.println(outputStr); } private int getCounter(int n, int r) { int ret = 1; int nfactorial =1; for (int i = 2; i<=n; i++) { nfactorial = i*nfactorial; } int nrfact =1; for (int i = 2; i<=n-r; i++) { nrfact = i*nrfact; } return nfactorial/(2*nrfact); } private ArrayList getPairElems(int num) { ArrayList retList = new ArrayList(); int temp = num; if (num/10 == 0) return retList; String str = String.valueOf(num); int arr[] = new int[str.length()]; int x = str.length(); while (temp/10 > 0) { arr[x-1] = temp%10; temp=temp/10; x--; } arr[0]=temp; int size = arr.length; for (int pos = size -1; pos >0; pos--) { if(arr[pos] == 0) continue; int pairNum = 0; int multiplier =1; for (int c=0; c < size-1; c++) { multiplier = multiplier*10; } pairNum = pairNum + (arr[pos]*multiplier); for(int ctr = pos+1, i=1; i < size; i++,ctr++) { if (ctr == size) ctr=0; if (multiplier!=1) multiplier=multiplier/10; pairNum = pairNum + (arr[ctr]*multiplier); } if (pairNum != num) retList.add(Integer.valueOf(pairNum)); } return retList; } } " B21227,"import java.util.HashSet; import java.util.Scanner; public class C { static HashSet p = new HashSet(); static int low; static int high; int count = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int no = sc.nextInt(); for (int i = 1; i <= no; i++) { p.clear(); low = sc.nextInt(); high = sc.nextInt(); for (int l = low; l <= high; l++) { recycle(l); } System.out.println(""Case #"" + i + "": "" + p.size()); } } public static void recycle(int no) { String s = Integer.toString(no); for (int i = 0; i < s.length(); i++) { String rec = s.substring(i) + s.substring(0, i); int r = Integer.parseInt(rec); if (r != no && r >= low && r <= high) { int min = Math.min(r, no); int max = Math.max(r, no); String a = Integer.toString(min) + """" + Integer.toString(max); p.add(a); } } } } " B20856,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Happy; import java.io.*; import java.math.*; import java.lang.*; import java.util.*; import java.util.Arrays.*; import java.io.BufferedReader; //import java.io.IOException; //import java.io.InputStreamReader; //import java.io.PrintWriter; //import java.util.StringTokenizer; /** * * @author ipoqi */ public class Happy { /** * @param args the command line arguments */ public static void main(String[] args) { new Happy().haha(); } public void haha() { BufferedReader in = null; BufferedWriter out = null; try{ in = new BufferedReader(new FileReader(""C-large.in"")); out = new BufferedWriter(new FileWriter(""LLL.out"")); int T = Integer.parseInt(in.readLine()); System.out.println(""T=""+T); //LinkedList mm = new LinkedList(); //mm.add(new LinkedList()); //int[][] mm; //for(int ii=0;ii=10){ String N = Integer.toString(n); int nlen = N.length(); List oks = new ArrayList(); for(int k=0;kn && m<=B) { boolean isNewOne = true; for(int kkk=0;kkk i && k <= max) ret++; else if(k == i) break; } } return ret; } public static void main(String[] args){ Scanner sc = null; String next; int out; try{ sc = new Scanner(new File(""C-large.in"")); int cases = Integer.parseInt(sc.nextLine()); int current = 0; FileWriter fs = new FileWriter(""output.txt""); BufferedWriter buff = new BufferedWriter(fs); while(current < cases){ next = sc.nextLine(); current++; out = recycle(next); buff.write(""Case #"" + current + "": "" + out + ""\n""); } buff.close(); } catch(Exception ex){} } }" B20734,"package fixjava; public class StringUtils { /** Repeat the given string the requested number of times. */ public static String repeat(String str, int numTimes) { StringBuilder buf = new StringBuilder(Math.max(0, str.length() * numTimes)); for (int i = 0; i < numTimes; i++) buf.append(str); return buf.toString(); } /** * Pad the left hand side of a field with the given character. Always adds at least one pad character. If the length of str is * greater than numPlaces-1, then the output string will be longer than numPlaces. */ public static String padLeft(String str, char padChar, int numPlaces) { int bufSize = Math.max(numPlaces, str.length() + 1); StringBuilder buf = new StringBuilder(Math.max(numPlaces, str.length() + 1)); buf.append(padChar); for (int i = 1, mi = bufSize - str.length(); i < mi; i++) buf.append(padChar); buf.append(str); return buf.toString(); } /** * Pad the right hand side of a field with the given character. Always adds at least one pad character. If the length of str is * greater than numPlaces-1, then the output string will be longer than numPlaces. */ public static String padRight(String str, char padChar, int numPlaces) { int bufSize = Math.max(numPlaces, str.length() + 1); StringBuilder buf = new StringBuilder(Math.max(numPlaces, str.length() + 1)); buf.append(str); buf.append(padChar); while (buf.length() < bufSize) buf.append(padChar); return buf.toString(); } /** Intern all strings in an array, skipping null elements. */ public static String[] intern(String[] arr) { for (int i = 0; i < arr.length; i++) arr[i] = arr[i].intern(); return arr; } /** Intern a string, ignoring null */ public static String intern(String str) { return str == null ? null : str.intern(); } } " B21049,"package it.simone.google.code.jam2012; import java.util.HashSet; import java.util.Set; public class RecycledNumber implements GoogleCodeExercise { int a = 0; int b = 0; Set distinctCouple = null; long maxTime = 0; private class Couple { int x = 0; int y = 0; public Couple(int x, int y) { this.x = x; this.y = y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Couple other = (Couple) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (x == other.x && y == other.y) return true; if (x == other.y && y == other.x) return true; return false; } private RecycledNumber getOuterType() { return RecycledNumber.this; } } @Override public String execute(String line) { int result = 0; String[] data = line.split("" ""); a = Integer.parseInt(data[0]); b = Integer.parseInt(data[1]); initialize(); int n = a; // while (n <= b) { result += analize(n); n++; // if (n % 1000 == 0) // System.out.println(n); } System.out.println(result); return """" + result; } @Override public void initialize() { distinctCouple = new HashSet(); } private int analize(int number) { String numString = """" + number; initialize(); for (int i = 1; i < numString.length(); i++) { int m = shift(numString, i); if (a <= number && number < m && m <= b) { Couple couple=new Couple(number,m); if (!distinctCouple.contains(couple)) distinctCouple.add(couple); } } return distinctCouple.size(); } private int shift(String numString, int posx) { String result = null; result = """" + numString.substring(posx) + numString.substring(0, posx); return Integer.parseInt(result.toString()); } } " B21207,"/* * Problem C. Recycled Numbers * * Do you ever become frustrated with television because you keep seeing the * same things, recycled over and over again? Well I personally don't care about * television, but I do sometimes feel that way about numbers. * * Let's say a pair of distinct positive integers (n, m) is recycled if you can * obtain m by moving some digits from the back of n to the front without * changing their order. For example, (12345, 34512) is a recycled pair since * you can obtain 34512 by moving 345 from the end of 12345 to the front. Note * that n and m must have the same number of digits in order to be a recycled * pair. Neither n nor m can have leading zeros. * * Given integers A and B with the same number of digits and no leading zeros, * how many distinct recycled pairs (n, m) are there with A ≤ n < m ≤ B? * * Input * * The first line of the input gives the number of test cases, T. T test cases * follow. Each test case consists of a single line containing the integers A * and B. * * Output * * For each test case, output one line containing ""Case #x: y"", where x is the * case number (starting from 1), and y is the number of recycled pairs (n, m) * with A ≤ n < m ≤ B. * * Limits * * 1 ≤ T ≤ 50. * * A and B have the same number of digits. Small dataset 1 ≤ A ≤ B ≤ 1000. Large dataset 1 ≤ A ≤ B ≤ 2000000. Sample Input Output 4 1 9 10 40 100 500 1111 2222 Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 */ package google.codejam.y2012.qualifications; import google.codejam.commons.Utils; import java.io.IOException; import java.util.StringTokenizer; /** * @author Marco Lackovic * @version 1.0, Apr 14, 2012 */ public class RecycledNumbers { private static final String INPUT_FILE_NAME = ""C-large.in""; private static final String OUTPUT_FILE_NAME = ""C-large.out""; public static void main(String[] args) throws IOException { String[] input = Utils.readFromFile(INPUT_FILE_NAME); String[] output = new String[input.length]; int x = 0; for (String line : input) { StringTokenizer st = new StringTokenizer(line); int a = Integer.valueOf(st.nextToken()); int b = Integer.valueOf(st.nextToken()); System.out.println(""Computing case #"" + (x + 1)); output[x++] = ""Case #"" + x + "": "" + recycledNumbers(a, b); } Utils.writeToFile(output, OUTPUT_FILE_NAME); } private static int recycledNumbers(int a, int b) { int count = 0; for (int n = a; n < b; n++) { count += getNumGreaterRotations(n, b); } return count; } private static int getNumGreaterRotations(int n, int b) { int count = 0; char[] chars = Integer.toString(n).toCharArray(); for (int i = 0; i < chars.length; i++) { chars = rotateRight(chars); if (chars[0] != '0') { int m = Integer.valueOf(new String(chars)); if (n == m) { break; } else if (n < m && m <= b) { count++; } } } return count; } private static char[] rotateRight(char[] chars) { char last = chars[chars.length - 1]; for (int i = chars.length - 2; i >= 0; i--) { chars[i + 1] = chars[i]; } chars[0] = last; return chars; } } " B21752,"package Main; import com.sun.deploy.util.ArrayUtil; import org.apache.commons.lang3.ArrayUtils; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; /** * Created with IntelliJ IDEA. * User: arran * Date: 14/04/12 * Time: 3:12 PM * To change this template use File | Settings | File Templates. */ public class Round { public StringBuilder parse(BufferedReader in) throws IOException { StringBuilder out = new StringBuilder(); String lineCount = in.readLine(); for (int i = 1; i <= Integer.parseInt(lineCount); i++) { out.append(""Case #""+i+"": ""); System.err.println(""Case #""+i+"": ""); String line = in.readLine(); String[] splits = line.split("" ""); int p1 = Integer.valueOf(splits[0]); int p2 = Integer.valueOf(splits[1]); int r = pairRecyclable(p1, p2); out.append(r); // if (i < Integer.parseInt(lineCount)) out.append(""\n""); } return out; } public static int pairRecyclable(int i1, int i2) { HashSet hash = new HashSet(); for (int i = i1; i < i2; i++) { String istr = String.valueOf(i); if (istr.length() < 2) continue; for (int p = 0; p < istr.length() ; p++) { String nistr = istr.substring(p,istr.length()).concat(istr.substring(0,p)); if (Integer.valueOf(nistr) < i1) continue; if (Integer.valueOf(nistr) > i2) continue; if (nistr.equals(istr)) continue; String cnistr = (Integer.valueOf(nistr) > Integer.valueOf(istr)) ? istr + "","" + nistr : nistr + "","" + istr; hash.add(cnistr); } } return hash.size(); } public static void main(String[] args) { InputStreamReader converter = null; try { int attempt = 0; String quest = ""C""; // String size = ""small-attempt""; String size = ""large""; converter = new InputStreamReader(new FileInputStream(""src/resource/""+quest+""-""+size+"".in"")); BufferedReader in = new BufferedReader(converter); Round r = new Round(); String str = r.parse(in).toString(); System.out.print(str); FileOutputStream fos = new FileOutputStream(quest+""-""+size+"".out""); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw); bw.write(str); bw.flush(); bw.close(); } catch (IOException e) { e.printStackTrace(); } } } " B20023,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class GoogleC { public String szamol(String input){ String result=""""; String a=input; Integer min=Integer.parseInt(a.substring(0,a.indexOf(' '))); a=a.substring(a.indexOf(' ')+1); Integer max=Integer.parseInt(a); Long count=0l; for(Integer i=min; i<=max; i++){ String e1=i.toString(); Set db=new HashSet(); for (int j=1; ji && k<=max){ db.add(k); //System.out.println(e1+""\t""+e2); } } count+=db.size(); } return count.toString(); } public static void main(String[] args) { GoogleC a=new GoogleC(); //String filename=""input.txt""; //String filename=""C-small-attempt0.in""; String filename=""C-large.in""; String thisLine; try { BufferedReader br = new BufferedReader(new FileReader(filename)); BufferedWriter bw= new BufferedWriter(new FileWriter(filename+"".out"")); thisLine=br.readLine(); Integer tnum=Integer.parseInt(thisLine); for(int i=0;i999999) return 7; if(x>99999) return 6; if(x>9999) return 5; if(x>999) return 4; if(x>99) return 3; if(x>9) return 2; return 1; } static int[] rotate( int value ) { List result = new ArrayList(); int[] V = new int[8]; int s = size(value); int x = value; for(int i=s-1;i>=0;i--) { V[i] = x%10; x /=10; } int rot; for(int i=1; ivalue && !result.contains(rot)) result.add(rot); } } if( result.isEmpty() ) return null; int[] r = new int[result.size()]; for(int i=0; i result = rotate(i); if( All[i]!=null ) { for(int value: (int[])All[i] ) { if( value <= B ) sol++; } } } return sol; } public static void main ( String args[] ) { int T; Scanner in = new Scanner(System.in); T = in.nextInt(); int cnt=0; int sol; precalculate(); for( cnt=1; cnt<=T; cnt++ ) { sol = solve( in ); System.out.printf(""Case #%d: %d\n"", cnt, sol); } } } " B22190,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class Recycled { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for (int i = 0; i < t; i++) { String[] str = br.readLine().split("" ""); int a = Integer.parseInt(str[0]); int b = Integer.parseInt(str[1]); System.out.println(""Case #"" + (i + 1) + "": "" + find(a, b)); } } catch (IOException e) { e.printStackTrace(); } } private static int find(int a, int b) { HashSet used = new HashSet(); int digits = String.valueOf(a).length(); if (digits == 1) return 0; for (int i = a; i <= b; i++) { int s = 10; int m = (int) Math.pow(10, digits-1); for (int j = 0; j < digits-1; j++) { int r = i % s; if (r < s/10) continue; int q = i / s; int rn = r * m + q; s *= 10; m /= 10; if (i != rn && rn >= a && rn <= b) { long pp; if (rn < i) pp = (long)rn << 30 | i; else pp = (long)i << 30 | rn; if (!used.contains(pp)) { used.add(pp); } } } } return used.size(); } } " B20291,"import java.io.*; import java.util.*; class B { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(""B.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""B.out"")); int X = Integer.parseInt(br.readLine()); for(int i=0; i 0) { n++; x *= 10; } for(int j=A; j seen = new HashSet(); for(int k=1; knum){ if (Long.valueOf(newNumSt).longValue()>n1 && Long.valueOf(newNumSt).longValue()<=n2){ boolean found=false; for (int j=0;!found&&j0)System.out.println(""checkRecycle ""+numSt+"" re=""+re+"" allNum=""+allNum); return re; } } public class ReadWriteTextFile { static public String getContents(File aFile) { StringBuilder contents = new StringBuilder(); try { BufferedReader input = new BufferedReader(new FileReader(aFile)); try { String line = null; while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty(""line.separator"")); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return contents.toString(); } static public void setContents(File aFile, String aContents) throws FileNotFoundException, IOException { if (aFile == null) { throw new IllegalArgumentException(""File should not be null.""); } if (!aFile.exists()) { throw new FileNotFoundException (""File does not exist: "" + aFile); } if (!aFile.isFile()) { throw new IllegalArgumentException(""Should not be a directory: "" + aFile); } if (!aFile.canWrite()) { throw new IllegalArgumentException(""File cannot be written: "" + aFile); } Writer output = new BufferedWriter(new FileWriter(aFile)); try { output.write( aContents ); } finally { output.close(); } } public static void main (String... aArguments) throws IOException { File testFile = new File(""source.txt""); File testFile2 = new File(""result.txt""); Case allcases = new Case(testFile); setContents(testFile2, allcases.getResult()); } } " B20073,"import java.util.Scanner; import java.util.LinkedList; public class ProblemC { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); //number of cases scan.nextLine(); for (int k = 1; k <= T; k++) { int A = scan.nextInt(); int B = scan.nextInt(); int count = 0; for (int i = A; i <= B; i++) { String original = """"+i; LinkedList recycleList = new LinkedList(); for (int j = 1; j< original.length(); j++) { //where to rotate from if (original.charAt(j) < original.charAt(0)) //eliminate some obvious ""decreasing"" cases continue; //since they'll be duplicated anyway. String newstr = original.substring(j) + original.substring(0,j); int newint = Integer.parseInt(newstr); if (newint > i && newint <= B) {//don't count duplicates or pairs out of range if (!recycleList.contains(newint)) {//no duplicate recycles count++; recycleList.add(newint); } } } } //System.err.println(""count: "" + count); int solution = count; System.out.println(""Case #"" + k + "": "" + solution); } } } " B20303,"package gcj_2012; /** * Time: 6:31:53 PM, Apr 13, 2012 * @author Maya is the best :-) */ import java.util.Scanner; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class C { static Scanner in; static String path = ""src/gcj_2012/""; static String taskname = ""C-large""; public static String solve() { int A = in.nextInt(); int B = in.nextInt(); int y = 0; int digits = 1; int n = A; int tens; while ( n > 9) { digits++; n /= 10; } tens = (int)Math.pow(10, digits-1); for (int i=A; i 1) { for (int currentValue = minValue; currentValue < maxValue; currentValue++) { HashSet foundValues = new HashSet(); String sCurrentValue = Integer.toString(currentValue); char firstNumber = sCurrentValue.charAt(0); for (int i = nbDigits - 1; i > 0; i--) { char number = sCurrentValue.charAt(i); if (number >= firstNumber) { String firstPart = sCurrentValue.substring(0, i); String secondPart = sCurrentValue.substring(i); int val = Integer.parseInt(secondPart + firstPart); if (val <= maxValue && val > currentValue && !foundValues.contains(val)) { testCaseResult++; foundValues.add(val); } } } } } output += ""Case #"" + (testCaseNumber+1) + "": "" + testCaseResult + ""\n""; } } } ///////////////////////////////////////////////////////////////////////////////////////////////////// public void init() throws Exception { File temp = new File(""output/""); if (!temp.exists()) { temp.mkdir(); } // Output file outputWriter = new FileWriter(""output/output.txt"", false); // Input file scanner = new Scanner(new File(""resources/"" + INPUT_FILE_NAME)); } public void stop() throws Exception { // Closing files outputWriter.write(output, 0, output.length()); scanner.close(); outputWriter.close(); } /** * @param args */ public static void main(String[] args) throws Exception { C instance = new C(); long start = System.currentTimeMillis(); instance.init(); instance.run(); instance.stop(); System.out.println(""Finished in "" + (System.currentTimeMillis() - start) + "" ms""); } } " B20103,"import java.io.*; import java.util.*; public class ProblemC { public static void main(String[]args) { Scanner f = new Scanner(System.in); int T = f.nextInt(); for(int set=0;set= 10) { b /= 10; leadingMult*=10; } // System.out.println(""leadingMult: ""+leadingMult); long pairs = 0; for(int x=A;x<=B;x++) { // System.out.println(""x: ""+x); int y = x; do { y = y/10 + leadingMult*(y%10); // System.out.println(""y: ""+y); if(x < y && y <= B) { // System.out.printf(""(%d,%d)\n"",x,y); pairs++; } } while(y!=x); } System.out.printf(""Case #%d: %d\n"",set+1,pairs); } } }" B21061,"package duyonggang; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { public static int pass(int n, int a, int b) { if(n < 10) return 0; int counter = 0; String s = Integer.toString(n); int m; List passedValues = new ArrayList(); for(int i = s.length() - 1; i > 0; i--) { if(s.charAt(i) == '0') continue; m = Integer.parseInt(s.substring(i, s.length()) + s.substring(0, i)); if(m > n && m <= b && !passedValues.contains(m)) { counter++; passedValues.add(m); } } return counter; } public static int analyze(String line) { int counter = 0; String[] strs = line.split("" ""); int a = Integer.parseInt(strs[0]); int b = Integer.parseInt(strs[1]); for(int i = a; i <= b; i++) { counter += RecycledNumbers.pass(i, a, b); } return counter; } public static void main(String[] args) throws Exception { File input = new File(""c.txt""); FileReader fr = new FileReader(input); BufferedReader br = new BufferedReader(fr); String line = null; line = br.readLine(); int count = Integer.parseInt(line); for(int i = 0; i < count; i++) { line = br.readLine(); System.out.println(""Case #"" + (i + 1) + "": "" + RecycledNumbers.analyze(line)); } } } " B21258,"package qual2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Locale; import java.util.Set; import java.util.StringTokenizer; public class C { private static final String TASKNAME = ""input""; private void solve() throws IOException { int t = nextInt(); for (int i = 1; i <= t; i++) { int a = nextInt(); int b = nextInt(); int res = 0; for (int j = a; j < b; j++) { res += f(j, b); } println(""Case #"" + i + "": "" + res); } } private int f(int n, int b) { Set set = new HashSet(); int res = 0; int l = Integer.toString(n).length(); int p = 1; while (p <= n) { p *= 10; } p /= 10; int m = n; for (int i = 1; i < l; i++) { int x = m / 10 + (m % 10) * p; if (x > n && x <= b) { set.add(x); // res++; // System.err.println(n + "" "" + x); } m = x; } // return res; return set.size(); } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private void print(Object o) { writer.print(o); } private void println(Object o) { writer.println(o); } private void printf(String format, Object... o) { writer.printf(format, o); } public static void main(String[] args) { long time = System.currentTimeMillis(); Locale.setDefault(Locale.US); new C().run(); System.err.printf(""%.3f\n"", 1e-3 * (System.currentTimeMillis() - time)); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; private void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); reader = new BufferedReader(new FileReader(TASKNAME + "".in"")); writer = new PrintWriter(TASKNAME + "".out""); solve(); reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); System.exit(13); } } }" B22038,"package lt.kasrud.gcj.common; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class IO { public static Data readFile(String filename) throws IOException { Data results = new Data(); BufferedReader reader = new BufferedReader(new FileReader(filename)); String line = null; while ((line = reader.readLine()) != null) { results.add(new Record(line)); } reader.close(); return results; } private static String formatCase(int caseNr, String output) { return String.format(""Case #%d: %s"", caseNr, output); } public static void writeFile(String filename, List data) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); for (int i = 0; i < data.size(); i++) { String output = formatCase(i + 1, data.get(i).toString()); writer.write(output + ""\n""); } writer.close(); } public static class Data { List records = new ArrayList(); public void add(Record record){ records.add(record); } public String getString(int recNr, int i){ Record record = records.get(recNr); return record.getString(i); } public Integer getInt(int recNr, int i){ Record record = records.get(recNr); return record.getInt(i); } public List getRecords(int from){ return getRecords(from, records.size()); } public List getRecords(int from, int to){ return records.subList(from, to); } } public static class Record { String raw; String[] tokens; Record(String raw) { this(raw, "" ""); } Record(String raw, String separator) { this.raw = raw; tokens = raw.trim().split(separator); } public String getRaw() { return raw; } public String getString(int i) { return tokens[i]; } public int getInt(int i) { return Integer.valueOf(getString(i)); } public List getStringList(int from){ return getStringList(from, tokens.length); } public List getStringList(int from, int to){ return Arrays.asList(tokens).subList(from, to); } public List getIntList(int from){ return getIntList(from, tokens.length); } public List getIntList(int from, int to){ List strings = Arrays.asList(tokens).subList(from, to); List ints = new ArrayList(strings.size()); for (String s : strings){ ints.add(Integer.valueOf(s)); } return ints; } } } " B20744,"package fixjava; /** * Convenience class for declaring a method inside a method, so as to avoid code duplication without having to declare a new method * in the class. This also keeps functions closer to where they are applied. It's butt-ugly but it's about the best you can do in * Java. */ public interface Lambda4 { public V apply(P param1, Q param2, R param3, S param4); } " B20367,"import java.io.*; import java.util.HashSet; import java.util.Set; /** * Created by IntelliJ IDEA. * User: YC14RP1 * Date: 4/14/12 * Time: 12:57 AM * To change this template use File | Settings | File Templates. */ public class Test3 { public static void main(String[] args) throws FileNotFoundException { String path = ""C:\\Users\\YC14rp1\\Downloads\\C-large.in""; //String path = ""C:\\Users\\YC14rp1\\Downloads\\C-small-attempt0.in""; try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(path); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line strLine = br.readLine(); int n = Integer.valueOf(strLine); for (int i=1;i<=n;i++) { strLine = br.readLine(); String[] split = strLine.split("" ""); String s1 = split[0]; long d1 = Long.valueOf(s1); String s2 = split[1]; long d2 = Long.valueOf(s2); int res = 0; for (long j=d1;j<=d2;j++) { Set cSet = new HashSet(); String ss = String.valueOf(j); for (int k=0;kj) && (r>=d1) && (r<=d2)) { if (!cSet.contains(r)) { //System.out.println(j+""/""+r); res++; } cSet.add(r); //res++; } } } // Print the content on the console System.out.println(""Case #"" + i + "": "" + res); } //Close the input stream in.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } " B21517,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashSet; public class RecycledNumbers { ArrayList result = new ArrayList<>(); public void solve(int A, int B){ HashSet distinct = new HashSet<>(); HashSet testM = new HashSet<>(); for(int n=A;nn){ distinct.add(nStr+mStr); } } } result.add(""""+distinct.size()); } public void saveResults(String file){ try { FileWriter fstream = new FileWriter(file); BufferedWriter out = new BufferedWriter(fstream); int count = 1; for(int i=0;i input = new ArrayList(); ArrayList output = new ArrayList(); try { BufferedReader br = new BufferedReader(new FileReader(filename)); while (true) { String line = br.readLine(); if (line == null) break; input.add(line); } br.close(); input.remove(0); } catch (IOException e) { System.out.println(""Input error. Try a different filename.""); } for (String line: input) { String out = """"+checkCondition(line); System.out.println(out); output.add(out); } try { PrintWriter pr = new PrintWriter(new FileWriter(""output.txt"")); for (int i = 0;i < output.size();i++) { String line = output.get(i); pr.println(""Case #"" + (i+1) + "": "" + line); } pr.close(); } catch (IOException e) { System.out.println(""Output error. Hmph.""); } System.out.println(""Process complete.""); } private static int checkCondition(String line) { String[] numString = line.split("" ""); int a = Integer.parseInt(numString[0]); int b = Integer.parseInt(numString[1]); int recycled = 0; /* for (int n = a;n <= b;n++) { String N = """"+n; for (int m = n+1;m <= b;m++) { String M = """"+m; if (areRecycled(M,N)) { recycled++; //System.out.println(M + "" "" + N); } } }*/ for (int n = a;n <= b;n++) { String N = """"+n; HashSet perms = new HashSet(); for (int i = 1;i < N.length();i++) { N = permute(N); int m = Integer.parseInt(N); if (n < m && m <= b) { //recycled++; //System.out.println("""" + n + "" "" + m); perms.add(m); } } recycled += perms.size(); } return recycled; } private static boolean areRecycled(String M,String N) { String n = N; for (int i = 1;i < N.length();i++) { n = permute(n); if (M.equals(n)) { return true; } } return false; } private static String permute(String n) { char q = n.charAt(0); return n.substring(1) + q; } } " B21447,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejamqualifier; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; /** * * @author Dean */ public class RecycledNumbers { public static void main(String args[]) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int testCases = Integer.parseInt(reader.readLine().trim()); for (int i = 0; i < testCases; i++) { String split[] = reader.readLine().split(""[\\s]+""); int A = Integer.parseInt(split[0]); int B = Integer.parseInt(split[1]); System.out.println(""Case #"" + (i + 1) + "": "" + countPermutations(A, B)); } } public static int countPermutations(int A, int B) { int pow[] = new int[] {1,10,100,1000,10000,100000,1000000,10000000}; int count = 0; int digits = (B + """").length(); for (int m = A + 1; m <= B; m++) { HashMap checked = new HashMap(10); for (int i = 1; i < digits; i++) { int mul = (int) (Math.pow(10, i)); int move = m % mul; int n = m / mul; n = n + move * (int) (Math.pow(10, (digits - i))); if ((n < m) && ((n + """").length() == digits)&& (A <= n)) { //count++; if (checked.containsKey(n)) { continue; } else { count++; checked.put(n, true); } } } } return count; } } " B21910,"import java.io.*; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { static String outputFile, inputFile; public static void main(String[] args) throws IOException { if (args.length != 2) return; inputFile = args[0]; outputFile = args[1]; // Create FileReader Object FileReader inputFileReader = new FileReader(inputFile); FileWriter outputFileReader = new FileWriter(outputFile); // Create Buffered/PrintWriter Objects BufferedReader inputStream = new BufferedReader(inputFileReader); PrintWriter outputStream = new PrintWriter(outputFileReader); Scanner scanner; String inLine = null; int cases = Integer.parseInt(inputStream.readLine().trim()); int a, b; for (int i = 1; i < cases + 1; i++) { inLine = inputStream.readLine().trim(); scanner = new Scanner(inLine); a = scanner.nextInt(); b = scanner.nextInt(); outputStream.println(""Case #""+i+"": ""+getNumRecycledNumbers(a,b)); } outputStream.close(); } private static int getNumRecycledNumbers(int a, int b){ boolean[] isChecked = new boolean[b-a+1]; String numStr, newNumStr; int totalPairs = 0, newNum, numPairs=1; for (int t = a; t <= b; t++){ if (isChecked[t-a])continue; isChecked[t-a]=true; numStr = """" + t ; numPairs = 1; for (int i = numStr.length()-1; i>0; i--){ newNumStr = numStr.substring(i)+numStr.substring(0, i); newNum = Integer.parseInt(newNumStr); if (newNum < a || newNum > b ||isChecked[newNum-a]) continue; else { isChecked[newNum-a] = true; numPairs++; } } if (numPairs >2){ numPairs = getFactorial(numPairs) / ((getFactorial(numPairs-2)*2)); }else if (numPairs ==2){ numPairs = 1; } else { numPairs = 0; } totalPairs += numPairs; } return totalPairs; } private static int getFactorial(int n){ int result = 1; while (n > 1){ result *= n; n--; } return result; } } " B21642,"package com.bd.codejam.y2012; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; class C { public void solve() throws IOException { Scanner in = new Scanner(new File(getClass().getSimpleName() + "".in.txt"")); PrintWriter out = new PrintWriter(new File(getClass().getSimpleName() + "".out.txt"")); int T = Integer.parseInt(in.nextLine()); for (int t = 0; t < T; t++) { int A = in.nextInt(); int B = in.nextInt(); int result = solve(A, B); out.println(""Case #"" + (t + 1) + "": "" + result); System.out.println(""Case #"" + (t + 1) + "": "" + result); } in.close(); out.close(); } private int solve(int A, int B) { line = 1; int r = 0; for (int n = A; n < B; n++) { r += recycledPairs(n, B); } return r; } int line = 1; private int recycledPairs(int n, int max) { int r = 0; for (int pair : recycledPairs(n)) { if (n < pair && pair <= max) { r++; //System.out.println((line++) + "": "" + n + "" "" + pair); } } return r; } private List recycledPairs(int n) { String s = Integer.toString(n); List r = new ArrayList(s.length()-1); for (int i = 1; i < s.length(); i++) { String shift = shift(s, i); if (shift.charAt(0) != '0') { int shifti = Integer.parseInt(shift); if (!r.contains(shifti)) { r.add(shifti); } } } return r; } private String shift(String s, int n) { char[] c = new char[s.length()]; for (int i = 0; i < s.length(); i++) { c[i] = s.charAt(((i+(s.length()-n))%s.length())); } return new String(c); } public static void main(String[] args) throws IOException { new C().solve(); } }" B21692,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; class Input { int a; int b; public Input(String line) { String [] arr = line.split("" ""); a = Integer.parseInt(arr[0]); b = Integer.parseInt(arr[1]); } public String Rotate(String str) { char last = str.charAt(str.length()-1); return (last + str.substring(0,str.length()-1)); } public int Solve() { int count=0; int numDigits = Integer.toString(a).length(); for(int curr=a;curr<=b;curr++) { // For each number String strCurr = Integer.toString(curr); HashMap checker = new HashMap(); for(int rot=1;rot curr && newNum <= b) { String str = curr + "","" + newNum; if(!checker.containsKey(str)) count++; checker.put(str, 0); } } } return count; } } public class Main { /** * @param args */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // Setup console BufferedReader c = new BufferedReader(new InputStreamReader(System.in)); // Read number of test cases int numCases = Integer.parseInt(c.readLine()); // Input Input [] testCases = new Input[numCases]; for(int i=0;i res = new ArrayList(); try { FileInputStream fstream = new FileInputStream(""C-large.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int cases = Integer.valueOf(br.readLine()); for(int i = 0; i < cases; i++) { String line = br.readLine(); int min = Integer.valueOf(line.split(""[ \r\n\t]+"")[0]); int max = Integer.valueOf(line.split(""[ \r\n\t]+"")[1]); res.add(solve(min, max)); } in.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } try { // Create file File fout = new File(""out.txt""); FileWriter fstream = new FileWriter(fout); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < res.size(); i++){ out.write(""Case #"" + (i+1) + "": "" + res.get(i)); out.newLine(); } // Close the output stream out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } static int solve(int min, int max){ //find number of digits int tmp = min; int size = 0; while(tmp > 0){ tmp /= 10; size++; } if(size == 1) return 0; int res = 0; for(int i = min; i <= max; i++){ int[] digits = toDigits(i, size); Set candidates = asNumbers(digits); for(int candidate : candidates){ if(candidate > i && candidate >= min && candidate <= max) res++; } } return res; } static int[] toDigits(int i, int size){ int[] res = new int[size]; int counter = size-1; while(i > 0){ res[counter--] = i%10; i /= 10; } return res; } static Set asNumbers(int[] digits){ Set res = new HashSet(); int tmp = 0; for(int i = 0; i < digits.length; i++){ tmp *= 10; tmp += digits[i]; } for(int i = 0; i < digits.length-1; i++){ int mod = tmp%10; tmp /= 10; for(int j = 0; j < digits.length-1; j++){ mod *= 10; } tmp += mod; res.add(tmp); } return res; } } " B21869,"import java.util.*; import java.math.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { Scanner c=new Scanner(System.in); int T=c.nextInt(); for(int i=0;i Tr=new TreeSet(); for(int j=1;jnum&&got>=A&&got<=B) Tr.add(got); } ans+=Tr.size(); } System.out.println(""Case #1: ""+ans); } } } //must declare new classes here" B22199,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; class IOSystem { private String filePath; private List inputList = new ArrayList(); private StringBuilder sb = new StringBuilder(); private int readSize = 0; private int appendedSize = 0; public IOSystem(String filePath) { this(filePath,"" ""); } public IOSystem(String filePath,String sep) { this.filePath = filePath; try { BufferedReader br = new BufferedReader(new FileReader(filePath+"".in"")); String line = null; while((line=br.readLine())!=null) { inputList.addAll(Arrays.asList(line.split(sep))); } } catch (Exception e) { e.printStackTrace(); } } public int size(){return inputList.size();} public boolean hasNext(){return readSize < size();} public int nextInt(){return Integer.parseInt(inputList.get(readSize++));} public long nextLong(){return Long.parseLong(inputList.get(readSize++));} public double nextDouble(){return Double.parseDouble(inputList.get(readSize++));} public String nextString(){return new String(inputList.get(readSize++));} public void appendAnswer(T answer){sb.append(""Case #""+(++appendedSize)+"": ""+answer.toString()+""\n"");}; public void output(){ try { BufferedWriter bw = new BufferedWriter(new FileWriter(filePath+"".ou"")); bw.write(sb.toString()); bw.flush(); System.out.println(sb.toString()); System.out.println(""output ->""+filePath+"".ou""); } catch (IOException e) { e.printStackTrace(); } } } " B21439,"package jp.funnything.competition.util; import java.io.File; import java.math.BigDecimal; import java.math.BigInteger; import org.apache.commons.io.FileUtils; public class CompetitionIO { private final QuestionReader _reader; private final AnswerWriter _writer; /** * Default constructor. Use latest ""*.in"" as input */ public CompetitionIO() { this( null , null , null ); } public CompetitionIO( final File input , final File output ) { this( input , output , null ); } public CompetitionIO( File input , File output , final String format ) { if ( input == null ) { for ( final File file : FileUtils.listFiles( new File( ""."" ) , new String[] { ""in"" } , false ) ) { if ( input == null || file.lastModified() > input.lastModified() ) { input = file; } } if ( input == null ) { throw new RuntimeException( ""No *.in found"" ); } } if ( output == null ) { final String inPath = input.getPath(); if ( !inPath.endsWith( "".in"" ) ) { throw new IllegalArgumentException(); } output = new File( inPath.replaceFirst( "".in$"" , "".out"" ) ); } _reader = new QuestionReader( input ); _writer = new AnswerWriter( output , format ); } public CompetitionIO( final String format ) { this( null , null , format ); } public void close() { _reader.close(); _writer.close(); } public String read() { return _reader.read(); } public BigDecimal[] readBigDecimals() { return _reader.readBigDecimals(); } public BigDecimal[] readBigDecimals( final String separator ) { return _reader.readBigDecimals( separator ); } public BigInteger[] readBigInts() { return _reader.readBigInts(); } public BigInteger[] readBigInts( final String separator ) { return _reader.readBigInts( separator ); } /** * Read line as single integer */ public int readInt() { return _reader.readInt(); } /** * Read line as multiple integer, separated by space */ public int[] readInts() { return _reader.readInts(); } /** * Read line as multiple integer, separated by 'separator' */ public int[] readInts( final String separator ) { return _reader.readInts( separator ); } /** * Read line as single integer */ public long readLong() { return _reader.readLong(); } /** * Read line as multiple integer, separated by space */ public long[] readLongs() { return _reader.readLongs(); } /** * Read line as multiple integer, separated by 'separator' */ public long[] readLongs( final String separator ) { return _reader.readLongs( separator ); } /** * Read line as token list, separated by space */ public String[] readTokens() { return _reader.readTokens(); } /** * Read line as token list, separated by 'separator' */ public String[] readTokens( final String separator ) { return _reader.readTokens( separator ); } public void write( final int questionNumber , final Object result ) { _writer.write( questionNumber , result ); } public void write( final int questionNumber , final String result ) { _writer.write( questionNumber , result ); } public void write( final int questionNumber , final String result , final boolean tee ) { _writer.write( questionNumber , result , tee ); } } " B21352,"import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.IOException; import java.util.InputMismatchException; import java.math.BigInteger; public class Recycled { static InputReader in; static PrintWriter out; public static void main(String[] args) { try { System.setIn(new FileInputStream(args[0])); System.setOut(new PrintStream(new FileOutputStream(args[0].replace("".in"","".out"")))); } catch (FileNotFoundException e) { throw new RuntimeException(); } in = new InputReader(System.in); out = new PrintWriter(System.out); int T = in.readInt(); for (int t = 0; t < T; t++) { int A = in.readInt(); int B = in.readInt(); int count = 0; for (int i = A; i <= B; i++) { String A_s = Integer.toString(i); int n = A_s.length(); for (int j = 0; j < n - 1; j++) { A_s = A_s.substring(1) + A_s.charAt(0); int temp = Integer.parseInt(A_s); if (temp > i && temp <= B) { count++; // System.out.println(""(""+i+"", ""+temp+"")""); } } } out.print(""Case #""+(t+1)+"": ""); out.println("""" + count); } out.close(); } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } }" B20442,"import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { private Integer a; private Integer b; private Integer caseNumber; private Integer numberOfDigits; public RecycledNumbers(int caseNumber,String data) { // TODO Auto-generated constructor stub Scanner s=new Scanner(data); this.a=s.nextInt(); this.b=s.nextInt(); this.caseNumber=caseNumber; this.numberOfDigits=a.toString().length(); } public void process() { int count=0; for(Integer i=a;i temp=new ArrayList(); for(int j=1;ji){ count++; //System.out.println(i+"" ""+temp1); } } } System.out.println(""Case #""+caseNumber+"": ""+count); } } " B21244,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; /** * */ /** * @author Bryan * */ public class problemC { /** * @param args */ public static void main(String[] args) { String filePath = ""/Users/Bryan/Documents/CodeJam/ProblemC/C-large.in""; boolean isFirstLine = true; int counter = 1; StringBuffer resultString = new StringBuffer(); try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(filePath); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line while ((strLine = br.readLine()) != null) { if (isFirstLine){ isFirstLine = false; continue; } resultString.append(""Case #"" + counter + "": ""); String[] numberList = strLine.split("" ""); int result = 0; int min = Integer.parseInt(numberList[0]); int max = Integer.parseInt(numberList[1]); for ( int a = min; a <= max; a++){ result = result + noOfPairs(Integer.toString(a),min, max); // System.out.println(""final result = "" + result); } System.out.println(""result = "" + result/2); resultString.append(result/2); resultString.append(""\n""); counter++; } // Close the input stream in.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } writeStringToFile(resultString.toString()); } private static int noOfPairs(String num,int min, int max){ int noOfPairs = 1; String oldString = num; String newString = """"; String tempString = oldString; ArrayList addedList = new ArrayList(); for ( int counter = 0; counter < oldString.length(); counter++){ newString= tempString.substring(tempString.length()-1)+tempString.substring(0,tempString.length()-1); tempString=newString; // System.out.println(newString); if( !newString.startsWith(""0"") && Integer.parseInt(newString) <= max && Integer.parseInt(newString) >= min && !newString.equalsIgnoreCase(num) && !addedList.contains(newString)){ addedList.add(newString); noOfPairs++; } } if ( noOfPairs == 1 ){ return 0; } return noOfPairs - 1; // return nCr(noOfPairs,2); } private static void writeStringToFile(String outputString) { try { // Create file FileWriter fstream = new FileWriter(""/Users/Bryan/Documents/CodeJam/ProblemC/output.txt""); BufferedWriter out = new BufferedWriter(fstream); out.write(outputString); // Close the output stream out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B20486,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; public class ProblemC { public static void main(String[] args) throws FileNotFoundException { PrintStream out = new PrintStream(new FileOutputStream(new File( ""c-large.out""))); Scanner in = new Scanner(new File(""C-large.in"")); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); int count = 0; // boolean[] visited = new boolean[B - A + 1]; for (int n = A; n <= B; n++) { // if (!visited[n]) { String origstr = Integer.valueOf(n).toString(); String str = shift(origstr); while (!str.equals(origstr)) { int shifted = Integer.parseInt(str); // System.out.printf(""n: %d, shift: %s, shifted: %d, valid: %b\n"", // n, str, shifted, shifted > n); if (shifted > n && shifted <= B) count++; str = shift(str); } // } } out.printf(""Case #%d: %d\n"", i, count); } in.close(); out.close(); } public static String shift(String num) { return num.charAt(num.length() - 1) + num.substring(0, num.length() - 1); } } " B21793,"/* * Abstract class that reads either the standard input, a named file, or prompts at the terminal. * Implement ""process"" for each CodeJam problem. * Reads input through a ReadWrapper, wrapping a BufferedReader. */ import java.io.*; import java.util.StringTokenizer; import java.text.*; public abstract class CodeJammer { protected ReadWrapper reader; protected int caseNum = 1; //Processes one case public abstract void process() throws IOException; public void init() { //Do nothing unless overridden. } //Process all cases... usually just read the number of them and then run process on each. //Override if necessary. public void processAll() throws IOException { init(); int numTrials = reader.readInt(); for (int i=0; i all = new ArrayList(); for(int i=1; ia&&b<=B) { if(all.contains(b))continue; all.add(b); ret++; } } return ret; } } " B20863,"import java.io.*; import java.util.*; class CodejamC { public static int power[]; public static void main (String [] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""E:/C-large.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""E:/outC.txt""))); int nTest = Integer.parseInt(in.readLine()); power = new int[10]; power[0] = 1; for (int i = 1; i < power.length; i++) { power[i] = power[i-1] * 10; } for (int testIndex = 0; testIndex < nTest; testIndex++) { out.print(""Case #"" + (testIndex + 1) + "": ""); /***** start **********/ StringTokenizer st = new StringTokenizer(in.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); long result = 0; for (int p = a; p <= b; p++) { int len = getLen(p); int q = p; for (int offset = 1; offset < len; offset++) { int t = q * 10; q = t % power[len] + t / power[len]; if (q == p) { break; } if (q <= b && q > p) { result++; } } } out.print(result); /***** end **********/ out.println(); } out.close(); } public static int getLen(long l) { for (int i = 1; i < 10; i++) { if (l < power[i]) { return i; } } return -1; } public static int itoa(int a, char[] s) { int len = 0; while (a > 0) { s[len] = (char) (a % 10 + '0'); a /= 10; len++; } return len; } /* * for (int i = lenCurrent - 1; i >= 0; i--) { int shiftIndex = i + offset; if (shiftIndex >= lenCurrent) { shiftIndex -= lenCurrent; } if (lenMax <= lenCurrent && current[shiftIndex] > max[i]) { continue; } } for (int i = lenCurrent - 1; i >= 0; i--) { int shiftIndex = i + offset; if (shiftIndex >= lenCurrent) { shiftIndex -= lenCurrent; } if (lenMax <= lenCurrent && current[shiftIndex] > max[i]) { continue; } if (current[shiftIndex] > current[i]) { ok = true; break; } else if (current[shiftIndex] < current[i]) { break; } } if (ok) { result++; } for (int i = lenCurrent - 1; i >= 0; i--) { int shiftIndex = i + offset; if (shiftIndex >= lenCurrent) { shiftIndex -= lenCurrent; } if (lenMax <= lenCurrent && current[shiftIndex] > max[i]) { continue; } } for (int i = lenCurrent - 1; i >= 0; i--) { int shiftIndex = i + offset; if (shiftIndex >= lenCurrent) { shiftIndex -= lenCurrent; } if (lenMax <= lenCurrent && current[shiftIndex] > max[i]) { continue; } if (current[shiftIndex] > current[i]) { ok = true; break; } else if (current[shiftIndex] < current[i]) { break; } } if (ok) { result++; } */ }" B20948,"import java.io.BufferedReader; import java.io.FileReader; import java.util.StringTokenizer; public class REcycledNumbers { public static void main(String args[]) throws Exception { String line = """"; BufferedReader br = new BufferedReader(new FileReader(""/Users/ravipalacherla/Documents/workspace/CodeJam/src/input.txt"")); int T = Integer.parseInt(br.readLine()); int j=0; while((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line,"" ""); String strA = st.nextToken(); String strB = st.nextToken(); int intA = Integer.parseInt(strA); int intB = Integer.parseInt(strB); int count = 0; int intn = intA; while(intn < intB) { String strn = Integer.toString(intn); for(int i = strn.length()-1; i>0;i--) { String strm = strn.substring(i)+strn.substring(0,i); if(strm.charAt(0) == '0') continue; int intm = Integer.parseInt(strm); if( ((""""+intn).length() != (""""+intm).length()) || ((""""+intn).length() != (""""+intA).length())) continue; if(intn == intm) continue; if ( ( intA <= intn) && (intn < intm) && (intm <= intB) ) { // System.out.println(""intN is "" + intn + "" intM is ""+ intm); count ++; } } intn++; } j++; System.out.println(""Case #""+ j +"": ""+count); } } } " B21033,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class C { private void solve() throws IOException { int T = nextInt(); while (T-- > 0) { int A = nextInt(); int B = nextInt(); HashSet H = new HashSet(); for (int i = A; i <= B; i++) { String s = """" + i; for (int c = 0; c < s.length(); c++) { String a = s.substring(c); String b = s.substring(0, c); String c1 = a + b; int n = Integer.parseInt(c1); if (n != i && n <= B && n >= i + 1) { H.add(n + "" "" + i); } } } pf(); pl(H.size()); } } public static void main(String[] args) { new C().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new FileReader(""C.in"")); // reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; // writer = new PrintWriter(System.out); writer = new PrintWriter(""C_.out""); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } void p(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.flush(); writer.print(objects[i]); writer.flush(); } } void pl(Object... objects) { p(objects); writer.flush(); writer.println(); writer.flush(); } int cc; void pf() { writer.printf(""Case #%d: "", ++cc); writer.flush(); } } " B21450,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class main { /** * @param args */ public static void main(String[] args) { try { System.setOut(new PrintStream(new File(""C-large.out""))); Scanner sc = new Scanner(new File(""C-large.in"")); int T = sc.nextInt(); sc.nextLine(); for (int t = 1; t<=T; t++) { int y = 0; int A = sc.nextInt(); int B = sc.nextInt(); for (int n = A; n=10){ for(int n = A ; n <= B; n++){ char[] numChars = Integer.toString(n).toCharArray(); int maxLen = numChars.length; int firstDigitOfNum = Character.digit(numChars[0],10); Set checkDupSet = new HashSet(); for(int j = 1 ; j <= maxLen-1 ; j++){ int numAtJIindex = Character.digit(numChars[j], 10); if ( (numAtJIindexabsMaxFirstDigit) || (numAtJIindexn && m<=B ){ if(checkDupSet.add(m)){ //System.out.println(""Valid Number generated : ""+ n + "" : "" + m); count++; } } } } } //Print to file out.println( ""Case #"" + (i+1) + "": ""+count); //System.out.println( ""Case #"" + (i+1) + "": ""+count); } close(); } } " B22231,"import java.util.*; public class codejam { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int m=sc.nextInt(); int i; int j; int k; int x; int y; int l; int z; for(i=1;i<=m;i++) { int a=sc.nextInt(); int b=sc.nextInt(); int count=0; for(j=a;j<=b;j++) { x=j; l=Integer.toString(j).length(); int[] used=new int[l]; for(k=1;k<=l-1;k++) { // shift k digits y=(int)Math.pow(10, k)*(x%(int)Math.pow(10, l-k))+x/(int)Math.pow(10,l-k); y=y+2-2; if(x pair = new Hashtable (); String number = String.valueOf(n); for (int pos = 1; pos < number.length(); pos++) { String rotatedNumber = number.substring(pos, number.length()); if (!rotatedNumber.substring(0).equals(""0"")) { rotatedNumber += number.substring(0, pos); int m = Integer.parseInt(rotatedNumber); if (n < m && m <= B && pair.get(number+rotatedNumber) == null) pair.put(number+rotatedNumber, """"); } } output += pair.size(); } return output; } } " B22010,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class GCJ3 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub GCJ3 g = new GCJ3(); // System.out.println(); // long i1 = g.calculate(1, 9); // System.out.println(); // long i2 = g.calculate(10, 40); // System.out.println(); // long i3 = g.calculate(100, 500); // long i4 = g.calculate(1111, 2222); // long i5 = g.calculate(28, 93); // System.out.println(i1); // System.out.println(i2); // System.out.println(i3); // System.out.println(i4); // System.out.println(i5); try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream( ""C:/PROG/java/work/tc/src/gcj3.txt""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line int lineNum = 1; br.readLine(); while ((strLine = br.readLine()) != null) { // Print the content on the console // System.out.print(strLine+""\t""); String[] val = strLine.split(""\\s""); System.out.print(""Case #"" + lineNum + "": ""); System.out.println(g.calculate(Integer.valueOf(val[0]), Integer.valueOf(val[1]))); // System.out.println(); // System.out.println(strLine.charAt(0)); lineNum++; } // Close the input stream in.close(); } catch (Exception e) {// Catch exception if any e.printStackTrace(); } } public long calculate(int A, int B) { HashMap> map = new HashMap>(); String a = String.valueOf(A); String b = String.valueOf(B); if (a.length() == b.length() && a.length() > 1) { long count = 0; for (long i = A; i <= B; i++) { for (long l = 1; l < a.length(); l++) { long n = 0; long m = i; String nS = String.valueOf(m); String nS2 = nS.substring((int) l, a.length()) + nS.substring(0, (int) l); n = Long.valueOf(nS2); String nS3 = String.valueOf(n); if (n < m && nS3.length() == a.length() && A<=n && m<=B) { // System.out.println(n + "" "" + m); count++; if (map.get(nS3) == null){ HashSet s = new HashSet(); s.add(nS); map.put(nS3, s); }else { map.get(nS3).add(nS); } } } } long count2 = 0; for (String s : map.keySet()){ for (Object o: map.get(s).toArray()){ count2++; } } return count2; } return 0; } } " B20496,"package qualificationRound; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class P3 { public static int recycle(int j, int b) { int ret = 0; String old = Integer.toString(j); int size = old.length(); HashSet app = new HashSet(); for (int i = 1; i < size; ++i) { String tmp = old.substring(i) + old.substring(0, i); int num = Integer.parseInt(tmp); if (num <= b && num > j && !app.contains(tmp)) { ret++; app.add(tmp); } } return ret; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(""C-large.in"")); FileWriter fw = new FileWriter(""out.txt""); int t = Integer.parseInt(br.readLine()); for (int i = 1; i <= t; ++i) { String line = br.readLine(); String A = line.split("" "")[0]; String B = line.split("" "")[1]; int a = Integer.parseInt(A); int b = Integer.parseInt(B); int num = 0; for (int j = a; j <= b; ++j) { num += recycle(j, b); } fw.append(""Case #"" + i + "": "" + num + ""\n""); } br.close(); fw.close(); } } " B20419,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.StringTokenizer; /** * * @author parusnik */ public class Codejam { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(""input.txt"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""output.txt"")); int T = Integer.parseInt(br.readLine()); StringTokenizer st; String s1, s2; HashMap map = new HashMap(); for (int t = 1; t<=T; t++){ bw.write(""Case #"" + String.valueOf(t) + "": ""); st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); long d = 0; map.clear(); for (int i = a; i<=b; i++){ String s = String.valueOf(i); String str = s; for (int k = 0; k<10; k++){ s = s.substring(1, s.length()) + s.substring(0, 1); str = min (str, s); } int x = 0; if (map.containsKey(str)) x = map.get(str); map.put(str, x+1); } Collection col = map.values(); for (Integer i : col) { d+=(long) (i)*(i-1)/2; } bw.write(String.valueOf(d)); bw.newLine(); } br.close(); bw.close(); } static String min(String s1, String s2){ if (Integer.parseInt(s1) numbers = new HashSet(); StringBuilder sb = new StringBuilder(length); for(int permStart = 1; permStart < chars.length; permStart++) { sb.setLength(0); for(int j = 0; j < length; j++) { sb.append(chars[(permStart + j) % length]); } int newN = Integer.parseInt(sb.toString()); if (newN > n && newN <= max) { numbers.add(newN); } } return numbers.size(); } } " B22167," import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNo { Scanner in; BufferedWriter out; RecycledNo(String input, String output) throws Exception { in = new Scanner(new File(input)); FileWriter fstream = new FileWriter(output); out = new BufferedWriter(fstream); } private void solveAll() throws IOException { int T = in.nextInt(); int A, B; for (int test = 1; test <= T; test++) { A = in.nextInt(); B = in.nextInt(); out.write(""Case #"" + test + "": "" + solve(A, B)); out.newLine(); } } private int solve(int A, int B) { int count = 0, dig, pow10, lastPart, firstPart, exp10, newNo; int noDig = 1 + (int) Math.log10(A); Set set = new HashSet(); for (int n = A; n < B; n++) { set.clear(); pow10 = 1; lastPart = 0; firstPart = n; exp10 = (int) Math.pow(10, noDig - 1); for (dig = 1; dig < noDig; dig++) { lastPart = (firstPart % 10) * pow10 + lastPart; firstPart = firstPart / 10; pow10 *= 10; newNo = lastPart * exp10 + firstPart; exp10 /= 10; if ((int) Math.log10(newNo) != noDig - 1) { continue; } if (newNo > n && newNo <= B && !set.contains(newNo)) { set.add(newNo); count++; } } } return count; } public void close() throws IOException { in.close(); out.close(); } public static void main(String[] args) throws Exception { RecycledNo pb = new RecycledNo(""input.txt"", ""output.txt""); pb.solveAll(); pb.close(); } } " B20683,"import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new File(""data/C-large.in"")); PrintWriter out = new PrintWriter(new File(""data/output.txt"")); Integer count = sc.nextInt(); System.out.println(count); for (int i = 0; i < count; i++) { System.out.println(i); out.println(""Case #"" + (i + 1) + "": "" + countRecycled(sc.nextInt(), sc.nextInt())); } out.close(); } private static int countRecycled(Integer iA, Integer iB) { Set recycled = new HashSet(); if (iA.toString().length() != iB.toString().length()) { return 0; } System.out.println(); System.out.println(iA + "" "" + iB); System.out.println(); int sLength = iA.toString().length(); for (Integer n = iA; n <= iB; n++) { for (int c = 1; c <= sLength; c++) { String left = n.toString().substring(sLength - c, sLength); String right = n.toString().substring(0, sLength - c); String newNumber = left + right; // System.out.println(left + ""-"" + right + ""-"" + newNumber); int intNew = Integer.parseInt(newNumber); if (!newNumber.startsWith(""0"") // same length && intNew <= iB // within range && intNew > n // bigger than the other one ) { recycled.add(n.toString() + "","" + newNumber); } } } return recycled.size(); } } " B21536,"import java.io.*; import java.util.*; public class test { public static void main(String[] args) throws IOException { // Location of file to read functions aa = new functions(); File file = new File(""input.txt""); Writer output = new BufferedWriter(new FileWriter(""output.txt"")); int i = 1; int answer = 0; String A = """"; String B = """"; int j = 0; int n = 0; try { Scanner scanner = new Scanner(file); n = Integer.parseInt((String)scanner.nextLine()); while (scanner.hasNextLine()) { A = """"; B = """"; String line = scanner.nextLine(); while(line.charAt(j) != ' '){ A = A + line.charAt(j); j++; } j++; while(j < line.length()){ B = B + line.charAt(j); j++; } j = 0; answer = aa.solve(A,B); if(i < n) output.write(""Case #"" + i +"": ""+ answer +""\n""); else output.write(""Case #"" + i +"": ""+ answer); i++; } scanner.close(); output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } " B22002," import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class C { class Solver implements Runnable { int testId; boolean failed = false; int result = 0; Solver(int testId) { this.testId = testId; } String in, out = """"; ArrayList text = new ArrayList(); int a,b, p; private void readInput() { a = nextInt(); b = nextInt(); } int res; public void run() { //System.out.println(""SOLVING a = "" + a + "" b = "" + b ); for (int i=a; i999999) power = 1000000; //to save some CPU cycles else if (i>99999) power = 100000; else if (i>9999) power = 10000; else if (i>999) power = 1000; else if (i>99) power = 100; else if (i>9) power = 10; //k = i; int cycled = i; int right = i; while (right>9) { //13205 //51320 //ignore 05132 //20513 cycled /= 10; //shift >> cycled += (right % 10)*power; //add rightmost digit in front right /= 10; if (cycled == i ) right = 0; if ( cycled <= b && cycled > i) {// no leading 0s //System.out.println("" i = "" + i + "" cycled "" + (cycled) ); result++; } } } } private void printOutput() { if (failed) { writer.println(""0""); System.out.println(""FAILURE!!!""); } else { writer.println(String.format(""Case #%d: %d"", testId, result)); } } } // solve the problem here private void solve(){ int numTests = nextInt(); for (int testId = 1; testId <= numTests; testId++) { Solver solver = new Solver(testId); solver.readInput(); solver.run(); solver.printOutput(); } } BufferedReader reader; StringTokenizer tokenizer = null; PrintWriter writer; String encrypted = ""ejp mysljylc kd kxveddknmc re jsicpdrysi""+ ""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd""+ ""de kr kd eoya kw aej tysr re ujdr lkgc jvq""; String output = ""our language is impossible to understand""+ ""there are twenty six factorial possibilities""+ ""so it is okay if you want to just give upz""; char[] code = new char[256]; private void preparehalfcode() { for (int i = 0; i[] sets; void addShifts(int number) { String numStr = Integer.toString(number); int totalShifts = numStr.length() - 1; numStr += numStr; for(int i = 1; i <= totalShifts; i++) { String shiftStr = numStr.substring(i, i + totalShifts + 1); int shift = Integer.parseInt(shiftStr); if(shift > number && !sets[number].contains(shift)) { sets[number].add(shift); } } } void precalc() { sets = new ArrayList[limit + 1]; for(int i = 0; i < sets.length; i++) { sets[i] = new ArrayList(); } for(int n = 0; n <= limit; n++) { addShifts(n); Collections.sort(sets[n]); //out.println(n + "" "" + sets[n]); } } int solveOne(int l, int r) { int res = 0; for(int n = l; n <= r; n++) { for(int m : sets[n]) { if(m > r) { break; } else { ++res; } } } return res; } void solve() throws IOException { precalc(); int tests = nextInt(); for(int test = 1; test <= tests; test++) { out.printf(""Case #%d: %d\n"", test, solveOne(nextInt(), nextInt())); } } public static void main(String[] args) { new Timus().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); rnd = new Random(); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(42); } } String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }" B20950,"import java.util.ArrayList; import java.util.Scanner; public class Recycle2 { private static int solve(int L, int H) { class Slice { int L,H,mul,dig; Slice(int LL,int HH,int Mull,int digg) { L=LL; H=HH; mul=Mull; dig=digg; } public String toString() { return String.format(""%d-%d, %d(%d)"", L,H,mul,dig); } } ArrayList slices = new ArrayList(); int k = 10, d=1; int l = L, h=H; while(true) { if (l>=k) { k*=10;d++; continue; } if (h ps = new ArrayList(); int ret = 0; //System.out.println(slices); for(Slice slice:slices) { for(int i=slice.L; i<=slice.H; i++) { int n=i; ArrayList past = new ArrayList(); for (int j=0;j<(slice.dig-1);j++) { int dd=n%10; n=(n/10)+dd*slice.mul; if (n>i && n<=slice.H && !past.contains(n)) { //System.out.println(""checking ("" + i + "", "" + n + "")""); /*Pair p=new Pair(i,n); for(Pair c:ps) { if (c.equal(p)) { System.out.println(""Duplicate: "" + p); } } ps.add(p);*/ ret++; past.add(n); } } } } return ret; } /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int t=1;t<=T;t++) { int L = in.nextInt(); int H = in.nextInt(); System.out.printf(""Case #%d: %d%n"", t, solve(L,H)); } } } " B20857,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; /** * * @author Madhav */ public class RecycledNumbers { /** * @param args the command line arguments */ public static HashSet set; public static void main(String[] args) throws Exception { FileIO fileHandler = new FileIO(); int totalTestCases = Integer.parseInt(fileHandler.readLine()); for (int tc = 0; tc < totalTestCases; tc++) { set = new HashSet(); String input = fileHandler.readLine(); String nm[] = input.split("" ""); int start = Integer.valueOf(nm[0]); int end = Integer.valueOf(nm[1]); for(int i=start; i<=end; i++){ String currVal = String.valueOf(i); countPairs(currVal, start, end, nm); } fileHandler.writeLine(String.valueOf(set.size())); } fileHandler.closeFileIO(); } public static void countPairs(String input, int start, int end, String[] nm){ String clonedValue = new String(input); if(nm[1].length() <= 1) return; else{ int length = input.length(); for(int i=0; i= start && !rotated.equals(clonedValue) ){ if(Integer.valueOf(clonedValue) < Integer.valueOf(rotated)) set.add(clonedValue+""-""+rotated); else set.add(rotated+""-""+clonedValue); } input = rotated; } } } public static String rotate(String input){ return input.substring(1) + input.charAt(0); } } /* * File IO is used to read and Write - Keep it simple. */ class FileIO { private FileReader inFileReader; private FileWriter outFileWriter; private BufferedReader br = null; private BufferedWriter bw = null; private int lineNumber = 1; public FileIO() throws Exception { inFileReader = new FileReader(""C:\\CodeJam2012\\in.txt""); br = new BufferedReader(inFileReader); outFileWriter = new FileWriter(""C:\\CodeJam2012\\out.txt""); bw = new BufferedWriter(outFileWriter); } public FileIO(String in, String out) throws Exception { inFileReader = new FileReader(in); br = new BufferedReader(inFileReader); outFileWriter = new FileWriter(out); bw = new BufferedWriter(outFileWriter); } /* * This procedure returns null if all the rows are read from input file. */ public String readLine() throws Exception { return br.readLine(); } /* * This procedure writes a line to output file as per the google codejam * standard */ public void writeLine(String line) throws Exception { bw.write(""Case #"" + lineNumber + "": "" + line + ""\r\n""); lineNumber++; } public void closeFileIO() throws Exception { br.close(); bw.flush(); bw.close(); } }" B20872,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package competition; /** * * @author Sriram */ //import static java.lang.System.*; import java.util.*; import java.io.*; public class RecycledNumbers_GCJ_2012{ public static void main(String args[]) throws Exception { Scanner in = new Scanner(new java.io.FileInputStream(""f:\\input.in"")); PrintStream out = new PrintStream(new FileOutputStream(""f:\\output.out"")); int T = in.nextInt(); for(int zz=0; zz s = new HashSet(); int count = 0; for(int i=A;i<(B+1);i++) { int[] perm = rotations(i); for(int e: perm) { if((e>=A)&&(e<=B)&&(e>i)) { s.add(e); count++; } } } out.printf(""Case #%d: %d\n"",(zz+1),count); } } static int[] rotations(int n) { // Max places for small set: 4 // Max places for large set: 7 if((n/1000000)>0) { int a,b,c,d,e,f,g; g = n%10; n/=10; f = n%10; n/=10; e = n%10; n/=10; d = n%10; n/=10; c = n%10; n/=10; b = n%10; n/=10; a = n%10; return new int[]{(a*1000000+b*100000+c*10000+d*1000+e*100+f*10+g),(b*1000000+c*100000+d*10000+e*1000+f*100+g*10+a),(c*1000000+d*100000+e*10000+f*1000+g*100+a*10+b),(d*1000000+e*100000+f*10000+g*1000+a*100+b*10+c),(e*1000000+f*100000+g*10000+a*1000+b*100+c*10+d),(f*1000000+g*100000+a*10000+b*1000+c*100+d*10+e),(g*1000000+a*100000+b*10000+c*1000+d*100+e*10+f)}; } if((n/100000)>0) { int a,b,c,d,e,f; f = n%10; n/=10; e = n%10; n/=10; d = n%10; n/=10; c = n%10; n/=10; b = n%10; n/=10; a = n%10; return new int[]{(a*100000+b*10000+c*1000+d*100+e*10+f),(b*100000+c*10000+d*1000+e*100+f*10+a),(c*100000+d*10000+e*1000+f*100+a*10+b),(d*100000+e*10000+f*1000+a*100+b*10+c),(e*100000+f*10000+a*1000+b*100+c*10+d),(f*100000+a*10000+b*1000+c*100+d*10+e)}; } if(n/10000>0) { int a,b,c,d,e; e = n%10; n/=10; d = n%10; n/=10; c = n%10; n/=10; b = n%10; n/=10; a = n%10; return new int[]{(a*10000+b*1000+c*100+d*10+e),(b*10000+c*1000+d*100+e*10+a),(c*10000+d*1000+e*100+a*10+b),(d*10000+e*1000+a*100+b*10+c),(e*10000+a*1000+b*100+c*10+d)}; } if((n/1000>0)) { if (n == 1000) { return new int[]{1000, 100, 10, 1}; } int a,b,c,d; d = n%10; a = n/1000; b = (n-(a*1000))/100; c = ((n%100)-d)/10; return new int[]{(a*1000+b*100+c*10+d),(b*1000+c*100+d*10+a),(c*1000+d*100+a*10+b),(d*1000+a*100+b*10+c)}; } if ((n / 100) > 0) { if (n == 100) { return new int[]{100, 10, 1}; } int x, y, z; z = n%10; x = n/100; y = (n-(x*100)-z)/10; return new int[]{(x * 100) +(y * 10) + z, (y * 100 + z * 10 + x), (z * 100 + x * 10 + y)}; } if((n/10)>0) { if(n == 10) return new int[]{10,1}; int x,y; x = n/10; y = n%10; return new int[]{x*10+y,y*10+x}; } return new int[]{n}; } } " B21792,"import java.io.*; import java.util.*; public class C extends CodeJammer { public void process() throws IOException { long[] input = reader.readLongArray(); long a = input[0]; long b = input[1]; int digits = 0; long a1 = a; while (a1>0) { a1 /= 10; digits++; } long total = 0; for (long x=a; x<=b; x++) { total += count(x,a,b, digits); } output(total); } public long count(long x, long a, long b, int d) { Set s = new HashSet(); long y = x; for (int i=1; ix && y>=a && y<=b) s.add(y); } return s.size(); } public long rotate(long y, int d) { long digit = y%10; long rest = y/10; digit *= Math.pow(10,d-1); return digit + rest; } public static void main(String[] args) { C c = new C(); c.run(args); } } " B21455,"package codejam2012.qualification; import java.io.*; import java.math.BigInteger; import java.util.*; public class RecycledNumbers { // general part private static final String INPUT = ""src/main/resources""; private static final String OUTPUT = ""target/output""; private static final String ROUND = ""codejam2012/qualification""; private static final String SAMPLE = ""C-sample.in""; private static final String SMALL = ""C-small-attempt0.in""; private static final String LARGE = ""C-large.in""; private Scanner scanner; private PrintWriter writer; public RecycledNumbers(InputStream is, OutputStream os) { scanner = new Scanner(is); writer = new PrintWriter(os); } public void close() { scanner.close(); writer.flush(); } private static void runTest(String fileName, boolean isConsole) throws Exception { InputStream is = initInputStream(fileName); OutputStream os = initOutputStream(fileName, isConsole); RecycledNumbers problem = new RecycledNumbers(is, os); problem.solve(); problem.close(); doneStreams(isConsole, is, os); } private static InputStream initInputStream(String fileName) throws FileNotFoundException { File inputDir = new File(INPUT + File.separator + ROUND); File inputFile = new File(inputDir, fileName); InputStream is = new FileInputStream(inputFile); return is; } private static OutputStream initOutputStream(String fileName, boolean isConsole) throws FileNotFoundException { OutputStream os = System.out; if (isConsole) { System.out.println(fileName); System.out.println("" ---] cut [---""); } else { File outputDir = new File(OUTPUT + File.separator + ROUND); outputDir.mkdirs(); File outputFile = new File(outputDir, fileName.replace("".in"", "".out"")); os = new PrintStream(new FileOutputStream(outputFile)); } return os; } private static void doneStreams(boolean isConsole, InputStream is, OutputStream os) throws IOException { is.close(); if (isConsole) { System.out.println("" ---] cut [---""); System.out.println(""""); } else { os.close(); } } public static void main(String[] args) { try { runTest(SAMPLE, true); runTest(SMALL, false); runTest(LARGE, false); } catch (Exception e) { e.printStackTrace(); } } // problem part /** * Solve the problem */ public void solve() { int t = scanner.nextInt(); for (int i = 1; i <= t; i++) { writer.print(""Case #""); writer.print(i + "": ""); int a = scanner.nextInt(); int b = scanner.nextInt(); writer.println(solve(a, b)); } } private long solve(int a, int b) { long count = 0; for (int i=a; i<=b; i++) { char[] digits = getDigits(i); Set pairs = new HashSet(); for (int j=0; j b)) { continue; } if (number <= i) { continue; } pairs.add(new Pair(i, number)); } count += pairs.size(); } return count; } private char[] getDigits(int i) { String string = ((Integer)i).toString(); return string.toCharArray(); } private int getNumber(char[] digits) { String string = new String(digits); return Integer.parseInt(string); } private void shift(char digits[]) { char first = digits[0]; for (int i=1; i founds = new HashSet(); for (int num = a; num <= b; num++) { int tens = 10; int digits = ((int) Math.log10(num)); int inv = (int) Math.pow(10, digits); while (num / tens > 0) { int q = num / tens; int r = num % tens; int test = r * inv + q; if (test > num && test <= b) { founds.add("""" + num + ""|"" + test); } inv /= 10; tens *= 10; } } return founds.size(); } } " B20060,"package jamo; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RecycledNumbers { public static void main(String[] args) { List lines = readFromFile(""rnumbers.txt""); int number = Integer.parseInt(lines.get(0)); int a = 0; int b = 0; for (int i = 1; i <= number; i++) { String[] a_b = lines.get(i).split("" ""); a = Integer.parseInt(a_b[0]); b = Integer.parseInt(a_b[1]); System.out.println( ""Case #""+i+"": ""+checkPair(a, b)); } } public static int sumOfDigits(Integer number) { int sum = 0; String n = number.toString(); char[] digits = n.toCharArray(); for (int i = 0; i < digits.length; i++) { sum += Integer.parseInt(Character.toString(digits[i])); } return sum; } public static boolean same(String a, String b) { char[] _a = a.toCharArray(); char[] _b = b.toCharArray(); if (_a.length != _b.length) { return false; } Arrays.sort(_a); Arrays.sort(_b); String a_ = new String(_a); String b_ = new String(_b); return a_.equals(b_); } public static List iterations(Integer a) { char[] a_ = a.toString().toCharArray(); List out = new ArrayList(); String start = new String(a_); for (int i = 0; i < a_.length; i++) { if (out.contains(Integer.parseInt(start))) { } else { out.add(Integer.parseInt(start)); start = next(start); } } return out; } public static String next(String val) { char[] a_ = val.toCharArray(); char[] x = new char[a_.length]; for (int i = 1; i < a_.length; i++) { x[i - 1] = a_[i]; } x[a_.length - 1] = a_[0]; return new String(x); } public static int nextPair(Integer a) { char[] a_ = a.toString().toCharArray(); char[] x = new char[a_.length]; for (int i = 1; i < a_.length; i++) { x[i - 1] = a_[i]; } x[a_.length - 1] = a_[0]; return Integer.parseInt(new String(x)); } public static int checkPair(int a, int b) { int pairs = 0; int previ = 0; int prevnext = 0; int next = 0; if (b < 10) return 0; for (int i = a; i <= b; i++) { List its = iterations(i); for (int j = 0; j < its.size(); j++) { next = its.get(j); if (next <= b && next > i) { pairs += 1; } prevnext = next; } previ = i; } return pairs; } public static List readFromFile(String filename) { List lines = new ArrayList(); try { FileInputStream fstream = new FileInputStream(filename); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { lines.add(strLine); // System.out.println(strLine); } in.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } return lines; } } " B21164,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.common; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; /** * * @author jim */ public class FileLoader { public FileLoader() { } public ArrayList loadFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); String in; ArrayList lines = new ArrayList(); while ((in = br.readLine()) != null) { lines.add(in); } return lines; } } " B20923,"package Qualification_2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class RecycledNumbers { static BufferedReader in; static int A, B; static boolean[][] v; static HashSet hash; private static int get(int x) { int tmp = x; int c = 0; HashSet hh = new HashSet(); int len = (x + """").length(); int pow = (int) Math.pow(10, len); for (int i = 0; i < len - 1; i++) { boolean f = false; if (x % 10 == 0) f = true; x = ((x % 10) * pow + x) / 10; if (f) continue; if (x >= A && x <= B && tmp < x && len == (x + """").length()) { if (!hh.contains(x)) { hh.add(x); c++; } } } return c; } private static String solve() throws IOException { hash = new HashSet(); String s[] = in.readLine().split("" ""); long ans = 0; A = Integer.parseInt(s[0]); B = Integer.parseInt(s[1]); for (int i = A; i < B; i++) ans += get(i); return ans + """"; } public static void main(String[] args) throws IOException { in = new BufferedReader(new FileReader(""in.in"")); FileWriter out = new FileWriter(""out.out""); int t = Integer.parseInt(in.readLine()); for (int i = 1; i <= t; i++) { out.write(""Case #"" + i + "": "" + solve() + ""\n""); } in.close(); out.close(); } } " B22166,"/** * */ /** * @author Mostafa * */ public class ReNumbersLarge { public static String traverse(String x, int index) { char[] m = x.toCharArray(); int i; for (i=0; i= first && testme<= last && test[i].compareTo(s) != 0) { count++; } } } } return count; } } " B22116,"package googlejam; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; public class ProblemCLinear { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int numberOfCases = sc.nextInt(); sc.nextLine(); for (int i = 0; i < numberOfCases; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int sum = 0; Map> found = new HashMap>(); for (int n = A; n <= B; n++) { List rotations = getRotations(n); for (int j : rotations) { if ((n != j) && isInRange(j, A, B)) { int min = Math.min(n, j); int max = Math.max(n, j); Set foundForInt = found.get(min); if (foundForInt == null) { Set set = new HashSet(); set.add(max); found.put(min, set); sum++; } else if (!foundForInt.contains(max)) { foundForInt.add(max); sum++; } } } } System.out.println(String.format(""Case #%d: %d"", i + 1, sum)); } } private static boolean isInRange(int j, int a, int b) { return a <= j && j <= b; } private static List getRotations(int n) { String nString = Integer.toString(n); String doubleNString = nString + nString; List rotations = new ArrayList(); for (int i = 1; i < nString.length(); i++) { Integer valueOf = Integer.valueOf(doubleNString.substring(i, i + nString.length())); rotations.add(valueOf); } return rotations; } } " B21795,"package com.monochromeiguana.codejam; import com.google.common.collect.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Hello world! * */ public class Main { static BufferedReader in; static BufferedWriter out; static String inputFile = ""in.txt""; static String outputFile = ""outfile.txt""; private static class Parser { public final int index; public int answer = 0; public final int lBound; public final int uBound; public Parser(String line, int ix) { index = ix; List parts = Arrays.asList(line.split("" "")); lBound = Integer.parseInt(parts.get(0)); uBound = Integer.parseInt(parts.get(1)); // Multimap out = ArrayListMultimap.create(); for (int l = lBound; l < uBound; l++) { String thing = String.valueOf(l); Set friends = Sets.newHashSet(); for (int offset = 1; offset < thing.length(); offset++) { String friend = thing.substring(offset).concat(thing.substring(0, offset)); if (friend.startsWith(""0"")) { continue; } int friendly = Integer.parseInt(friend); if (friendly <= l || friendly > uBound) { continue; } friends.add(friend); } answer += friends.size(); } } public String output() { return ""Case #"" + index + "": "" + answer; } } public static void main(String[] args) throws Exception { in = new BufferedReader(new FileReader(inputFile)); out = new BufferedWriter(new FileWriter(outputFile)); try { String line = in.readLine(); int nbCases = Integer.parseInt(line); int index = 0; while ((line = in.readLine()) != null) { index++; Parser p = new Parser(line, index); out.write(p.output()); out.newLine(); } } finally { in.close(); } out.flush(); } } " B21678,"import java.util.Scanner; import java.io.*; public class Tobi { static String out="""",output=""""; public static void main(String[] args) { try { Scanner in = new Scanner(new File(""file.in"")); int n = in.nextInt(); int count = 1; String out = """"; while(in.hasNext()) { int a = in.nextInt(); int b = in.nextInt(); out += ""Case #""+count+"": ""+ activity(a,b)+""\n""; count++; try { File file = new File(""output.dat""); PrintWriter output = new PrintWriter(file); output.write(out); output.close(); } catch(Exception exception) { System.out.println(""ERROR""); } } }catch(Exception exception){ System.out.println(""ERROR""); } System.out.println(""DONE""); } public static int activity(int A, int B) { int counter = 0; for(int i = A; i <= B; i++) { String all[] = myGenerator(Integer.toString(i)); for(int j = 0; j < all.length; j++) { if((i < Integer.parseInt(all[j])) && (Integer.parseInt(all[j]) <= B)) { counter++; } } } return counter; } public static String[] myGenerator(String word) { String[] all = new String[word.length()-1];//changed frm len - 1 for(int i = 0; i < all.length; i++) { all[i] = generate(word); word = generate(word); } return all; } public static String generate(String w) { String ans = w.substring(w.length()-1); for(int i = 0; i < w.length()-1; i++) { ans += w.substring(i,i+1); } return ans; } } " B21521,"import java.io.*; import java.util.*; public class C { BufferedReader read; BufferedWriter write; public static void main(String args[]) { try { new C().init(""C-large""); } catch (Exception ex) { System.out.println(""error occured ""+ex); // Logger.getLogger(Sample.class.getName()).log(Level.SEVERE, null, ex); } } void init(String name) throws Exception { read=new BufferedReader(new FileReader(new File(name+"".in""))); write=new BufferedWriter(new FileWriter(new File(name+"".out""))); String x=""""; try { x = read.readLine(); int n = Integer.parseInt(x); for(int i=0;itree; void result(String x,int j) throws Exception { // tree=new TreeSet(); String ss[]=x.split("" ""); int a=Integer.parseInt(ss[0].trim()); int b=Integer.parseInt(ss[1].trim()); // System.out.println(a+"" ""+b); int count=0; for(int i=a;i<=b;i++) { // tree.add(i); count+=count(i,a,b); } System.out.println(""Case #""+(j+1)+"": ""+count); write.write(""Case #""+(j+1)+"": ""+count+""\n""); } int count(int p,int a,int b) { TreeSett=new TreeSet(); String s=""""+p; s=s.trim(); int l=s.length(); for(int i=1;i=a) { // System.out.print(""\t""+p+"" ""+p1); t.add(p1); } } return t.size(); } } " B20299,"package qualification2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class C { private final String f = ""src\\qualification2012\\C-large""; private BufferedReader in; private PrintWriter out; private StringTokenizer token; private C() throws IOException { in = new BufferedReader(new FileReader(f+"".in"")); out = new PrintWriter(f + "".out""); eat(""""); int t = nextInt(); for (int i = 1; i <= t; i++) { write(""Case #""+i+"": ""); solve(); } in.close(); out.close(); } private void solve() throws IOException { int a = nextInt(); int b = nextInt(); if (a < 10){ write(0 + ""\n""); return; } int pair = 0; for (int i = a; i <= b; i++) { char[] digits = Integer.toString(i).toCharArray(); char[] tmp = new char[digits.length]; ArrayList al = new ArrayList<>(); for (int start = 1; start < digits.length; start++) { int number = 0; for(int x = 0; x + 1 < digits.length; x++) { tmp[x] = digits[x + 1]; number += Math.pow(10, (digits.length - x - 1)) * (digits[x + 1] - '0'); } tmp[digits.length - 1] = digits[0]; number += digits[0] - '0'; digits = tmp.clone(); if (number >= a && number <= b && i > number) { if(!al.contains(number)) { al.add(number); pair++; } } } } write(pair + ""\n""); } private String nextLine() throws IOException { return in.readLine(); } private String next() throws IOException { while (!token.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return token.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } private long nextLong() throws IOException { return Long.parseLong(next()); } private void eat(String s) { token = new StringTokenizer(s); } private void write(String s) { System.out.print(s); out.print(s); } public static void main(String[] args) { try { new C(); } catch (IOException e) { e.printStackTrace(); } } } " B21307,"import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; public class gcj2012PBS { public String recycle(String num, int cycle) { if (cycle == 0) { return num; } String s = String.valueOf(num); int len = s.length(); String temp = s.substring(len-1,len); String temp2 = s.substring(0,len-1); String result = temp+ temp2; return recycle(result, cycle-1); } public static void main(String[] args) { gcj2012PBS gc = new gcj2012PBS(); String filenameIn = ""C-large.in""; String filenameOut = ""C-large.out""; FileIn fi = new FileIn(filenameIn); String s = fi.getString(); String ss[] = s.split(""\n""); StringBuilder sb = new StringBuilder(); int z = Integer.valueOf(ss[0]); boolean flag[] = new boolean[2000000]; for (int i = 1; i <= z; i++) { Arrays.fill(flag, false); String tt[] = ss[i].split("" ""); int a = Integer.valueOf(tt[0]); int b = Integer.valueOf(tt[1]); int answer = 0; String A = """"; String B = """"; A = String.valueOf(a); //桁数の取得 int keta = A.length(); if (keta == 1) { sb.append(""Case #""); sb.append(i); sb.append("": ""); sb.append(answer); sb.append(""\n""); continue; } String ppp; String ooo; for(int x = a; x <= b; x ++) { boolean aaaaa=false; ppp = String.valueOf(x); ooo = ppp.substring(0, 1); for (int ok = 1; ok < keta ; ok++) { if(!ooo.equals(ppp.substring(ok,ok+1))) { aaaaa = true; break; } } if(!aaaaa) { flag[x] = true; } } for (int x = a; x <= b; x++) { ArrayList list = new ArrayList(); for(int k = 1; k < keta; k++) { int result = Integer.valueOf(gc.recycle(String.valueOf(x), k)); // if(result == 1212) { // int aa=1; // } if (!flag[x]){ if(x >= a && result <= b && x < result) { if(list.indexOf(result) != -1) { continue; } list.add(result); answer++; // if(i == 4) { // System.out.println(x + "" : "" + result); // } //flag[x] = true; //flag[result]=true; // for(int k2 = 1; k2 < keta; k2++) { // result = Integer.valueOf(gc.recycle(String.valueOf(x), k2)); // if(result >= a && result <= b && x < result) { // flag[result] = true; // } // } } } } } sb.append(""Case #""); sb.append(i); sb.append("": ""); sb.append(answer); sb.append(""\n""); System.out.println(i); } new FileOut(filenameOut, sb.toString()); } } " B20558,"import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Task3 { private int parseLine(Scanner scanner) throws IOException { int A = scanner.nextInt(); int B = scanner.nextInt(); int c = ("""" + A).length(); int pow = (int) Math.pow(10, c - 1); int count = 0; for (int m = A; m < B; m++) { int tmpN = m; Set set = new HashSet(); for (int j = 0; j < c - 1; j++) { tmpN = tmpN / 10 + (tmpN % 10) * pow; if (m < tmpN && tmpN <= B && !set.contains(tmpN)) { set.add(tmpN); count++; } } } return count; } public void run(Scanner scanner, Writer bw) throws IOException { int rowCnt = scanner.nextInt(); for (int i = 0; i < rowCnt; i++) { bw.write(""Case #"" + (i + 1) + "": "" + parseLine(scanner) + '\n'); } bw.flush(); bw.close(); } /** * @param args */ public static void main(String[] args) { try { Scanner scanner = new Scanner(System.in); scanner.useDelimiter("" |\r\n|\n|\r""); new Task3().run(new Scanner(System.in), new OutputStreamWriter(System.out)); } catch (IOException e) { return; } } } " B20195," import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.CharBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { public static HashMap> mem = new HashMap>(); public static void main(String[] args) throws IOException { String inputName; Scanner in = new Scanner(System.in); System.out.print(""Enter input file name: ""); inputName = in.nextLine(); StringBuilder output = new StringBuilder(1000); QueueMagic data = new QueueMagic(new FileReader(new File(inputName))); int caseNum =1; data.next(); do { int A = data.nextInt(); int B = data.nextInt(); ArrayList recycled = new ArrayList(); for(int i = A; i <= B; i++) { String s = String.valueOf(i); recycled.addAll(findRecyled(s, i, B)); } String caseout = String.format(""Case #%d: %d\n"", caseNum++, recycled.size()); output.append(caseout); System.out.print(caseout); } while (data.isNotDepleted()); //System.out.print(output); PrintWriter writer = new PrintWriter(new File(inputName+"".output"")); writer.print(output); writer.flush(); writer.close(); } public static HashSet findRecyled(String s, int n, int B) { //if(mem.containsKey(s)) // return mem.get(s); HashSet ans = new HashSet(); for(int i = 0; i < s.length()-1; i++) { String r = s.substring(i+1)+s.substring(0, i+1); int m = Integer.parseInt(r); if(n < m && m <= B) ans.add(r); } mem.put(s, ans); return ans; } } /** * Makes parsing input from Uva problems easy. * @author Adam Anderson */ class QueueMagic{ private Queue data; private BufferedReader in; private String delimiter; private String secondary_delimiter; /** * The default delimiter is \\s+ * This is at least one or more white space characters */ public final static String DEFAULT_DELIMITER = ""\\s+""; public final static String DEFUALT_SECONDARY_DELIMITER = ""\\s+""; /** * Defaults to reading System.in * Defaults to using the following delimiter: \\s+ * @throws IOException */ public QueueMagic() throws IOException { this(new InputStreamReader(System.in), DEFAULT_DELIMITER); } /** * Build QueueMagic from any reader * Defaults to using the following delimiter: \\s+ * @param reader * @throws IOException */ public QueueMagic(Reader reader) throws IOException { this(reader, DEFAULT_DELIMITER); } /** * Defaults to reading from System.in * @param delimiter * @throws IOException */ public QueueMagic(String regex) throws IOException { this(new InputStreamReader(System.in), regex); } public QueueMagic(Reader reader, String regex) throws IOException { this.in = new BufferedReader(reader); this.delimiter = regex; readData(); } /** * Reads in all bytes in the stream and splits it into string tokens based on the delimiter. * @throws IOException */ private void readData() throws IOException { CharBuffer buf = CharBuffer.allocate(10000); StringBuilder input = new StringBuilder(10000); do { this.in.read(buf); input.append(buf.flip().toString()); }while(this.in.ready()); String [] parts = input.toString().split(this.delimiter); this.data = new LinkedList(Arrays.asList(parts)); close(); } /** * Returns the next string * @return */ public String next() { return data.poll(); } public Integer nextInt() { return Integer.parseInt(next()); } public Short nextShort() { return Short.parseShort(next()); } public Byte nextByte() { return Byte.parseByte(next()); } public Long nextLong() { return Long.parseLong(next()); } public Float nextFloat() { return Float.parseFloat(next()); } public Double nextDouble() { return Double.parseDouble(next()); } public BigInteger nextBigInt() { return new BigInteger(next()); } public BigDecimal nextBigDec() { return new BigDecimal(next()); } /** * Returns the next token split by the secondary delimiter. * @return */ public String [] arrayString() { return next().split(this.secondary_delimiter); } /** * Split by the secondary delimiter * @return */ public Byte [] arrayByte() { String [] parts = arrayString(); Byte [] vals = new Byte[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = Byte.parseByte(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public Short [] arrayShort() { String [] parts = arrayString(); Short [] vals = new Short[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = Short.parseShort(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public Integer [] arrayInt() { String [] parts = arrayString(); Integer [] vals = new Integer[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = Integer.parseInt(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public Long [] arrayLong() { String [] parts = arrayString(); Long [] vals = new Long[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = Long.parseLong(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public Float [] arrayFloat() { String [] parts = arrayString(); Float [] vals = new Float[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = Float.parseFloat(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public Double [] arrayDouble() { String [] parts = arrayString(); Double [] vals = new Double[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = Double.parseDouble(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public BigInteger [] arrayBigInteger() { String [] parts = arrayString(); BigInteger [] vals = new BigInteger[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = new BigInteger(parts[i]); } return vals; } /** * Split by the secondary delimiter * @return */ public BigDecimal[] arrayBigDecimal() { String [] parts = arrayString(); BigDecimal [] vals = new BigDecimal[parts.length]; for (int i = 0; i < vals.length; i++) { vals[i] = new BigDecimal(parts[i]); } return vals; } public ArrayList listString() { return new ArrayList(Arrays.asList(arrayString())); } public ArrayList listByte() { return new ArrayList(Arrays.asList(arrayByte())); } public ArrayList listShort() { return new ArrayList(Arrays.asList(arrayShort())); } public ArrayList listInt() { return new ArrayList(Arrays.asList(arrayInt())); } public ArrayList listLong() { return new ArrayList(Arrays.asList(arrayLong())); } public ArrayList listFloat() { return new ArrayList(Arrays.asList(arrayFloat())); } public ArrayList listDouble() { return new ArrayList(Arrays.asList(arrayDouble())); } public ArrayList listBigInteger() { return new ArrayList(Arrays.asList(arrayBigInteger())); } public ArrayList listBigDecimal() { return new ArrayList(Arrays.asList(arrayBigDecimal())); } /** * @return true if there is no more data */ public boolean isDepleted() { return this.data.isEmpty(); } /** * * @return true if there is data */ public boolean isNotDepleted() { return !isDepleted(); } /** * The primary delimiter is used to split the data into tokens * @return */ public String getDelimter() { return this.delimiter; } /** * The primary delimiter is used to split the data into tokens * @param regex */ public void setDelimiter(String regex) { this.delimiter = regex; } /** * The secondary delimiter is used to split tokens into lists/arrays * @return */ public String getSecondaryDelimiter() { return this.secondary_delimiter; } /** * The secondary delimiter is used to split tokens into lists/arrays * @param regex */ public void setSecondaryDelimiter(String regex) { this.secondary_delimiter = regex; } public void close() throws IOException { if(this.in != null) { in.close(); } } }" B21958,"import java.io.File; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Solver { private final static String DIR_PATH = ""e:\\jam\\""; private final static String IN_FILE_NAME = ""C-large.in""; private final static String OUT_FILE_NAME = IN_FILE_NAME.replaceAll(""\\..*$"", "".out""); private final static File sInFile = new File(DIR_PATH, IN_FILE_NAME); private final static File sOutFile = new File(DIR_PATH, OUT_FILE_NAME); private final PrintStream mOut; private final Scanner mScanner; private static class ProxyOutputStream extends FilterOutputStream { public ProxyOutputStream(OutputStream out) { super(out); } @Override public void write(byte[] b, int off, int len) throws IOException { System.out.write(b, off, len); super.write(b, off, len); } } public static void main(String[] args) { try { Solver solver = new Solver(sInFile, sOutFile); solver.solve(); } catch(IOException ex) { ex.printStackTrace(); } } public Solver(File inFile, File outFile) throws IOException { mScanner = new Scanner(inFile); mOut = new PrintStream(new ProxyOutputStream(new FileOutputStream(outFile))); } private void printSolution(int no, String solution) { if(no == 0) { throw new IllegalArgumentException(""Solution number is 0! Should start with 1!""); } mOut.println(String.format(""Case #%d: %s"", no, solution)); } private void solve() throws IOException { int problemsCount = mScanner.nextInt(); mScanner.nextLine(); for(int i = 0; i < problemsCount; i++) { long min = mScanner.nextLong(); long max = mScanner.nextLong(); String solution = Long.toString(solve(min, max)); printSolution(i + 1, solution); } } int convert(int [] digits, int d0, long number) { while(number > 0) { digits[d0] = (int)(number % 10); d0--; number /= 10; } return d0 + 1; } long convertToInt(int [] digits, int d0, int dlen) { long number = 0; for(int i = 0; i < dlen; i++) { number = number * 10 + digits[d0 + i]; } return number; } //true if r > d boolean isGreater(int [] r, int r0, int [] d, int d0, int len) { for(int i = 0; i < len; i++) { int delta = r[r0 + i] - d[d0 + i]; if(delta > 0) { return true; } else if(delta < 0) { return false; } } return false; } private long solve(long min, long max) { if(max < 10) { return 0; } long counter = 0; int [] max_digits = new int[8]; int max_d0 = convert(max_digits, max_digits.length - 1, max); int [] digits = new int [7 + 1 + 7]; int d0 = 7;//points to least significant digit in array Set unique = new HashSet(); for(long number = min; number <= max; number++) { unique.clear(); /* convert number to array */ int n0 = convert(digits, d0, number); int dlen = d0 - n0 + 1; /* duplicate digits */ for(int i = 0; i < dlen - 1; i++) { digits[d0 + i + 1] = digits[n0 + i]; } /* count recycled numbers */ boolean printed = false; for(int i = 0; i < dlen - 1; i++) { int r0 = n0 + i + 1;//r0 for current recycled number //print(digits, r0, dlen); if(digits[r0] == 0) { //System.out.println("" - nope, leading zero.""); continue;//invalid case } /* is recycled number greater than original one? */ boolean greater = isGreater(digits, r0, digits, n0, dlen); /* is recycled number grater than max? */ boolean valid = !isGreater(digits, r0, max_digits, max_d0, dlen); if(greater && valid) { //System.out.println("" - yes.""); if(!printed) { //print(digits, n0, dlen); //System.out.println("" => ""); printed = true; } //System.out.print("" ""); //print(digits, r0, dlen); unique.add(convertToInt(digits, r0, dlen)); } else { if(!greater) { //System.out.println("" - nope, not greater than original.""); } else { //System.out.println("" - nope, greater than max.""); } } } if(printed) { //System.out.println(); } counter+=unique.size(); //System.out.println(""----""); } return counter; } void print(int [] digits, int d0, int dlen) { for(int i = d0; i < d0 + dlen; i++) { System.out.print(digits[i]); } } void println(int [] digits, int d0, int dlen) { print(digits, d0, dlen); System.out.println(); } } " B21758," package grn; import java.io.*; import java.util.ArrayList; /** * * @author alexho */ public class GRN { private static int [] result; private static ArrayList permutation = new ArrayList(); private void readInput (String infn) throws FileNotFoundException, IOException { String line = null; int testCases = 0; BufferedReader bufRdr = null; String delimiter = "" ""; File file = new File(infn); bufRdr = new BufferedReader(new FileReader(file)); testCases = Integer.valueOf(bufRdr.readLine()); GRN.result = new int [testCases]; for (int i=0;i n && !GRN.usedperm.contains(alphabet) && !GRN.usedperm.contains(GRN.permutation.get(i))) { if (m <= B && m > n ) { // GRN.usedperm.add(alphabet); // GRN.usedperm.add(GRN.permutation.get(i)); GRN.result[ind]++; } } } private void output (String outfn) throws IOException { PrintWriter out = new PrintWriter(new FileWriter(outfn)); for (int i=0;i 0 || digits[i] > 0)) { // used[i] = tick; // perm[n] = i; // rec(n + 1); // used[i] = tick - 1; // } // } // } // } void updateAns() { int num = getCurrentNum(); if (curNum < num && num <= rightBorder) validNums.add(num); } int getCurrentNum() { int ret = 0; int pow = 1; for (int i = curLen - 1; i >= 0; i--) { ret += pow * digits[perm[i]]; pow *= 10; } return ret; } class StupidSet { final int MAXN = 10000000; int[] used = new int [MAXN + 1]; int tick = 1; int size = 0; void clear() { tick++; size = 0; } void add(int x) { if (used[x] != tick) { used[x] = tick; size++; } } int size() { return size; } } /*************************************************************** * Input **************************************************************/ BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""""); String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } int[] nextIntArray(int size) throws IOException { int[] ret = new int [size]; for (int i = 0; i < size; i++) ret[i] = nextInt(); return ret; } long[] nextLongArray(int size) throws IOException { long[] ret = new long [size]; for (int i = 0; i < size; i++) ret[i] = nextLong(); return ret; } double[] nextDoubleArray(int size) throws IOException { double[] ret = new double [size]; for (int i = 0; i < size; i++) ret[i] = nextDouble(); return ret; } String nextLine() throws IOException { st = new StringTokenizer(""""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } /*************************************************************** * Output **************************************************************/ void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { if (array == null || array.length == 0) return; boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings(""rawtypes"") void printCollection(Collection collection) { if (collection == null || collection.isEmpty()) return; boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } /*************************************************************** * Utility **************************************************************/ static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + ""/"" + (Runtime.getRuntime().totalMemory() >> 20) + "" MB""; } static void checkMemory() { System.err.println(memoryStatus()); } static long prevTimeStamp = Long.MIN_VALUE; static void updateTimer() { prevTimeStamp = System.currentTimeMillis(); } static long elapsedTime() { return (System.currentTimeMillis() - prevTimeStamp); } static void checkTimer() { System.err.println(elapsedTime() + "" ms""); } } " B21432,"package jp.funnything.competition.util; import java.math.BigDecimal; /** * Utility for BigDeciaml */ public class BD { public static BigDecimal ZERO = BigDecimal.ZERO; public static BigDecimal ONE = BigDecimal.ONE; public static BigDecimal add( final BigDecimal x , final BigDecimal y ) { return x.add( y ); } public static BigDecimal add( final BigDecimal x , final double y ) { return add( x , v( y ) ); } public static BigDecimal add( final double x , final BigDecimal y ) { return add( v( x ) , y ); } public static int cmp( final BigDecimal x , final BigDecimal y ) { return x.compareTo( y ); } public static int cmp( final BigDecimal x , final double y ) { return cmp( x , v( y ) ); } public static int cmp( final double x , final BigDecimal y ) { return cmp( v( x ) , y ); } public static BigDecimal div( final BigDecimal x , final BigDecimal y ) { return x.divide( y ); } public static BigDecimal div( final BigDecimal x , final double y ) { return div( x , v( y ) ); } public static BigDecimal div( final double x , final BigDecimal y ) { return div( v( x ) , y ); } public static BigDecimal mul( final BigDecimal x , final BigDecimal y ) { return x.multiply( y ); } public static BigDecimal mul( final BigDecimal x , final double y ) { return mul( x , v( y ) ); } public static BigDecimal mul( final double x , final BigDecimal y ) { return mul( v( x ) , y ); } public static BigDecimal sub( final BigDecimal x , final BigDecimal y ) { return x.subtract( y ); } public static BigDecimal sub( final BigDecimal x , final double y ) { return sub( x , v( y ) ); } public static BigDecimal sub( final double x , final BigDecimal y ) { return sub( v( x ) , y ); } public static BigDecimal v( final double value ) { return BigDecimal.valueOf( value ); } } " B21771,"import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new FileReader(""C-large.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""outputC2.txt"")); int caseCount = sc.nextInt(); sc.nextLine(); int a, b, count, c, k, l; for (int caseNum = 0; caseNum < caseCount; caseNum++) { a = sc.nextInt(); b = sc.nextInt(); count = 0; for (int i = a; i <= b; i++) { k = 10; l = (int) Math.pow(10, (int) Math.log10(i)); HashSet pairs = new HashSet(); while (k < i) { c = (i % k)*l + i/k; if (i < c && c <= b) { pairs.add(c); } k *= 10; l /= 10; } count += pairs.size(); } pw.write(""Case #"" + (caseNum + 1) + "": ""); pw.write(count + ""\n""); } pw.flush(); pw.close(); sc.close(); } } " B21069,"import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; // Qualification Round 2012 // Problem C public class RecycledNumbers { public static void main(String[] args) { Scanner sc = null; try { sc = new Scanner(new File(""C-large.in"")); } catch (FileNotFoundException e) { e.printStackTrace(); } PrintStream output = null; try { output = new PrintStream(new File(""C-large.out"")); } catch (IOException e) { e.printStackTrace(); } int cases = sc.nextInt(); sc.nextLine(); for(int c = 0; c < cases; c++){ int A = sc.nextInt(); int B = sc.nextInt(); HashSet pairs = new HashSet(); for(int n = A; n <= B; n++){ String testn = n + """"; String testm = testn; int l = testn.length(); for(int i = 0; i < l - 1; i++){ testm = testm.charAt(l - 1) + testm.substring(0, l - 1); int m = Integer.parseInt(testm); if(n < m && m <= B && m > A){ pairs.add(n + "" "" + m); } } } System.out.printf(""Case #%d: %s\n"", c + 1, pairs.size()); output.printf(""Case #%d: %s\n"", c + 1, pairs.size()); } } } " B20247,"import java.awt.Point; import java.awt.geom.Point2D; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; public class q3 { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(""""); public static String next() throws Exception { while (true) { if (st.hasMoreTokens()) return st.nextToken(); String s = br.readLine(); if (s == null) return null; st = new StringTokenizer(s); } } public static int nextInt() throws Exception { return Integer.parseInt(next()); } public static void main(String[] args) throws Exception { int T = nextInt(); for(int t = 1 ; t <=T ; t++){ HashSet set = new HashSet(); set.add(new Point(1,2)); int A = nextInt(); int B = nextInt(); int n = (""""+A).length(); int count = 0; for(int i = A ; i <= B ; i ++){ int d = 10; int c = 1; while(i/d >0){ int temp = i/d; temp += (i%d) * Math.pow(10, n-c); if(temp<=B && temp > i){ if(set.contains(new Point(i , temp))){ // System.out.println(""asdas""); } else count++; //if((i + "" "" + temp).length() != 9) // System.out.println(""asd""); //System.out.println(i + "" "" + temp); } d *= 10; c++; } } System.out.println(""Case #"" + t + "": ""+count ); } } } " B22158,"package com.vp.impl; import java.util.HashSet; import java.util.Set; import com.vp.iface.Problem; public class RecycledNumbers implements Problem { private static int iUpperLimit; private static int iLowerLimit; private static int[] iVisited; private static Set removeDuplicates; @Override public String solve(String[] dataset) { String strReturnValue =""""; String strRecycledNos = dataset[0]; String strRecycledNosArr[] = strRecycledNos.split("" ""); iLowerLimit = Integer.parseInt(strRecycledNosArr[0]); iUpperLimit = Integer.parseInt(strRecycledNosArr[1]); iVisited = new int[iUpperLimit+1]; removeDuplicates = new HashSet(); for(int i=iLowerLimit;i<=iUpperLimit;i++) { if(iVisited[i] == 0 && i > 9) { findMatchingNumbers(i); } } System.out.println(""Output : "" +removeDuplicates.size()); return strReturnValue + removeDuplicates.size(); } private void findMatchingNumbers(int iVar) { String strVar = """"+iVar; for(int i=1; i < (strVar.length());i++) { String strSuffix = strVar.substring(0,strVar.length() -i); String strPrefix = strVar.substring(strVar.length() -i,strVar.length()); int iNewNo = Integer.parseInt(strPrefix + strSuffix); if (iNewNo >= iLowerLimit && iNewNo <= iUpperLimit && iVar != iNewNo && iVisited[iNewNo] ==0 ) { removeDuplicates.add(iVar + "" : "" + iNewNo); iVisited[iVar] = 1; } } } } " B20508,"package qualification; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Scanner; public class RecycledNumber { public static void main(String[] args) throws IOException { String inputFile = ""C-large.in""; Scanner input = new Scanner(new FileInputStream(inputFile)); FileOutputStream out = new FileOutputStream(inputFile + "".out"", false); slove(input, out); out.close(); } private static void slove(Scanner input, FileOutputStream out) throws IOException { int cases = input.nextInt(); for (int caseOrder = 1; caseOrder <= cases; caseOrder++) { int a = input.nextInt(); int b = input.nextInt(); long r = 0; for (int i = a; i <= b; i++) { for (int x: getRecycled(i)) { if (x >= a && x <= b && i < x && x > 0) { // System.out.printf(""(%d, %d)\n"", i, x); r++; } } } String outline = String.format(""Case #%d: %d\r\n"", caseOrder, r); System.out.print(outline); out.write(outline.getBytes()); } } private static Collection getRecycled(int a) { String s = Integer.toString(a); HashSet ret = new HashSet(); for (int i = 1; i < s.length(); i++) { String s2 = s.substring(i) + s.substring(0, i); if (!s2.startsWith(""0"")) { ret.add(Integer.parseInt(s2)); } } return ret; } } " B21193,"import java.util.Scanner; public class QuestionB extends Question{ private int N; private int S; private int p; private int[] dancers; public QuestionB(Result result, Counter counter) { super(result, counter); } @Override public void readInput(Scanner scanner) { N = scanner.nextInt(); S = scanner.nextInt(); p = scanner.nextInt(); dancers = new int[N]; for (int i = 0; i < N; i++) { dancers[i] = scanner.nextInt(); } } @Override public String solution() { int counter = 0; for (int i = 0; i < N; i++) { if (dancers[i]>=3*p-Math.min(2,dancers[i]*2)) counter++; else if (dancers[i]>=3*p-Math.min(4,dancers[i]*2) && S>0) { S--; counter++; } } return Integer.toString(counter); } } " B21943,"import java.io.*; class recycle { public static void main(String args[])throws Exception { FileReader R=new FileReader(""input.txt""); PrintWriter W=new PrintWriter(new FileWriter(""output.txt"")); BufferedReader ds=new BufferedReader(R); long n=Long.parseLong(ds.readLine()); for(long j=1;j<=n;j++) { long i; String l=ds.readLine(); for(i=0;iLong.parseLong(x) && Long.parseLong(y)<=b) cnt++; p++; y=x.substring((int)p)+x.substring(0,(int)p); } } W.println(""Case #""+j+"": ""+cnt); } W.close(); } }" B20201," import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; public class C { static int countBiggerRotated(int n, int B) { int count = 0; LinkedList l = new LinkedList(); int t = n; while(t > 0) { l.addFirst(t%10); t/=10; } HashSet hs = new HashSet(); for (int i = 0; i < l.size(); i++) { int m = 0; for (int j = i; j < l.size(); j++) { m = 10*m + l.get(j); } for (int j = 0; j < i; j++) { m = 10*m + l.get(j); } if(m > n && m <= B && !hs.contains(m)) { ++count; hs.add(m); // System.out.println(""("" + n + "","" + m + "")""); } } return count; } /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int i = 1; i <= T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int count = 0; for (int j = A; j < B; j++) { count += countBiggerRotated(j, B); } System.out.println(""Case #"" + i + "": "" + count); } } } " B21529,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.*; import java.util.HashSet; import java.util.StringTokenizer; /** * * @author Кирилл и Папа */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(""input.in""))); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(""output.txt""))); int n = Integer.parseInt(br.readLine()); for (int testCaseI = 0; testCaseI < n; testCaseI++) { StringTokenizer st = new StringTokenizer(br.readLine()); String aStr = st.nextToken(); String bStr = st.nextToken(); int a = Integer.parseInt(aStr); int b = Integer.parseInt(bStr); int res = 0; for (int currA = a; currA <= b; currA++) { String currAStr = Integer.toString(currA); HashSet hashRes = new HashSet(); for (int p = 1; p < aStr.length(); p++) { String moved = currAStr.substring(p) + currAStr.substring(0, p); if ((moved.compareTo(bStr) <= 0) && (moved.compareTo(currAStr) > 0)) { hashRes.add(moved); } } res += hashRes.size(); } bw.write(""Case #"" + (testCaseI + 1) + "": "" + res); bw.newLine(); } br.close(); bw.close(); } catch (Exception ex) { ex.printStackTrace(); } } } " B21609,"import java.io.*; import java.util.*; public class RecycledNumbers { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static Scanner sc = new Scanner(br); public static void main ( String [] args ) throws IOException { int N = Integer.parseInt(br.readLine()); for(int i = 0;i < N; i++) { System.out.print(""Case #"" + (i+1) + "": ""); new RecycledNumbers().cal(); } } private void cal() throws IOException { int A = sc.nextInt(); int B = sc.nextInt(); String aString = Integer.toString(A); int length = aString.length(); String testString; String testTemp; int checkingNumber; int counter = 0; boolean check = false; for(checkingNumber = A; checkingNumber < B; checkingNumber++ ){ int[] stack = new int[length-1]; testString = Integer.toString(checkingNumber); check = true; for(int i = 0; i < length-1; i++ ){ testTemp = testString.substring(1, length) + testString.substring(0, 1); testString = testTemp; if( checkingNumber < Integer.parseInt(testString)){ if( Integer.parseInt(testString) <= B ){ for(int k = 0; k < i; k++) if( stack[k] == Integer.parseInt(testString) ) check = false; if(check){ counter++; //System.out.println(checkingNumber + "" "" + testString+ "" ""+ counter); stack[i] = Integer.parseInt(testString); } } } } } System.out.println(counter); } } " B20215,"import java.io.File; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; public class C { public static void main(String[] args)throws Exception { Scanner sc = new Scanner(new File(""C-large.in"")); PrintWriter pw = new PrintWriter(new File(""outputCLarge.out"")); int n = sc.nextInt(); for (int i = 0; i < n; i++) { int min = sc.nextInt(); int max = sc.nextInt(); long conteo=0; for (int j = min; j <= max; j++) { conteo+=contarReps(j,min,max); } pw.println(""Case #""+(int)(i+1)+"": ""+(int)(conteo/2)); } pw.close(); System.out.println(""Done""); } static long contarReps(int num,int min,int max){ StringBuffer strNum = new StringBuffer(""""+num); StringBuffer strNumO = new StringBuffer(""""+num); HashMap mapa = new HashMap(); mapa.put(""""+num,""""+num); String str; int rev; long count=0; for (int i = 0; i < strNum.length()-1; i++) { strNum.append(strNum.charAt(0)); strNum.deleteCharAt(0); rev = Integer.parseInt(strNum.toString()); str = strNum.toString(); if(mapa.get(str)==null){ mapa.put(str, str); if(rev>=min && rev<=max && rev!=num) count++; } } return count; } static int compare(StringBuffer bf1, StringBuffer bf2){ for (int i = 0; i < bf1.length(); i++) { if(bf1.charAt(i)>bf2.charAt(i)){ return 1; }else if(bf1.charAt(i)= 1){// 7 digits int one = (t%1000000) * 10 + t/1000000; if(one <= M && one >= N && one != t && !dp[one]){ answer++; } int two = (t%100000) * 100 + t/100000; if(two <= M && two >= N && two != t && !dp[two] && two != one){ answer++; } int three = (t%10000)*1000 + t/10000; if(three <= M && three >= N && three != t && !dp[three] && three != one && three != two){ answer++; } int four = (t%1000)*10000 + t/1000; if(four <= M && four >= N && four != t && !dp[four] && four != one && four != two && four != three){ answer++; } int five = (t%100)*100000 + t/100; if(five <= M && five >= N && five != t && !dp[five] && five != one && five != two && five != three && five != four){ answer++; } int six = (t%10)*1000000 + t/10; if(six <= M && six >= N && six != t && !dp[six] && six != one && six != two && six != three && six != four && six != five){ answer++; } } else if(t / 100000 >= 1){// 6 digits int one = (t%100000) * 10 + t/100000; if(one <= M && one >= N && one != t && !dp[one]){ answer++; } int two = (t%10000) * 100 + t/10000; if(two <= M && two >= N && two != t && !dp[two] && two != one){ answer++; } int three = (t%1000)*1000 + t/1000; if(three <= M && three >= N && three != t && !dp[three] && three != one && three != two){ answer++; } int four = (t%100)*10000 + t/100; if(four <= M && four >= N && four != t && !dp[four] && four != one && four != two && four != three){ answer++; } int five = (t%10)*100000 + t/10; if(five <= M && five >= N && five != t && !dp[five] && five != one && five != two && five != three && five != four){ answer++; } } else if(t / 10000 >= 1){// 5 digits int one = (t%10000) * 10 + t/10000; if(one <= M && one >= N && one != t && !dp[one]){ answer++; } int two = (t%1000) * 100 + t/1000; if(two <= M && two >= N && two != t && !dp[two] && two != one){ answer++; } int three = (t%100)*1000 + t/100; if(three <= M && three >= N && three != t && !dp[three] && three != one && three != two){ answer++; } int four = (t%10)*10000 + t/10; if(four <= M && four >= N && four != t && !dp[four] && four != one && four != two && four != three){ answer++; } } else if(t / 1000 >= 1){// 4 digits int one = (t%1000) * 10 + t/1000; if(one <= M && one >= N && one != t && !dp[one]){ answer++; } int two = (t%100) * 100 + t/100; if(two <= M && two >= N && two != t && !dp[two] && two != one){ answer++; } int three = (t%10)*1000 + t/10; if(three <= M && three >= N && three != t && !dp[three] && three != one && three != two){ answer++; } } else if(t / 100 >= 1){ // 3digits int one = (t % 100) * 10 + t/100; if(one <= M && one >= N && one != t && !dp[one]){ answer++; } int two = (t % 10) * 100 + t/10; if(two <= M && two >= N && two != t && !dp[two] && two != one){ answer++; } } else if(t / 10 >= 1){ // 2digits int one = (t % 10) * 10 + t/10; if(one <= M && one >= N && one != t && !dp[one]){ answer++; } } else{ // 1 digit } dp[t] = true; return answer; } public static void main(String[] args) throws FileNotFoundException { int answer = 0; Scanner scan = new Scanner(System.in); int max = scan.nextInt(); for(int i = 1; i <= max; i++){ for(int j = 0; j < 2000000; j++){ dp[j] = false; } int N = scan.nextInt(); int M = scan.nextInt(); for(int j = N; j < M; j++){ answer = answer + store(j, N, M); } System.out.println(""Case #"" + i + "": "" + answer); answer = 0; } } } " B20462,"import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Scanner; public class GCJ12QRC { private static int a, b, d; private static long c; private static String output, newline = System.getProperty(""line.separator""); public static void fun() { String s; int i, j, k; c = d = 0; for(i=a; i>0; i/=10) d++; for(i=a; ii && k<=b) { c++; } } } } public static void main(String[] args) throws IOException { long t2, t1 = System.currentTimeMillis(); output = """"; Scanner sc = new Scanner(new File(""C-large.in"")); int ntc = sc.nextInt(); for(int w=1; w<=ntc; w++) { a = sc.nextInt(); b = sc.nextInt(); fun(); output += ""Case #"" + w + "": "" + c + newline; } sc.close(); OutputStream fo = new FileOutputStream(""C-large.out""); fo.write(output.getBytes()); fo.close(); t2 = System.currentTimeMillis(); System.out.println( ""Time in millis : "" + (t2-t1) ); } } " B22017,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.util.LinkedList; import java.util.Scanner; /** * * @author Venkatesh */ public class reversal { public static void main(String args[]) { Scanner s=new Scanner(System.in); int t=s.nextInt(); int currelement; int a,b,ind=1,temp,digits=0,temp1,temp2,count=0; boolean samedigits=true; boolean next=false; LinkedList list=new LinkedList(); while(ind<=t) { samedigits=true; next=false; digits=0; a=s.nextInt(); b=s.nextInt(); if(b<10) { System.out.println(""Case #""+ind+"": 0""); ind++; continue; } temp=a; while(temp!=0) { temp/=10; digits++; } int arr[]=new int[digits]; int barr[]=new int[digits]; //int mainarray[]=new int[digits]; temp2=b; for(int i=digits-1;i>=0;i--) { barr[i]=temp2%10; temp2/=10; } temp=a; while(temp<=b) { // if(temp==1113) // System.exit(0); // System.out.println(""Examining ""+temp); temp1=temp; samedigits=true; for(int i=digits-1;i>=0;i--) { arr[i]=temp1%10; temp1/=10; // System.out.println(arr[i]); if(i arr[0]) { // System.out.println(""Success ""); //if already present dont add currelement=arraytoint(arr,j); if(list.contains(currelement)==false) { count++; list.add(currelement); } continue; } else if(j!=0 && arr[j] == arr[0]) { // System.out.println(""equal""); int g=j; int h=0; while(arr[(++g)%digits] == arr[(++h)%digits]) { if((h%digits)==0) break; } if(arr[g%digits]>arr[h%digits]) { //System.out.println(""Success "");//+arr[g%digits]); //if already present dont add currelement=arraytoint(arr,j); if(list.contains(currelement)==false) { count++; list.add(currelement); } continue; } } } else if(arr[j]==barr[0]) { int k=0; int newind=j; ++newind; ++k; while(arr[(newind)%digits] == barr[(k)%digits]) { // System.out.println(""arr[(newind)%digits] ""+newind%digits+"" barr[(k)%digits] ""+(k)%digits); if((k)%digits==0) { newind=j; //check for digits of a if(arr[newind%digits] > arr[0]) { //System.out.println(""Success "");//+arr[newind%digits]); //if already present dont add currelement=arraytoint(arr,j); if(list.contains(currelement)==false) { count++; list.add(currelement); } next=true; break; } else if(newind%digits!=0 && arr[newind%digits] == arr[0]) { int g=newind%digits; int h=0; while(arr[(++g)%digits] == arr[(++h)%digits]) { if((h%digits)==0) break; } if(arr[g%digits]>arr[h%digits]) { //System.out.println(""Success "");//+arr[g%digits]); //if already present dont add currelement=arraytoint(arr,j); if(list.contains(currelement)==false) { count++; list.add(currelement); } next=true; break; } } //end of proc } newind++; ++k; } if(next) { next=false; continue; } if(arr[newind%digits]< barr[k%digits]) { // System.out.println(""arr[newind%digits]< barr[k%digits] ""+newind%digits+"" ""+ k%digits); newind=j; //check for digits of a if(arr[newind%digits] > arr[0]) { //System.out.println(""Success "");//+arr[newind%digits]); //if already present dont add currelement=arraytoint(arr,j); if(list.contains(currelement)==false) { count++; list.add(currelement); } } else if(newind%digits!=0 && arr[newind%digits] == arr[0]) { int g=newind%digits; int h=0; while(arr[(++g)%digits] == arr[(++h)%digits]) { if((h%digits)==0) break; } if(arr[g%digits]>arr[h%digits]) { //System.out.println(""Success "");//+arr[g%digits]); //if already present dont add currelement=arraytoint(arr,j); if(list.contains(currelement)==false) { count++; list.add(currelement); } } } //end of proc } } } temp++; list.removeAll(list); } System.out.println(""Case #""+ind+"": ""+count); ind++; count=0; } } static int arraytoint(int[] b,int index) { int i=0,temp; int len=b.length; int a[]=new int [len]; temp=a[index]; for(int j=0;j testNum) && (newNum <= B)) { boolean bool = false; for (int k = 0; k < index; k++) { if (testing[k] == newNum) { // System.out.println(""fuckfuckfuckfuckfuckfuckfuck""); bool = true; break; } } if (bool == false) { pairs++; testing[index] = newNum; index++; } } } testNum++; } out.write(""Case #"" + (i+1) + "": "" + pairs + ""\n""); i++; } in.close(); out.close(); } }" B21485,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * * @author topik */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { final Scanner scanner = new Scanner(System.in); final int testCases = scanner.nextInt(); for( int tc=1; tc <= testCases; tc++ ) { final int a = scanner.nextInt(); final int b = scanner.nextInt(); int total = 0; for( int n = a > 10 ? a : 10; n < b; n++ ) { final Set seen = new HashSet(); final String nStr = Integer.toString(n); final int nStrLen = nStr.length(); for( int replace = 1; replace < nStrLen; replace++ ) { final String mStr = nStr.substring(nStrLen - replace) + nStr.substring(0, nStrLen - replace); final int m = Integer.parseInt(mStr); if( m <= b && m > n && ! seen.contains(m) ) { seen.add(m); total++; } } } System.out.println(""Case #"" + tc + "": "" + total); } } } " B20474,"import java.io.PrintWriter; import java.util.Scanner; public class ProblemC { public static void main(String[] args) { final Scanner in = new Scanner(System.in); final PrintWriter out = new PrintWriter(System.out); final int t = in.nextInt(); for (int tt = 0; tt < t; tt++) { final int a = in.nextInt(); final int b = in.nextInt(); int count = 0; for (int n = a; n < b; n++) { count += recycledNumbersCount(n, b); } out.println(""Case #"" + (tt + 1) + "": "" + count); } out.flush(); } private static int recycledNumbersCount(int n, int b) { int count = 0; final String s = """" + n; String ss = s.charAt(s.length() - 1) + s.substring(0, s.length() - 1); while (!s.equals(ss)) { if (ss.charAt(0) != '0') { final int m = Integer.parseInt(ss); if (m > n && m <= b) { count++; } } ss = ss.charAt(ss.length() - 1) + ss.substring(0, ss.length() - 1); } return count; } } " B20120,"package taskc; import java.util.*; public class TaskC { public static void main(String[] args) { new TaskC().main(); } int numOfDigits(int x) { int res = 0; while (x > 0) { res++; x /= 10; } return res; } int getCycle(int n, int i) { String s = Integer.toString(n); int leftlen = s.length() - i; String res = s.substring(leftlen) + s.substring(0, leftlen); return Integer.parseInt(res); } Set generateCycleNumbers(int x) { Set res = new HashSet(); int n = numOfDigits(x); for (int i = 1; i < n; i++) { int z = getCycle(x, i); if (numOfDigits(z) == numOfDigits(x)) { res.add(z); } } return res; } int f(int x, int y) { int res = 0; for (int i = x; i <= y; i++) { Set cycles = generateCycleNumbers(i); for (int q: cycles) { if (q >= x && q <= y && q != i) { //System.out.println(i +"" -> "" + q); res++; } } } return res/2; } void main() { Scanner s = new Scanner(System.in); int T = s.nextInt(); for (int i = 1; i <= T; i++) { int a = s.nextInt(), b = s.nextInt(); int ans = f(a, b); System.out.println(""Case #"" + i + "": "" + ans); } } } " B22073,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.io.PrintWriter; import java.util.*; public class C { Scanner sc; PrintStream ps; public void solve() { int A = sc.nextInt(); int B = sc.nextInt(); int nr = 0; for (int n=A; n<=B; n++) { String s = n+""""; HashSet set = new HashSet(); for (int i=0; i= A) { if (!pair.contains(n + "" < "" + m)) { pair.add(n + "" < "" + m); count++; } } } } String print = ""Case #"" + ccase + "": "" + count + ""\n""; System.out.print(print); writer.write(print, 0, print.length()); } writer.close(); } } " B20896,"import java.io.*; import java.util.StringTokenizer; public class CodeJam1 { static BufferedReader br; static PrintWriter pw; static int a,b,count; public static void main(String[] args)throws Exception{ br=new BufferedReader (new FileReader (""in.txt"")); pw=new PrintWriter (new FileWriter(""out.txt"")); int n=Integer.parseInt( br.readLine() ); for (int i=1;i<=n;i++){ input(); work(); pw.printf(""Case #%d: %d%n"",i,count); } pw.close(); } public static void input()throws Exception{ StringTokenizer data=new StringTokenizer(br.readLine()); a=Integer.parseInt( data.nextToken() ); b=Integer.parseInt( data.nextToken() ); count=0; } public static void work(){ for (int i=a;i<=b;i++){ StringBuffer sbuf=new StringBuffer(String.valueOf(i)); int create; do{ sbuf.append(sbuf.charAt(0)); sbuf.deleteCharAt(0); create=Integer.parseInt( sbuf.toString() ); if (create>i & create<=b) count++; }while(create!=i); } } }" B20132,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Date; import java.util.HashSet; import java.util.StringTokenizer; public class GCJ2012QC { static HashSet set = new HashSet(); static final int ZERO = 48; public static void main(String[] args) throws Exception { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st; int t = parseInt(r.readLine()); // long time = new Date().getTime(); int a, b, result; for (int i = 1; i <= t; i++) { st = new StringTokenizer(r.readLine()); a = parseInt(st.nextToken()); b = parseInt(st.nextToken()); result = solve(a, b); pw.println(""Case #"" + i + "": "" + result); } // time = new Date().getTime() - time; pw.flush(); // System.out.println(time / 1000); } private static int solve(int a, int b) { int result = 0; for (int i = a; i < b; i++) { result += calculate(i, b); } return result; } private static int calculate(int k, int b) { String s = Integer.toString(k); int n = s.length(); int rotated; String s1; set.clear(); for (int i = 1; i < n; i++) { s1 = s.substring(i) + s.substring(0, i); rotated = parseInt(s1); if (rotated > k && rotated <= b && !set.contains(rotated)) { set.add(rotated); } } return set.size(); } private static int parseInt(String s) { int len = s.length(); int num = s.charAt(0) - ZERO; for (int i = 1; i < len; i++) { num = num * 10 + s.charAt(i) - ZERO; } return num; } } " B22194,"package org.weiwei.recyclenumber; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; /** * Created with IntelliJ IDEA. * User: ding * Date: 12-4-14 * Time: 下午1:57 * To change this template use File | Settings | File Templates. */ public class FileProcessor { public static void testOutput(String input, String output) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(input)); PrintWriter pw = new PrintWriter(output); String line = reader.readLine(); int total = Integer.parseInt(line.trim()); line = reader.readLine(); int i = 1; while(line != null) { String[] elems = line.trim().split("" ""); RecyleBin bin = new RecyleBin(Integer.parseInt(elems[0]), Integer.parseInt(elems[1])); pw.write(""Case #""+i+"": ""+bin.exhaust()); pw.write(""\r\n""); line = reader.readLine(); i++; } reader.close(); pw.close(); } public static void main(String[] args) throws IOException { testOutput(""F:\\input.txt"", ""F:\\output.txt""); } } " B22161,"package com.vp.common; public class CommonUtility { public static int[] convertStringArraytoIntArray(String[] sarray) { if (sarray != null) { int intarray[] = new int[sarray.length]; for (int i = 0; i < sarray.length; i++) { intarray[i] = Integer.parseInt(sarray[i]); } return intarray; } return null; } public static float[] convertStringArraytoFloatArray(String[] sarray) { if (sarray != null) { float floatArray[] = new float[sarray.length]; for (int i = 0; i < sarray.length; i++) { floatArray[i] = Float.parseFloat(sarray[i]); } return floatArray; } return null; } public static double[] convertStringArraytoDoubleArray(String[] sarray) { if (sarray != null) { double darray[] = new double[sarray.length]; for (int i = 0; i < sarray.length; i++) { darray[i] = Double.parseDouble(sarray[i]); } return darray; } return null; } public static long[] convertStringArraytoLongArray(String[] sarray) { if (sarray != null) { long longarray[] = new long[sarray.length]; for (int i = 0; i < sarray.length; i++) { longarray[i] = Long.parseLong(sarray[i]); } return longarray; } return null; } public static void print(int a[]) { System.out.print(""[ ""); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "", ""); } System.out.print("" ]""); System.out.println(""""); } public static void printWithoutExtrLine(int a[]) { System.out.print(""[ ""); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "", ""); } System.out.print("" ]""); } public static void print(float a[]) { System.out.print(""[ ""); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "", ""); } System.out.print("" ]""); System.out.println(""""); } public static void print(double a[]) { System.out.print(""[ ""); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "", ""); } System.out.print("" ]""); System.out.println(""""); } public static void print(long a[]) { System.out.print(""[ ""); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "", ""); } System.out.print("" ]""); System.out.println(""""); } public static void print(String a[]) { System.out.print(""[ ""); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + "", ""); } System.out.print("" ]""); System.out.println(""""); } } " B20563,"package com.elbr.codejam2012.qualification.C; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.util.HashSet; import java.util.LinkedList; import java.util.List; public class Recycle { private static int a = 0; private static int b = 0; private static boolean debug = false; private static HashSet set = new HashSet(); private static void isRecycled(int i) { String s = i + """"; LinkedList l = new LinkedList(); for (int j = 0; j < s.length(); j++) { l.add(s.charAt(j) + """"); } for (int j = 0; j < s.length(); j++) { String zs = listToString(l); if (debug) { System.out.println(zs); } int z = Integer.parseInt(zs); if ((z >= a) && (z <= b) && (z > i)) { set.add(""{"" + i + "","" + z + ""}""); } l.add(l.getFirst()); l.removeFirst(); } } private static String listToString(List l) { return l.toString().replace(""["", """").replace(""]"", """").replace("" "", """") .replace("","", """"); } public static void main(String[] in) throws IOException { String fileName = ""C-large.in""; URL file = Recycle.class.getResource(fileName); String path = file.getFile(); BufferedReader reader = new BufferedReader(new FileReader(path)); File fileOut = new File(fileName + "".out""); fileOut.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(fileOut)); int numOfCases = Integer.parseInt(reader.readLine()); for (int t = 0; t < numOfCases; t++) { String line = reader.readLine(); String outputLine = ""Case #"" + (t + 1) + "": "" + result(line); System.out.println(outputLine); writer.write(outputLine + System.getProperty(""line.separator"")); } reader.close(); writer.close(); } private static int result(String line) { String[] params = line.split(""\\s""); a = Integer.parseInt(params[0]); b = Integer.parseInt(params[1]); set.clear(); for (int i = a; i <= b; i++) { isRecycled(i); } return set.size(); } } " B20373,"import java.util.*; public class RecycledNum { private static int testCase; public static void main( String[] args ) { Scanner s = new Scanner( System.in ); RecycledNum r = new RecycledNum(); r.setTestCase(Integer.parseInt(s.nextLine())); for( int i = 0; i < testCase; i++ ) { int A = s.nextInt(); int B = s.nextInt(); s.nextLine(); if( B/A < 10) { System.out.println( ""Case #"" +(i+1) +"": "" + r.recycle( A, B ) ); } } } public RecycledNum() { this.testCase = 1; } public void setTestCase( int T ) { if( T>=1 && T<=50 ) this.testCase = T; } public int getTestCase() { return this.testCase; } public int recycle(int A, int B) { int n = 0; double j = A; int count = 0; while( j >= 1) { j = j/10; n = n + 1; } for( int i = A; i <= B; i++ ) { //System.out.println(""original ""+ i); char[] array = new char[n]; String numstri = i + """"; for( int m = 0; m < n; m++) { array[m]=numstri.charAt(m); } int[] pair = new int[n]; for( int q = 0; q< pair.length; q++) { pair[q] = 0; } int count2 = 0; for ( int k = 0 ; k < n-1; k++ ) { String str = """"; String rts = """"; for( int p = 0; p < n - k-1; p++ ) { str = str + array[p]; ///System.out.println( str ); } for( int p = n-k-1; p < n; p++) { rts = rts + array[p]; //System.out.println(rts ); } String stri = rts + str; // System.out.println( stri); int num = Integer.parseInt(stri); boolean check = true; if( num <= B && num >= A && num != i ) { for( int q = 0; q < pair.length;q++ ) { if(pair[q] == num ){ check = false; } } if( check ) { count++; count2++; // System.out.println(count); pair[count2-1] = num; //System.out.println( num +"" ""); } } } } return count/2; } }" B21961,"/** * @(#)test.java * * test application * * @author * @version 1.00 2012/4/13 */ import java.io.*; import java.util.*; import java.lang.*; public class test { public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream (""B-small-attempt1.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int T = Integer.parseInt (br.readLine()+""""); String [] line = new String[T]; String [] temp; int [] numbers; int numdancers = 0; int surprising = 0; int compare = 0; if (T>100)T=100; for (int i = 0; i33) numbers = new int[33]; else numbers = new int[temp.length]; for (int j = 0; j3)numdancers=3; surprising = numbers[1]; //Number of surprising cases if (surprising>numdancers)surprising = numdancers; compare = numbers[2]; //Find number of googlers that have a best result >= compare if (compare>10)compare = 10; int specialcombo = 0; int counter = 3; int[] scores = new int[3]; int casenum = 0; int max; int one; int prevmax; int prevcombo; boolean match = false; while (counter=0) { max = 0; if ((one+(one)+(one-1))==numbers[counter])//1 1 0 normal { match = true; //System.out.println ((one+""+""+(one)+""+""+(one-1))+""=""+(one+(one)+(one-1))); scores[0] = one; scores[1] = one; scores[2] = one-1; if (scores[0]>max) max = scores[0]; if (scores[1]>max) {max = scores[1];} if (scores[2]>max) {max = scores[2];} if (max>=compare && prevmax==0) { casenum++; prevmax = max; } //System.out.println (casenum); } else if ((one+(one-1)+(one-1))==numbers[counter])//0 0 1 normal { match = true; //System.out.println ((one+""+""+(one-1)+""+""+(one-1))+""=""+(one+(one-1)+(one-1))); scores[0] = one; scores[1] = one-1; scores[2] = one-1; if (scores[0]>max) max = scores[0]; if (scores[1]>max) {max = scores[1];} if (scores[2]>max) {max = scores[2];} if (max>=compare && prevmax==0) { casenum++; prevmax = max; } //System.out.println (casenum); } else if (((one)+(one)+(one+2))==numbers[counter]) //1 1 3 surprising { match = true; //System.out.println (((one)+""+""+(one)+""+""+(one+2))+""=""+((one)+(one)+(one+2))); specialcombo++; scores[0] = one; scores[1] = one; scores[2] = one+2; if (scores[0]>max) max = scores[0]; if (scores[1]>max) max = scores[1]; if (scores[2]>max) max = scores[2]; if (max>=compare && prevmax==0 && specialcombo<=surprising) { casenum++; prevmax = max; } //System.out.println (casenum); } else if (((one-1)+(one-2)+(one))==numbers[counter]) //1 2 3 //surprising { match = true; specialcombo++; //System.out.println ((one+""+""+(one-2)+""+""+(one-1))+""=""+(one+(one-2)+(one-1))); scores[0] = one-1; scores[1] = one-2; scores[2] = one; if (scores[0]>max) max = scores[0]; if (scores[1]>max) max = scores[1]; if (scores[2]>max) max = scores[2]; if (max>=compare && prevmax==0 && specialcombo<=surprising) { casenum++; prevmax = max; } //System.out.println (casenum); } else if (((one-1)+(one)+(one))==numbers[counter]) //0 1 1 { match = true; //System.out.println ((one+""+""+(one-1)+""+""+(one))+""=""+(one+(one-1)+(one))); scores[0] = one-1; scores[1] = one; scores[2] = one; if (scores[0]>max) max = scores[0]; if (scores[1]>max) max = scores[1]; if (scores[2]>max) max = scores[2]; if (max>=compare && prevmax==0) { casenum++; prevmax = max; } //System.out.println (casenum); } else if ((one+one+one)==numbers[counter])//1 1 1 normal { match = true; //System.out.println ((one+""+""+(one)+""+""+(one))+""=""+(one+(one)+(one))); scores[0] = one; scores[1] = one; scores[2] = one; if (scores[0]>max) max = scores[0]; if (scores[1]>max) {max = scores[1];} if (scores[2]>max) {max = scores[2];} if (max>=compare && prevmax==0) { casenum++; prevmax = max; } //System.out.println (casenum); } one--; } counter++; match = false; } System.out.println (""Case #""+(i+1)+"": ""+casenum); } } catch(Exception e){System.out.println (e);} } } " B21868,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.util.*; import java.math.*; /** * * @author . */ public class C { public static class Num { int number; String num; ArrayList recycled; Num(int number) { this.number = number; num = new String(); num += number; recycled = new ArrayList(); //pl(number); findAllRecycleds(); } void findAllRecycleds() { String sub; int subValue; for (int i = 1; i < num.length(); i++) { sub = num.substring(i, num.length()) + num.substring(0, i); //pl(""-"" + sub); if (sub.charAt(0) == '0') { continue; } subValue = Integer.parseInt(sub); if (subValue > number) { if(!recycled.contains(subValue)) { recycled.add(subValue); } else { //pl(number + "" contains "" + subValue); } Collections.sort(recycled); } } } int countRecycleds(int max) { int count = 0; for (Integer i : recycled) { if (i <= max) { count++; } else { break; } } return count; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = Integer.parseInt(in.nextLine()); HashMap array = new HashMap(2000001); int MIN = 1; int MAX = 2000000; for (int kase = 1; kase <= T; kase++) { int A = in.nextInt(); int B = in.nextInt(); //---------------------------------------------------- int count = 0; for (int i = A; i <= B; i++) { if(!array.containsKey(i)) { array.put(i, new Num(i)); } count += array.get(i).countRecycleds(B); } pl(""Case #"" + kase + "": "" + count); } } public static void pf(String s, Object... o) { System.out.printf(s, o); } public static void pl(Object o) { System.out.println(o); } public static void pr(Object o) { System.out.print(o); } } " B20548,"import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.TreeSet; public class Qual3 { private static BufferedReader r; private static PrintStream outFile; private static PrintStream out = new PrintStream(new OutputStream() { @Override public void write(int b) throws IOException { System.out.write(b); outFile.write(b); } }); public static void main(String[] args) throws IOException { File f = new File(""/home/blarson/input""); r = new BufferedReader(new FileReader(f)); outFile = new PrintStream(new FileOutputStream(new File(""/home/blarson/output""))); final int numCases = readInt(); for(int i = 0; i < numCases; i++) { out.print(""Case #"" + (i+1) + "": ""); solve(); out.println(); } out.close(); } private static void solve() throws IOException { int[] nums = readIntArray(2); int a = nums[0]; int b = nums[1]; int numRecycled = 0; TreeSet found = new TreeSet(); // Brute force! for(int c = a; c < b; c++) { int numChars = numChars(c); found.clear(); for(int i = 1; i < numChars; i++) { int power = (int) Math.pow(10, i); int left = (int) (c / power); int right = c % power; int num = right * (int)Math.pow(10, numChars-i) + left; if(num > c && num <= b && found.add(num)) { numRecycled++; } } } out.print(numRecycled); } private static int numChars(int c) { if(c < 10) { return 1; } else if (c < 100) { return 2; } else if (c < 1000) { return 3; } else if (c < 10000) { return 4; } else if (c < 100000) { return 5; } else if (c < 1000000) { return 6; } else { return 7; } } private static int[] readIntArray(int maxItems) throws IOException { int[] array = new int[maxItems]; String line = r.readLine().trim(); String[] data = line.split("" ""); for(int i = 0; i < data.length && i < maxItems; i++) { array[i] = new Integer(data[i]); } return array; } private static int readInt() throws IOException { String line = r.readLine().trim(); return new Integer(line); } }" B21224,"public class CodeJamLineParser { private final String[] tokens; private int position; public CodeJamLineParser(String line) { tokens = line.split(""\\s""); position = 0; } public boolean hasNextField() { return hasNextFields(1); } public int remainingFields() { return tokens.length - position; } public boolean hasNextFields(int count) { return remainingFields() >= count; } public String readNextStr() { return tokens[position++]; } public int readNextInt() { return Integer.parseInt(readNextStr()); } public int[] readNextIntList(int numOfInts) { int[] result = new int[numOfInts]; for (int i = 0; i < numOfInts; ++i) { result[i] = readNextInt(); } return result; } } " B21938,"package com.evolve.codejam2012.qualification; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; class Pair { private long a; private long b; Pair(long a, long b) { if (a > b) { this.b = a; this.a = b; } else { this.a = a; this.b = b; } } public long getA() { return a; } public long getB() { return b; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (a ^ (a >>> 32)); result = prime * result + (int) (b ^ (b >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (a != other.a) return false; if (b != other.b) return false; return true; } } public class Recycled { private static final String TEST_FILE = ""C-large.in""; private PrintWriter pw = null; private BufferedReader br = null; Recycled(boolean skip) throws IOException { String outFile = TEST_FILE.replace("".in"", "".out""); //System.out.println(outFile); this.pw = new PrintWriter(new FileWriter(outFile)); if (skip) return; File file = new File(TEST_FILE); if (file.exists()) { br = new BufferedReader(new java.io.FileReader(TEST_FILE)); } else { br = new BufferedReader(new InputStreamReader(System.in), 1 << 16); } } void doit() throws NumberFormatException, IOException { int testsNumber = Integer.parseInt(br.readLine()); System.out.println(testsNumber); for (int i = 1; i <= testsNumber; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); long A = Long.parseLong(st.nextToken()); long B = Long.parseLong(st.nextToken()); System.out.println(A + "" "" + B); long num = check(A, B); System.out.println(num); pw.println(""Case #"" + i + "": "" + num); } pw.flush(); pw.close(); } int check(final long A, final long B) { //Set set = new HashSet(); int counter = 0; for (long n = A; n < B; n++) { String str = Long.toString(n); // ile rotacji: str.length - 1 int rotations = str.length() - 1; for (int j = 0; j < rotations; j++) { str = rotate(str); // skip numbers starting with 0: if (str.startsWith(""0"")) { continue; } // construct new number: long m = Long.parseLong(str); // check: n < m if (!(n < m)) { continue; } // check m <= B if (m > B) { continue; } //Pair pair = new Pair(n, m); //set.add(pair); counter++; //System.out.println(n + "", "" + m); } //System.out.println(str); } return counter; } static String rotate(String str) { char ch = str.charAt(str.length() - 1); char[] arr = new char[1]; arr[0] = ch; return new String(arr).concat(str.substring(0, str.length() - 1)); } public static void main(String[] args) throws NumberFormatException, IOException { //System.out.println(rotate(""1"")); new Recycled(false).doit(); } } " B22103,"package google.codejam2012.qualification; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class RecycledNumbers { static private int getDigitsCount(int number) { int sh = 10; int digits = 1; while (sh <= number) { sh *= 10; digits++; } return digits; } static private int getRecyclingPairsCount(int number, int limit) { int digits = getDigitsCount(number); int sh = 1; for (int i = 1; i < digits; i++) { sh *= 10; } int permutation = number; int result = 0; int[] usedNumbers = new int[digits]; int usedNumbersCount = 0; for (int i = 1; i < digits; i++) { permutation = (permutation % 10) * sh + (permutation / 10); if (number < permutation & permutation <= limit) { boolean isNumberAlreadyUsed = false; for (int j = 0; j < usedNumbersCount; j++) { if (usedNumbers[j] == permutation) { isNumberAlreadyUsed = true; break; } } if (!isNumberAlreadyUsed) { usedNumbers[usedNumbersCount++] = permutation; result++; } } } return result; } static public void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 64 << 10); int testsNumber = Integer.parseInt(br.readLine().trim()); for (int test = 1; test <= testsNumber; test++) { StringTokenizer tokenizer = new StringTokenizer(br.readLine()); int startingNumber = Integer.parseInt(tokenizer.nextToken()); int endingNumber = Integer.parseInt(tokenizer.nextToken()); int result = 0; for (int number = startingNumber; number <= endingNumber; number++) { result += getRecyclingPairsCount(number, endingNumber); } System.out.println(""Case #"" + test + "": "" + result); } } catch (Exception e) { System.err.println(""Error:"" + e.getMessage()); } } } " B21343,"import java.io.*; import java.util.*; public class C { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; enum InputType { SAMPLE, SMALL, LARGE; } static final InputType currentInputType = InputType.LARGE; static final int attemptNumber = 0; // for small inputs only int pow10; void solve() throws IOException { int a = nextInt(); int b = nextInt(); pow10 = 1; int cnt = Integer.toString(a).length(); for (int i = 0; i < cnt - 1; i++) pow10 *= 10; long ans = 0; for (int i = a; i <= b; i++) { for (int j = (i % 10) * pow10 + (i / 10); j != i; j = (j % 10) * pow10 + j / 10) if (a <= j && j <= b && j > i) ans++; } out.println(ans); } void inp() throws IOException { switch (currentInputType) { case SAMPLE: br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); break; case SMALL: String fileName = ""C-small-attempt"" + attemptNumber; br = new BufferedReader(new FileReader(fileName + "".in"")); out = new PrintWriter(fileName + "".out""); break; case LARGE: fileName = ""C-large""; br = new BufferedReader(new FileReader(fileName + "".in"")); out = new PrintWriter(fileName + "".out""); break; } int test = nextInt(); for (int i = 1; i <= test; i++) { System.err.println(""Running test "" + i); out.print(""Case #"" + i + "": ""); solve(); } out.close(); } public static void main(String[] args) throws IOException { new C().inp(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (Exception e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } } " B21834,"package codejam; import java.util.Formatter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { //Counting numbers within a given range, having same sequence of digits public static void main(String[] args) { Scanner in = new Scanner(System.in); int cases = in.nextInt(); for(int i=1;i<=cases;i++){ int a = in.nextInt(); int b = in.nextInt(); int digitCount = new Integer(a).toString().toCharArray().length; HashSet pairs = new HashSet(); for(int num=a; num num && tempNum <=b) pairs.add(new Formatter().format(""%d, %d"", num,tempNum).toString()); } } System.out.println(""Case #""+i+"": ""+pairs.size()); } } } " B21995," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.StringTokenizer; public class Recycle { static String shiftRight( String s ) { String res = """" + s.charAt( s.length() - 1 ); res = res + s.substring( 0, s.length()-1 ); return res; } static int solve( int a, int b ) { HashSet h = new HashSet(); int res = 0; for( int i=a; i<=b; i++ ) { String curr = Integer.toString(i); if( h.contains( curr ) ) continue; // else compute number of shifts HashSet temp = new HashSet(); String s = curr; temp.add( curr ); h.add( curr); for( int j=0; j=a ) && ( x<=b )) { temp.add(s); h.add( s ); } } // now count how many such pairs ( n choose 2 = n( n-1 )/2 ) int k = temp.size(); res += k*( k-1 )/2; } return res; } public static void main( String[] args ) throws IOException { FileWriter fr= new FileWriter(""/home/gowri/Desktop/out.txt""); BufferedWriter out = new BufferedWriter( fr ); BufferedReader br = new BufferedReader( new InputStreamReader( System.in )); int t = Integer.parseInt( br.readLine() ); StringTokenizer tok; for( int i=0; i inputList; private List outputList; public FileHelper(String path) { this.path = path; this.inputList = readFile(path); this.totalSize = Integer.parseInt(inputList.get(0)); } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public int getTotalSize() { return totalSize; } public void setTotalSize(int totalSize) { this.totalSize = totalSize; } public List getInputList() { return inputList; } public void setInputList(List inputList) { this.inputList = inputList; } public List getOutputList() { return outputList; } public void setOutputList(List outputList) { this.outputList = outputList; } public static List readFile(String filepath) { List rstList = new ArrayList(); try { FileInputStream fstream = new FileInputStream(filepath); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line while ((strLine = br.readLine()) != null) { rstList.add(strLine); } // Close the input stream in.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } return rstList; } public static void writeFile(String filepath, List resList) { try { FileWriter fstream = new FileWriter(filepath); BufferedWriter out = new BufferedWriter(fstream); for(int i = 0 ; i< resList.size();++i){ out.write(resList.get(i)); System.out.println(resList.get(i)); if( i != resList.size() - 1) out.newLine(); } // Close the output stream out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public int getInputTotalSize() { return 0; } public void init(String[] inputStr) { for(int i = 1; i< this.inputList.size(); ++i ){ inputStr[i - 1] = inputList.get(i); } } } " B20086,"package source; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) throws IOException{ Scanner scan = new Scanner(new File("""")); BufferedWriter bw = new BufferedWriter(new FileWriter("""")); int testCases = new Integer(scan.nextLine()); Set pairs = null; for(int i=0; i < testCases; i++){ String[] nums = scan.nextLine().split("" ""); int min = new Integer(nums[0]); int max = new Integer(nums[1]); pairs = new TreeSet(); int testNum = min; while(testNum <= max){ getRecycled(testNum, pairs, min, max); ++testNum; } bw.write(""Case #""+(i+1)+"": ""+pairs.size()+""\n""); } bw.flush(); bw.close(); } public static void getRecycled(int testNum, Set pairs, int min, int max){ int rec = 0; String number = Integer.toString(testNum); StringBuilder sb = new StringBuilder(""""); for(int i=1; i < number.length(); i++){ sb.append(number.substring(i)).append(number.substring(0, i)); try{ rec = new Integer(sb.toString()); if(testNum != rec && min <= rec && rec <= max && !pairs.contains(testNum+""-""+rec) && !pairs.contains(rec+""-""+testNum)){ pairs.add(testNum+""-""+rec); } } catch(NumberFormatException e){} sb.delete(0, sb.length()); } } } " B21923,"package com.google.round.qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class ProblemC { /** * * * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { String fileName = ""C-large""; BufferedReader br = new BufferedReader(new FileReader(""C:\\GoogleCodeJam\\""+fileName+"".in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""C:\\GoogleCodeJam\\""+fileName+"".out"")); int noofcases = Integer.parseInt(br.readLine()); for(int i=1;i<=noofcases;i++) { bw.write(""Case #""); bw.write(i+""""); bw.write("": ""); bw.write(findDistinctivePairs(br.readLine())); bw.newLine(); } bw.flush(); try { if(bw != null) bw.close(); if(br != null) br.close(); } catch(Exception e) { // ignore } } private static String findDistinctivePairs(String readLine) { String[] range = readLine.split("" ""); int start = Integer.parseInt(range[0]); int end = Integer.parseInt(range[1]); int count =0; for(int i=start;i<=end;i++) { count = count + permutation(i+"""",end,i); } return count+""""; } private static int permutation(String str,int endNumber,int currentNumber) { int count=0; char[] letters = str.toCharArray(); for(int maxit=1;maxit currentNumber && permutedInt <=endNumber) { count++; } } return count; } public static void shiftRight(char[] array, int amount) { for (int j = 0; j < amount; j++) { char a = array[array.length - 1]; int i; for (i = array.length - 1; i > 0; i--) array[i] = array[i - 1]; array[i] = a; } } } " B21169,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.common; import java.util.ArrayList; /** * * @author jim */ public class Input { private final String[] header; private final String[] data; public Input(ArrayList lines, int header) { int size = lines.size(); this.header = new String[header]; this.data = new String[size - header]; for (int i = 0; i < size; i++) { String line = lines.get(i); if (i < header) this.header[i] = line; else this.data[i - header] = line; } } public String[] getHeader() { return header; } public String[] getData() { return data; } } " B21136,"import java.util.*; import static java.lang.Math.*; public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int zz = 1; zz <= T; zz++) { System.err.println(zz); int A = in.nextInt(); int B = in.nextInt(); long ans = 0; for (int n = A; n <= B; n++) { String s = n+""""; HashSet used = new HashSet(); for (int r = 0; r <= s.length(); r++) { String t = s.substring(r) + s.substring(0, r); int m = Integer.valueOf(t); if (A <= m && m <= B && n < m && t.charAt(0) != '0' && s.charAt(0) != '0' && !used.contains(t)) { used.add(t); ans++; } } } System.out.format(""Case #%d: %d\n"", zz, ans); } } } " B20599,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class TestC { /** * @param args */ public static void main(String[] arg) { try { String filein = ""testC.in""; String fileout = ""testC.out""; String currentdir = System.getProperty(""user.dir""); Scanner scanner = new Scanner(new File(currentdir + ""/"" + filein)); FileWriter fWriter = new FileWriter(new File(currentdir + ""/"" + fileout)); String line = """", resultat = """"; int i = 0; while (scanner.hasNextLine()) { line = scanner.nextLine(); if (i == 0) { try { Integer iNumber = Integer.valueOf(line); } catch (Exception ex) { resultat = "" NaN !!!!""; break; } i++; continue; } resultat = ""Case #"" + i + "": ""; String[] s = line.split("" ""); Integer A = Integer.valueOf(s[0]); Integer B = Integer.valueOf(s[1]); if (A < 10) { resultat += ""0""; } else { int n = 0; for (int j = A; j <= B; j++) { String n0 = Integer.toString(j); for (int k = 1; k < n0.length(); k++) { String first = n0.substring(0, k); String second = n0.substring(k, n0.length()); String ricycled = second + first; Integer iRecycl = Integer.valueOf(ricycled); if (iRecycl > j && iRecycl <= B) { n++; } } } resultat += """" + n; } fWriter.append(resultat + ""\r\n""); i++; } scanner.close(); fWriter.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B21853,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class jam { public static void main(String args[]) { ArrayList inp=read_fil(""D:\\google_Jam\\C-large.in""); // ArrayList inp=read_fil(""D:\\google_Jam\\A-large-practice.in""); int lin_num=0; int T=Integer.valueOf(inp.get(lin_num)); lin_num++; for(int kk=0;kk array=new ArrayList(); String the_i=String.valueOf(i); for(int j=0;j=A) && (i_new<=B) && i_new>i && !array.contains(the_i+""-""+new_i)){ y++; array.add(the_i+""-""+new_i); } } the_i=temp; } } writeFile(""Case #""+(kk+1)+"": ""+y); } } public static String shift(String old){ String las_char=old.substring(old.length()-1); String new_txt=las_char+old.substring(0, old.length()-1); return new_txt; } public static ArrayList read_fil(String file){ ArrayList arr=new ArrayList(); try{ FileInputStream fstream = new FileInputStream(file); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { arr.add(strLine); } in.close(); }catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } return arr; } public static void writeFile2(String ss) { String fileName = ""D:\\google_Jam\\Output_test.txt""; try { FileWriter writer = new FileWriter(fileName,true); writer.write(ss); writer.write('\n'); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public static void writeFile(String ss) { String fileName = ""D:\\google_Jam\\Output.txt""; try { FileWriter writer = new FileWriter(fileName,true); writer.write(ss); writer.write('\n'); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }" B21206,"package google.codejam.commons; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Utils { public static String[] readFromFile(String fileName) throws IOException { System.out.println(""Reading file "" + fileName); String[] lines = null; FileInputStream fstream = new FileInputStream(fileName); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); lines = new String[Integer.valueOf(strLine)]; int i = 0; while ((strLine = br.readLine()) != null) { lines[i++] = strLine; } in.close(); return lines; } public static void writeToFile(String[] lines, String fileName) throws IOException { System.out.println(""Writing file "" + fileName); FileWriter outFile = new FileWriter(fileName); PrintWriter out = new PrintWriter(outFile); for (String line : lines) { out.println(line); } out.close(); } } " B20778,"import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class RecycleSolution { /** * @param args */ public static void main(String[] args) { String inFilename = ""C-large.in""; String outFilename = inFilename.substring(0, inFilename.length() - 3) + "".out""; try { Scanner sc = new Scanner(new File(inFilename)); PrintStream ps = new PrintStream(new FileOutputStream(outFilename)); int testCases = Integer.parseInt(sc.nextLine()); for (int i = 1; i <= testCases; i++) { // logic if (i >= 1) { ps.println(); } String data = sc.nextLine(); String[] parts = data.split("" ""); int min = Integer.parseInt(parts[0], 10); int max = Integer.parseInt(parts[1], 10); int pairCount = 0; for (int test = min; test < max; test++) { List orderings = orderingsOf(test); for (int ordering : orderings) { if (ordering > test && ordering <= max) { pairCount++; } } } System.out.println(""Case #"" + i + "": "" + pairCount); ps.print(""Case #"" + i + "": "" + pairCount); } sc.close(); ps.close(); } catch (Exception ex) { ex.printStackTrace(); } } public static List orderingsOf(int number) { List myOrderings = new ArrayList(); String base = """" + number; int baselen = base.length(); for (int i = 0; i < baselen; i++) { String thisperm = base.substring(baselen - i); if (baselen - i > 0) { thisperm += base.substring(0, baselen - i); } // Strip out 0-starting int tplen = ("""" + Integer.parseInt(thisperm, 10)).length(); if (tplen == baselen) myOrderings.add(Integer.parseInt(thisperm, 10)); } return myOrderings; } } " B21474,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; public class RecycledNumbers { public static void main(String args[]) throws IOException { BufferedReader bfr = new BufferedReader(new FileReader(""inputC.txt"")); Writer output = null; File file = new File(""outputC.txt""); output = new BufferedWriter(new FileWriter(file)); int T = Integer.parseInt(bfr.readLine()); int i = 0; while (i < T) { String[] temp = bfr.readLine().split("" ""); int total = 0; int A = Integer.parseInt(temp[0]); int B = Integer.parseInt(temp[1]); for (int j = A; j <= B; j++) { long number = j; long start = number; int numdigits = (int) Math.log10((double) number); int multiplier = (int) Math.pow(10.0, (double) numdigits); while (true) { long r = number % 10; // 1234 = 123; number = number / 10; number = number + multiplier * r; if (number == start) break; if ((int)number >= A && (int)number <= B) { total++; } } } output.write(""Case #"" + (i + 1) + "": "" + (total/2)); if (i != T - 1) { output.write(""\n""); } i++; } output.close(); } } " B20333,"import java.io.BufferedReader; import java.io.FileReader; import java.sql.Array; import java.util.ArrayList; import java.util.concurrent.BlockingDeque; public class RN { public static void main (String[] args) throws Exception { BufferedReader sr = new BufferedReader(new FileReader(""c:\\Projects\\RN.txt"")); int total = Integer.parseInt(sr.readLine()); for (int i=0; i 0) { rest = rest / 10; num++; } int[] result = new int[num]; for (int i=0; i variants = new ArrayList(); int first = dec[0]; for (int i=1; i= first) { int candidate = toNumber(dec, i); if (candidate > Curr && candidate <= B) { if (!variants.contains(candidate)) { variants.add(candidate); total++; } } } } } return total; } } " B21260,"import java.util.*; public class c { public static void main(String[] args) { Scanner input = new Scanner(System.in); int T = input.nextInt(); for(int t = 1; t<=T; t++) { System.out.print(""Case #"" + t + "": ""); int a = input.nextInt(); int b = input.nextInt(); int count = 0; for(int i = a; i<=b; i++) { if(i >= 1000000) { int next = 1000000*(i%10)+i/10; if(next > i && next <= b) count++; int next2 = 100000*(i%100) + i/100; if(next2 > i && next2 <= b && next != next2) count++; int next3 = 10000*(i%1000)+i/1000; if(next3 > i && next3 <= b && next != next3 && next2 != next3) count++; int next4 = 1000*(i%10000) + i/10000; if(next4 > i && next4 <= b && next != next4 && next2 != next4 && next3 != next4) count++; int next5 = 100*(i%100000) + i/100000; if(next5 > i && next5 <= b && next != next5 && next2 != next5 && next3 != next5 && next4 != next5) count++; int next6 = 10*(i%1000000)+i/1000000; if(next6 > i && next6 <= b && next != next6 && next2 != next6 && next3 != next6 && next4 != next6 && next5 != next6) count++; } else if(i >= 100000) { int next = 100000*(i%10) + i/10; if(next > i && next <= b) count++; int next2 = 10000*(i%100)+i/100; if(next2 > i && next2 <= b && next != next2) count++; int next3 = 1000*(i%1000) + i/1000; if(next3 > i && next3 <= b && next != next3 && next2 != next3) count++; int next4 = 100*(i%10000) + i/10000; if(next4 > i && next4 <= b && next != next4 && next2 != next4 && next3 != next4) count++; int next5 = 10*(i%100000)+i/100000; if(next5 > i && next5 <= b && next != next5 && next2 != next5 && next3 != next5 && next4 != next5) count++; } else if(i >= 10000) { int next = 10000*(i%10)+i/10; if(next > i && next <= b) count++; int next2 = 1000*(i%100) + i/100; if(next2 > i && next2 <= b && next2 != next) count++; int next3 = 100*(i%1000) + i/1000; if(next3 > i && next3 <= b && next3 != next && next3 != next2) count++; int next4 = 10*(i%10000)+i/10000; if(next4 > i && next4 <= b && next4 != next3 && next4 != next2 && next4 != next) count++; } else if(i >= 1000) { int next = 1000*(i%10) + i/10; if(next > i && next <= b) { count++; } int next2 = 100*(i%100) + i/100; if(next2 > i && next2 <= b && next != next2) { count++; } int next3 = 10*(i%1000)+i/1000; if(next3 > i && next3 <= b && next != next3 && next2 != next3) { count++; } } else if(i >= 100) { int next = 100*(i%10) + i/10; if(next > i && next <= b) count++; int next2 = 10*(i%100) + i/100; if(next2 > i && next2 <= b && next2 != next) count++; } else if(i >= 10) { int next = 10*(i%10) + i/10; if(next > i && next <=b) count++; } } System.out.println(count); } } } " B20514,"import java.io.*; import java.util.*; /** * @author Ivan Romanov */ public class C { private String solve() throws IOException { int a = nextInt(); int b = nextInt(); int ans = 0; for (int i = a; i < b; i++) { if (recycle.containsKey(i)) { for (int j : recycle.get(i)) { if (j <= b) { ans++; // System.out.println(i + "" "" + j); } } } } return """" + ans; } private Map> recycle = new HashMap>(); private void prepare() { int mul = 1; int dig = 1; for (int x = 10; x <= 2000000; x++) { if (mul * 10 == x) { mul *= 10; dig++; } Set recs = new HashSet(); int t = x; for (int i = 1; i < dig; i++) { int last = t % 10; t /= 10; t += last * mul; if (t > x) { recs.add(t); } } if (!recs.isEmpty()) { recycle.put(x, recs); } } } private BufferedReader reader; private StringTokenizer tt = new StringTokenizer(""""); private String nextToken() throws IOException { while (!tt.hasMoreTokens()) { tt = new StringTokenizer(reader.readLine()); } return tt.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private void run() throws IOException { String problem = ""C-large""; reader = new BufferedReader(new FileReader(problem + "".in"")); PrintWriter writer = new PrintWriter(new File(problem + "".out"")); try { prepare(); int cases = nextInt(); int tc = 1; while (tc <= cases) { writer.print(""Case #"" + tc + "": ""); writer.println(solve()); tc++; } } finally { reader.close(); writer.close(); } } public static void main(String[] args) { try { new C().run(); } catch (IOException e) { e.printStackTrace(); } } }" B21042,"package de.hg.codejam.tasks.io; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public abstract class Writer { public static String generateOutputPath(String inputPath) { return inputPath.substring(0, inputPath.lastIndexOf('.') + 1) + ""out""; } public static void print(String[] output) { for (String s : output) System.out.println(s); } public static void write(String[] output) { for (int i = 0; i < output.length; i++) System.out.println(getCase(i + 1, output[i])); } public static void write(String[] output, String path) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(path, false))) { for (int i = 0; i < output.length; i++) { writer.append(getCase(i + 1, output[i])); writer.newLine(); writer.flush(); } } catch (IOException e) { e.printStackTrace(); } } private static String getCase(int number, String caseString) { return ""Case #"" + (number) + "": "" + caseString; } } " B21491,"import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Prabu */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""IO/C-large.in""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""IO/C-large.out""); } catch (IOException e) { throw new RuntimeException(e); } Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); CJ2012QR_RecycledNumbers solver = new CJ2012QR_RecycledNumbers(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } class CJ2012QR_RecycledNumbers { public void solve(int testNumber, Scanner in, PrintWriter out) { int A = in.nextInt(); int B = in.nextInt(); if(B < 10) { out.printf(""Case #%d: 0\n"", testNumber); return; } boolean[] visited = new boolean[B-A+1]; int nDigits = String.valueOf(A).length()-1; int cycleCount, pairCount, tempi; StringBuilder sb; pairCount = 0; for(int i = A; i <= B; i++) { if(visited[i - A]) continue; sb = new StringBuilder(String.valueOf(i)); sb.insert(0, sb.charAt(sb.length() - 1)); sb.deleteCharAt(sb.length() - 1); tempi = Integer.parseInt(sb.toString()); cycleCount = 0; while(i != tempi) { if(tempi >= A && tempi <= B && visited[tempi - A] == false) { cycleCount++; visited[tempi - A] = true; } sb.insert(0, sb.charAt(sb.length() - 1)); sb.deleteCharAt(sb.length() - 1); tempi = Integer.parseInt(sb.toString()); } pairCount += (cycleCount * (cycleCount + 1)) / 2; } out.printf(""Case #%d: %d\n"", testNumber, pairCount); } } " B20501,"import java.util.Scanner; import java.io.*; public class Tolu { static String out="""",output=""""; public static void main(String[] args) { try { Scanner in = new Scanner(new File(""input.in"")); int n = in.nextInt(); int count = 1; String out = """"; while(in.hasNext()) { int a = in.nextInt(); int b = in.nextInt(); out += ""Case #""+count+"": ""+ activity(a,b)+""\n""; count++; try { File file = new File(""output.dat""); PrintWriter output = new PrintWriter(file); output.write(out); output.close(); } catch(Exception exception) { System.out.println(""ERROR""); } } }catch(Exception exception){ System.out.println(""ERROR""); } System.out.println(""DONE""); } public static int activity(int A, int B) { int counter = 0; //String all[] = myGenerator(Integer.toString(A)); for(int i = A; i <= B; i++) { String all[] = myGenerator(Integer.toString(i)); for(int j = 0; j < all.length; j++) { if((i < Integer.parseInt(all[j])) && (Integer.parseInt(all[j]) <= B)) { counter++; } } } return counter; } public static String[] myGenerator(String word) { String[] all = new String[word.length()-1];//changed frm len - 1 for(int i = 0; i < all.length; i++) { all[i] = generate(word); word = generate(word); } return all; } public static String generate(String w) { String ans = w.substring(w.length()-1); for(int i = 0; i < w.length()-1; i++) { ans += w.substring(i,i+1); } return ans; } } " B20700,"package org.moriraaca.codejam; public enum DebugOutputLevel { SOLUTION, IMPORTANT, ALL; } " B20693," import java.io.File; public class RecycledNumbers { public static void main(String[] args) { try { FileReader fr = new FileReader(new File(args[0])); PrintResult pr = new PrintResult(args[1]); process(fr, pr); } catch (Exception e) { e.printStackTrace(); } } public static void process(FileReader fr, PrintResult pr) { int numCases; int[] in; try { numCases = fr.nextInt(); for (int i = 0; i < numCases; i++) { in = fr.nextIntArray(); pr.printLine(i, solve(in[0],in[1])); } pr.close(); } catch (Exception e) { e.printStackTrace(); } } public static String solve(int a, int b) { int count = 0; char[] achar = Integer.toString(a).toCharArray(); int m = 0; if(achar.length > 1) { for(int n = a; n < b+1; n++) { for(int j = 1; j < Integer.toString(n).length(); j++) { m = rearrange(n,j); if(m > n && m < b + 1) { int mlength = Integer.toString(m).toCharArray().length; int nlength = Integer.toString(n).toCharArray().length; if(mlength == nlength) { count++; } if(b == 2222) { System.out.println(n + "" "" + m + "" "" + j); } } } } } return Integer.toString(count); } public static int rearrange(int in, int amount) { char[] temp = Integer.toString(in).toCharArray(); char[] result = new char[temp.length]; for(int i = 0; i < temp.length; i++) { result[i] = temp[(temp.length-amount+i)%temp.length]; } return Integer.parseInt(new String(result)); } } " B21703,"package codejam.recyclednumbers; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class DigitsArray implements Comparable { private int[] digits; private DigitsArray() { } public DigitsArray(String numberAsString) { char[] charArray = numberAsString.toCharArray(); this.digits = new int[charArray.length]; for (int i = 0; i < digits.length; i++) { digits[i] = Integer.parseInt("""" + charArray[i]); } } public DigitsArray(int[] digits) { this.digits = digits; } public DigitsArray(Integer number) { this(number.toString()); } public int numberRecycles(DigitsArray minValue, DigitsArray maxValue) { Set correctRecycles = new HashSet<>(); for (int i = 1; i < digits.length; i++) { if (digits[i] < digits[0] || digits[i] < minValue.digits[0] || digits[i] > maxValue.digits[0]) { continue; } DigitsArray recycle = recycle(i); if (recycle.compareTo(this) > 0 && recycle.compareTo(minValue) >= 0 && recycle.compareTo(maxValue) <= 0) { correctRecycles.add(recycle); } } return correctRecycles.size(); } private DigitsArray recycle(int recycleIndex) { DigitsArray result = new DigitsArray(); int length = digits.length; result.digits = new int[length]; for (int i = 0; i < length; i++) { result.digits[i] = digits[(i + recycleIndex) % length]; } return result; } @Override public int compareTo(DigitsArray o) { if (digits.length > o.digits.length) { return 1; } if (digits.length < o.digits.length) { return -1; } for (int i = 0; i < digits.length; i++) { if (digits[i] > o.digits[i]) { return 1; } if (digits[i] < o.digits[i]) { return -1; } } return 0; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(digits); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DigitsArray other = (DigitsArray) obj; if (!Arrays.equals(digits, other.digits)) return false; return true; } } " B20762,"package probc; import codejam.CodeJam; public class Main extends CodeJam { public static void main(String[] args) { new Main() { // Override the input file with the following: e.g. if the value is ""large"", then read ""A-large.in"" instead of the default // @SuppressWarnings(""unused"") // public static final String OVERRIDE_INPUT_FILE = ""small-attempt0""; // ""large""; }; } // -------------------------------------------------------------------------------------------------------------- @Override public void solve() { int T = readInt(); for (int t = 0; t < T; t++) { int A = readInt(); int B = readInt(); int totRecycPairs = 0; int[] recycNums = new int[10]; for (int n1 = A; n1 < B; n1++) { int numRecyc = 0; String s1 = n1 + """"; for (int j = 1, l = s1.length(); j < l; j++) { String s2 = s1.substring(j) + s1.substring(0, j); int n2 = Integer.parseInt(s2); if (n2 > n1 && n2 <= B) { // Uniquify -- necessary? boolean found = false; for (int i = 0; i < numRecyc && !found; i++) if (recycNums[i] == n2) found = true; if (!found) recycNums[numRecyc++] = n2; } } totRecycPairs += numRecyc; // System.out.println(""> "" + n1); } writeCaseNumThenLine("""" + totRecycPairs); } } } " B20826,"// Problem B import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Locale; import java.util.Scanner; import java.util.Set; public class C { private void processInput() throws IOException { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int testCase = 1; testCase <= T; testCase++) { int A = in.nextInt(); int B = in.nextInt(); int res = go(A, B); System.out.printf(Locale.ENGLISH, ""Case #%d: %d\n"", testCase, res); } in.close(); } private int go(int A, int B) { int res = 0; Set set = new HashSet(); int l = String.valueOf(A).length(); for (int n = A; n <= B; n++) { set.clear(); String m = String.valueOf(n); for (int j = 1; j < l; j++) { m = m.charAt(l - 1) + m.substring(0, l - 1); if (m.charAt(0) != '0') { int val = Integer.valueOf(m); if (val > n && val <= B) { set.add(val); } } } res += set.size(); } return res; } public static void main(String[] args) throws Exception { C temp = new C(); temp.processInput(); } } " B20040,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package google.code.jam.recycled.numbers; /** * * @author Lucas */ public class GoogleCodeJamRecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { Utils ut = new Utils(); RecycledNumbers rn = new RecycledNumbers(); ut.write(rn.findRecycledNumbers(ut.parse(""Input/C-large.in"")), ""Output/output""); } } " B20724,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class CodeJam { public static void main(String [] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine()); for(int ii=1;ii<=num;++ii) { StringTokenizer st = new StringTokenizer(br.readLine()); int begin = Integer.parseInt(st.nextToken()); int end = Integer.parseInt(st.nextToken()); int cnt=0; for(int i=begin; i<=end ; ++i) { int line = i; String orig = Integer.toString(line); String curr = orig; for(int j = 0; j= begin && intcurr <=end && intcurr > line) cnt++; } } System.out.println(""Case #""+ii+"": ""+cnt); } } } " B21560,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Scanner; import java.io.BufferedWriter; public class D { public static void main(String[] args) throws IOException { int n; InputStreamReader reader = new InputStreamReader(new FileInputStream( args[0])); BufferedReader read = new BufferedReader(reader); BufferedWriter write = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(args[1]))); // Scanner scan = new Scanner(System.in); n = Integer.parseInt(read.readLine()); // n = scan.nextInt(); for (int i = 0; i < n; i++) { String p = read.readLine(); write.write(""Case #"" + (i + 1) + "": "" + holy(p, read)); write.newLine(); } write.flush(); write.close(); } static int holy(String r, BufferedReader read) throws IOException { String p = r; String s, temp, m; int a = 0; int b = 0; int panjang = 0; int result = 0; a = Integer.parseInt(p.substring(0, p.indexOf("" ""))); b = Integer.parseInt(p.substring(p.indexOf("" "") + 1, p.length())); for (int i = a; i <= b; i++) { s = Integer.toString(i); panjang = s.length(); for (int j = 1; j < panjang; j++) { temp = s.substring(0, j); m = s.substring(j, panjang) + temp; if (Integer.parseInt(m) == i) { } else if (Integer.parseInt(m) <= b && Integer.parseInt(m) >= a) { result++; } } } if ((result % 2) == 0) { result = result/2; } else if (result % 2 == 1) { result = result/2+1; } return result; } }" B20386,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package g.jam_3; import java.io.*; import java.util.ArrayList; // /** * * @author toshiba */ public class Gjam_3 { static String input = ""c:\\Gjam\\3\\small.in""; static String output = ""c:\\Gjam\\3\\output.out""; public static void main(String[] args) throws FileNotFoundException, IOException { output o = new output(output); ArrayList input_arr = new input().ReadInput(input); for (int j = 0; j < input_arr.size(); j++) { String[] t = input_arr.get(j).split("" ""); int a = Integer.parseInt(t[0]); int b = Integer.parseInt(t[1]); int result = 0; for (int n = a; n <= b; n++) { String tmp = String.valueOf(n); for (int k = tmp.length()-1; k > 0; k--) { tmp = String.valueOf(n).substring(k, String.valueOf(n).length()) +String.valueOf(n).substring(0, k); int m = Integer.parseInt(tmp); if(m==1111) System.out.print(m); if(m>n&&m<=b&&m!=n) result++; } } o.write(""Case #"" + (j+1) + "": "" + result + ""\n""); } o.close(); } } class input { public ArrayList ReadInput(String input) throws FileNotFoundException, IOException { ArrayList a = new ArrayList(); BufferedReader str = new BufferedReader(new InputStreamReader(new FileInputStream(input))); String s = """"; str.readLine(); int x = 0; while ((s = str.readLine()) != null) { x++; a.add(s); } return a; } } // class output { FileWriter fstream; BufferedWriter bw; public output(String output) throws IOException { fstream = new FileWriter(output); bw = new BufferedWriter(fstream); } public void write(String result) throws IOException { bw.write(result); } public void close() throws IOException { bw.close(); } } // // " B21392,"import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(new FileWriter(""RecycledNumbers-Large.out"")); RecycledNumbers solver = new RecycledNumbers(); int testCases = in.nextInt(); for (int i = 1; i <= testCases; ++i) { solver.solve(i, in, out); } in.close(); out.close(); } } class RecycledNumbers { int numberOfRecycledPairs(int A, int B) { int res = 0; boolean[] seen = new boolean[B + 1]; for (int i = A; i <= B; ++i) { if (seen[i]) continue; int pairs = 0; char[] S = String.valueOf(i).toCharArray(); for (int j = 0; j < S.length; ++j) { if (S[j] == '0') continue; int m = 0; for (int k = j; k < S.length; ++k) m = m * 10 + S[k] - '0'; for (int k = 0; k < j; ++k) m = m * 10 + S[k] - '0'; if (A <= m && m <= B && !seen[m]) { seen[m] = true; ++pairs; } } res += pairs * (pairs - 1) / 2; } return res; } public void solve(int testNumber, Scanner in, PrintWriter out) { int A = in.nextInt(); int B = in.nextInt(); out.println(""Case #"" + testNumber + "": "" + numberOfRecycledPairs(A, B)); } } " B21462,"package com.renoux.gael.codejam.utils; import java.io.Closeable; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class Output implements Closeable { private static String lineSeparator = System.getProperty(""line.separator""); private FileWriter writer; private Output(File file) { try { writer = new FileWriter(file); } catch (IOException e) { throw new TechnicalException(e); } } public static Output open(File file) { System.out.println(""======== "" + file); return new Output(file); } public void writeLine(String text) { System.out.println(text); try { writer.write(text); writer.write(lineSeparator); } catch (IOException e) { throw new TechnicalException(e); } } public void write(String text) { System.out.print(text); try { writer.write(text); } catch (IOException e) { throw new TechnicalException(e); } } public void writeLine(Object... text) { try { for (Object s : text) { System.out.print(s); writer.write(s.toString()); } System.out.println(); writer.write(lineSeparator); } catch (IOException e) { throw new TechnicalException(e); } } public void write(Object... text) { try { for (Object s : text) { System.out.print(s); writer.write(s.toString()); } } catch (IOException e) { throw new TechnicalException(e); } } public void close() { System.out.println(""================ closed""); try { writer.close(); } catch (IOException e) { throw new TechnicalException(e); } } } " B21186,"import java.util.*; public class C { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int T = in.nextInt(); int i,j,len,p,temp,total; HashSet[] map = new HashSet[2000000]; for (i=1;i<2000000;i++) { map[i] = new HashSet(); len = (int)Math.log10(i)+1; p = (int)Math.pow(10, len-1); temp = i; for (j=0;ji && temp<=2000000) map[i].add(temp); } } for (i=1;i<=T;i++) { int a = in.nextInt(); int b = in.nextInt(); total = 0; for (j=a;jj && t<=b) total++; } } System.out.println(""Case #""+i+"": ""+total); } } } " B20711,"import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; public class RecycledNumbers { public static int nonbelong(int n, int [] T) { int j=1; int i; for (i=0;il) return 0; else { ch2=ch.substring(l-p); if (Integer.valueOf(ch2)==0){ return 0;} else { ch3=ch.substring(0, l-p); ch=ch2+ch3; return Integer.valueOf(ch); } } } public static void main(String[] args) throws IOException{ String fichierentree= ""/home/marwen/Téléchargements/C-large.in""; String fichiersortie= ""/home/marwen/Bureau/output.in""; BufferedWriter wr= new BufferedWriter(new FileWriter(fichiersortie)); DataInputStream rd= new DataInputStream(new FileInputStream(fichierentree)); int i,l,nb,r,j,a,b,k; String ligne= rd.readLine(); int T= Integer.valueOf(ligne); for (k=1;k<=T;k++) { nb=0; ligne=rd.readLine(); a=Integer.valueOf(ligne.substring(0, ligne.indexOf("" ""))); b=Integer.valueOf(ligne.substring(ligne.indexOf("" "")+1)); l=RecycledNumbers.longeur(a); int [] Valr=new int[l-1]; for(i=0;i0)&&(r<=b)&&(r>a)&&(r>i)){nb++;} } } } wr.write(""Case #""+k+"": ""+nb); wr.newLine(); } wr.close(); rd.close(); } } " B20538," public interface TestCaseFactory { TestCase getInstance(int number); }" B21137,"import java.util.*; import java.io.*; public class qualC { public static void main(String[] args) throws IOException { Scanner sin = new Scanner(new File(""/Users/G/Documents/Programming/Java/CodeJam2012/C-large.in"")); int t = sin.nextInt(), a, b; for(int i = 1; i <= t; ++i) { a = sin.nextInt(); b = sin.nextInt(); int ret = 0; for(long j = a; j <= b; ++j) { if(j >= 10) { int length = 0; long firstPosition, shift=j; for(firstPosition = 1; firstPosition <= shift; firstPosition*=10) length++; firstPosition /= 10; long[] numbers = new long[length]; for(int k = 0; k < length; ++k) { long lastDigit = shift%10; shift /= 10; shift += firstPosition*lastDigit; numbers[k] = shift; boolean found = false; for(int m = 0; m < k; ++m) { if(shift == numbers[m]) { found = true; break; } } if(shift >= a && shift <= b && j < shift && lastDigit != 0 && !found) { ret++; } } } } System.out.println(""Case #""+i+"": ""+ret); } } } " B21612,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.StringTokenizer; public class ProblemC { private static final String OUT = ""C:/workspaces/tc/CodeJam/src/C.out""; private static final String IN = ""D:/downloads/C-large.in""; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(IN)); BufferedWriter bw = new BufferedWriter(new FileWriter(OUT)); int T = Integer.parseInt(br.readLine()); for (int i = 0; i < T; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); String num = st.nextToken(); int k = num.length(); int A = Integer.parseInt(num); int B = Integer.parseInt(st.nextToken()); int res = 0; int mult = 1; for (int j = 0; j < k - 1; j++) { mult *= 10; } Map> map = new HashMap>(2000000); for (int j = A; j <= B; j++) { int t = j; for (int l = 0; l < k - 1; l++) { int rem = t % 10; t = rem * mult + t / 10; if (t > j && t <= B && t >= A) { Set set = map.get(j); if (set == null) { set = new HashSet(6); } set.add(t); map.put(j, set); } } } for (Entry> entry : map.entrySet()) { res += entry.getValue().size(); } bw.write(""Case #"" + (i + 1) + "": "" + res + ""\n""); } bw.close(); } } " B20651,"import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; public class ProblemC { public static void main(String[] args) throws Exception { Scanner in = new Scanner(// // System.in // new FileInputStream(""c-small.in"") new FileInputStream(""c-large.in"") ); PrintStream out = new PrintStream( // // System.out // new FileOutputStream(""c-small.out"") new FileOutputStream(""c-large.out"") ); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); int res = 0; for (int x = A; x < B; x++) { res += cycle(x, A, B); } out.println(""Case #"" + i + "": "" + res); } } private static int cycle(int n, int A, int B) { int m = n; int digits = (int) Math.log10(n) + 1; if (digits == 1) return 0; int mul = 1; for (int i = 1; i < digits; i++) mul *= 10; int ret = 0; HashSet used = new HashSet(); for (int i = 0; i < digits; i++) { m = (m / 10) + (m % 10) * mul; if (m > n && m != n && m <= B && !used.contains(m)) { ret++; used.add(m); } } return ret; } } " B21736,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class QC { static final String TASK_ID = ""qc""; static BufferedReader reader; static PrintWriter writer; public static void main(String[] args) { try { long now = System.currentTimeMillis(); reader = new BufferedReader(new FileReader(TASK_ID + "".in"")); writer = new PrintWriter(TASK_ID + "".out""); int numTests = Integer.parseInt(reader.readLine()); for (int testId = 0; testId < numTests; testId++) { Solver solver = new Solver(testId); solver.readInput(); solver.run(); solver.printOutput(); } reader.close(); writer.close(); System.out.println(System.currentTimeMillis() - now + ""ms""); } catch (Exception e) { throw new RuntimeException(e); } } static class Solver { private int testId; private int A, B; private int result; public Solver(int testId) { this.testId = testId; } public void run() { int digit = (int) Math.log10(A) + 1; int div=1; int pow = (int) Math.pow(10,digit); //System.out.println(""=============== A=""+A+"" B=""+B+"" ====================""); for (int n=A; n<=B; n++) { int div2 = div; int pow2 = pow; int[] matches = new int[digit-1]; int count = 0; for (int j=1; j set = new HashSet(); int nc = sc.nextInt(); for (int tc = 1; tc <= nc; tc++) { int a = sc.nextInt(); int b = sc.nextInt(); int len = Integer.toString(a).length(); char[] c = new char[len]; int res = 0; for (int i = a; i <= b; i++) { set.clear(); int t = i; for (int j = len - 1; j >= 0; j--) { c[j] = (char) (t % 10 + '0'); t /= 10; } for (int j = 0; j < len - 1; j++) { char tmp = c[len - 1]; for (int k = len - 1; k > 0; k--) { c[k] = c[k - 1]; } c[0] = tmp; int blah = Integer.valueOf(new String(c)); if (blah > i && blah <= b) set.add(blah); } res += set.size(); } pw.printf(""Case #%d: %d\n"", tc, res); } pw.close(); } public static void main(String[] args) throws IOException { new C().work(); } } " B21738," import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author JY */ public class ProblemC{ private static int testNum; private static int[][] data; public static void main(String[] args) { input(); int[] result = calc(); output(testNum, result); } private static void input() { Scanner in = null; in = new Scanner(System.in); testNum = Integer.parseInt(in.nextLine()); data = new int[testNum][]; for (int i = 0; i < testNum; i++) { String line = in.nextLine(); String[] nums = line.split("" ""); data[i] = new int[2]; data[i][0] = Integer.parseInt(nums[0]); data[i][1] = Integer.parseInt(nums[1]); } } private static int[] calc() { HashSet hs = new HashSet(); int[] res = new int[testNum]; for (int i = 0; i < testNum; i++) { int result = 0; int a = data[i][0]; int b = data[i][1]; int length = getLength(b); for (int number = a; number <= b; number++) { hs.clear(); for (int shifts = 1; shifts < length; shifts++) { int shiftnum = shift(number, shifts); if (shiftnum <= b && shiftnum > number && !hs.contains(shiftnum)) { result++; hs.add(shiftnum); } } } res[i] = result; } return res; } private static int getLength(int n) { return String.valueOf(n).length(); } private static int shift(int num, int shift) { String numS = String.valueOf(num); int len = numS.length(); numS = reverse(numS, 0, len - shift - 1); numS = reverse(numS, len - shift, len - 1); numS = reverse(numS, 0, len - 1); return Integer.parseInt(numS); } private static String reverse(String target, int start, int end) { char[] tar = target.toCharArray(); while (start < end) { char tmp = tar[start]; tar[start] = tar[end]; tar[end] = tmp; start++; end--; } return new String(tar); } private static void output(int testNum, int[] res) { for (int i = 0; i < testNum; i++) { System.out.printf(""Case #%d: %s\n"", i + 1, res[i]); } } } " B20034,"package c; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); sc.nextLine(); int nbr = 1; while (t-- > 0) { int a = sc.nextInt(); int b = sc.nextInt(); int score = 0; Set set = new HashSet(); while (a < b) { if (!set.contains(a)){ String s = a+""""; Set temp = new HashSet(); for (int i = 0; i < s.length(); i++) { if (s.charAt(0) != '0'){ int asdf = Integer.parseInt(s); if (a <= asdf && asdf <= b){ temp.add(asdf); } } s = s.substring(1, s.length()) + s.charAt(0); } set.addAll(temp); int n = temp.size(); while (n > 1){ score += --n; } } a++; } System.out.printf(""Case #%d: %d\n"", nbr++, score); } } } " B20532,"import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashMap; public class RecycledNumbers{ /** * @param args */ public static void main(String[] args) { try { File inf = new File(""/home/jeyram/Downloads/""+""C-large.in""); File of = new File(""/home/jeyram/Downloads/""+""rl-rn-large-output.in""); FileInputStream in = new FileInputStream(inf); FileOutputStream out = new FileOutputStream(of); // Get the object of DataInputStream //DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line if ((strLine = br.readLine()) != null) { System.out.println (strLine); int itrs= Integer.parseInt(strLine); int count=0; //#test cases while (count < itrs) { if ((strLine = br.readLine()) != null){ // input str String[] inst = strLine.split("" ""); //start no final int A = Integer.parseInt(inst[0]); //end no final int B = Integer.parseInt(inst[1]); //no of numbers int y=0; //no of iterations check 3 for 4 digit number int exp = (String.valueOf(A)).length()-1; int exC=1; while (exC<=exp){ int n =A; while(n<=B){ int pow =1; for(int p1=1;p1n) && (String.valueOf(n)).length()==(String.valueOf(m)).length()){//valid pair //System.out.println("":""+n +"":""+m); y++; } } n++; } exC++; } //System.out.println(""output string""+y); //write as Case #1: 2 3 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); bw.write(""Case #""+(count+1)+"": ""+y); bw.newLine(); bw.flush(); } count++; } } //Close the input stream in.close(); out.close(); }catch (Exception e) { e.printStackTrace(); } finally{ } } }" B21039,"package de.hg.codejam.tasks.numbers.controller; import de.hg.codejam.tasks.io.Reader; import de.hg.codejam.tasks.io.Writer; import de.hg.codejam.tasks.numbers.help.Converter; import de.hg.codejam.tasks.numbers.service.Calculator; public class Test { public static void main(String[] args) { String inputPath = ""file/C-large.in""; String outputPath = Writer.generateOutputPath(inputPath); // System.out.println(""=== READ FILE: "" + inputPath + "" ===""); String[] input = Reader.readFile(inputPath); // Writer.print(input); int[][] inputInts = Converter.convert(input); // System.out.println(""=== CALCULATION: Start ===""); int[] results = Calculator.calculate(inputInts); // System.out.println(""=== CALCULATION: End ===""); // System.out.println(""=== RESULTS ===""); String[] resultStrings = Converter.convert(results); // Writer.write(resultStrings); // System.out.println(""=== WRITE TO FILE: "" + outputPath + "" ===""); Writer.write(resultStrings, outputPath); System.out.println(""=== FILE WRITTEN ===""); } } " B20258,"package codejam.recycled_numbers; import java.io.IOException; import java.util.ArrayList; import codejam.filestuff.FileStuff; public class RecycledNumbers { public static void main(String[] args) throws IOException { FileStuff fs = new FileStuff(""C-large.in"",""C-large.out"",""recycled_numbers""); ArrayList input = new ArrayList(); input = fs.ReadFromFile(); ArrayList output = new ArrayList(); int xCase = Integer.valueOf(input.get(0)); int xPointer = 1; for (int i=1;i<=xCase;i++) { String strOut = ""Case #"" + String.valueOf(i) + "":""; String strLine = input.get(xPointer); xPointer++; String[] arrLine = strLine.split("" ""); int xA = Integer.valueOf(arrLine[0]); int xB = Integer.valueOf(arrLine[1]); int xRec = 0; /*for (int a=xA;a<=xB;a++) { int xLen = String.valueOf(a).length(); int xLimit = 1; for (int b=1;b<=xLen;b++) xLimit *= 10; if (xLimit > xB) xLimit = xB+1; for (int b=a+1;b arrHist = new ArrayList(); for (int b=1;b a) && (xRot <= xB) && (boolTwins == false)) { xRec++; } } } strOut += "" "" + String.valueOf(xRec); output.add(strOut); } fs.WriteToFile(output); System.out.print(""Done!!!""); } public static boolean isRecycled(int num1,int num2) { String str1 = String.valueOf(num1); String str2 = String.valueOf(num2); boolean boolRes = false; if (str1.length() == str2.length()) { for (int i=1;i map; HashMap masterList = new HashMap(); String num; char[] temp; int i,j,k,len; int n, count=0; for (k=a; k<=b; k++) { if (masterList.containsKey(k)) continue; num = Integer.toString(k); char[] digits = num.toCharArray(); len = digits.length; map = new HashMap(); for (i=0; i= a && n <= b) { map.put(n, true); masterList.put(n, true); } } len = map.size(); count += (len*(len-1))/2; } return count; } }" B20003,"package qualification; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Scanner; import java.util.TreeMap; import java.util.Vector; public class ProblemC { static Scanner scan = new Scanner(System.in); public static void main(String[] args) { int cases = scan.nextInt(); for ( int i = 1; i <= cases; i++ ) { System.out.println(""Case #"" + i + "": "" + solveCase()); } } public static int solveCase() { int A = scan.nextInt(); int B = scan.nextInt(); Map map = new HashMap(); Integer[] digits; for ( int i = A; i <= B; i++ ) { digits = getDigits(i); addToMap(digits, map); } int result = 0; for ( Long l : map.values() ) { result += (l * (l-1)) / 2; } return result; } public static void addToMap(Integer[] n, Map map) { Vector rots = getRotationSymmetricValues(n); // Remember to handle leading 0! All must have same length for ( Integer num : rots) { if ( map.containsKey(num) ) { map.put(num, map.get(num)+1); return; } } map.put(digitsToNum(n), 1L); } public static Vector getRotationSymmetricValues(Integer[] n) { Vector result = new Vector(); int origNum = digitsToNum(n); Queue v = new LinkedList(); for ( int i = 0; i < n.length; i++ ) { v.add(n[i]); } while (true) { Integer first = v.poll(); v.add(first); if ( v.peek() == 0 ) continue; int num = 0; for ( Integer i : v) { num *= 10; num += i; } if ( num == origNum ) break; result.add(num); } return result; } public static int digitsToNum(Integer[] digits) { int num = 0; for ( int i = 0; i < digits.length; i++ ) { num *= 10; num += digits[i]; } return num; } static Comparator comp = new Comparator() { @Override public int compare(Integer arg0, Integer arg1) { if ( arg0 == 0 ) return 1; else if ( arg1 == 0) return -1; else return arg0.compareTo(arg1); } }; public static Integer[] getDigits(int n) { int numDigits = (int)Math.log10(n) + 1; Integer[] digits = new Integer[numDigits]; for ( int i = 0; i < numDigits; i++ ) { digits[numDigits-1-i] = n % 10; n /= 10; } return digits; } } " B20409,"package com.codejam; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; public class CodeJam13 { char map[]; public static void main(String[] args) { Scanner fileIn = null; FileWriter fileOut = null; try { fileIn = new Scanner(new File(""input.txt"")); fileOut = new FileWriter(new File(""output.in"")); int noOfTestCases = Integer.parseInt(fileIn.nextLine()); int testCase = 0; while (fileIn.hasNextLine()) { testCase++; int count=0; String sa = fileIn.next(); int len = sa.length(); int factor = (int)Math.pow(10,len-1); int a = Integer.parseInt(sa); int a1=a; int b = fileIn.nextInt(); fileIn.nextLine(); while(a1<=b){ HashSet set = new HashSet(); for(int i=0;i=a1 && newA<=b){ if(set.add(newA)){ count++; } } a=newA; } //System.out.println(a1 + "" "" + count); a=++a1; } fileOut.write(""Case #"" + testCase + "": "" + count + ""\n""); } fileIn.close(); fileOut.close(); } catch (IOException ex) { System.out.println(ex.getMessage()); } } } " B21768,"package google; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws FileNotFoundException, IOException { IO.changeGoogleIO('C', 1); Scanner input = new Scanner(System.in); int n = input.nextInt(); int a, b; int x, digit; int len; int result0; String s; String result; for (int i = 0; i < n; ++i) { result = ""Case #"" + (i + 1) + "": ""; a = input.nextInt(); b = input.nextInt(); result0 = 0; for (int j = a; j <= b; ++j) { s = j + """"; len = s.length(); do { s = s.charAt(len - 1) + s.substring(0, len - 1); x = Integer.parseInt(s); if ((x > j) && (x >= a) && (x <= b)) ++result0; } while (x != j); } result += result0; System.out.println(result); } } } " B20109,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycle; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class Recycle { public static int recyclepos(String a, String b) { int iter = 0; int c = Integer.parseInt(a); // System.out.println(c); int d = Integer.parseInt(b); // System.out.println(d); int e = a.length(); // System.out.println(e); int x = c; int[] s = new int[d-c]; int[] s1 = new int[a.length()]; for(int i = 0; i < d-c; i++) { s[i] = x; x++; } for(int i = 0; i < d - c + 1; i++) { int h = Integer.parseInt(a); if (i != 0 && s[i-1] != 0) { for(int j = e - 1; j > 0; j--) { String f = a.substring(e-j) + a.substring(0, e-j); //System.out.println(f); int g = Integer.parseInt(f); //System.out.println(g); s1[j] = g; for(int y = 0; y < s1.length; y++) { if(y == j); else if(s1[y] == g) { g = 0; break; } } if(g > c && g > h && g <= d) iter = iter + 1; //System.out.println(""interations: ""+ iter); } } if(i < d-c){ a = String.valueOf(s[i]); } } return iter; } public static void main(String[] args) throws FileNotFoundException, IOException { FileReader theFileID = new FileReader(""C-large.in""); BufferedReader inFile = new BufferedReader(theFileID); FileWriter fw = new FileWriter(""output.txt""); PrintWriter output = new PrintWriter(fw); String line; int numCases = 0; if((line = inFile.readLine()) != null) numCases = Integer.parseInt(line); String[] x = null; for(int i = 0; (line = inFile.readLine()) != null && i < numCases; i++) { x = line.split("" ""); String a = x[0]; String b = x[1]; int y = recyclepos(a, b); output.write(""Case #""+ (i + 1) + "": "" + y); output.println(); } inFile.close(); output.close(); fw.close(); System.out.println(recyclepos(""1"", ""9"")); System.out.println(recyclepos(""10"", ""40"")); System.out.println(recyclepos(""100"", ""500"")); System.out.println(recyclepos(""1111"", ""2222"")); } } " B20947,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.Writer; import java.util.Arrays; /** * Recycled Numbers * @author shibink * */ public class Recycle { public static int getCount(String str) { int count = 0; long tmp = 0; int numDigits = 0; if ((str == null) || (str.isEmpty())) { return count; } String[] strArray = str.split("" ""); // It should be 2 if (strArray.length != 2) { return 0; } long num1 = Long.parseLong(strArray[0]); long num2 = Long.parseLong(strArray[1]); tmp = num1; // Find number of digits in num1 & num2 while (tmp > 0) { numDigits++; tmp = tmp / 10; } long arr[] = new long[numDigits]; int cnt; for (long i = num1; i <= num2; i++) { Arrays.fill(arr, 0); cnt = 0; for (long val = i, j = 1; j < numDigits; j++) { tmp = val % 10; if (tmp == 0) { val = val/10; continue; } val = (int) (tmp * Math.pow(10, (numDigits - 1)) + (val / 10)); for (int k=0; k i) && (val <= num2)) { count++; } } } return count; } public static void processFile(String fileName) throws IOException { FileInputStream fstream = new FileInputStream(fileName); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); // use buffering Writer output = new BufferedWriter(new FileWriter(""output.txt"")); try { String strLine = null; int numRecycle = 0; int count = 0; if ((strLine = br.readLine()) != null) { count = Integer.parseInt(strLine); } // Read File Line By Line for (int i = 1; i <= count; i++) { if ((strLine = br.readLine()) == null) { return; } numRecycle = getCount(strLine); System.out.println(""Case #"" + i + "": "" + numRecycle); StringBuffer outBuff = new StringBuffer(""Case #"" + i + "": "" + numRecycle + ""\n""); output.write(outBuff.toString()); } } finally { // Close the input stream in.close(); output.close(); } } /** * @param args */ public static void main(String[] args) { String fileName = ""input.in""; try { processFile(fileName); } catch (IOException e) { // TODO Log error } return; } } " B21204,"import java.awt.datatransfer.*; import java.awt.Toolkit; public class Repeat { private static String inp; public Repeat() { } public static void main(String[] args) { Transferable temp = (Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null)); try { inp = (String) temp.getTransferData(DataFlavor.stringFlavor); } catch (Exception e) { System.out.println(e); } System.out.println(inp); System.out.println(""Breakdown >"" + inp.substring(inp.indexOf(""\n""))); //int iterations = Integer.parseInt(inp.substring(inp.indexOf(""\n""))); String[] newlineSplit = inp.split(""\n""); int iterations = Integer.parseInt(newlineSplit[0]); System.out.println(iterations); System.out.println(""Solutions:\n\n\n\n""); //String cases = inp.substring(inp.indexOf(""\n"")); for(int i = 1; i < newlineSplit.length;i++) { String[] nums = newlineSplit[i].split("" ""); getCount(Integer.parseInt(nums[0]) ,Integer.parseInt(nums[1]), i); } } public static void getCount(int a, int b, int caseNum) { int count = 0; while(a <= b) { String sA = """" + a; String sB = """" + b; //System.out.println(sA + "" "" + sB); for(int i = 0; i < sA.length();i++) { String temp = sA.substring(sA.length() - i-1) + sA.substring(0,sA.length() - i - 1); int iT = Integer.parseInt(temp); int iA = Integer.parseInt(sA); //System.out.println("">>["" + temp + ""] "" + (iT - iA) ); if(iT - iA > 0 && iT <= b) { count++; //System.out.println("">>>>>>> "" + sA + "" "" + temp + "" "" + (iT - iA)); } //else //System.out.println("">>["" + temp + ""] "" + (iT - iA) ); } a++; } System.out.println(""Case #"" + caseNum + "": "" + count); } } " B20000,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledNumbers { static String input; static int[][] data; static int length; static String output = """"; public static String readInput(String file) { BufferedReader in = null; try { in = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String content = """"; try { String line; while((line = in.readLine()) != null) { content = content.concat(line+""\n""); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return content; } public static void writeOutput(String output, String filename) { BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(filename)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //out.print(output); try { out.write(output); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void parseInput(String in) { String[] lines = in.split(""\\r?\\n""); String[][] line_content = new String[lines.length][2]; length = Integer.parseInt(lines[0]); for(int i=1;i temp2 = new ArrayList(); String temp; for(int i=1;i<10;i++) for(int j=0;j<10;j++) { temp = """" + i + j; temp2.add(temp); } for(int i=1;i<10;i++) for(int j=0;j<10;j++) for(int k=0;k<10;k++) { temp = """" + i + j + k ; temp2.add(temp); } for(int i=1;i<10;i++) for(int j=0;j<10;j++) for(int k=0;k<10;k++) for(int l=0;l<10;l++) { temp = """" + i + j + k + l; temp2.add(temp); } for(int i=1;i<10;i++) for(int j=0;j<10;j++) for(int k=0;k<10;k++) for(int l=0;l<10;l++) for(int m=0;m<10;m++) { temp = """" + i + j + k + l + m; temp2.add(temp); } for(int i=1;i<10;i++) for(int j=0;j<10;j++) for(int k=0;k<10;k++) for(int l=0;l<10;l++) for(int m=0;m<10;m++) for(int n=0;n<10;n++) { temp = """" + i + j + k + l + m + n; temp2.add(temp); } for(int j=0;j<10;j++) for(int k=0;k<10;k++) for(int l=0;l<10;l++) for(int m=0;m<10;m++) for(int n=0;n<10;n++) for(int p=0;p<10;p++) { temp = """" + '1' + j + k + l + m + n + p; temp2.add(temp); } String[] perms = new String[temp2.size()]; temp2.toArray(perms); int total=0; int x; int T= in.nextInt(); for(int t=0;t distinct = new HashSet(); for(int i=0;iB) break; distinct.clear(); temp = perms[i]; if(Integer.parseInt(perms[i])>=A && Integer.parseInt(perms[i])<=B) { distinct.add(Integer.parseInt(perms[i])); for(int j=0;j=A && temp.charAt(0) != '0') distinct.add(x); } total+= distinct.size()-1; //if(distinct.size()>1) // System.out.println(perms[i] + "" "" + (distinct.size()-1)); } } out.println(""Case #""+ (t+1) +"": "" + total/2); } in.close(); out.close(); } } " B20112,"package com.nitrous.codejam; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; public class CodeJamProblem3 { public static void readFile(String inputFile) throws IOException { File in = new File(inputFile); File dir = in.getParentFile(); File outFile = new File(dir, in.getName()+"".out""); System.out.println(""Output file is ""+outFile.getAbsolutePath()); PrintWriter out = new PrintWriter(outFile); BufferedReader reader = new BufferedReader(new FileReader(in)); String line = null; int testCaseCount = Integer.parseInt(reader.readLine().trim()); System.out.println(""Read count=""+testCaseCount); for (int testCase = 0 ; testCase < testCaseCount; testCase++) { line = reader.readLine(); String[] numStrArr = line.split("" ""); int min = Integer.parseInt(numStrArr[0]); int max = Integer.parseInt(numStrArr[1]); int count = 0; for (int current = min; current <= max; current++) { count += countRecycled(current, max); } out.println(""Case #""+(testCase+1)+"": ""+count); } out.flush(); out.close(); } private static int countRecycled(int current, int maxValue) { String curAsStr = String.valueOf(current); int maxLen = curAsStr.length(); HashSet unique = new HashSet(); for (int len = 1; len < maxLen; len++) { String move = curAsStr.substring(0, len); String mid = curAsStr.substring(len); String newStr = mid + move; while (newStr.length() > 1 && newStr.startsWith(""0"")) { newStr = newStr.substring(1); } int newNum = Integer.parseInt(newStr); if (newNum > current && newNum <= maxValue) { unique.add(newNum); } } return unique.size(); } public static void main (String[] args) throws IOException { readFile(""D:/workspace/CodeJam/data/C-large.in""); } } " B20944,"package main; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; import com.google.common.base.Charsets; import com.google.common.base.Splitter; import com.google.common.io.Files; public class Recycle2 { public static void main(String[] args) throws IOException{ final JFileChooser fc = new JFileChooser(new File(""C:\\Users\\munsey\\Documents\\jam"")); FileNameExtensionFilter filter = new FileNameExtensionFilter(""txt"", ""txt""); fc.setFileFilter(filter); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); List lines = Files.readLines(file, Charsets.UTF_8); Iterator itr = lines.iterator(); itr.next(); int caseNum = 0; while(itr.hasNext()) { caseNum++; Iterator minMax = Splitter.on("" "").split(itr.next()).iterator(); int min = Integer.parseInt(minMax.next()); int max = Integer.parseInt(minMax.next()); int size = 0; for(int k = min; k <= max ; k++){ size += recycle(k, min, max); } System.out.println(""Case #"" + caseNum + "": "" + (size/2)); } } } public static int recycle(int input, int min, int max){ Set output = new HashSet(); String sInput = Integer.valueOf(input).toString(); StringBuffer build; for(int i = 0; i < sInput.length(); i++){ build = new StringBuffer(); for(int j = 0; j < sInput.length(); j++){ build.append(sInput.charAt((i + j) % sInput.length())); } if(build.charAt(0) != 0 && !build.toString().equals(sInput)){ int x = Integer.parseInt(build.toString()); if(x >= min && x <= max){ output.add(x); } } } return output.size(); } } " B22042,"package google.solver; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; public class ProblemPackageCreator implements ChallengeConstants{ private final String packageName; private String directoryName; private String challengeDef; private String readerName; private String challengeName; private String packagePath; ProblemPackageCreator(String packageName){ this.packageName = packageName; packagePath = ""google.contest.""+packageName; directoryName = BASE_DIR+DELIMITER+packageName; challengeDef = BASE_DIR+DELIMITER+packageName+DELIMITER+CHALLENGE_DEFINITION; readerName = packageName.substring(0,1).toUpperCase()+packageName.substring(1)+""Reader""; challengeName = packageName.substring(0,1).toUpperCase()+packageName.substring(1)+""Challenge""; } private void create() { try{ createDirectory(); createTestIn(); createChallengeDefinition2(); createReader(); createChallenge(); } catch(Exception e){ throw new RuntimeException(e); } } private void createTestIn() { writeToPath(TEST_IN, """"); } private void createChallenge() { String def =""package ""+packagePath+"";\n\n""+ ""import google.loader.Challenge;\n""+ ""import google.problems.AbstractChallenge;\n\n""+ ""public class ""+challengeName+"" extends AbstractChallenge implements Challenge {\n\n""+ ""public ""+challengeName+""(int number) {\n""+ ""super(number);\n""+ ""setResult(\""\"");\n""+ ""}\n""+ ""}\n""; writeJava(challengeName, def); } private void createReader() { String def = ""package ""+packagePath+"";\n\n""+ ""import google.loader.Challenge;\n""+ ""import google.problems.AbstractReader;\n\n""+ ""public class ""+readerName+"" extends AbstractReader {\n \n""+ ""@Override\n""+ ""protected Challenge createChallenge(int number) {\n""+ ""int theLine = getActualLine();\n""+ ""String[] lines = getLines();\n""+ ""int value = Integer.parseInt(getLines()[theLine]);\n""+ challengeName+"" chal = new ""+challengeName+""(number);\n""+ ""setActualLine(theLine+1);\n""+ ""return chal;\n""+ ""}\n""+ ""\n""+ ""}\n""; writeJava(readerName, def); } private void writeToPath(String fileName, String text){ write(directoryName+DELIMITER+fileName, text); } private void writeJava(String baseName, String text) { writeToPath(baseName+"".java"", text); } private void createChallengeDefinition() { String def = ""fileName=""+TEST_IN+""\n""+ ""# fileName=A-small-practice.in\n""+ ""# fileName=A-large-practice.in\n""+ ""# fileName=B-small-practice.in\n""+ ""# fileName=B-large-practice.in\n""+ ""# fileName=C-small-practice.in\n""+ ""# fileName=C-large-practice.in\n""+ ""readerClassName=""+packagePath+"".""+readerName; write(challengeDef, def); } private void createChallengeDefinition2() { String def = ""fileName=""+TEST_IN+""\n""+ ""# fileName=""+packageName+""-small-practice.in\n""+ ""# fileName=""+packageName+""-large-practice.in\n""+ ""readerClassName=""+packagePath+"".""+readerName; write(challengeDef, def); } private void createDirectory() throws Exception{ File file = new File(directoryName); if(! file.exists()){ file.mkdir(); }else{ throw new RuntimeException(""alreadyExisting""); } } public static void main(String[] args) { String packageName =CHALLENGE_NAME; ProblemPackageCreator creator = new ProblemPackageCreator(""A""); creator.create(); creator = new ProblemPackageCreator(""B""); creator.create(); creator = new ProblemPackageCreator(""C""); creator.create(); } public static void write(String aFileName, String text) { try{ FileWriter fstream = new FileWriter(aFileName); BufferedWriter out = new BufferedWriter(fstream); out.write(text); out.close(); }catch (Exception e){ throw new RuntimeException(e); } } } " B21348,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; public class Recycle { public static String recycle(int a, int b) { int result = 0; int digit, temp, cnt; String str; int array[] = new int[b + 1]; for (int i = 0; i < b; i++){ array[i] = 0; } for (int i = a; i < b; i++){ if (array[i] == 1) continue; array[i] = 1; str = i+""""; digit = str.length(); temp = i; cnt = 0; for (int j = 0; j < digit - 1; j++){ temp = (temp / 10) + (temp % 10)*(int)Math.pow(10, digit - 1); if (temp == i) break; if (a <= temp && temp <= b){ if(array[temp] == 0){ cnt++; array[temp] = 1; //System.out.println(String.format(""(%d, %d)"", i, temp)); } } } result += factorial(cnt); } return """" + result; } public static int factorial(int a){ if (a <= 0) return 0; return a + factorial(a - 1); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int T = 0; String str = """"; File input = new File(args[0]); FileReader fileReader; BufferedReader br; File output = new File(""output_recycle.txt""); BufferedWriter bw; StringTokenizer tokenizer; try { bw = new BufferedWriter(new FileWriter(output)); fileReader = new FileReader(input); br = new BufferedReader(fileReader); str = br.readLine(); T = Integer.parseInt(str); for (int i = 0; i < T; i++) { int a; int b; str = br.readLine(); tokenizer = new StringTokenizer(str); a = Integer.parseInt(tokenizer.nextToken()); b = Integer.parseInt(tokenizer.nextToken()); bw.write(String.format(""Case #%d: %s\n"", i+1, recycle(a, b))); } br.close(); fileReader.close(); bw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B21446,"package codejam; import java.io.*; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class RecycledNumbers { public static final String LINE_SEPARATOR = System.getProperty(""line.separator""); public static int recycleNum(int a, int b) { Map map = new HashMap(); int n = String.valueOf(a).length(); int c = 0; for (int i = a; i <= b; i++) { for (int j = 1; j < n ; j++) { int rNum = rotateRight(i, j); if (i < rNum && rNum <= b) { if (!map.containsKey(rNum) || map.get(rNum) != i) { map.put(rNum, i); c++; } } } } return c; } private static int rotateRight(int i, int j) { int length = String.valueOf(i).length(); int sP = (int) Math.pow(10, j); int bP = (int) Math.pow(10, length - j); int rem = i % sP; return ((i - rem) / sP) + (rem * bP); } public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new File(""D:\\codejam\\C-large.in"")); Writer writer = new OutputStreamWriter(new FileOutputStream(""D:\\codejam\\C-large.out"")); Integer n = Integer.valueOf(scanner.nextLine()); for (int i = 1; i <= n; i++) { System.out.println(); int a = scanner.nextInt(); int b = scanner.nextInt(); writer.write(""Case #"" + i + "": "" + recycleNum(a, b)); writer.write(LINE_SEPARATOR); } scanner.close(); writer.close(); } } " B20971,"import java.util.*; class Recycle{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int testcase, A, B; testcase = sc.nextInt(); for(int i=1;i<=testcase;i++){ A = sc.nextInt(); B = sc.nextInt(); System.out.println(""Case #""+i+"": ""+countpair(A,B)); } } public static int countpair(int A, int B){ int numdigit, temp = A, temp2, counter; int[] remember; counter = 0; while(A<=B){ remember = new int[7]; numdigit = (int)Math.log10((double)A) + 1; temp = A; for(int i=0;i A && checker<=B){ for(i=0;i set = new HashSet(); //if (set.isEmpty()) System.out.print(""\nSET IS EMPTY""); for (int i = min; i <= max; i++) { String s = """" + i; for (int r = 1; r < s.length(); r++) { String m = returnM(s, r); int num = Integer.parseInt(m); String mn = s + m; //System.out.printf(""%d(%s)(*%d*), "", i, m, num); if((num >= min) && (num <= max) && (num != i)) set.add(mn); } } //if (set.isEmpty()) System.out.print(""\nSET IS EMPTY""); int c = set.size()/2; System.out.printf(""Case #%d: %d\n"", t+1, c); } } public static String returnM(String s, int r){ int N = s.length(); if(r != N){ String i = s.substring(0, N - r); i = s.substring(N - r, N) + i; return i; } else return s; } } " B21855,"package gcj2012; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class RecycledNumbers { private static final class IntPair { Integer a, b; IntPair(Integer a,Integer b) { this.a = a; this.b = b; } @Override public boolean equals(Object obj) { IntPair other = (IntPair) obj; return a.equals(other.a) && b.equals(other.b); } @Override public int hashCode() { return a.hashCode() * b.hashCode(); } } private static Map beenThereDoneThat; public static void main(String[] args) throws IOException { Scanner scn = new Scanner(new File(""C-large.txt"")); PrintWriter output = new PrintWriter(new FileWriter(""out2.txt"")); int size = scn.nextInt(); for (int i = 1; i <= size; i++) { int total = 0; int a = scn.nextInt(); int b = scn.nextInt(); for (int j = a; j <= b; j++) { total += count(j, b); } output.write(""Case #"" + i + "": "" + total); output.write('\n'); } output.close(); } private static int count(Integer curr, Integer max) { String currString = curr.toString(); int currSize = currString.length(); if (currSize == 1) { return 0; } beenThereDoneThat = new HashMap(); int localCount = 0; //i is start index of end part, which is moving to the front for (int i = 1; i < currSize; i++) { String newCurr = currString.substring(i) + currString.substring(0, i); int newCurrInt = Integer.valueOf(newCurr); if (newCurrInt > curr && newCurrInt <= max) { IntPair pair = new IntPair(curr, newCurrInt); if (beenThereDoneThat.get(pair) == null) { beenThereDoneThat.put(pair, new Object()); localCount++; } // if (localCount == 1) { // System.out.print(curr); // } // System.out.print("" ""+newCurrInt); } } // if (localCount !=0) { // System.out.println(); // } return localCount; } } " B22114," import java.util.*; import java.io.*; public class rcycn { public static void main(String[] args) throws Exception { BufferedReader inputer = new BufferedReader(new FileReader(""rcycn.in"")); PrintWriter outputer = new PrintWriter(new BufferedWriter(new FileWriter(""rcycn.out""))); int T = Integer.parseInt(inputer.readLine()); for(int i = 0; i < T; i++) { StringTokenizer st = new StringTokenizer(inputer.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int answer = 0; if(B >= 10) for(int n = A; n <= B; n++) for(String m = rotate(String.valueOf(n)); Integer.parseInt(m) != n; m = rotate(String.valueOf(m))) if(Integer.parseInt(m) <= B && Integer.parseInt(m) > n) answer++; outputer.println(""Case #"" + (i + 1) + "": "" + answer); } outputer.close(); inputer.close(); } public static String rotate(String n) { return n.substring(n.length() - 1) + n.substring(0, n.length() - 1); } }" B21922,"import java.io.*; import java.util.*; import java.math.*; /** @author Samuel Ahn */ public class C { public static void main(String args[]) throws Exception { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); int sum = 0; for (int n = A; n < B; n++) { String x = Integer.toString(n); ArrayList list = new ArrayList(); for (int j = 1; j < x.length(); j++) { String a = x.substring(0, j); String b = x.substring(j); int tmp = Integer.parseInt(b + a); if ((tmp > n) && (tmp <= B) && (!list.contains(tmp))) { sum++; list.add(tmp); //break; } } } System.out.printf(""Case #%d: %d\n"", i, sum); } } }" B21310,"import java.io.File; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNumbers { private static Scanner scan; private static PrintWriter writer; private static File input = new File(""C-large.in""); private static File output = new File(""C-large.out""); public static void main(String[] args) throws Exception { scan = new Scanner(input); writer = new PrintWriter(output); int total = scan.nextInt(); int A, B; for (int t = 1; t <= total; t++) { A = scan.nextInt(); B = scan.nextInt(); if (B < 10) { String result = ""Case #"" + t + "": "" + 0; System.out.println(result); writer.println(result); continue; } else if (A == 1111 && B == 2222) { System.out.println(287); continue; } int match = 0; // String str = """"; for (int n = A, lv, tmp; n <= B; n++) { lv = 10; while (n > (tmp = lv * 10)) lv = tmp; for (int i = 10, j = lv, m; i <= lv; i *= 10, j /= 10) { m = (n / i) + (n % i) * j; // System.out.print(n + "" "" + m); if (n < m && m <= B) { // System.out.print("" MATCH""); match++; // str += (match + "" "" + n + "" "" + m + ""\n""); } // System.out.println(); } } String result = ""Case #"" + t + "": "" + match; System.out.println(result); writer.println(result); // System.out.print(str); } writer.flush(); } } " B20607,"import java.io.File; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class C { public static void main(String[] args) throws Exception{ long tIni=System.currentTimeMillis(); Scanner s=new Scanner(new File(""./data/C.txt"")); PrintWriter pw=new PrintWriter(new File(""./data/C_sol.txt"")); int ncases=s.nextInt();s.nextLine(); for(int curr=0;currA && resp<=B && resp>j ) { boolean ok=true; for(int i=0;ii && Integer.parseInt(o)<=B ){ boolean ok=true; int resp=Integer.parseInt(o); for(int j=0;j visited = new ArrayList(); for(int n = a; n <= b; n++){ String ns = """" + n; for(int j = 1; j <= ns.length() - 1; j++){ int m = (int)((n % Math.pow(10, ns.length() - j)) * Math.pow(10, j)) + (n / (int)Math.pow(10, ns.length() - j)); if(!visited.contains(m) && m > n && m >= a && m <= b){ count++; visited.add(m); //System.out.println(n + "" "" + m); } } visited.clear(); } //count /= 2; fout.println(""Case #"" + (i + 1) + "": "" + count); fout.flush(); s = fin.readLine(); } } }" B21418,"import java.io.*; import java.util.HashSet; public class ProblemC { public static void main(String[] args) throws Exception { String base = ""C-large""; BufferedReader reader = new BufferedReader(new FileReader(base+"".in"")); BufferedWriter writer = new BufferedWriter(new FileWriter(base+"".out"")); int place = 0; reader.readLine(); while (reader.ready()) { String line = reader.readLine(); String[] strs = line.split("" ""); int a = Integer.parseInt(strs[0]); int b = Integer.parseInt(strs[1]); int num = solve(a,b); writer.write(""Case #"" + (++place) + "": "" + num+'\n'); } reader.close(); writer.close(); } public static int solve(int a, int b) { int number = 0; for (int i=a;i<=b;i++) { HashSet set = new HashSet(); String str = i+""""; for (int p=str.length()-1;p>=1;p--) { String test = str.substring(p) + str.substring(0,p); int j = Integer.parseInt(test); String test2 = j+""""; if (i < j && j <= b && str.length()==test2.length() && !set.contains(j)) { set.add(j); number++; } } } return number; } } " B20249,"package codejam.qual2012; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; public class C { public int count(int start, int end) { int count = 0; for (int i = start; i <= end; i++) { String a = Integer.toString(i); Set unique = new HashSet(); String b = a; for (int j = 0; j < a.length() - 1; j++) { b = b.substring(a.length() - 1, a.length()) + b.substring(0, a.length() - 1); if (unique.contains(b)) { continue; } else { unique.add(b); } // System.out.println(b); int bi = Integer.parseInt(b); if (bi > i && bi <= end) { // System.out.println(a + "": "" + b); count++; } } } return count; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintStream out = new PrintStream(new BufferedOutputStream(System.out)); String line = in.readLine(); int testCases = Integer.parseInt(line); C c = new C(); // Read in all test cases for (int testCase = 1; testCase <= testCases; testCase++) { line = in.readLine(); String[] data = line.split("" ""); int start = Integer.parseInt(data[0]); int end = Integer.parseInt(data[1]); out.println(""Case #"" + testCase + "": "" + c.count(start, end)); } out.flush(); } } " B21894,"import java.io.*; import java.util.*; public class q3 { public static void main(String []args) throws IOException { PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter(""output.txt""))); BufferedReader br=new BufferedReader(new FileReader(""input.txt"")); int arr[]=new int[2]; int limit=Integer.parseInt(br.readLine()); String x2; int count=0; for(int li=1;li<=limit;li++) {count=0; x2=br.readLine(); int j=0; StringTokenizer st =new StringTokenizer(x2); while (st.hasMoreElements()) { String token = st.nextElement().toString(); arr[j]=Integer.parseInt(token); j++; } for(int a1=arr[0];a1<=arr[1];a1++) { String x1=String.valueOf(a1); int l=x1.length(); String final1=""""; for(int x=1;x<=(l-1);x++) { final1=x1.substring(l-x,l)+x1.substring(0,l-x); int check=Integer.parseInt(final1); if(a1 numbers = new TreeSet(); for(int i = 1; i <= cases; i++) { a = in.nextInt(); b = in.nextInt(); numDigits = (a + """").length(); count = 0; for(int j = a; j < b; j++) { oStr = j + """"; numbers.clear(); for(int k = 1; k < numDigits; k++) { nStr = oStr.substring(numDigits - k) + oStr.substring(0, numDigits - k); newNum = Integer.parseInt(nStr); if(newNum > j && newNum <= b) { numbers.add(newNum); } } count += numbers.size(); } w.write(String.format(""Case #%d: %d\n"", i, count)); } w.close(); } } " B20597,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class ProblemC { private String line = """"; private String fileContents = """"; private String delim = ""\r\n""; private String fileName = ""C-small-attempt0.in""; public void solve() { StringTokenizer st = new StringTokenizer(fileContents,delim); StringTokenizer lineToken = null; int count = 1; int testCases = 0; int lower = 0; int upper = 0; int y = 0; ArrayList numbersList = new ArrayList(); testCases = Integer.parseInt(st.nextToken()); while(st.hasMoreTokens()) { line = st.nextToken(); System.out.print(""Case #""); System.out.print(count++); System.out.print("": ""); lineToken = new StringTokenizer(line,"" ""); lower = Integer.parseInt(lineToken.nextToken()); upper = Integer.parseInt(lineToken.nextToken()); y = 0; int numberLen = 0; for(int i=lower; i l = new ArrayList(); for (int k=0;kB||ti<=i) continue; if (!l.contains(ti)) { l.add(ti); n++; } } } return n; } public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""input.txt"")); int num = Integer.parseInt(in.readLine()); for (int i=0;i hs = new HashSet(); for(int i = startnum; i <=endnum ; i++){ String source = String.valueOf(i); String rotated = String.valueOf(i); int numofrotation = 1; while(numofrotation0){ hs.add(source+rotated); }else{ hs.add(rotated+source); } } numofrotation++; } } return hs.size(); } public static String getRotatedString(String source){ return source.substring(source.length()-1)+source.substring(0, source.length()-1); } // public static int getRecycledNumber2(String start, String end){ // int startnum = Integer.parseInt(start); // int endnum = Integer.parseInt(end); // int numofdigit = start.length(); // // int result =0; // // for (int i = startnum ; i <=endnum ; i++){ // for(int j = i+1 ; j <= endnum ; j++){ // int numofrotation = 1; // while(numofrotation results = new HashSet<>(); /** * @param args */ public static void main(String[] args) { if (args.length == 1) { String fileName = args[0]; ProblemThree problemOne = new ProblemThree(); try { problemOne.solveFile(fileName); } catch (FileNotFoundException fnf) { System.out.println(""File not found!""); System.out.println(fnf.getMessage()); } catch (IOException e) { System.out.println(""Could not read file!""); } } else { System.out.println(""Need 1 argument!""); } } private void solveFile(String fileName) throws IOException { StringBuilder output = new StringBuilder(); File file = new File(fileName); FileReader fileReader = new FileReader(file); BufferedReader reader = new BufferedReader(fileReader); String numberOfCasesString = reader.readLine(); int numberOfCases = Integer.parseInt(numberOfCasesString); for (int i = 1; i <= numberOfCases; i++) { output.append(""Case #"" + i + "": ""); output.append(solveLine(reader.readLine())); output.append(""\r\n""); } //output.append(results.size()); FileWriter writer = new FileWriter(fileName.replace("".in"", "".out"")); writer.write(output.toString()); writer.close(); } private String solveLine(String lineToBeSolved) { int result = 0; String[] parts = lineToBeSolved.split("" ""); int startingNumber = Integer.parseInt(parts[0]); int endingNumber = Integer.parseInt(parts[1]); for (int i = startingNumber; i <= endingNumber; i++) { countRecycled(i, endingNumber); } result = results.size(); results = new HashSet<>(); return """" + result; } private void countRecycled(int source, int endingNumber) { StringBuilder builder = new StringBuilder(); builder.append(source); for (int i = 1; i < builder.length(); i++) { String checkNumber = builder.substring(i) + builder.substring(0,i); int resultNumber = Integer.parseInt(checkNumber); if (resultNumber > source && resultNumber <= endingNumber) { results.add("""" + source + """" + resultNumber); } } } } " B21497,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; /** * */ /** * @author Pandapotan Christian * */ public class RecycledNumbers { /* * Write string to a file with specified path */ public static void writeFile(String filePath, String content){ try{ PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); out.write(content); out.close(); } catch(IOException e){ e.printStackTrace(); } } /* * Return array that contains each lines of the input file, null if the reading process failed */ public static ArrayList getLines(String filePath){ ArrayList lines = null; try{ lines = new ArrayList(); String s; BufferedReader in = new BufferedReader( new FileReader(filePath)); while ((s = in.readLine()) != null) { lines.add(s); } in.close(); }catch(IOException e){ e.printStackTrace(); } return lines; } /** * Replace value with the real path */ public static final String fileIn = ""D:\\CodeJam\\RecycledNumbers-large.in""; /** * @param args */ public static void main(String[] args) { //get input from file ArrayList lines = getLines(fileIn); //process data if(lines!=null){ System.out.println(""System Start""); long systemStart = System.currentTimeMillis(); String firstLine = lines.get(0); int T = Integer.parseInt(firstLine); //Main Algorithm StringBuffer result = new StringBuffer(); for(int testIdx = 1; testIdx<=T; testIdx++){ System.out.println(""Test Case Number: ""+testIdx); long start = System.currentTimeMillis(); String param[] = lines.get(testIdx).split("" ""); int A = Integer.parseInt(param[0]); int B = Integer.parseInt(param[1]); int total = countRecycle(A, B); long elapsedTime = System.currentTimeMillis() - start; System.out.println(""Case #""+testIdx+"" takes ""+elapsedTime+""ms.""); //Append the result with the previous testcase result.append(""Case #""+testIdx+"": ""+ total+""\n""); } //write the result to a file String fileOut = fileIn.replace("".in"", "".out""); writeFile(fileOut, result.toString()); System.out.println(""SUCCESS""); long elapsedTimeSyetem = System.currentTimeMillis() - systemStart; System.out.println(""Time Elapsed to run whole test case: ""+elapsedTimeSyetem+""ms""); } } public static int countRecycle(int A, int B){ int count = 0; for(int i = A; i<=B; i++){ String number = i+""""; HashMap checker = new HashMap(); for(int charIdx = 1; charIdxi && newNumber<=B) checker.put(newNumber, true); } count += checker.size(); } return count; } } " B21712,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; public class CodeJamSolverRecycle { public static HashMap> valueToIndexMap=new HashMap>(); public static void main(String[] args) { int numTestCases=0; int numLinePerTestCase=1; int currentCase=0; String inputFileName=""C-large.in""; //String inputFileName=""input.in""; BufferedReader br=null; StringBuilder solutionString=new StringBuilder(); int lineCount=0; try{ String line; br=new BufferedReader(new FileReader(inputFileName)); while((line=br.readLine())!=null){ lineCount++; if(lineCount==1){ numTestCases=Integer.parseInt(line); continue; } String[] splittedLine=line.split(""\\s+""); long a=Long.parseLong(splittedLine[0]); long b=Long.parseLong(splittedLine[1]); String solution=getSolution(a,b); System.out.println(solution); currentCase++; solutionString.append(""Case #""+currentCase+"": ""+solution+""\n""); } br.close(); writeTextToFile(inputFileName.replace("".in"", "".out""), solutionString.toString().trim()); } catch(IOException ex){ System.out.println(""Unable to read from file!""); ex.printStackTrace(); } } private static String getSolution(long a, long b) { HashSet resultSet=new HashSet(); for(long n=a;n<=b;n++){ String nString=Long.toString(n); for(int i=1;i>(); for(int i=0;i indicesList=new ArrayList(); if(valueToIndexMap.containsKey(intArray[i])){ indicesList=valueToIndexMap.get(intArray[i]); } indicesList.add(i); valueToIndexMap.put(intArray[i], indicesList); } return intArray; } public static void writeTextToFile(String fileName, String textToWrite){ try{ BufferedWriter bw= new BufferedWriter( new FileWriter(fileName)); bw.write(textToWrite); bw.close(); } catch(IOException ex){ System.out.println(""Unable to write to file!""); ex.printStackTrace(); } } } " B20368,"package Practice; import java.util.ArrayList; import java.util.Scanner; public class B { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int t = 1; int a, b; ArrayList[] v = new ArrayList[2000010]; for (int i = 0; i < v.length; i++) v[i] = new ArrayList(); while (n-- > 0) { a = in.nextInt(); b = in.nextInt(); int cnt = 0; long x; String s = a + """"; int len = s.length(); long pow = 1; for (int i = 0; i < len - 1; i++) pow *= 10; for (int i = a; i <= b; i++) v[i].clear(); for (int i = a; i <= b; i++) { x = i; for (int j = 0; j < len; j++) { if (x % 10 == 0) { long tm = 10; while (x % tm == 0) { tm *= 10; } x = (x % tm) * pow / (tm / 10) + x / (tm); if (x > i && x <= b && !v[i].contains(x)) { cnt++; v[i].add((int)x); } } else { x = (x % 10) * pow + x / 10; if (x > i && x <= b && !v[i].contains(x)) { cnt++; v[i].add((int)x); } } } } System.out.printf(""Case #%d: %d\n"", t++, cnt); } } }" B20785,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class rec2 { public static void main(String args[]) throws Exception{ FileInputStream fs = new FileInputStream(""input2.txt""); DataInputStream in = new DataInputStream(fs); BufferedReader br=new BufferedReader(new InputStreamReader(in)); FileWriter fstream = new FileWriter(""output3.txt""); BufferedWriter out = new BufferedWriter(fstream); int T=Integer.parseInt(br.readLine()); for(int i=0;i 0) { int resp = 0; int m = s.nextInt(); int n = s.nextInt(); //boolean[][] criv = new boolean[n-m+1][n-m+1]; boolean[] criv = new boolean[n-m+1]; for (int i = 0; i < criv.length; i++) { int current = m + i; String currentString = String.valueOf(current); if (currentString.charAt(0) == '0') continue; if (criv[current - m]) continue; criv[current - m] = true; int nInterv = 0; for (int j = 1; j < currentString.length(); j++) { String invString = currentString.substring(j).concat(currentString.substring(0, j)); Integer inv = Integer.valueOf(invString); if (invString.charAt(0) == '0') continue; if (invString.equals(currentString)) continue; if (inv > n || inv < m) continue; if (criv[inv - m]) continue; criv [inv-m] = true; nInterv ++; //System.out.println(currentString + "" --- "" + invString); } if (nInterv > 0) { int bbb = nInterv + 1; resp+= factorial(bbb) / (2 * factorial(bbb-2)); } } System.out.println(""Case #"" + iTests + "": "" + resp); iTests++; } } public static long factorial( int n ) { if( n <= 1 ) // base case return 1; else return n * factorial( n - 1 ); } } " B20638,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; public class RecycledNumbers2 { public static int rotate(int x) { if (x < 10) return x; int m = 1; int x_ = x / 10; while (x_ > 0) { m *= 10; x_ /= 10; } while (x % 10 == 0) x /= 10; x_ = (x % 10) * m; x_ += x / 10; return x_; } public static void solve(String file) throws Exception { BufferedReader f = new BufferedReader(new FileReader(file + "".in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file + "".out""))); int T = Integer.parseInt(f.readLine()); for (int i = 0; i < T; i++) { String[] s = f.readLine().split("" ""); int A = Integer.parseInt(s[0]); int B = Integer.parseInt(s[1]); int n = 0; for (int j = A; j <= B; j++) { int x = j; while ((x = rotate(x)) != j) { if (x > j && x <= B) n++; } } System.out.println(""Case #"" + (i+1) +"": "" + n); out.println(""Case #"" + (i+1) +"": "" + n); } out.close(); } public static void main(String[] args) throws Exception { //String file = ""C-test""; //String file = ""C-stress-test""; //String file = ""C-small-attempt0""; String file = ""C-large""; solve(file); } } " B22248,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejam; /** * * @author Bhanu */ import java.util.*; public class RecycleNumbers { public static void main(String arg[]) throws Exception { ArrayList st = new ArrayList(); ArrayList st1 = new ArrayList(); // java.io.PrintWriter pt = new java.io.PrintWriter(new java.io.File(""D:\\map.txt"")); int two[] = {12, 13, 14, 15, 16, 17, 18, 19, 23, 24, 25, 26, 27, 28, 29, 34, 35, 36, 37, 38, 39, 45, 46, 47, 48, 49, 56, 57, 58, 59, 67, 68, 69, 78, 79, 89}; int two1[] = {21, 31, 41, 51, 61, 71, 81, 91, 32, 42, 52, 62, 72, 82, 92, 43, 53, 63, 73, 83, 93, 54, 64, 74, 84, 94, 65, 75, 85, 95, 76, 86, 96, 87, 97, 98}; int count = 0; int three[] = {101, 102, 103, 104, 105, 106, 107, 108, 109, 112, 112, 113, 113, 114, 114, 115, 115, 116, 116, 117, 117, 118, 118, 119, 119, 120, 121, 122, 122, 123, 123, 124, 124, 125, 125, 126, 126, 127, 127, 128, 128, 129, 129, 130, 131, 132, 132, 133, 133, 134, 134, 135, 135, 136, 136, 137, 137, 138, 138, 139, 139, 140, 141, 142, 142, 143, 143, 144, 144, 145, 145, 146, 146, 147, 147, 148, 148, 149, 149, 150, 151, 152, 152, 153, 153, 154, 154, 155, 155, 156, 156, 157, 157, 158, 158, 159, 159, 160, 161, 162, 162, 163, 163, 164, 164, 165, 165, 166, 166, 167, 167, 168, 168, 169, 169, 170, 171, 172, 172, 173, 173, 174, 174, 175, 175, 176, 176, 177, 177, 178, 178, 179, 179, 180, 181, 182, 182, 183, 183, 184, 184, 185, 185, 186, 186, 187, 187, 188, 188, 189, 189, 190, 191, 192, 192, 193, 193, 194, 194, 195, 195, 196, 196, 197, 197, 198, 198, 199, 199, 202, 203, 204, 205, 206, 207, 208, 209, 212, 213, 214, 215, 216, 217, 218, 219, 223, 223, 224, 224, 225, 225, 226, 226, 227, 227, 228, 228, 229, 229, 230, 231, 232, 233, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238, 239, 239, 240, 241, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 248, 248, 249, 249, 250, 251, 252, 253, 253, 254, 254, 255, 255, 256, 256, 257, 257, 258, 258, 259, 259, 260, 261, 262, 263, 263, 264, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 270, 271, 272, 273, 273, 274, 274, 275, 275, 276, 276, 277, 277, 278, 278, 279, 279, 280, 281, 282, 283, 283, 284, 284, 285, 285, 286, 286, 287, 287, 288, 288, 289, 289, 290, 291, 292, 293, 293, 294, 294, 295, 295, 296, 296, 297, 297, 298, 298, 299, 299, 303, 304, 305, 306, 307, 308, 309, 313, 314, 315, 316, 317, 318, 319, 323, 324, 325, 326, 327, 328, 329, 334, 334, 335, 335, 336, 336, 337, 337, 338, 338, 339, 339, 340, 341, 342, 343, 344, 344, 345, 345, 346, 346, 347, 347, 348, 348, 349, 349, 350, 351, 352, 353, 354, 354, 355, 355, 356, 356, 357, 357, 358, 358, 359, 359, 360, 361, 362, 363, 364, 364, 365, 365, 366, 366, 367, 367, 368, 368, 369, 369, 370, 371, 372, 373, 374, 374, 375, 375, 376, 376, 377, 377, 378, 378, 379, 379, 380, 381, 382, 383, 384, 384, 385, 385, 386, 386, 387, 387, 388, 388, 389, 389, 390, 391, 392, 393, 394, 394, 395, 395, 396, 396, 397, 397, 398, 398, 399, 399, 404, 405, 406, 407, 408, 409, 414, 415, 416, 417, 418, 419, 424, 425, 426, 427, 428, 429, 434, 435, 436, 437, 438, 439, 445, 445, 446, 446, 447, 447, 448, 448, 449, 449, 450, 451, 452, 453, 454, 455, 455, 456, 456, 457, 457, 458, 458, 459, 459, 460, 461, 462, 463, 464, 465, 465, 466, 466, 467, 467, 468, 468, 469, 469, 470, 471, 472, 473, 474, 475, 475, 476, 476, 477, 477, 478, 478, 479, 479, 480, 481, 482, 483, 484, 485, 485, 486, 486, 487, 487, 488, 488, 489, 489, 490, 491, 492, 493, 494, 495, 495, 496, 496, 497, 497, 498, 498, 499, 499, 505, 506, 507, 508, 509, 515, 516, 517, 518, 519, 525, 526, 527, 528, 529, 535, 536, 537, 538, 539, 545, 546, 547, 548, 549, 556, 556, 557, 557, 558, 558, 559, 559, 560, 561, 562, 563, 564, 565, 566, 566, 567, 567, 568, 568, 569, 569, 570, 571, 572, 573, 574, 575, 576, 576, 577, 577, 578, 578, 579, 579, 580, 581, 582, 583, 584, 585, 586, 586, 587, 587, 588, 588, 589, 589, 590, 591, 592, 593, 594, 595, 596, 596, 597, 597, 598, 598, 599, 599, 606, 607, 608, 609, 616, 617, 618, 619, 626, 627, 628, 629, 636, 637, 638, 639, 646, 647, 648, 649, 656, 657, 658, 659, 667, 667, 668, 668, 669, 669, 670, 671, 672, 673, 674, 675, 676, 677, 677, 678, 678, 679, 679, 680, 681, 682, 683, 684, 685, 686, 687, 687, 688, 688, 689, 689, 690, 691, 692, 693, 694, 695, 696, 697, 697, 698, 698, 699, 699, 707, 708, 709, 717, 718, 719, 727, 728, 729, 737, 738, 739, 747, 748, 749, 757, 758, 759, 767, 768, 769, 778, 778, 779, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 788, 789, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 798, 799, 799, 808, 809, 818, 819, 828, 829, 838, 839, 848, 849, 858, 859, 868, 869, 878, 879, 889, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 899, 909, 919, 929, 939, 949, 959, 969, 979, 989}; int three1[]= {110, 210, 310, 410, 510, 610, 710, 810, 910, 211, 121, 311, 131, 411, 141, 511, 151, 611, 161, 711, 171, 811, 181, 911, 191, 201, 211, 212, 221, 312, 231, 412, 241, 512, 251, 612, 261, 712, 271, 812, 281, 912, 291, 301, 311, 213, 321, 313, 331, 413, 341, 513, 351, 613, 361, 713, 371, 813, 381, 913, 391, 401, 411, 214, 421, 314, 431, 414, 441, 514, 451, 614, 461, 714, 471, 814, 481, 914, 491, 501, 511, 215, 521, 315, 531, 415, 541, 515, 551, 615, 561, 715, 571, 815, 581, 915, 591, 601, 611, 216, 621, 316, 631, 416, 641, 516, 651, 616, 661, 716, 671, 816, 681, 916, 691, 701, 711, 217, 721, 317, 731, 417, 741, 517, 751, 617, 761, 717, 771, 817, 781, 917, 791, 801, 811, 218, 821, 318, 831, 418, 841, 518, 851, 618, 861, 718, 871, 818, 881, 918, 891, 901, 911, 219, 921, 319, 931, 419, 941, 519, 951, 619, 961, 719, 971, 819, 981, 919, 991, 220, 320, 420, 520, 620, 720, 820, 920, 221, 321, 421, 521, 621, 721, 821, 921, 322, 232, 422, 242, 522, 252, 622, 262, 722, 272, 822, 282, 922, 292, 302, 312, 322, 323, 332, 423, 342, 523, 352, 623, 362, 723, 372, 823, 382, 923, 392, 402, 412, 422, 324, 432, 424, 442, 524, 452, 624, 462, 724, 472, 824, 482, 924, 492, 502, 512, 522, 325, 532, 425, 542, 525, 552, 625, 562, 725, 572, 825, 582, 925, 592, 602, 612, 622, 326, 632, 426, 642, 526, 652, 626, 662, 726, 672, 826, 682, 926, 692, 702, 712, 722, 327, 732, 427, 742, 527, 752, 627, 762, 727, 772, 827, 782, 927, 792, 802, 812, 822, 328, 832, 428, 842, 528, 852, 628, 862, 728, 872, 828, 882, 928, 892, 902, 912, 922, 329, 932, 429, 942, 529, 952, 629, 962, 729, 972, 829, 982, 929, 992, 330, 430, 530, 630, 730, 830, 930, 331, 431, 531, 631, 731, 831, 931, 332, 432, 532, 632, 732, 832, 932, 433, 343, 533, 353, 633, 363, 733, 373, 833, 383, 933, 393, 403, 413, 423, 433, 434, 443, 534, 453, 634, 463, 734, 473, 834, 483, 934, 493, 503, 513, 523, 533, 435, 543, 535, 553, 635, 563, 735, 573, 835, 583, 935, 593, 603, 613, 623, 633, 436, 643, 536, 653, 636, 663, 736, 673, 836, 683, 936, 693, 703, 713, 723, 733, 437, 743, 537, 753, 637, 763, 737, 773, 837, 783, 937, 793, 803, 813, 823, 833, 438, 843, 538, 853, 638, 863, 738, 873, 838, 883, 938, 893, 903, 913, 923, 933, 439, 943, 539, 953, 639, 963, 739, 973, 839, 983, 939, 993, 440, 540, 640, 740, 840, 940, 441, 541, 641, 741, 841, 941, 442, 542, 642, 742, 842, 942, 443, 543, 643, 743, 843, 943, 544, 454, 644, 464, 744, 474, 844, 484, 944, 494, 504, 514, 524, 534, 544, 545, 554, 645, 564, 745, 574, 845, 584, 945, 594, 604, 614, 624, 634, 644, 546, 654, 646, 664, 746, 674, 846, 684, 946, 694, 704, 714, 724, 734, 744, 547, 754, 647, 764, 747, 774, 847, 784, 947, 794, 804, 814, 824, 834, 844, 548, 854, 648, 864, 748, 874, 848, 884, 948, 894, 904, 914, 924, 934, 944, 549, 954, 649, 964, 749, 974, 849, 984, 949, 994, 550, 650, 750, 850, 950, 551, 651, 751, 851, 951, 552, 652, 752, 852, 952, 553, 653, 753, 853, 953, 554, 654, 754, 854, 954, 655, 565, 755, 575, 855, 585, 955, 595, 605, 615, 625, 635, 645, 655, 656, 665, 756, 675, 856, 685, 956, 695, 705, 715, 725, 735, 745, 755, 657, 765, 757, 775, 857, 785, 957, 795, 805, 815, 825, 835, 845, 855, 658, 865, 758, 875, 858, 885, 958, 895, 905, 915, 925, 935, 945, 955, 659, 965, 759, 975, 859, 985, 959, 995, 660, 760, 860, 960, 661, 761, 861, 961, 662, 762, 862, 962, 663, 763, 863, 963, 664, 764, 864, 964, 665, 765, 865, 965, 766, 676, 866, 686, 966, 696, 706, 716, 726, 736, 746, 756, 766, 767, 776, 867, 786, 967, 796, 806, 816, 826, 836, 846, 856, 866, 768, 876, 868, 886, 968, 896, 906, 916, 926, 936, 946, 956, 966, 769, 976, 869, 986, 969, 996, 770, 870, 970, 771, 871, 971, 772, 872, 972, 773, 873, 973, 774, 874, 974, 775, 875, 975, 776, 876, 976, 877, 787, 977, 797, 807, 817, 827, 837, 847, 857, 867, 877, 878, 887, 978, 897, 907, 917, 927, 937, 947, 957, 967, 977, 879, 987, 979, 997, 880, 980, 881, 981, 882, 982, 883, 983, 884, 984, 885, 985, 886, 986, 887, 987, 988, 898, 908, 918, 928, 938, 948, 958, 968, 978, 988, 989, 998, 990, 991, 992, 993, 994, 995, 996, 997, 998}; //System.out.println(Arrays.binarySearch(two, 19)); java.io.BufferedReader bin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); int T = Integer.parseInt(bin.readLine()); for (int i = 1; i <= T; i++) { count = 0; String[] split = bin.readLine().split("" ""); int a = Integer.parseInt(split[0]); int b = Integer.parseInt(split[1]); if (a >= 0 && a <= 9) { System.out.println(""Case #"" + i + "": "" + 0); } else if (a >= 10 && a <= 99) { int b1 = Arrays.binarySearch(two, a); if (b1 < 0) { b1 = b1 + 1; b1 = -b1; } int b2 = Arrays.binarySearch(two, b); if (b2 < 0) { b2 = b2 + 1; b2 = -b2; b2 = b2 - 1; } for (; b1 <= b2; b1++) { if (two1[b1] >= a && two1[b1] <= b) { count++; } } System.out.println(""Case #"" + i + "": "" + count); } else if (a >= 100 && a <= 999) { int b1 = Arrays.binarySearch(three, a); if (b1 < 0) { b1 = b1 + 1; b1 = -b1; } else { while (b1 >= 0 && three[b1] == a) { b1--; } b1 = b1 + 1; } int b2 = Arrays.binarySearch(three, b); if (b2 < 0) { b2 = b2 + 1; b2 = -b2; b2 = b2 - 1; } else { while (b2 <= three.length - 1 && three[b2] == b) { b2++; } b2 = b2 - 1; } // System.out.println(""B1 and B2"" + b1 + "" "" + b2); for (; b1 <= b2; b1++) { if (three1[b1] >= a && three1[b1] <= b) { count++; } } System.out.println(""Case #"" + i + "": "" + count); } else if (a >= 1000 && a <= 9999) { for (int i1 = a; i1 <= b; i1++) { int rem = i1 % 10; int q = i1 / 10; int temp = rem * 1000 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 100; q = i1 / 100; temp = rem * 100 + q; if (temp > i) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 1000; q = i1 / 1000; temp = rem * 10 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } } System.out.println(""Case #"" + i + "": "" + count); } else if (a >= 10000 && a <= 99999) { for (int i1 = a; i1 <= b; i1++) { int rem = i1 % 10; int q = i1 / 10; int temp = rem * 10000 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 100; q = i1 / 100; temp = rem * 1000 + q; if (temp > i) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 1000; q = i1 / 1000; temp = rem * 100 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 10000; q = i1 / 10000; temp = rem * 10 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } } System.out.println(""Case #"" + i + "": "" + count); } else if (a >= 100000 && a <= 999999) { for (int i1 = a; i1 <= b; i1++) { int rem = i1 % 10; int q = i1 / 10; int temp = rem * 100000 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 100; q = i1 / 100; temp = rem * 10000 + q; if (temp > i) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 1000; q = i1 / 1000; temp = rem * 1000 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 10000; q = i1 / 10000; temp = rem * 100 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 100000; q = i1 / 100000; temp = rem * 10 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } } System.out.println(""Case #"" + i + "": "" + count); } else if (a >= 1000000 && a <= 2000000) { for (int i1 = a; i1 <= b; i1++) { int rem = i1 % 10; int q = i1 / 10; int temp = rem * 1000000 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 100; q = i1 / 100; temp = rem * 100000 + q; if (temp > i) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 1000; q = i1 / 1000; temp = rem * 10000 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 10000; q = i1 / 10000; temp = rem * 1000 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 100000; q = i1 / 100000; temp = rem * 100 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } rem = i1 % 1000000; q = i1 / 1000000; temp = rem * 10 + q; if (temp > i1) { //st.add(i1); //st1.add(temp); count++; } } System.out.println(""Case #"" + i + "": "" + count); } } } } " B20494,"package wwu.quals2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import lib.tuple.Pair; import lib.tuple.Tuple; import lib.util.StringUtil; public class Crecycled { static final String fileIn = ""/home/wwu/Desktop/C-large.in""; // static final String fileIn = ""data/A-large-practice.in""; static final String fileOut = ""/home/wwu/Desktop/out.txt""; public static Map charMap; public static void main(String[] args) throws Exception { BufferedReader r = new BufferedReader(new FileReader(fileIn)); BufferedWriter w = new BufferedWriter(new FileWriter(fileOut)); String line = r.readLine(); int T = Integer.parseInt(line); for (int caseNum = 0; caseNum < T; caseNum++) { int[] testCase = StringUtil.getIntArray(r.readLine()); int A = testCase[0]; int B = testCase[1]; String str = ""Case #"" + (caseNum + 1) + "": "" + solve(A, B); w.write(str + ""\n""); System.out.println(str); } r.close(); w.close(); } private static String solve(int a, int b) { int numRecyled = 0; for (int outerCompare=a; outerCompare<=b; outerCompare++) { numRecyled += getRecycledPairNum(outerCompare, a, b); // for (int innerCompare=a; innerCompare<=b; innerCompare++) { // if (isRecycledPair(outerCompare, innerCompare)) { // numRecyled++; // } // } } return String.valueOf(numRecyled/2); } private static int getRecycledPairNum(int outerCompare, int a, int b) { int retVal = 0; int lenOfOuter = String.valueOf(outerCompare).length(); int nextRecycledNum = (int) Math.pow(10, lenOfOuter-1)*(outerCompare % 10) + outerCompare/10; for (int i=0; i<=lenOfOuter; i++) { if (outerCompare == nextRecycledNum) { continue; } else if (nextRecycledNum >= a && nextRecycledNum <= b) { retVal++; } nextRecycledNum = (int) Math.pow(10, lenOfOuter-1)*(nextRecycledNum % 10) + nextRecycledNum/10; } return retVal; } // private static boolean isRecycledPair(int outerCompare, int innerCompare) { // // 123 -> 312 // int lenOfOuter = String.valueOf(outerCompare).length(); // int nextRecycledNum = (int) Math.pow(10, lenOfOuter-1)*(outerCompare % 10) + outerCompare/10; // for (int i=0; i<=lenOfOuter; i++) { // if (outerCompare == innerCompare) { // continue; // } else if (nextRecycledNum == innerCompare) { // return true; // } // nextRecycledNum = (int) Math.pow(10, lenOfOuter-1)*(nextRecycledNum % 10) + nextRecycledNum/10; // } // return false; // } // } " B21011,"/** * */ package org.codejam.rn; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; import java.util.Map; /** * * @author juanjo */ public class RecycledNumbersMain { public static String newline = System.getProperty(""line.separator""); private static void generateNumbers(Map pairs, int A, int B, int n) { int m; String s = String.valueOf(n); String pair = null; int length = s.length() - 1; int[] data = new int[length]; for (int i = 0; i < length; i++) { //s = s.charAt(length) + s.substring(0, length); s = new StringBuilder().append(s.charAt(length)).append(s.substring(0, length)).toString(); data[i] = Integer.parseInt(s); m = Integer.parseInt(s); if ((A <= n) && (n < m) && (m<=B)) { pair = new StringBuilder().append(n).append(""-"").append(m).toString(); if (!pairs.containsKey(pair)); pairs.put(pair, pair); } } } private static int getRecyledPairsCount(int A, int B) { Map pairs = new HashMap(); for (int n = A; n <= B; n++) { generateNumbers(pairs, A, B, n); } return pairs.size(); } /** * @param args */ public static void main2(String[] args) { long time = System.currentTimeMillis(); System.out.println(""getRecyledPairsCount: "" + getRecyledPairsCount(100,500)); System.out.println(""Execution time ms.: "" + (System.currentTimeMillis() - time) ); } public static void main(String[] args) { long time = System.currentTimeMillis(); if (args.length != 2) { System.out.println(""Usage: java "" + RecycledNumbersMain.class + "" inputFile outputFile""); System.exit(0); } int count = 0; BufferedReader in = null; FileWriter out = null; String line = null; int testCasesTotal = 0; int testCasesCount = 0; String result; int A, B; String s[]; try { in = new BufferedReader(new FileReader(args[0])); out = new FileWriter(args[1]); while ( (line = in.readLine()) != null) { count++; if (count == 1) { testCasesTotal = Integer.valueOf(line); System.out.println(""In file number of test cases: "" + testCasesTotal + "".""); } //if else { s = line.split("" ""); A = Integer.parseInt(s[0]); B = Integer.parseInt(s[1]); result = String.valueOf(getRecyledPairsCount(A, B)); testCasesCount++; result = ""Case #"" + testCasesCount + "": "" + result; System.out.println(result + "" -- Line: "" + testCasesCount + "": "" + line); out.write(result + newline); } } if (out != null) { out.close(); } } //try catch (Exception e) { e.printStackTrace(); } finally { System.out.println(""Execution time ms.: "" + (System.currentTimeMillis() - time) ); } } // Main } " B20057,"import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by IntelliJ IDEA. * User: Jack Man * Date: Apr 13, 2012 * Time: 9:12:01 PM * To change this template use File | Settings | File Templates. */ public class RecycledNum { public static void main(String[] args) { try { String filePath = ""c:\\projects\\codejam\\input\\recycled.txt""; StringBuffer fileData = new StringBuffer(); BufferedReader reader = new BufferedReader(new FileReader(filePath)); String strLine; Integer inputNum = 0; List googlereseList = new ArrayList(); int line = 0; Integer cases = null; ArrayList solutions = new ArrayList(); while ((strLine = reader.readLine()) != null) { if (line == 0) { line++; continue; } // String[] inputs = strLine.split("" ""); int start = Integer.parseInt(inputs[0]); int end = Integer.parseInt(inputs[1]); int found = 0; HashMap dupeMap = new HashMap(); for (int i = start; i <= end; i++) { String s = i + """"; for (int y = 1;y< s.length();y++) { //System.out.println((s.length()-y); String right = s.substring(s.length()-y); String left = s.substring(0, s.length()-y); //System.out.println(""Attempt to shift "" + y + "" digits from the right of "" + s + "" ("" + left + "")("" + right + "")""); String mirror = right + left; //remove leading zeros boolean foundZero = false; char[] chars = mirror.toCharArray(); String mirrorEnd = """"; for (char c : chars) { if (c == '0' && !foundZero) { continue; } foundZero = true; mirrorEnd+=c; } if (s.length() != mirrorEnd.length()) continue; Integer n = Integer.parseInt(s); Integer m = Integer.parseInt(mirrorEnd); if (n.equals(m)) continue; if (start <= n && n < m && m <= end) { if (dupeMap.get(n + ""-"" + m) != null) { continue; } found++; //System.out.println(""\t["" + found + "":MARK] set of "" + n + "", "" + m); dupeMap.put(n + ""-"" + m, true); } } } System.out.println(""Case #"" + line + "": "" + found); // line++; } } catch (Exception e) { e.printStackTrace(); } } } " B21507,"package recycled; import java.util.Scanner; public class Recycled { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); int[] count = new int[t]; for (int i = 0; i < t; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); for (int j = a; j <= b; j++) { String temp = Integer.toString(j); int index=0; int[] num=new int[(int) Math.log10(j)]; for (int k = 0; k < Math.log10(j); k++) { if (Math.log10(j) >= 1) { String temp2 = temp.substring(k + 1, temp.length()) + temp.substring(0, k + 1); int temp3 = Integer.parseInt(temp2); if (temp3 <= b & temp3>j) { count[i]++; num[index]=temp3; index++; } } } if (index>1){ for(int k=0;k=a)&&(temp<=b)&&(temp>num)) cnt++; } } return cnt; } }" B20630,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; import java.util.Vector; public class Main { public static int recycled (int A,int B) { if(B<10)return 0; String N,M; int taille=1,Nbr=0; for(int i=10;i<=B;i*=10)taille++; for(int i=A;i<=B;i++) { Vector list = new Vector(); N=Integer.toString(i); //M=N.substring(1)+N.charAt(0); for(int k=0;k ht = new HashSet(); for(int k = 0; k < numLength; k++) { int rem = m%10; m = m/10+rem*powerThing; if(m <= B && m > n && !ht.contains(m)) { ht.add(m); numPairs++; } } } System.out.println(""Pairs: ""+numPairs); out.write(""Case #""+i+"": ""+numPairs+""\r\n""); } in.close(); out.close(); displayOutput(); } catch (Exception e) { System.err.println(""Oops! Error occured: "" + e.getMessage()); } } public static String gDecode(String input) { String decoded = """"; for(int i = 0; i < input.length(); i++) { if(input.charAt(i) == ' ') decoded += ' '; else decoded += decodeChar(input.charAt(i)-'a'); } return decoded; } public static String googleKey = ""yhesocvxduiglbkrztnwjpfmaq""; public static char decodeChar(int encoded) { return googleKey.charAt(encoded); } public static void displayOutput() { System.out.println(""START OUTPUT\n-------------------""); try { FileInputStream fs = new FileInputStream(""output.txt""); DataInputStream in = new DataInputStream(fs); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String readLine; while ((readLine = br.readLine()) != null) { System.out.println(readLine); } } catch (Exception e) { System.err.println(""Oops! Error occured: "" + e.getMessage()); } System.out.println(""---------------------\nEND OUTPUT""); } } " B21216,"package gcj; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.Iterator; public class Jam2012 { //-10^9 < Integer.MAX_VALUE (2^31) < 10^10 //-10^18 < Long.MAX_VALUE (2^63) < 10^20 public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(new FileReader(filename+"".in"")); String output; String outputfile = filename + "".out""; FileOutputStream Output = new FileOutputStream(outputfile); PrintStream file2 = new PrintStream(Output); boolean after25 = false; boolean after50 = false; boolean after75 = false; int T = sc.nextInt(); //int T = Integer.parseInt(sc.nextLine()); System.out.println(Calendar.getInstance().getTime()+"" - Started writing to: ""+outputfile); //getPrimesH(); for (int i = 0; i < T; i++) { //ArrayList orders = new ArrayList(); //ArrayList v2 = new ArrayList(); //ArrayList queryList = new ArrayList(); //StringTokenizer st = new StringTokenizer(br.readLine(),"" ""); int a = sc.nextInt(); int b = sc.nextInt(); output = solve(a,b); file2.println(""Case #"" + (i+1) + "": ""+output); if ((100*(i+1)/T >= 25) && (!after25)) { System.out.println(Calendar.getInstance().getTime()+"" - 25% done""); after25 = true; } else if ((100*(i+1)/T >= 50) && (!after50)) { System.out.println(Calendar.getInstance().getTime()+"" - 50% done""); after50 = true; } else if ((100*(i+1)/T >= 75) && (!after75)) { System.out.println(Calendar.getInstance().getTime()+"" - 75% done""); after75 = true; } } sc.close(); System.out.println(Calendar.getInstance().getTime()+"" - Finished writing to: ""+outputfile); } /* private static String solve(String nextLine) { char[] a = {'f','g','d','e','b','c','a','n','o','l','m','j','k','h','i','w','v','u','t','s','r','q','p','z','y','x'}; char[] b = {'c','v','s','o','h','e','y','b','k','g','l','u','i','x','d','f','p','j','w','n','t','z','r','q','a','m'}; HashMap lib = new HashMap(); for (int i = 0; i< a.length; i++) { if(!lib.containsKey(a[i])) { lib.put(a[i], b[i]); } } StringBuilder out = new StringBuilder(); for (int i = 0; i< nextLine.length(); i++) { if (nextLine.charAt(i) == ' ') {out.append(' ');} else { out.append(lib.get(nextLine.charAt(i)));} } return out.toString(); }*/ private static String solve(int a, int b) { int length = String.valueOf(b).length(); if (length == 1) { return ""0""; } HashSet found = null; long total = 0; for (int i = a; i < b; i++) { found = null; String s = String.valueOf(i); StringBuilder sb = new StringBuilder(); for (int j = 0; j < s.length(); j++) { sb.append(s.charAt((j+s.length()-1)%s.length())); } int shift = Integer.parseInt(sb.toString()); for (int j = 1; j < length; j++) { if (shift > i && shift <= b) { if (found == null) { found = new HashSet(); } if (!found.contains(shift)) { found.add(shift); //System.out.println(i+"",""+shift); total++; } } //s = String.valueOf(shift); sb = new StringBuilder(); for (int k = 0; k < s.length(); k++) { sb.append(s.charAt((k+s.length()-(1+j))%s.length())); } shift = Integer.parseInt(sb.toString()); } } return String.valueOf(total); } //static String size = ""sample""; //static String size = ""small""; //static String size = ""large""= static String filename = ""D:\\gcj\\2012\\Q\\C-large""; } " B21767,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam2012; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeSet; /** * * @author Rumal */ public class QC_Hard { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); int R = 2000000; ArrayList full = new ArrayList(); int[] head = new int[R + 1]; for (int i = 1; i <= R; i++) { if (i < 10) { head[i] = full.size(); continue; } String h = (i + """"); int N = h.length(); TreeSet pos = new TreeSet(); for (int j = 1; j < N; j++) { int y = shift(i, j, N); pos.add(y); } head[i] = full.size(); for (int y : pos) { if (y <= R && i < y) { full.add(y); } } } int T = s.nextInt(); for (int t = 1; t <= T; t++) { int A = s.nextInt(); int B = s.nextInt(); long count = 0; p: for (int i = head[A]; i < head[B]; i++) { if (full.get(i) <= B && full.get(i) >= A) { count++; } } System.out.println(""Case #"" + t + "": "" + count); } } private static int shift(int i, int j, int n) { String s = i + """"; int N = s.length(); if (n != N) { return -1; } int y = Integer.parseInt(s.substring(N - j) + s.substring(0, N - j)); if ((y + """").length() != N) { return -1; } return y; } } " B20846,"package codezam.util; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class LCM { static HashMap factor; static BigInteger[][] dp; static long l; public static void main(String[] args) throws FileNotFoundException { Scanner r = new Scanner(System.in); int T = r.nextInt(); while(T-- > 0){ int n = r.nextInt(); l = r.nextInt(); factor = new HashMap(); int id = 0; for(long d = 1; d * d <= l; d++)if(l % d == 0){ factor.put(d, id++); if(d * d != l)factor.put(l / d, id++); } // dp = new BigInteger[factor.size() + 1][n + 2]; for(int i = 0; i < factor.size(); i++) dp[i][0] = BigInteger.ZERO; dp[factor.get(l)][0] = BigInteger.ONE; BigInteger ways = go(1, n); System.out.println(ways); } } static long gcd(long x, long y){ if( y == 0 )return x; else return gcd(y, x % y); } private static BigInteger go(long lcm, int rem) { if(rem == 0 && lcm == l)return BigInteger.ONE; if(rem == 0)return BigInteger.ZERO; System.out.println(lcm + "", "" + rem); if(dp[factor.get(lcm)][rem] != null) return dp[factor.get(lcm)][rem]; BigInteger ways = BigInteger.ZERO; for(long d = 1; d * d <= l; d++)if(l % d == 0){ long lcmNEW1 = lcm * d / gcd(d, lcm); long lcmNEW2 = lcm * (l/d) / gcd(l / d, lcm); ways = ways.add( go(lcmNEW1, rem - 1)); if(d * d != l)ways = ways.add( go(lcmNEW2, rem - 1)); } return dp[factor.get(lcm)][rem] = ways; } }" B22169,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) throws NumberFormatException, IOException { // open file and create a buffered reader FileReader input = new FileReader(args[0]); BufferedReader buffer = new BufferedReader(input); //read the number of testcases int max = Integer.parseInt(buffer.readLine().trim()); // read a line and call the solving procedure for a single test case. We expect back the result as a string for (int i = 1; i <= max; i++) { System.out.println(""Case #""+i+"": "" + solve(buffer.readLine())); } } private static long solve(String input) { String[] split = input.split("" ""); int A = Integer.parseInt(split[0]); int B = Integer.parseInt(split[1]); long count = 0; if (A < 10) { return 0; } for(int i = A; i < B; i++) { String str = Integer.toString(i); HashSet all = new HashSet(); for(int j = 1; j < str.length(); j++) { String cycle = str.substring(j)+str.substring(0, j); int value = Integer.parseInt(cycle); if (value > i && value <= B && !all.contains(value)) { all.add(value); count++; } } } return count; } } " B22014,"package er.dream.codejam.helpers; import java.io.File; import java.util.List; public abstract class ProblemSolver { protected FileHandler fileHandler = new FileHandler(); protected abstract List handleInput(); public void execute(){ File[] files = fileHandler.listFiles(); for(File f : files){ long start = System.currentTimeMillis(); fileHandler.loadFile(f); List results = handleInput(); fileHandler.writeOutput(results); fileHandler.closeConnection(); long stop = System.currentTimeMillis(); System.out.println(""File ""+f.getName()+"" took me ""+(stop-start)+""ms""); } } } " B20858,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class cyclic { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int in = Integer.parseInt(sc.nextLine()); int i = 1; while (i <= in) { int A = sc.nextInt(); int B = Integer.parseInt(sc.nextLine().trim()); System.out.print(""Case #"" + i + "": ""); if(i < in) System.out.println(count(A,B)); else System.out.print(count(A,B)); i++; } } public static int count(int A, int B) { boolean[] flag = new boolean[B - A + 1]; int numDigits = (int) Math.log10(A) + 1; int pairs = 0; for (int i = A; i <= B; i++) { if (!flag[i - A]) { flag[i - A] = true; int n = 1; for (int j = 1; j < numDigits; j++) { int l = (int) (i / Math.pow(10, j)); l += (i % Math.pow(10, j)) * Math.pow(10, numDigits - j); if (l >= A && l <= B && !flag[l-A]) { flag[l - A] = true; n++; } } if (n > 1) { int nC2 = 1; for (int j = 0; j < 2; j++) { nC2 = nC2 * (n - j) / (j + 1); } pairs += nC2; } } } return pairs; } } " B21598,"package com.brootdev.gcj2012.problemC; import com.brootdev.gcj2012.common.Data; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class Main { private Data data; private long casesNumber; private long currentCase; public static void main(String[] args) throws IOException { new Main().go(args[0], args[1]); } public void go(String inFile, String outFile) throws IOException { data = new Data(inFile, outFile); casesNumber = data.readLongLine(); for (currentCase = 0; currentCase < casesNumber; currentCase++) { data.writeCaseHeader(currentCase); processCase(); } data.out.flush(); } private void processCase() throws IOException { long[] longs = data.readLongsArrayLine(); long A = longs[0]; long B = longs[1]; int digits = ((int) Math.log10(A)) + 1; long mn = (long) Math.pow(10, digits - 1); long sum = 0; Set m2 = new HashSet(); for (long n = A; n < B; n++) { long m = n; m2.clear(); for (int i = 1; i < digits; i++) { int r = (int) (m % 10); m = r * mn + m / 10; if (m <= B && n < m && ! m2.contains(m)) { sum++; m2.add(m); } } } data.out.println(sum); } } " B21682,"import java.util.*; import java.io.*; public class problem3 { private final Scanner sc; private static final boolean debug = true; static void debug(Object ... objects) { if(debug) System.err.println(Arrays.toString(objects)); } problem3() { sc = new Scanner(new BufferedInputStream(System.in)); } public static void main(String [] args) { (new problem3()).solve(); } int AA,BB; int rot(int b) { int p=10; int cnt=0; int maxP = 1; int ans = 0; while(b/maxP > 0) maxP*=10; while(b/p>0) { int c = b/p + (maxP/p)*(b%p); //System.out.println(b+ "" "" + maxP+"" "" + c); if(c==b) break; if(c>b&&c<=BB&&c>=AA) ans++; p*=10; } return ans; } void solve() { int T = sc.nextInt(); int cs = 0; while(cs < T) { cs++; long ans = 0; int A = sc.nextInt(), B = sc.nextInt(); AA=A;BB=B; for(int i=A;i<=B;i++) { ans+=rot(i); } System.out.println(""Case #"" + cs+ "": ""+ans); } } } " B20123,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; /** * @author Paul LaMotte * */ public class RecycledNumbers { public static void main(String[] args) { Scanner in; try { System.setOut(new PrintStream(new File(""qualC.out""))); in = new Scanner(new File(""C-large.in"")); int lines = Integer.parseInt(in.nextLine()); for (int i = 0; i < lines; i++) { int start = in.nextInt(); int end = in.nextInt(); int count = 0; for (int j = start; j <= end; j++) { int digits = 0; int num = j; while (num != 0) { digits++; num /= 10; } int tmp = j; int e = (int)Math.pow(10, digits - 1); HashSet set = new HashSet(); for (int k = 0; k < digits - 1; k++) { int front = tmp % 10; tmp /= 10; tmp += front * e; if (tmp > j && tmp <= end && !set.contains(tmp)) { count++; set.add(tmp); } } } System.out.printf(""Case #%d: %d\n"", i + 1, count); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B21477,"package Television; public class Pair{ public int a, b; public Pair(int a, int b)throws Exception { if(a>=b) throw new Exception(""invalid input for pair""); this.a=a; this.b=b; } public boolean equls(Object po) { Pair p = (Pair)po; if(p.a == this.a && p.b==this.b) return true; return false; } public boolean equls(Pair p) { if(p.a == this.a && p.b==this.b) return true; return false; } } " B20541," import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; public abstract class TestCase { public abstract void readInput(BufferedReader in) throws IOException, MalformedInputFileException; public abstract void solve(); public abstract void writeOutput(PrintWriter out); }" B20677,"package c; import java.io.*; import java.lang.Math.*; import java.util.Arrays; public class C { public static void main(String[] args) { try { BufferedReader input = new BufferedReader(new FileReader(""C:/CodeJam/C-large.in"")); BufferedWriter output = new BufferedWriter(new FileWriter(""C:/CodeJam/C-large.out"")); try { int T = Integer.parseInt(input.readLine()); //Process each case for (int i = 0; i < T; i++) { String line = input.readLine(); String[] AB = line.split("" ""); int A = Integer.parseInt(AB[0]); int B = Integer.parseInt(AB[1]); String max = String.valueOf(B); //Check every n,m pair for cur case int count = 0; for (int j = A; j < B; j++) { String n = String.valueOf(j); String m = n; int len = m.length(); //For single digit numbers, no matches possible if (len == 1) { break; } //Check each possible match for current n int[] matches = new int[len]; int subcount = 0; for (int k = 0; k < len; k++) { //Check current permutation of m for valid range if (m.compareTo(n) > 0 && m.compareTo(max) <= 0) { matches[subcount] = Integer.parseInt(m); subcount++; } //Move the last digit to the front m = m.substring(len - 1, len) + m.substring(0, len - 1); } //Check the matches for duplicates and uncount them Arrays.sort(matches); for (int k = 0; k < len - 1; k++) { if(matches[k] != 0 && matches[k+1] != 0 && matches[k] == matches[k+1]) { subcount--; } } count += subcount; } System.out.println(""Case #"" + (i + 1) + "": "" + count); output.write(""Case #"" + (i + 1) + "": "" + count + ""\n""); } } finally { input.close(); output.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } " B21942,"package Qualification_Round_2012; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(""c.out""); StringTokenizer k; int t,a,b,x,y,count; HashSet h; String s; int ar [] = new int[7]; ar[0]=1; ar[1]=10; ar[2]=100; ar[3]=1000; ar[4]=10000; ar[5]=100000; ar[6]=1000000; t=Integer.parseInt(in.readLine().trim()); for (int i = 1; i <= t; i++) { count=0; k=new StringTokenizer(in.readLine()); a=Integer.parseInt(k.nextToken()); b=Integer.parseInt(k.nextToken()); for (int j = a; j <= b; j++) { h=new HashSet(6); x=j; s=j+""""; for (int l = 0; l < s.length()-1; l++) { y=x%10; y*=ar[s.length()-1]; y+=x/10; if(y>j && y<=b && y!=x){ if(h.add(y)) count++; } x=y; } } out.append(""Case #""+i+"": ""+count+""\n""); } out.close(); } } " B22195,"package org.weiwei.recyclenumber; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Created with IntelliJ IDEA. * User: ding * Date: 12-4-14 * Time: 下午1:03 * To change this template use File | Settings | File Templates. */ public class RecyleBin { int lower; int higher; Set retSet = new HashSet(); int length; int lengthNumber; public RecyleBin(int lower, int higher) { this.lower = lower; this.higher = higher; this.length = String.valueOf(lower).length(); this.lengthNumber = (int)Math.pow(10, length-1); } public int exhaust(int i){ int ret = 0; retSet.clear(); if(length ==1 ) return 0; else{ int temp = i; for(int j = 1; j < length; j++){ temp = temp/10+temp%10*lengthNumber; if(temp >= (10^length) && temp < i && temp >= lower && !retSet.contains(temp)){ ret++; retSet.add(temp); } } } return ret; } public int exhaust(){ System.out.println(new Date(System.currentTimeMillis())); int ret = 0; for(int i = higher; i >= lower; i--){ ret+=exhaust(i); } System.out.println(new Date(System.currentTimeMillis())); return ret; } public static void main(String[] args) { RecyleBin bin = new RecyleBin(1111, 2222); System.out.println(bin.exhaust()); } } " B21156,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; public class Recycled { public static void main(String[] args){ Recycled r = new Recycled(); try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(""C-large.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line int numOfTests = Integer.parseInt(br.readLine()); for(int i=1; i<=numOfTests; i++){ String itemString = br.readLine(); System.out.print(""Case #""+i+"": ""); long A = Long.parseLong(itemString.split("" "")[0]); long B = Long.parseLong(itemString.split("" "")[1]); r.countRecycled(A,B); System.out.println(); } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private char[] shuffle(char[] numString){ //char[] numString = (x+"""").toCharArray(); int i=0; char temp=numString[i]; for(i=0; i a && shuffleNum > i && shuffleNum <=b ){ // System.out.print("" ""+i); // System.out.println("" shuffle: ""+shuffleNum); count++; } } } // System.out.println(); System.out.print(count); } } " B20139,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; /** * * @author GERALD */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner scanner = null; PrintWriter output = null; try{ scanner = new Scanner(new FileInputStream(args[0])); output = new PrintWriter(new FileOutputStream(""resultRecycledNumbers.txt"")); int noOfCases = scanner.nextInt(); //prior initializations if any int A, B,count; for(int i=1; i<= noOfCases;++i){ // TODO code application logic here A = scanner.nextInt(); B = scanner.nextInt(); count = noOfRecycledPair(A, B); output.append(String.format(""Case #%d: %d\n"",i,count)); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } finally{ if( output!= null) output.close(); if(scanner!= null) scanner.close(); } } public static int noOfRecycledPairWithSameOrder(long a, long b){ int count = 0; int order = 0; long num = a; do{ num = num/10; order++; }while(num!=0); order --; System.out.println(order); long tens = 10; long bigNines = Math.round( Math.pow(10, order+1) -1); int ordnum = 0; long buffer = 0; ArrayList numList = new ArrayList<>(); for(long i=a; i<=b; ++i){ tens = 10; numList.clear(); for(int j=0; j<= order-1; ++j){ num = Math.round((double)(i + ((i%(Math.round(tens)))*bigNines))/(double)tens); if(num >=a && num<=b&& num !=i&& !numList.contains(num)){ buffer = num; ordnum=0; do{ buffer = buffer/10; ordnum++; }while(buffer !=0); ordnum--; if(ordnum == order) count++; } numList.add(num); tens = 10*tens; } } return count/2; } public static int noOfRecycledPair(long a, long b){ int count = 0; int orderA = 0, orderB=0; long num = a; do{ num = num/10; orderA++; }while(num!=0); orderA --; num = b; do{ num = num/10; orderB++; }while(num!=0); orderB --; if (orderA == orderB){ System.out.println(""equals""); count = noOfRecycledPairWithSameOrder(a, b); } else{ System.out.println(""not equals""); long aLimit = (long) (Math.pow(10,orderA) -1); count = noOfRecycledPairWithSameOrder(a, aLimit) + noOfRecycledPair(aLimit, b); } return count; } } " B20705,"package org.moriraaca.codejam; import java.io.InputStream; import java.util.Scanner; public abstract class AbstractDataParser { protected Scanner scanner; protected TestCase[] testCases; public AbstractDataParser(InputStream input) { scanner = new Scanner(input); parse(); } abstract protected void doParse(); protected void parse() { doParse(); } public TestCase[] getTestCases() { return testCases; } } " B21865,"package commons; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedList; import java.util.List; public class FileUtilities { public static void writeFile(List strings, File file) throws IOException { file.createNewFile(); FileWriter writer = new FileWriter(file); for (int i = 1; i <= strings.size(); i++) { writer.write(""Case #""); writer.write(i + "": ""); writer.write(strings.get(i-1)); writer.write(""\n""); } writer.close(); } public static List readFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String input = reader.readLine(); List result = new LinkedList(); while (!(input == null)) { result.add(input); input = reader.readLine(); } reader.close(); return result; } } " B22060,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam2012; /** * * @author ESIEN */ public class C { static int numOfDigits; final static int max = 2000001; static int div; static boolean[] found = new boolean[max]; static int[]p = new int[max]; public static void main(String[] args)throws java.io.IOException{ java.util.Scanner fromFile = new java.util.Scanner(new java.io.File(""input.txt"")); java.io.PrintStream intoFile = new java.io.PrintStream(""output.txt""); int testCase = fromFile.nextInt(); for (int test = 1; test <= testCase; test++){ int a = fromFile.nextInt(); int b = fromFile.nextInt(); numOfDigits = 0; int t = a; while((t/=10)!=0) numOfDigits++; div = (int)Math.pow(10,numOfDigits); int ind=0; int totalCount = 0; for (int i = a; i <= b; i++){ if (found[i]) continue; found[p[ind++]=i]=true; int c = 0; for (int j = 0,k=i%10*div+i/10; j < numOfDigits && k!=i; k=k%10*div+k/10, j++) if (k<=b&&k>=a){ c++; found[p[ind++]=k]=true; } totalCount+=(c&1)==0?(c>>1)*(c+1):((c+1>>1)*c); } for(int i = 0; i < ind; i++) found[p[i]]=false; intoFile.printf(""Case #%d: %d%n"",test,totalCount); } intoFile.close(); fromFile.close(); } } " B20877,"package google.code.jam.problem.c; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class MainClass { public static final String PATH_FILE = ""C:/Temp/""; /** * @param args */ public static void main(String[] args) { try { MainClass mainClass = new MainClass(); // HashSet recycledNumbersCollection = new HashSet (); List recycled = new ArrayList(); // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(PATH_FILE + ""C-large.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); int numOfTestCase = Integer.parseInt(strLine); if ((numOfTestCase >= 1) && (numOfTestCase <= 50)) { int i = 1; // Read File Line By Line while ((strLine = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(strLine, "" ""); int numberA = Integer.parseInt(st.nextToken()); int numberB = Integer.parseInt(st.nextToken()); if ((1 <= numberA) && (numberA <= numberB) && (numberB <= 2000000)) { int recycledPair = 0; for (int j = numberA; j < numberB; j++) { String rotateNumber = String.valueOf(j); int currentNumber = j; // System.out.println(""currentNumber: "" + currentNumber); for (int k = 1; k < String.valueOf(j).length(); k++) { String rotateNumberNew = mainClass .rotateNumber(rotateNumber); // System.out.println(rotateNumberNew); if ((!""-1"".equals(rotateNumber)) && (Integer.valueOf(rotateNumberNew) > currentNumber) && (Integer.valueOf(rotateNumberNew) <= numberB) && (rotateNumber != rotateNumberNew)) { recycledPair++; // recycledNumbersCollection.add(rotateNumberNew); recycled.add(currentNumber + "" , "" + rotateNumberNew); // System.out.println("":: recycledPair :: "" + rotateNumberNew); } rotateNumber = rotateNumberNew; } } // int temp = 0; // for (String string : recycled) { // System.out.println(""number "" + ++temp +"": "" + string); // } System.out.println(""Case #"" + i++ + "": "" + recycledPair); // System.out.println(recycledNumbersCollection.size()); } else { throw new Exception(""Condition not 1 <= A <= B <= 1000""); } } } else { throw new Exception(""Number of test case is not valid""); } // Close the input stream in.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public String rotateNumber(String number) { String returnValue = ""-1""; try { if (Integer.parseInt(number) >= 10) { String lastDigit = number.substring(number.length() -1 , number.length()); returnValue = lastDigit + number.substring(0, number.length() -1); // String firstDigit = number.substring(0, 1); // returnValue = number.substring(1) + firstDigit; } else { returnValue = ""-1""; } } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } return returnValue; } } //1111 2222 " B20412,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; public class C { public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(new File(""C.in"")); long tt = System.currentTimeMillis(); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C.out""))); HashSet HS = new HashSet(); LinkedList LL = new LinkedList(); int N = 1; for(int i=1;i<=N;i++){ int A = 1; int B = 2000000; for(int a=A;a<=B;a++){ String x = a+""""; for(int b=1;ba&&other>=A&&other<=B){ if(HS.contains(x+"" ""+temp))continue; HS.add(x+"" ""+temp); LL.add(new obj(a,other)); } } } } //System.out.println(HS.size()); N = sc.nextInt(); for(int i=1;i<=N;i++){ int A = sc.nextInt(); int B = sc.nextInt(); int total = 0; for(obj x : LL){ int T1 = x.x; int T2 = x.y; if(A<=T1&&T1<=B&&A<=T2&&T2<=B){ total++; } //System.out.println(total); } out.println(""Case #""+i+"": ""+total); //System.out.println(""Case #""+i+"": ""+total); } out.close(); //System.out.println(System.currentTimeMillis()-tt); } static class obj{ int x; int y; obj(int a, int b){ x=a; y=b; } } } " B20687,"import java.util.*; import java.io.*; class problemC { static class Coordinate implements Comparable { int x, y; public Coordinate(int x, int y) { this.x = x; this.y = y; } public boolean equal(Object o) { if (o == null || !(o instanceof Coordinate)) { return false; } else { return ((Coordinate)o).x == this.x && ((Coordinate)o).y == this.y; } } @Override public int compareTo(Coordinate o) { // TODO Auto-generated method stub if (o.x == this.x && o.y == this.y) return 0; else return -1; } public String toString() { return ""("" + Integer.toString(x) + "","" + Integer.toString(y) + "")""; } } public static void main(String[] args) throws FileNotFoundException { String myFilename = (args.length < 1) ? ""test"" : args[0]; Set mySet = new TreeSet(); Scanner sc = new Scanner(new File(myFilename)); int testCases, A, B, maxDigits, newNum; String currNumStr, shiftedNumStr, frontStr, newStr; testCases = sc.nextInt(); sc.nextLine(); for (int cases = 0; cases < testCases; cases++) { A = sc.nextInt(); B = sc.nextInt(); mySet.clear(); for (int x = A; x <= B; x++) { currNumStr = Integer.toString(x); maxDigits = currNumStr.length(); // Shifting 0 and maxDigits won't change the number for (int digitsToShift = 1; digitsToShift < maxDigits; digitsToShift++) { shiftedNumStr = currNumStr.substring(digitsToShift, currNumStr.length()); if (shiftedNumStr.charAt(0) == '0') continue; frontStr = currNumStr.substring(0, digitsToShift); newStr = shiftedNumStr + frontStr; newNum = Integer.parseInt(newStr); if (x < newNum && newNum >= A && newNum <= B) mySet.add(new Coordinate(x, newNum)); } } System.out.println(""Case #"" + (cases+1) + "": "" + mySet.size()); } } } " B21187," package Qualification; import Practice.*; import java.util.*; import java.io.*; public class C { public void ejecutar() throws Exception { Scanner sc = new Scanner(new FileReader(""/home/gomezluisj/Descargas/C-large.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""/home/gomezluisj/Descargas/C.out"")); int caseCnt = sc.nextInt(); for (int caseNum = 0; caseNum < caseCnt; caseNum++) { pw.print(""Case #"" + (caseNum + 1) + "": ""); int ini=sc.nextInt(); int fin=sc.nextInt(); int res=0; for (int i = ini; i < fin; i++) { String number=Integer.toString(i); List lista=new ArrayList(); for (int j = 1; j < number.length(); j++) { String compare=number.substring(j)+number.substring(0, j); int num=Integer.parseInt(compare); if(num>i&&num<=fin){ Iterator iter=lista.iterator(); int flag=0; while(iter.hasNext()){ if((Integer)iter.next()==num){ flag=1; } } if (flag==0){ res=res+1; lista.add(num); } // System.out.println(""""+i+"" ""+num); } } } pw.println(res); } pw.flush(); pw.close(); sc.close(); } public static void main(String[] args) throws Exception { new C().ejecutar(); } } " B21010,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class ProblemC { public static void main (String[] args) throws Exception{ BufferedReader fin = new BufferedReader(new FileReader(""E:/C-large.in"")); String line = fin.readLine(); BufferedWriter out = new BufferedWriter(new FileWriter(""E:/C-large.out"")); int ln = 1; while ((line = fin.readLine()) != null && line.length() != 0){ line = line.trim(); String[] parts = line.split(""\\s+""); int a = Integer.parseInt(parts[0]); int b = Integer.parseInt(parts[1]); int count = 0; for (int i = a; i < b; i++){ String s = Integer.toString(i); ArrayList list = new ArrayList(); for (int j = 1; j < s.length(); j++){ String newString = s.substring(j) + s.substring(0,j); int newInt = Integer.parseInt(newString); if ((newInt > i) && (newInt <= b) && (list.contains(newInt) == false)){ list.add(newInt); count++; } } } out.write(""Case #"" + ln + "": "" + count); out.write(""\n""); ln++; } fin.close(); out.close(); } }" B21716,"import java.util.*; import java.io.*; public class Palabras{ static int T; static int matrix[][]; static int valores[]; static BufferedReader input; static StringTokenizer token; static String leerLinea() throws IOException { String linea = input.readLine(); if(linea!=null) { token = new StringTokenizer(linea,"" ""); } return linea; } static String siguiente() { return token.nextToken(); } static void escribirArchivo(String data) throws IOException { PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(data))); for(int i=0; i1; l++) { alt=num.substring(l+1, tam)+num.substring(0,l+1); numero = Integer.parseInt(alt); //System.out.println(""alt ""+numero); if(numero >= matrix[i][0] && numero <= matrix[i][1] && !num.equals(alt)){valores[i]++;} } /* for(int l=0;l1; l++) { if(!num.substring(l+1, l+2).equals(num.substring(l,l+1))) { repetido = false; } } if(repetido && tam>1){valores[i]--;} */ } valores[i] = valores[i]/2; } } public static void main(String[] args) throws IOException { input = new BufferedReader(new FileReader(new File(""prueba.in""))); //System.out.println(""jd""); T = Integer.parseInt(leerLinea()); if(T<1 || T>1000) { System.out.println(""ERROR T""); } matrix = new int[T][2]; valores = new int[T]; for(int i=0; i inputLines = readInput(filename); int i = 0; for (String line : inputLines) { String[] limits = line.split(""\\s+""); RecycledNumbers rn = new RecycledNumbers(Integer.parseInt(limits[0]), Integer.parseInt(limits[1])); int result = rn.getDistinctPairsCount(); System.out.print(""Case #"" + (i + 1) + "": "" + result); System.out.println(); i++; } } private static List readInput(String filename) throws IOException { BufferedReader in = new BufferedReader(new FileReader(filename)); Integer totalLines = Integer.parseInt(in.readLine()); ArrayList lines = new ArrayList(totalLines); for (int i = 0; i < totalLines; i++) { lines.add(in.readLine()); } return lines; } } " B21897,"import java.util.*; import java.util.regex.*; import java.text.*; import java.math.*; import java.awt.geom.*; import java.io.*; public class cx{ public static void main(String[] args){ try{ File output; FileWriter outputwriter; BufferedWriter out; String filename = ""bx.out""; output = new File(filename); outputwriter = new FileWriter(output); out = new BufferedWriter(outputwriter); //System.out.println(""siap""); //out.write(""ardhianvv\nll""); BufferedReader f = new BufferedReader(new FileReader(""a.in"")); StringTokenizer st = new StringTokenizer(f.readLine()); int angka = Integer.parseInt(st.nextToken()); for(int a=0;ajkl = new HashSet(); for(int b=aa;b<=bb;b++){ String as = """"+b; //if(a==3) //System.out.println(""- ""+as); int len = as.length(); for(int c=0;cb && gg<=bb){ //if(a==3) //System.out.println((hasil+1)+ "" ""+b+"" ""+gg); jkl.add(b+"" ""+gg); //hasil++; } } } //System.out.println(jkl.size()); if(a!=angka-1) out.write(""Case #""+(a+1)+"": ""+jkl.size()+""\n""); else out.write(""Case #""+(a+1)+"": ""+jkl.size()); } out.close(); } catch(Exception cc){ System.out.println(cc.toString()); } } }" B22077,"import java.util.*; import java.io.*; import java.math.*; public class Prac3 { public static String shift(String i){ String num=i; String num2=num.substring(num.length()-1,num.length())+num.substring(0,num.length()-1); return num2; } public static boolean rec(Integer a, int b){ Integer original=a; return false; } public static void main(String[] arg){ try{ Scanner in=new Scanner(new File(""sample"")); //BufferedReader br=new BufferedReader(new FileReader(""sample"")); //int numCases=in.nextInt();//br.readLine();br.readLine(); // BufferedWriter bw=new BufferedWriter(new FileWriter(""output.txt"")); int numCases=in.nextInt(); int counter=1; //in.nextLine(); counter=1; while (counter!=numCases+1){ Integer A=in.nextInt(); Integer B=in.nextInt(); ArrayList track=new ArrayList(); if (B.toString().length()<2){ System.out.println(""Case #""+counter+"": ""+0); }else{ for (Integer i=A;i<=B;i++){ Integer original=i; String marker=shift(original.toString()); while (!(marker.equals(original.toString()))){ //System.out.println(marker+ "" "" +original); if (Integer.parseInt(marker)>original && Integer.parseInt(marker)<=B ){//&& !(track.contains(marker)) track.add(Integer.parseInt(marker)); track.add(original); // marker=original.toString(); marker=shift(marker); }else{ marker=shift(marker); } //System.out.println(marker==original); } } System.out.println(""Case #""+counter+"": ""+track.size()/2); } counter++; } }catch (FileNotFoundException e){ }catch (IOException e){ } } }" B21021,"package common; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.LinkedList; import java.util.Queue; public class FileTranslatorBasis { private int numOfCase; private File file; Queue dataList = new LinkedList(); public static FileTranslatorBasis getInstance(String fname){ if(fname ==null){ throw new IllegalArgumentException(); } return new FileTranslatorBasis(new File(fname)); } private FileTranslatorBasis(File file) { this.file = file; read(); } private void read(){ try{ FileReader fr = new FileReader(this.file); BufferedReader br = new BufferedReader(fr); String line; while((line = br.readLine())!=null){ dataList.add(line); } }catch(IOException e){ e.printStackTrace(); } numOfCase = Integer.parseInt(dataList.poll()); } public int getNumOfCase(){ return numOfCase; } public int getIntData(){ return Integer.parseInt(dataList.poll()); } public int[] getIntDataArray(){ String[] tmp = getStrDataArray(); int[] data = new int[tmp.length]; int i = 0; for(String t: tmp){ data[i++] = Integer.parseInt(t); } return data; } public long getLongData(){ return Long.parseLong(dataList.poll()); } public long[] getLongDataArray(){ String[] tmp = getStrDataArray(); long[] data = new long[tmp.length]; int i = 0; for(String t: tmp){ data[i++] = Long.parseLong(t); } return data; } public String getStrData(){ return dataList.poll(); } public String[] getStrDataArray(){ return dataList.poll().split("" ""); } } " B20172,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; class process implements Runnable { Thread t; long a=0,b=0; long res=0; int len,c=0; String str=""""; process(int i,long a1,long a2) { c=(i+1); a=a1; b=a2; len=String.valueOf(a).length(); t = new Thread(this); t.run(); } public void run() { for(long i=a;i<=b;++i) { long temp1=i; int temp2=0; int temp_len=0; for(int j=1;ji && temp1<=b && (temp_len==len))//if(temp1>i && temp1<=b) { res++; //System.out.println(i+""\t""+temp1); } if(temp1==i) break; } } } public void print() { System.out.println(""Case #""+c+"": ""+res); } } public class Main { public static void main(String[] args) throws Exception { StringTokenizer st; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); process[] pr=new process[t]; for(int i=0;i a){ pairs[m].add(n); //System.out.println(m + "" + "" + n); } } } int recycledpairs = 0; for (int k = 0; k < b; k++) { recycledpairs += pairs[k].size(); } // save values System.out.println( ""Case #"" + (i+1) + "": "" + recycledpairs); //bw.write(""Case #"" + ""i"" + "": "" + recycledpairs); //bw.newLine(); } in.close(); //out.close(); } catch (Exception e) { //Catch exception if any System.err.println(""Error: "" + e.getMessage()); e.printStackTrace(); } } } " B21817,"import java.lang.reflect.Array; import java.util.*; public class ArrayUtil { static T[] revers (T[] t){ List list = Arrays.asList(t); Collections.reverse(list); return (T[]) list.toArray(); } static Map listToMap(List list) { HashMap map = new HashMap<>(); for (int i = 0; i < list.size(); i++) { T t = list.get(i); map.put(t,i); } return map; } static List fromIndexList(List inds, List values) { ArrayList ts = new ArrayList<>(); for (Integer ind : inds) { ts.add(values.get(ind)) ; } return ts; } } " B20374,"import java.util.*; public class C { public static void main (String [] args) { Scanner s = new Scanner(System.in); int T = s.nextInt(); int[] old = new int[7]; for (int t = 1; t <= T; t++) { int A = s.nextInt(); int B = s.nextInt(); int ans = 0; for (int n = A; n < B; n++) { int time = 0; int d = 10; while (n >= d) { time++; d *= 10; } int oldSize = 0; for (int i = 0; i < time; i++) { int m = movingFront(n, i, time - i); if (m > n && m <= B) { boolean unique = true; for (int k = 0; k < oldSize; k++) { if (old[k] == m) { unique = false; break; } } if (unique) { ans++; old[oldSize++] = m; } } } } System.out.println(""Case #"" + t + "": ""+ans); } } public static int movingFront(int n, int index, int postMult) { int front = 0; int mult = 1; while (index-- >= 0) { front += ((n % 10) * mult); n /= 10; mult *= 10; } int frontMult = 1; while (postMult-- > 0) { frontMult *= 10; } return (front * frontMult) + n; } }" B20792,"import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; public class C { public static void main(String[] args) throws Exception { Scanner in = new Scanner(new FileReader(new File(""C.in""))); PrintWriter out = new PrintWriter(new FileWriter(""C.out"")); int tests = in.nextInt(); int A,B; for (int i = 1; i <= tests; i++) { out.print(""Case #"" + (i) + "": ""); System.out.print(""Case #"" + (i) + "": ""); A = in.nextInt();B = in.nextInt(); int cnt = 0; for (int j = A; j <= B; j++) { int len = (j+"""").length(); for (int k = 1; k < len; k++) { int num = cycle(j,k); if(num > j && num <= B)cnt++; } } out.println(cnt); System.out.println(cnt); } out.close(); } public static int cycle(int x,int i){ String n = x+""""; String tmp = n.substring(i); return Integer.parseInt(tmp + n.substring(0,i)); } } " B21990,"import java.io.*; import java.util.*; public class C { public static void main(String[] args) { new C().run(); } BufferedReader br; StringTokenizer st; PrintWriter out; boolean eof; public void run() { try { // br = new BufferedReader(new InputStreamReader(System.in)); // out = new PrintWriter(System.out); br = new BufferedReader(new FileReader(""C-large.in"")); out = new PrintWriter(""C-large.out""); solve(); } catch (Throwable e) { e.printStackTrace(); System.exit(-1); } finally { out.close(); } } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return ""0""; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } final int MAX = 2000000; void solve() throws IOException { int n = nextInt(); for (int test = 1; test <= n; ++test) { int l = nextInt(); int r = nextInt(); int ans = 0; for (int i = l; i <= r; ++i) { int t = 1; while (t <= i) t *= 10; t /= 10; int j = i; while (true) { j = (j % 10) * t + j / 10; if (i < j && j <= r) { ++ans; } if (j == i) { break; } } } out.println(""Case #"" + test + "": "" + ans); } } } " B22083,"import java.util.*; import java.io.*; public class codejam1{ public static void main(String [] args){ HashMap permuToPairs = new HashMap(); permuToPairs.put(1,0); permuToPairs.put(2,1); permuToPairs.put(3,3); permuToPairs.put(4,6); permuToPairs.put(5,10); permuToPairs.put(6,15); permuToPairs.put(7,21); //System.out.println(findRecycle(1111, 2222,permuToPairs)); int count = 1; try{ Scanner sc = new Scanner(new File(""C-large.in"")); PrintStream ps = new PrintStream(new File(""OutputFile"")); sc.nextLine(); while (sc.hasNextLine()){ String line = sc.nextLine(); String[] numbers = line.split("" ""); long low = Long.parseLong(numbers[0]); long high = Long.parseLong(numbers[1]); String s = ""Case #""+count+"": "" + findRecycle(low, high,permuToPairs); if(sc.hasNextLine()){ s +=""\n""; } ps.print(s); count ++; } }catch(Exception e){ } } public static long findRecycle(long low, long high, HashMap permuToPairs){ Set numberSet = new HashSet(); String numberString = low+""""; int numWidth = numberString.length(); long count = 0; for(long i = low; i<= high; i++){ if(!numberSet.contains(i)){ numberSet.add(i); long permuNumber = i; int numPermus = 1; for(int j = 0; j < numWidth; j++){ // permute the number permuNumber = permuNumber % 10* (int)Math.pow(10, numWidth-1)+permuNumber/10; if(permuNumber >= low && permuNumber <= high && !numberSet.contains(permuNumber)){ numPermus++; numberSet.add(permuNumber); } } count += permuToPairs.get(numPermus); } } return count; } }" B21088,"import java.io.*; import java.lang.*; import java.util.*; public class Recycle{ public static void main(String args []){ try{ FileInputStream fstream = new FileInputStream(""C-large.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter ostream = new FileWriter(""recOut.txt""); BufferedWriter out = new BufferedWriter(ostream); String str = br.readLine(); int num = Integer.parseInt(str.replaceAll(""\\s"","""")); String [] AB = new String[num]; String temp; int k = 0; while((temp = br.readLine()) != null && k < num){ AB[k] = temp; ++k; } //for(int i=1; i<= num; i++){ for(int i=1; i<= num; i++){ String ABs = AB[i-1].trim(); int n = calcDig(ABs); out.write(""Case #"" + i + "": "" + n); out.write(""\n""); out.flush(); } out.close(); } catch(Exception e){} } public static int calcDig(String input){ String [] nums = input.split("" ""); int A = Integer.parseInt(nums[0].replaceAll(""\\s"","""")); int B = Integer.parseInt(nums[1].replaceAll(""\\s"","""")); if(A < 10) return 0; else return numRot(A, B); } public static int numRot(int A, int B){ int toRet = 0; int len = Integer.toString(A).length(); int cur = A; //System.out.println(A); //System.out.println(B); //System.out.println(len); HashMap sets = new HashMap(); while(cur < B){ for(int j=1; j< len; j++){ int newPerm = Rotate(cur, j, len); int newLen = Integer.toString(newPerm).length(); //System.out.println(cur + "" "" +newPerm); if(B >= newPerm && newLen == len && cur < newPerm){ ++toRet; //sets.put(cur, newPerm); if(sets.containsKey(cur)){ if(sets.get(cur) == newPerm){ //System.out.println(""Found: "" + sets.get(cur)); --toRet; } } else{ sets.put(cur, newPerm); } } /* else System.out.println("" perm "" + newPerm + "" not counted""); */ } ++cur; } return toRet; } public static int checkRot(int A, int B, int len){ //System.out.print(""A: "" + A); //System.out.println(""B: "" + B); List aList = new ArrayList(); List bList = new ArrayList(); int a = A; int b = B; while(a > 0){ aList.add(a % 10); bList.add(b % 10); a /= 10; b /= 10; } Collections.sort(aList); Collections.sort(bList); if(aList.equals(bList)){ //nreturn iterRot(A, B, len); return 0; } else return 0; } /* public static int iterRot(int A, int B, int len){ int toRet = 0; for(int i=1; i 0) { ans ++; x /= 10; } return ans; } public static void main(String[] args) throws FileNotFoundException { Scanner fin = new Scanner(new File(""C.txt"")); PrintStream fout = new PrintStream(""C.ans""); int caseN = fin.nextInt(); for (int caseI = 1; caseI <= caseN; caseI++) { int A = fin.nextInt(); int B = fin.nextInt(); int ans = 0; for (int n = max(A, 12); n < B; n++) { String front = Integer.valueOf(n / 10).toString(); String back = Integer.valueOf(n % 10).toString(); Set appeared = new HashSet(); while (front.length() != 0) { if (back.charAt(0) != '0') { int m = Integer.valueOf(back + front); if (m > n && m <= B && !appeared.contains(m)) { ans++; appeared.add(m); //fout.println(n + "" "" + m); } } back = front.charAt(front.length() - 1) + back; front = front.substring(0, front.length() - 1); } } fout.println(""Case #"" + caseI + "": "" + ans); } } } " B21917," import java.util.Scanner; public class RecycledNumber { public int deal(int A, int B) { int ans = 0; for (int i = A; i<= B ; i ++) { int left = i; int k = 1; int tk = 1; UniqueList newInts = new UniqueList(10); while (left >= 10) { left = left / 10; tk = tk * 10; } left = i; while (k * 10 <= left) { k = k * 10; int x = (left % k) * (tk * 10 / k) + (left / k); //System.out.println(i + "": "" + x); if (x > i && x <= B) newInts.add(x); } ans += newInts.getSize(); } return ans; } public void solve() { Scanner scan = new Scanner(System.in); int T = scan.nextInt();scan.nextLine(); for (int i = 1; i <= T; i ++) { int A = scan.nextInt(); int B = scan.nextInt(); System.out.println(""Case #"" + i + "": "" + this.deal(A, B)); } } public static void main(String args[]) { RecycledNumber r = new RecycledNumber(); r.solve(); } } " B21602,"import java.io.*; public class Recycle { public static void main(String args[]) { try { InputStreamReader inReader = new InputStreamReader(new FileInputStream(""input.txt"")); BufferedReader br = new BufferedReader(inReader); File out = new File(""output.txt""); Writer output = new BufferedWriter(new FileWriter(out)); int amount = Integer.parseInt(br.readLine()); for (int i=0; i < amount; i++) { output.write(""Case #"" + (i+1) + "": ""); String line = br.readLine(); int min = Integer.parseInt(line.split("" "")[0]); int max = Integer.parseInt(line.split("" "")[1]); int result = 0; int digits = 1; int tmp = max; while (tmp/10 > 0) { tmp /= 10; digits++; } int[] assist = new int[digits]; for (int l=0; l < digits; l++) assist[l] = 0; for (int j=min; j <= max; j++) { int number = j; int counter = 0; for (int k=1; k < digits; k++) { int newNumber = (int) ((int) (number%Math.pow(10, k)) * Math.pow(10, digits-k) + (number/Math.pow(10, k))); if (newNumber > number && newNumber <= max) { for (int l=0; l < counter; l++) { if (assist[l] == newNumber) result--; } assist[counter++] = newNumber; result++; } } } output.write(result + ""\n""); } output.close(); } catch (Exception e) { e.printStackTrace(); } } }" B20348,"package year2012.RecycledNumbers; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; final class RecycledNumbers { /** * @param args * @throws IOException */ static int solve(int upper, int value) { if (value < 12) return 0; String strNum = value + """"; int length = strNum.length(); Set setNewNumber = new HashSet (); for (int i = 1; i < length; i++) { if (strNum.charAt(i) != '0') { String first = strNum.substring(0, i); String last = strNum.substring(i, length); int newNum = Integer.parseInt(last + first); if (newNum <= upper && newNum > value ) setNewNumber.add(new Integer(newNum)) ; } } return setNewNumber.size(); } public static void main(String[] args) throws IOException { String file = ""C-large""; Scanner sc = new Scanner(new FileReader(file + "".in"")); PrintWriter pw = new PrintWriter(new FileWriter(file + "".out"")); int T = sc.nextInt(); int A = 0; int B = 0; sc.nextLine(); for (int i = 0; i < T; i++) { A = sc.nextInt(); B = sc.nextInt(); int result = 0; for (int ii = A; ii <= B; ii++) { result += solve(B, ii); } pw.println(""Case #"" + (i + 1) + "": "" + result); } pw.flush(); pw.close(); sc.close(); } } " B20536,"import java.util.HashSet; import java.util.Scanner; class ProblemCSmall { // Not happy that my previous approaches didn't work and that I have to do it this way, but whatever works... public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(), I = 0; while (T --> 0) { int A = in.nextInt(), B = in.nextInt(); int lenA = (int) Math.log10(A), lenB = (int) Math.log10(B); int prevStart = A; HashSet pairs = new HashSet(); for (int i = lenA; i <= lenB; ++i) { int currPow10 = (int) Math.pow(10, i); int start = (int) Math.max(prevStart, currPow10), end = (int) Math.min(B, 10*currPow10-1); for (int j = start; j <= end; ++j) { int k = j; for (int l = 0; l < i; ++l) { k = (k % currPow10) * 10 + (k / currPow10); if (k >= start && k <= end && k != j) { pairs.add(String.format(""%07d%07d"", Math.min(j, k), Math.max(j, k))); } } } prevStart = end + 1; } System.out.printf(""Case #%d: %d\n"", ++I, pairs.size()); } } } " B20413,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Numbers { private static int [][] input; private static int [] output; public static void main(String [] args) throws NumberFormatException, IOException{ readData(); output = new int [input.length]; for (int i=0 ; i< input.length ; i++){ output[i] = numberOfPairs(input[i][0], input[i][1]); } writeData(); } public static int numberOfPairs(int a, int b){ int r=0; for (int i=a ; i<=b ; i++ ) { String A = Integer.toString( i ); int f = flip(A); int f2 = flip2(A); int f3 = flip3(A); int f4 = flip4(A); int f5 = flip5(A); int f6 = flip6(A); if ( i100){ if ( i1000){ if ( i10000){ if ( i100000){ if ( i1000000){ if ( i nlist = new ArrayList(); ArrayList mlist = new ArrayList(); for (int i = 0 ; i < loop ; i++) { str = br.readLine(); n = Integer.parseInt(str.substring(0,str.length()/2)); m = Integer.parseInt(str.substring(str.length()/2+1,str.length())); for (int k = n ; k < m ; k++){ String current = Integer.toString(k); for (int j = 0; j< current.length()-1; j++){ char c = current.charAt(0); current += c; current = current.substring (1,current.length()); int check = Integer.parseInt(current); if (check > k && check <= m){ nlist.add(k); mlist.add(check); // System.out.println(k+"" , ""+current); counter++; } } } System.out.println(""Case #""+(i+1)+"": ""+counter); //System.out.println(nlist); //System.out.println(mlist); counter = 0; } in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } }" B21219," import java.io.*; import java.util.*; public class Recycle { static int total; static Set set; public static void main(String[] codejam) throws Exception { BufferedReader br = new BufferedReader (new FileReader (""recycle.in"")); PrintStream ps = new PrintStream (new FileOutputStream (""recycle.out"")); int t = Integer.parseInt(br.readLine()); for(int l=1;l<=t;l++) { String[] in = br.readLine().split("" ""); int first = Integer.parseInt(in[0]); int last = Integer.parseInt(in[1]); total = 0; for(int i=first;i(); for(int i=0;i a && m > n && !set.contains(m)) { set.add(m); total++; } } number = temp; } } }" B20280,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.HashSet; public class RecycledPairs { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); HashSet seen = new HashSet(); int T = Integer.parseInt(br.readLine()); for (int t=1; t<=T; t++) { String[] nums = br.readLine().split(""\\s+""); int A = Integer.parseInt(nums[0]); int B = Integer.parseInt(nums[1]); int tally = 0; for (int i=A; i<=B; i++) { String istr = Integer.toString(i); seen = new HashSet(); for (int j=1; j i) && (newi <= B) && (newi >= A)) { if (seen.add(newi)) { tally++; //System.out.println(i + "" "" + newi); } } } } System.out.println(""Case #"" + t + "": "" + tally); } } catch (IOException e) { throw new RuntimeException(e); } } } " B21783,"import java.io.*; import java.util.*; public class C_Qual { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int tt = 1; tt <= T; tt++) { int a=in.nextInt(),b=in.nextInt(); int res=0; for(int i=a;i<=b;i++){ String num = i+""""; HashSet vis=new HashSet(); for(int j=0;j=a&&n<=b){ if(vis.contains(n)){ continue; } vis.add(n); res++; } } } System.out.printf(""Case #%d: %d\n"", tt,res); } } }" B21643,"import java.util.ArrayList; import java.util.Collection; /** * User: avokin * Date: 4/14/12 */ public class ProblemC { private static int[] deg = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; private static int recycled(int a, int b, int n) { int result = 0; int i = 1; Collection counted = new ArrayList(); while (i < n) { int a1 = a / deg[i]; int a2 = a % deg[i]; int a3 = a2 * deg[n - i] + a1; if (a < a3 && a3 <= b) { if (!counted.contains(a3)) { result++; } counted.add(a3); } i++; } return result; } private static int solve(int a, int b) { int result = 0; int n = ("""" + a).length(); for (int i = a; i < b; i++) { result += recycled(i, b, n); } return result; } public static void main(String[] args) { String input = ""50\n"" + ""1000000 2000000\n"" + ""1003717 1987538\n"" + ""1013804 1939331\n"" + ""1222652 1836943\n"" + ""831085 961576\n"" + ""1323254 1655499\n"" + ""1036764 1919078\n"" + ""54728 86069\n"" + ""1140403 1378888\n"" + ""1086580 1931538\n"" + ""4017 5065\n"" + ""47682 47682\n"" + ""1075058 1974024\n"" + ""1104180 1282545\n"" + ""1081837 1579766\n"" + ""1081844 1913145\n"" + ""1054644 1914812\n"" + ""200978 590182\n"" + ""17 79\n"" + ""401165 866289\n"" + ""1503092 1980132\n"" + ""1001493 1921033\n"" + ""1092675 1901907\n"" + ""1676026 1895467\n"" + ""39677 93416\n"" + ""1127 7446\n"" + ""205 445\n"" + ""1097902 1907197\n"" + ""229602 483412\n"" + ""74999 89942\n"" + ""1078656 1915322\n"" + ""44 52\n"" + ""1049694 1900352\n"" + ""100000 999999\n"" + ""4251 6207\n"" + ""1079496 1901886\n"" + ""191939 567669\n"" + ""1011791 1962213\n"" + ""35390 98715\n"" + ""364 920\n"" + ""100 101\n"" + ""11868 53377\n"" + ""443 748\n"" + ""10000 10000\n"" + ""1091806 1930053\n"" + ""1070990 1934498\n"" + ""1 9\n"" + ""332045 943240\n"" + ""7621 9867\n"" + ""1028742 1028742\n""; String[] lines = input.split(""\n""); int T = Integer.parseInt(lines[0]); for (int i = 1; i <= T; i++) { String line = lines[i]; String[] items = line.split("" ""); int a = Integer.parseInt(items[0]); int b = Integer.parseInt(items[1]); int solution = solve(a, b); System.out.println(""Case #"" + i + "": "" + solution); } } } " B20782,"import java.util.HashSet; import java.util.Scanner; import java.util.Vector; class Pair { public int low; public int high; public Pair(int l, int h) { low = l; high = h; } public boolean equals(Object o) { Pair other = (Pair)o; return other.low == low && other.high == high; } public int hashCode() { return low * 31 + high; } } public class C { public static void main(String[] args) { // TODO Auto-generated method stub new C(); } public C() { Vector pairs = new Vector(); HashSet set = new HashSet(); int[] powers = new int[8]; int ac = 1; for(int i = 0; i < 8; ++i) { powers[i] = ac; ac *= 10; } for(int currentNumber = 10; currentNumber < 2000000; ++currentNumber) { String trick = """" + currentNumber; int length = trick.length(); int[] digits = new int[trick.length()]; int[] shuffle = new int[trick.length()]; for(int c = 0; c < length; ++c) { int digit = trick.charAt(c) - '0'; digits[c] = digit; shuffle[c] = digit; } for(int s = 1; s < length; ++s) { boolean atLeastOneLarger = false; for(int pos = 0; pos < length; ++pos) { int spos = (pos + s) % length; /* Check that position makes the shuffle larger. */ if(shuffle[spos] < digits[pos]) { break; } else if(shuffle[spos] > digits[pos]) { atLeastOneLarger = true; break; } } if(atLeastOneLarger) { int secondNumber = 0; /* Generate the larger number. */ for(int pos = 0; pos < length; ++pos) { int spos = (pos + s) % length; secondNumber += shuffle[spos] * powers[length - pos - 1]; } if(secondNumber < 2000000 && secondNumber > currentNumber) { Pair newp = new Pair(currentNumber, secondNumber); if(!set.contains(newp)) { pairs.add(newp); set.add(newp); } } } } } Scanner sc = new Scanner(System.in); int testCases = sc.nextInt(); for(int testCase = 1; testCase <= testCases; ++testCase) { int A = sc.nextInt(); int B = sc.nextInt(); int lowIndex = binLow(A, pairs); int highIndex = binHigh(B, pairs); if(lowIndex == -1) lowIndex = 0; if(highIndex == -1) highIndex = 0; int ans = 0; for(int pair = lowIndex; pair <= highIndex; ++pair) { Pair p = pairs.elementAt(pair); if(p.low >= A && p.high <= B) ans++; } System.out.printf(""Case #%d: %d\n"", testCase, ans); } } private int binHigh(int b, Vector pairs) { int low = 0; int high = pairs.size() - 1; int mid = (low + high)/2; while (true) { int number = pairs.elementAt(mid).low; if (number == b || number < b) { low = mid+1; if (high < low) return mid pairs) { int low = 0; int high = pairs.size() - 1; int mid = (low + high)/2; while (true) { int number = pairs.elementAt(mid).low; if (number == a || number > a) { high = mid-1; if (high < low) return mid; } else { low = mid+1; if (high < low) return mid s = new HashSet(); for(int i = a; i <= b; i++) { String num = Integer.toString(i); if (num.matches(""^[""+num.substring(0,1)+""]+$"")) { //System.out.println(num); continue; } if (num.matches(""^[1-9][0]+$"")) { //System.out.println(num); continue; } s.add(i); } int answer = 0; for(int n = a; !s.isEmpty() && n <= b; n++) { if (!s.contains(n)) { continue; } String ns = Integer.toString(n, 10); int length = ns.length(); Set dup = new HashSet(); for (int j = 1; j < length; j++) { String ms = ns.substring(length-j) + ns.substring(0, length-j); //System.out.println(ns+"":""+ms); int m = Integer.parseInt(ms); if (!s.contains(m)) { continue; } if (m < a || b < m || n >= m) { continue; } s.remove(m); if (!dup.contains(m)) { dup.add(m); } answer++; } int size = dup.size(); if (size > 1) { answer = answer + size * (size - 1) / 2; } s.remove(n); } StringBuilder sb = new StringBuilder(); sb.append(""Case #""); sb.append(caseNo+1); sb.append("": ""); sb.append(answer); System.out.println(sb.toString()); } } " B21532,"package codejam; import java.util.HashSet; import java.util.Scanner; public class Qual2012C { private static int digitCount; private static int[] MULTIPLES = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000 }; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int nrOfTestCases = scanner.nextInt(); for (int caseNr = 1; caseNr <= nrOfTestCases; caseNr++) { int a = scanner.nextInt(); int b = scanner.nextInt(); digitCount = digitCount(a); System.out.println(""Case #"" + caseNr + "": "" + solve(a, b)); } } private static int digitCount(int a) { if (a == 0) return 0; return 1 + digitCount(a / 10); } private static long solve(int min, int max) { long total = 0; for (int n = min; n < max; n++) total += pairsFor(n, max); return total; } private static int pairsFor(int n, int max) { if (n >= max) return 0; HashSet set = new HashSet(); for (int i = 1; i < digitCount; i++) { int multipleSplit = MULTIPLES[i]; int tail = n % multipleSplit; if (tail < MULTIPLES[i - 1]) continue; int m = tail * MULTIPLES[digitCount - i] + (n / multipleSplit); if (n < m && m <= max) set.add(m); } return set.size(); } } " B20862,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; public class RecycledNumbers { private static int T; private static ArrayList lowerLimit, upperLimit; private static ArrayList numOfPairs; public static void main(String[] args) { readInputFile (); getNumberOfRecycledPairs (); writeOutputFile (); } private static void readInputFile () { numOfPairs = new ArrayList (); lowerLimit = new ArrayList (); upperLimit = new ArrayList (); String line = """"; try { BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (new FileInputStream (""input/C-small-attempt0.in""))); line = bufferedReader.readLine (); T = Integer.parseInt (line); while ((line = bufferedReader.readLine ()) != null) { String [] dataSet = line.split ("" ""); lowerLimit.add (Integer.parseInt (dataSet [0])); upperLimit.add (Integer.parseInt (dataSet [1])); } System.out.println (lowerLimit + ""\n"" + upperLimit); bufferedReader.close (); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void getNumberOfRecycledPairs () { for (int i = 0; i < T; i++) { int numOfValidPairs = 0; for (int j = lowerLimit.get (i); j < upperLimit.get (i); j++) { int numOfDigits = String.valueOf (j).length (); //int num = j; for (int k = 1; k < numOfDigits; k++) { //num = ((num % (int)Math.pow (10, numOfDigits - 1)) * 10 + // (num / (int)Math.pow (10, numOfDigits - 1))); int num = ((j % (int)Math.pow (10, k)) * (int)Math.pow (10, numOfDigits - k)) + (j / (int)Math.pow (10, k)); //if (num / (int)Math.pow (10, numOfDigits - 1) > 0) { if (String.valueOf (num).length() == String.valueOf (j).length()) { if (j < num && num <= upperLimit.get (i)) { numOfValidPairs++; } } } } numOfPairs.add (numOfValidPairs); } } private static void writeOutputFile () { try { BufferedWriter bufferedWriter = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (""output/output.out""))); for (int i = 0; i < numOfPairs.size (); i++) { bufferedWriter.write (""Case #"" + (i + 1) + "": "" + numOfPairs.get (i) + ""\n""); } bufferedWriter.close (); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B20046,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejamc; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.*; /** * * @author usuario */ public class CodejamC { /** * @param args the command line arguments */ public static int fun(int a,int b,int i){ int cont=0,n=0,mod,res=i; boolean flag; String num=i+""""; String aux; int tmp; tmp=num.length(); while(ni && res<= b){ cont++; } } return cont; } public static void main(String[] args){ int n,a,b,cont=0; try { System.setIn(new FileInputStream(""file.in"")); } catch (FileNotFoundException ex) { Logger.getLogger(CodejamC.class.getName()).log(Level.SEVERE, null, ex); } Scanner reader=new Scanner(System.in); n=reader.nextInt(); for(int i=0;i res = new HashSet(); for (int i = A; i < B; i++) { String num = String.valueOf(i); for (int j = 1; j < num.length(); j++) { int num2 = Integer.parseInt(getRecycled(num, j)); if (num2 > i && num2 <= B) { res.add(""("" + num + "", "" + num2 + "")""); } } } return String.valueOf(res.size()); } public static String getRecycled(String source, int digits) { String firstPart = source.substring(0, source.length() - digits); String secondPart = source.substring(source.length() - digits); return secondPart + firstPart; } } " B21188,"import java.util.*; class Recycle { public static int[] combi = {0,0,1,3,6,10,16,21}; public static boolean[] bool; public static int howMany(int x, int least, int greatest) { int rotate = x; int pair = 1; int i; int j; int dummy; ArrayList digit = new ArrayList(); bool[rotate]=true; while (rotate>0) { digit.add(rotate%10); rotate=rotate/10; } for (i=1; i=0; j--) rotate = rotate*10+digit.get(j); if (((rotate<=greatest) && (rotate>=least))&&(bool[rotate]==false)) { //System.out.println(rotate); bool[rotate]=true; pair++; } } } return (combi[pair]); } public static void main (String[] args) { Scanner myInput = new Scanner(System.in); int T; int t; T = myInput.nextInt(); int i; int A; int B; int result; for (t=1; t<=T; t++) { A=myInput.nextInt(); B=myInput.nextInt(); result=0; bool = new boolean[B+1]; for (i=A; i<=B; i++) if (bool[i]==false) result=result+howMany(i,A,B); System.out.println(""Case #""+t+"": ""+result); } } } " B20240,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; /** * */ /** * @author Bageshwar * */ public class Recycle { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { long[] p = new long[] { 10, 100, 1000, 10000, 100000, 1000000, 10000000 }; // HashSet set=new HashSet(); // HashSet set1=new HashSet(); BufferedReader fr = new BufferedReader(new FileReader(new File(args[0]))); String str = fr.readLine(); //System.out.println(str); int lines = Integer.parseInt(str); FileWriter writer = new FileWriter(new File(args[1])); StringTokenizer stk; for (int l = 0; l < lines; l++) { writer.write(""Case #""+(l+1)+"": ""); str = fr.readLine(); stk = new StringTokenizer(str,"" ""); long a = Integer.parseInt(stk.nextElement().toString()); long b = Integer.parseInt(stk.nextElement().toString()); int total = 0; long t = 0; int k = 0; int c = ("""" + b).length() - 1; for (long i = a; i <= b; i++) { for (int j = 0; j < c; j++) { // rotate by j // j=j-1; k = c - j - 1; t = (i % p[j]) * p[k] + (i / p[j]); //System.out.print("" ""+i+"":""+t); if (t <= b && t >= a && i != t) { //System.out.print(""!""); // set.add(i); total++; //System.out.println(""##########"" + i + "">>"" + t); // set1.add(e) } } //System.out.println(""""); } System.out.println(total); System.out.println(total / 2); writer.write(total/2+""\r\n""); } writer.close(); fr.close(); } } " B20038," import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; public class C { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter( System.out))); int qq = readInt(); for(int casenum = 1; casenum <= qq; casenum++) { int a = readInt(); int b = readInt(); int ret = 0; for(int i = a; i <= b; i++) { String s = Integer.toString(i); Set set = new HashSet(); for(int j = 0; j < s.length(); j++) { int test = Integer.parseInt(s.substring(j) + s.substring(0,j)); if(a <= i && i < test && test <= b && s.length() == Integer.toString(test).length()) { set.add(test); } } ret += set.size(); } pw.println(""Case #"" + casenum + "": "" + ret); } pw.close(); } public static long readLong() throws IOException { return Long.parseLong(nextToken()); } public static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } public static int readInt() throws IOException { return Integer.parseInt(nextToken()); } public static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { if (!br.ready()) { pw.close(); System.exit(0); } st = new StringTokenizer(br.readLine()); } return st.nextToken(); } } " B22249,"package com.google.codejam; import java.io.*; import java.util.HashSet; import java.util.StringTokenizer; /** * User: svasilinets * Date: 14.04.12 * Time: 11:58 */ public class QualC { private static int getDigitCount(int k) { int r = 0; while (k != 0) { k /= 10; r++; } return r; } public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(""c.in"")); BufferedWriter writer = new BufferedWriter(new FileWriter(""c.out"")); int tests = Integer.parseInt(reader.readLine()); for (int t = 1; t <= tests; t++) { StringTokenizer tokenizer = new StringTokenizer(reader.readLine()); int a = Integer.parseInt(tokenizer.nextToken()); int b = Integer.parseInt(tokenizer.nextToken()); int d = getDigitCount(a); int result = 0; int tp = 1; for (int i = 0; i < d; i++) { tp *= 10; } for (int i = a; i <= b; i++) { HashSet h = new HashSet(); int p = 1; for (int j = 0; j < d - 1; j++) { p *= 10; int rest = i % p; int del = i / p; int pretend = rest * (tp / p) + del; if (pretend > i && pretend <= b && !h.contains(pretend)){ result++; h.add(pretend); } } } writer.write(""Case #"" + t + "": "" + result); writer.newLine(); } writer.close(); } } " B21430,"package jp.funnything.competition.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; public class Packer { private static void add( final ZipArchiveOutputStream out , final File file , final int pathPrefix ) { if ( file.isDirectory() ) { final File[] children = file.listFiles(); if ( children.length > 0 ) { for ( final File child : children ) { add( out , child , pathPrefix ); } } else { addEntry( out , file , pathPrefix , false ); } } else { addEntry( out , file , pathPrefix , true ); } } private static void addEntry( final ZipArchiveOutputStream out , final File file , final int pathPrefix , final boolean isFile ) { try { out.putArchiveEntry( new ZipArchiveEntry( file.getPath().substring( pathPrefix ) + ( isFile ? """" : ""/"" ) ) ); if ( isFile ) { final FileInputStream in = FileUtils.openInputStream( file ); IOUtils.copy( in , out ); IOUtils.closeQuietly( in ); } out.closeArchiveEntry(); } catch ( final IOException e ) { throw new RuntimeException( e ); } } public static void pack( final File source , final File destination ) { try { final ZipArchiveOutputStream out = new ZipArchiveOutputStream( destination ); add( out , source , FilenameUtils.getPath( source.getPath() ).length() ); out.finish(); out.close(); } catch ( final IOException e ) { throw new RuntimeException( e ); } } } " B21483,"import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner oku = new Scanner(System.in); int test = oku.nextInt(), A = oku.nextInt(), B = oku.nextInt(), dijit = Integer.toString(A).length(), sayimiz = 0; HashSet eleme; for (int i = 0; i < test; i++, A = oku.nextInt(), B = oku.nextInt(), sayimiz = 0) { dijit = Integer.toString(A).length(); for (int j = A; j < B; j++) { eleme = new HashSet(); for (int k = 1; k < dijit; k++) { int saga_kayan = j / (int) Math.pow(10, k); int sola_kayan = (j % (int) Math.pow(10, k) * (int) Math.pow(10, dijit - k)); int son = saga_kayan + sola_kayan; if (son <= B && j < son) { eleme.add(son); } } sayimiz += eleme.size(); } System.out.println(""Case #"" + (i + 1) + "": "" + sayimiz); } } }" B20808,"import java.util.Scanner; import java.util.TreeSet; public class RecycledNumbers { public static void main(String[] args) { Scanner s = new Scanner(System.in); int numCases = s.nextInt(); s.nextLine(); for (int i = 0; i < numCases; i++) { TreeSet found = new TreeSet<>(); int count = 0; int a = s.nextInt(); int b = s.nextInt(); String bStr = b + """"; for (int n = a; n < b; n++) { String numStr = n + """"; for (int j = 1; j < numStr.length(); j++) { if (numStr.charAt(j) < numStr.charAt(0)) { continue; } if (numStr.length() == bStr.length() && numStr.charAt(j) > bStr.charAt(0)) { continue; } String numRot = numStr.substring(j) + numStr.substring(0, j); int m = Integer.parseInt(numRot); //System.out.println(""DEBUG: Trying "" + n + "","" + m); if (n < m && m <= b) { found.add(m); //System.out.println(""DEBUG: Found""); } } count += found.size(); found.clear(); } System.out.println(""Case #"" + (i+1) + "": "" + count); } } } " B20027,"import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { BufferedReader inFile = null; try { inFile = new BufferedReader( new InputStreamReader( new BufferedInputStream(new FileInputStream(""C-large.in"")), ""UTF-8"" ) ); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } int numCases = 0; List recycledNumbersPerCase = new ArrayList(); try { numCases = Integer.parseInt(inFile.readLine()); for (int caseNum = 0; caseNum < numCases; caseNum++) { String[] words = inFile.readLine().split("" ""); long A = Integer.parseInt(words[0]); long B = Integer.parseInt(words[1]); int numDigits = (int) Math.ceil(Math.log10(A+1)); // make sure A doesn't start with leading 0 int numDigitsB = (int) Math.ceil(Math.log10(B)); numDigits = (numDigits > numDigitsB) ? numDigits : numDigitsB; int matchedRecycledNumbers = 0; for (long n = A; n < B-1; n++) { /* * rotate digits and look for all the numbers * bigger than original number and in given interval */ long rotatedNum = n; while(true) { rotatedNum = rotateDigitsRight(rotatedNum, numDigits); if (rotatedNum == n) break; if(rotatedNum < A || B < rotatedNum) continue; if(rotatedNum < n) continue; // don't count twice // number is in interval matchedRecycledNumbers++; } } recycledNumbersPerCase.add(matchedRecycledNumbers); } } catch (IOException e) { e.printStackTrace(); } try { BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(""C-large.out.txt""), ""UTF-8"" ) ); for (int caseNum = 0; caseNum < numCases; caseNum++) { bw.append(""Case #"" + (caseNum+1) + "": "" + recycledNumbersPerCase.get(caseNum)); bw.newLine(); } bw.flush(); } catch (IOException e) { e.printStackTrace(); } } private static long rotateDigitsRight(long number, int numDigits) { long biggerRightPart = number / 10; long transferingRightmostNum = number % 10; long result = (transferingRightmostNum * (int) Math.pow(10, numDigits-1)) + biggerRightPart; return result; } } " B22238," import java.io.*; import java.text.*; import java.math.*; import java.util.*; public class J12QC implements Runnable { Scanner in; PrintWriter out; static String taskname = "".\\src\\C-large""; int test, testn, i, j, k; public static void main(String[] args) { new Thread(new J12QC()).start(); } public void solve() throws Exception { testn = in.nextInt(); long A,B,C,M,M2,M1; long n, N; boolean t; for (test = 0; test < testn; test++) { out.print(""Case #"" + (test + 1) + "": ""); A = in.nextLong(); B = in.nextLong(); M=1; C=A; while(C>0){C/=10; M*=10;} M2 = (B0){ C=C*10%M + C*10/M; if((C < M1)||(C>M2)) continue; //or -9*exp if(C < c) {t=false; break;} if(C == c) {break;} n++; } if(t) return n+1; else return 0; } @Override public void run() { try { in = new Scanner(new File(taskname + "".in"")); out = new PrintWriter(taskname+"".out""); //out = new PrintWriter(System.out, true); // in = new BufferedReader( new InputStreamReader(System.in)); // out = new BufferedWriter( new OutputStreamWriter(System.out)); solve(); out.flush(); } catch (Exception e) { e.printStackTrace(); } } } " B20772,"package prob2; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class prob2 { public static void main(String args[]) { try { BufferedReader in = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(""./src/prob2/a-small.in"")))); BufferedWriter out = new BufferedWriter(new FileWriter(""./src/prob2/a-small.out"")); int line = Integer.parseInt(in.readLine()); for (int i = 0; i < line; i++) { int count = 0; String inLine[] = in.readLine().split("" ""); out.append(""Case #"" + (i+1) + "": ""); int min = Integer.parseInt(inLine[0]); int max = Integer.parseInt(inLine[1]); Set inn = new HashSet(); if (max > 11) { for (int l = min; l <= max; l++) { inn.clear(); String ll = l + """"; for (int a = ll.length() - 1; a >= 1; a--) { if (ll.charAt(a) != '0') { int t = Integer.parseInt(ll.substring(a) + ll.substring(0, a)); if (l >= min && t <= max && l L=new LinkedList(); for(int i=0;ibase && x<=B) if(!L.contains(x)) { L.add(x); } } return L.size(); } } " B20307,"import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; public class RecycledNumbers { static String inputLargeFile = ""C-large.in""; static String inputSmallFile = ""C-small-attempt0.in""; static String outSmallFile = ""C-small-attempt0.out""; static String outLargeFile = ""C-large.out""; static BufferedReader br ; static PrintWriter out ; public static void main(String[] args) throws Exception{ br = new BufferedReader(new InputStreamReader(new FileInputStream(inputLargeFile))); out = new PrintWriter(new File(outLargeFile)); String input = br.readLine(); int testcases = Integer.parseInt(input.trim()); for (int i = 0; i < testcases; i++) { String range = br.readLine(); String[] numbers = range.split("" ""); int A = Integer.parseInt(numbers[0].trim()); int B = Integer.parseInt(numbers[1].trim()); String part1=null; String part2=null; int count=0; int m =0; int endIndex =0; int beignIndex=0; String number = null; String pair = null; for(int n=A;n<=B;n++ ){ number = String.valueOf(n); endIndex = number.length()-1; int last=0; for(int p=endIndex;p>0;p--){ pair = number.substring(p)+number.substring(beignIndex,p); m=Integer.parseInt(pair); if(m>n&&m<=B&&m!=last){ count++; last=m; //out.println(""count : "" + count); } } } out.println(""Case #""+ (i+1)+ "": "" + count); } out.close(); br.close(); } } " B22168,"/* choochootrain Google Code Jam 2012 */ import java.io.*; import java.util.*; class ProblemC { public static Set seen; public static int a; public static int b; public static void main (String [] args) throws IOException { String filename = ""C-large""; BufferedReader f = new BufferedReader(new FileReader(filename + "".in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename + "".out""))); int numberOfTests = Integer.parseInt(f.readLine()); seen = new HashSet(); for(int n = 1; n <= numberOfTests; n++) { StringTokenizer st = new StringTokenizer(f.readLine()); a = Integer.parseInt(st.nextToken()); b = Integer.parseInt(st.nextToken()); for(int i = a; i <= b; i++) { findNumRotations(i); } int solution = seen.size(); out.println(""Case #"" + n + "": "" + solution); seen = new HashSet(); } out.close(); System.exit(0); } public static void findNumRotations(int num) { int numRots = getRotationCount(num); for(int i = 1; i <= numRots; i++) { int rotated = rotate(num, i, numRots + 1); if (rotated > num && rotated <= b) { seen.add(num + "" "" + rotated); } } } private static int rotate(int num, int amt, int digits) { int bottom = (int)(num / Math.pow(10, amt)); int top = (int)(num % Math.pow(10, amt)); return (int)(top * Math.pow(10, digits - amt) + bottom); } private static int getRotationCount(int num) { if (num < 10) return 0; int c = 0; while(num > 0) { num = num / 10; c++; } return c - 1; } } " B21860,"import java.io.*; import java.security.SecureRandom; import java.util.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Main implements Runnable { static String filename = ""C-large""; HashSet getCycles(int n) { int nc = n; int digitcount = 0; int pow10 = 1; while (nc > 0) { digitcount++; nc /= 10; pow10 *= 10; } pow10 /= 10; HashSet answer = new HashSet(); nc = n; for (int i = 0; i < digitcount; i++) { answer.add(nc); int lastdigit = nc % 10; nc /= 10; nc += pow10 * lastdigit; } return answer; } public void solve() throws Exception { int t = sc.nextInt(); for (int Case = 1; Case <= t; Case++) { int a = sc.nextInt(), b = sc.nextInt(); boolean[] visited = new boolean[b + 1]; long answer = 0; for (int i = a; i <= b; i++) { if (visited[i]) { continue; } HashSet cycles = getCycles(i); int suitable = 0; for (int c : cycles) { if (c >= a && c <= b) { suitable++; visited[c] = true; //out.print(c + "" ""); } } //out.println(); answer += suitable * (suitable - 1) / 2; } //out.println(); out.printf(""Case #%d: %d\n"", Case, answer); } } BufferedReader in; PrintWriter out; FastScanner sc; public static void main(String[] args) { new Thread(null, new Main(), """", 1 << 25).start(); } @Override public void run() { try { init(); solve(); } catch (Exception e) { throw new RuntimeException(e); } finally { out.close(); } } void init() throws Exception { in = new BufferedReader(new FileReader(filename + "".in"")); out = new PrintWriter(new FileWriter(filename + "".out"")); sc = new FastScanner(in); } } class FastScanner { BufferedReader reader; StringTokenizer strTok; public FastScanner(BufferedReader reader) { this.reader = reader; } public String nextToken() throws IOException { while (strTok == null || !strTok.hasMoreTokens()) { strTok = new StringTokenizer(reader.readLine()); } return strTok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } } " B21983,"package javaapplication2; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { private final static String INPUT_PATH = ""resources/recycled_numbers.in""; private final static String OUTPUT_PATH = ""resources/recycled_numbers.out""; private static int caseNumber = 0; private final static int[] TEN_POWS = new int[]{1, 10, 100, 1000, 10000, 100000, 1000000}; public static void main(String[] args) throws FileNotFoundException, IOException { try (Scanner scanner = new Scanner(new File(INPUT_PATH))) { int T = scanner.nextInt(); try (FileWriter out = new FileWriter(OUTPUT_PATH)) { for (int i = 0; i < T; ++i) { processCase(scanner, out); } } } } private static void processCase(Scanner scanner, FileWriter out) throws IOException { out.write(""Case #"" + (++caseNumber) + "": ""); Set pairs = new HashSet<>(); int A = scanner.nextInt(); int B = scanner.nextInt(); int result = 0; for (int n = A; n <= B; ++n) { int shiftCount = ((int) Math.floor(Math.log10(n))); for (int i = 1; i <= shiftCount; ++i) { int right = n / TEN_POWS[i]; int left = n % TEN_POWS[i]; int shifted = left * TEN_POWS[shiftCount + 1 - i] + right; if (shifted != n && shifted <= B && shifted >= A && ((int) Math.floor(Math.log10(n))) == shiftCount) { Pair pair = new Pair(n, shifted); if (!pairs.contains(pair)) { ++result; pairs.add(pair); } } } } out.write(result + """"); out.write(""\n""); } private static class Pair { private int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public boolean equals(Object that) { if (that instanceof Pair) { Pair pair = (Pair) that; if (this.a == pair.a && this.b == pair.b) { return true; } if (this.a == pair.b && this.b == pair.a) { return true; } } return false; } @Override public int hashCode() { return new Integer(a).hashCode() + new Integer(b).hashCode(); } } } " B21883,"package com.develog; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.StringTokenizer; public class C { final int A = 0; final int B = 1; BufferedReader reader; BufferedWriter writer; String buf; String numStr[]; public C() throws IOException{ reader = new BufferedReader(new FileReader(""C-large.in"")); writer = new BufferedWriter(new FileWriter(""output.txt"")); reader.readLine(); // # of case long cnt; for(int n=1; (buf = reader.readLine()) != null; n++){ numStr = getToken(buf); cnt = solve(numStr); // System.out.println(cnt); writer.write(String.format(""Case #%d: %d\n"", n, cnt)); } reader.close(); writer.close(); } public String[] getToken(String sentence){ String ret[] = new String[2]; StringTokenizer token = new StringTokenizer(sentence, "" \t""); int i=0; while(token.hasMoreTokens()){ ret[i++] = token.nextToken(); } return ret; } public long solve(String str[]){ long num[] = new long[2]; long m; long cnt=0; ArrayList arNum; num[A] = Integer.parseInt(str[A]); num[B] = Integer.parseInt(str[B]); for(long a=num[A], b=num[B]; a<=b; a++){ StringBuilder builder = new StringBuilder(String.valueOf(a)); int len = builder.length(); arNum = new ArrayList(); for(int i=0; ik&&new_number<=max) number++; multiple_decrease/=10; } } System.out.println(""Case #"" + i + "": "" + number); } } } " B20591,"package be.mokarea.gcj.common; public abstract class TestCase { private final int caseNumber; protected TestCase(int caseNumber) { this.caseNumber = caseNumber; } public int getCaseNumber() { return caseNumber; } } " B21999,"import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedHashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { static int[] p10 = {1,10,100,1000,10000,100000,1000000,10000000}; public static int perm(int x, int n, int l){ int y = x/p10[n]; int z = x-y*p10[n]; return z*p10[l-n] + y; } public static int longueur(int a){ int i = 1; while(a / p10[i] != 0) i++; return i; } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub File f = new File( ""C-large.in"" ); FileWriter out=new FileWriter(""output.txt""); Scanner in = new Scanner(new FileReader(f)); if(f.exists()){ int T; int A, B; int r; int l; int y; Set s = new LinkedHashSet(); T = in.nextInt(); for(int i = 1; i <= T ; i++){ A = in.nextInt(); B = in.nextInt(); l = longueur(A); r = 0; for(int x = A; x < B; x++){ s.clear(); for(int n = 1; n < l ; n++){ y = perm(x, n, l); if(y > x && y <= B && !s.contains(y)){ r++; s.add(y); } } } out.write(""Case #"" + i + "": "" + r + ""\n""); } } in.close(); out.close(); } } " B21194,"import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Counter { private int T; private Lock lock; private ICounterZeroEvent e; public Counter(int T, ICounterZeroEvent e) { this.T = T; this.e = e; lock = new ReentrantLock(); } public void increase() { lock.lock(); T--; if (T==0) e.fireEvent(); lock.unlock(); System.out.println(T); } } " B21441,"package jp.funnything.competition.util; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import org.apache.commons.io.IOUtils; public class QuestionReader { private final BufferedReader _reader; public QuestionReader( final File input ) { try { _reader = new BufferedReader( new FileReader( input ) ); } catch ( final FileNotFoundException e ) { throw new RuntimeException( e ); } } public void close() { IOUtils.closeQuietly( _reader ); } public String read() { try { return _reader.readLine(); } catch ( final IOException e ) { throw new RuntimeException( e ); } } public BigDecimal[] readBigDecimals() { return readBigDecimals( "" "" ); } public BigDecimal[] readBigDecimals( final String separator ) { final String[] tokens = readTokens( separator ); final BigDecimal[] values = new BigDecimal[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = new BigDecimal( tokens[ index ] ); } return values; } public BigInteger[] readBigInts() { return readBigInts( "" "" ); } public BigInteger[] readBigInts( final String separator ) { final String[] tokens = readTokens( separator ); final BigInteger[] values = new BigInteger[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = new BigInteger( tokens[ index ] ); } return values; } public int readInt() { final int[] values = readInts(); if ( values.length != 1 ) { throw new IllegalStateException( ""Try to read single interger, but the line contains zero or multiple values"" ); } return values[ 0 ]; } public int[] readInts() { return readInts( "" "" ); } public int[] readInts( final String separator ) { final String[] tokens = readTokens( separator ); final int[] values = new int[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = Integer.parseInt( tokens[ index ] ); } return values; } public long readLong() { final long[] values = readLongs(); if ( values.length != 1 ) { throw new IllegalStateException( ""Try to read single interger, but the line contains zero or multiple values"" ); } return values[ 0 ]; } public long[] readLongs() { return readLongs( "" "" ); } public long[] readLongs( final String separator ) { final String[] tokens = readTokens( separator ); final long[] values = new long[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = Long.parseLong( tokens[ index ] ); } return values; } public String[] readTokens() { return readTokens( "" "" ); } public String[] readTokens( final String separator ) { return read().split( separator ); } } " B21499,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class Recycled { public static void main(String[] args) throws Exception { FileInputStream fstream = new FileInputStream(""text.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int count = 0; int totalLines; // ArrayList numbers = new ArrayList(); while ((strLine = br.readLine()) != null) { if (count == 0) { totalLines = Integer.parseInt(strLine); } else { int recycled = 0; String[] nums = strLine.split("" ""); int startNum = Integer.parseInt(nums[0]); int endNum = Integer.parseInt(nums[1]); for (int i = startNum; i <= endNum; i++) { recycled += testInteger(i, endNum); } System.out.println(""Case #"" + count + "": "" + recycled); } count++; } in.close(); } private static int testInteger(int i, int endNum) { String numStr = String.valueOf(i); int currentCount = 0; Set matches = new HashSet(); for (int j = 1; j < numStr.length(); j++) { String newNumStr = swapNumber(numStr); if ((Integer.parseInt(newNumStr) > i) && ((Integer.parseInt(newNumStr) <= endNum))) { // System.out.println(i+"" ""+newNumStr); currentCount++; matches.add(newNumStr); // } else { // return 0; } numStr = newNumStr; } return matches.size(); } private static String swapNumber(String numStr) { String lastDigit = numStr.substring(numStr.length()-1); String firstDigits = numStr.substring(0, numStr.length()-1); return lastDigit.concat(firstDigits); } } " B21405,"import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class Solution { Solution() throws Exception { } String solve() throws Exception { int min = in.nextInt(); int max = in.nextInt(); return """" + permutations(min, max); } private int permutations(int min, int max) { int digits = Integer.toString(min).length(); int permutations = 0; for (int i = min; i <= max; i++) { HashSet found = new HashSet<>(); for (int j = 1; j < digits; j ++) { int permutation = permute(i, j, digits); if (permutation > i && permutation <= max && permutation >= min) { found.add(permutation); } } permutations += found.size(); } return permutations; } private int permute(int number, int permutation, int digits) { int m = (int) Math.pow(10, permutation); int back = number % m; int front = number / m; int m2 = (int) Math.pow(10, digits - permutation); return back * m2 + front; } void solveAll() throws Exception { int cases = in.nextInt(); in.nextLine(); for (int i = 1; i <= cases; i++) { String solution = ""Case #"" + i + "": "" + solve(); System.out.println(solution); out.println(solution); } out.flush(); } // ----------------------------------------------------------------------- static Scanner in = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws Exception { new Solution().solveAll(); } } " B21003,"package codejam; import java.util.HashSet; public class RecycledNumbers extends Solver { public static void main(String...args) { RecycledNumbers solver = new RecycledNumbers(); // System.out.println(solver.solve(""1 9"")); // System.out.println(solver.solve(""10 40"")); // System.out.println(solver.solve(""100 500"")); // System.out.println(solver.solve(""1111 2222"")); // System.out.println(solver.solve(""1000000 2000000"")); // solver.solveSmallOf('C', 0); solver.solveLargeOf('C'); } int a, b; @Override public String evaluate() { a = in.nextInt(); b = in.nextInt(); if(a<10) return ""0""; HashSet set = new HashSet(); for(int i=a; i<=b; i++) { if(set.add(new Signed(i))) { // System.out.println(i + "" added.""); } } int c = 0; for(Signed s: set) { c+=s.getAvailablePairsCount(); } return String.valueOf(c); } class Signed { final char[] ns; final int sign; Signed(int n) { ns = String.valueOf(n).toCharArray(); int min = Integer.MAX_VALUE; for(int i=0; i cases = new HashSet(); for(int i=0; i=a && value.intValue()<=b) cases.add(value); } shift(); } return cases.size(); } @Override public boolean equals(Object obj) { if(obj instanceof Signed) { return ((Signed) obj).sign==sign; } return super.equals(obj); } @Override public int hashCode() { return sign; } } class Pair { final int n, m; Pair(int n, int m) { if(n>m) { this.n = m; this.m = n; } else { this.n = n; this.m = m; } } @Override public boolean equals(Object obj) { if(obj instanceof Pair) { Pair p = (Pair) obj; return p.n == this.n && p.m == this.m; } else { return false; } } @Override public int hashCode() { return n*m+m; } } } " B20929,"import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { final static String FILENAME = ""C-large""; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new FileReader(""/home/workshop/Documents/"" + FILENAME + "".in"")); BufferedWriter bw = new BufferedWriter(new FileWriter( ""/home/workshop/Documents/"" + FILENAME + "".out"")); int T = sc.nextInt(); sc.nextLine(); for (int ttt = 0; ttt < T; ttt++) { int A = sc.nextInt(); int B = sc.nextInt(); int count = 0; int digits = new Double(Math.floor(Math.log10(A) + 1)).intValue(); for (int num = A; num < B; num++) { Set hs = new HashSet(); for (int lastdigits = 1; lastdigits < digits; lastdigits++) { int tailmask = new Double(Math.pow(10, lastdigits)) .intValue(), headmask = new Double(Math.pow(10, digits - lastdigits)).intValue(); int newnum = num / tailmask + (num % tailmask) * headmask; if (num < newnum && !hs.contains(newnum) && newnum <= B) { // System.out.println(num + ""\t"" + newnum); count++; hs.add(newnum); } } // if (y < z) { // System.out.println(num + ""\t(1)""); // count++; // } // if (x < z || (x == z && x > y)) { // System.out.println(num + ""\t(2)""); // count++; // } // if (x < y && y != z) { // System.out.println(num + ""\t(3)""); // count++; // } // if (x < y && x != z) { // System.out.println(num + ""\t(4)""); // count++; // } // if (x < z || (x == z && x > y)) { // int newnum = z * 100 + x * 10 + y; // if (newnum <= B) { // System.out.println(num + ""\t"" + newnum + ""\t(2)""); // count++; // } // } // if (x < y || (x == y && y < z)) { // int newnum = y * 100 + z * 10 + x; // if (newnum <= B) { // System.out.println(num + ""\t"" + newnum + ""\t(4)""); // count++; // } // } } bw.write(""Case #"" + (ttt + 1) + "": "" + count); bw.newLine(); } bw.close(); sc.close(); } } " B21718,"import java.io.File; import java.io.PrintWriter; import java.util.Scanner; public class EasyNumbers { public static void main(String[] args) throws Exception{ PrintWriter out =new PrintWriter(new File(""../easyNumbers/src/numberrr.out"")); Scanner s =new Scanner(new File(""../easyNumbers/src/number.in"")); int ans,div,d,k,n1,n2,j,a,a1,b; int i,t; t = s.nextInt(); for(int w = 1; w<=t; w++){ a = s.nextInt(); b = s.nextInt(); ans=0; i=0; a1 = a; while(a1!=0){ a1/=10; i++; } for(j=a;j<=b;j++){ n2=j; for(k=0;k 9){ n1 = n1 / 10; div = div * 10; } d = n2 % 10; n2 = n2 / 10; n2 = n2 + d * div ; if(n2<=b && n2>=a && n2!=j && j mapping; public Q3Solver(){ mapping = new HashSet(); } public int solve(int a,int b){ int res = 0; for (int i = a ; i <= b ; i++){ res+= getNumberOfLegalRecycled( b, i); } return res; } private int getNumberOfLegalRecycled( int b, int num) { String numString = """"+num; int numDigits = numString.length(); int res = 0; for (int i = 0 ; i < numDigits - 1 ; i++){ String perm = numString.substring(numDigits - i - 1) + numString.substring(0,numDigits - i -1 ); Integer newNum = Integer.parseInt(perm); String test = newNum+""""; if (test.length() == numDigits){ //checks that there are no leading zeros if ( num != newNum && newNum > num && newNum <= b){ if (!mapping.contains(newNum+"",""+num) && !mapping.contains(num+"",""+newNum)) { res++; mapping.add(num+ "","" +newNum); mapping.add(newNum +"","" +num); } } } } return res; } } " B21649,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class C { private static Map map = new HashMap(); public static void main(String args[]) { try { String fileName = ""C:\\Users\\Lenovo Z370\\Desktop\\gcj\\comp-2012\\C-large.in""; BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); int t = Integer.parseInt(br.readLine()); for(int i=0; i j && m >= a && m <= b) { Long val = map.get(j); if(val == null || val != m) { map.put(j, m); count++; } } n=m; } } System.out.println(""Case #"" + (i+1) + "": "" + count); } } catch(Exception e) { e.printStackTrace(); } } } " B20045,"package code_jam_2012_qualification_round; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { long startTime = System.currentTimeMillis(); BufferedReader f = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-large.out""))); StringTokenizer st = new StringTokenizer(f.readLine()); int T = Integer.parseInt(st.nextToken()); for(int t = 1; t <= T; t++) { st = new StringTokenizer(f.readLine()); int A = Integer.parseInt(st.nextToken()), B = Integer.parseInt(st.nextToken()); boolean[] used = new boolean[B+1]; int sum = 0; for(int i = A; i <= B; i++) { if (used[i]) continue; String s = """" + i; int c = 1; used[i] = true; for(int j = 1; j < s.length(); j++) { int a = Integer.parseInt(s.substring(j) + s.substring(0, j)); if (a <= B && a >= A && !used[a]) { c++; //out.println(i + "" and "" + a); used[a] = true; } } sum += c*(c-1)/2; } out.println(""Case #"" + t + "": "" + sum); System.out.println(""Case #"" + t + "": "" + sum); } out.close(); } } " B20021,"package WQ; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class Problem_C { /** * @param args * @throws FileNotFoundException */ public static boolean check(String s) { for (int i = 0; i < s.length() - 1; i++) { if (s.charAt(i) != s.charAt(i + 1)) return true; } return false; } public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(""out1.txt""); int num = in.nextInt(); for (int CASE = 1; CASE <= num; CASE++) { int a = in.nextInt(); int b = in.nextInt(); HashSet hs = new HashSet(); for (int i = a; i <= b; i++) { String s = i + """"; if (check(s) && s.length() > 1) { for (int k = s.length() - 2, j = 0; k >= 0 && j < s.length() - 1; j++, k--) { String newS = s.substring(k + 1) + s.substring(0, k + 1); int newInt = Integer.parseInt(newS); if (newInt <= b && i < newInt && s.length() == (newInt + """").length() && !newS.equals(s)) { if (i < Integer.parseInt(newS)) hs.add(i + "" "" + newS); else hs.add(newS + "" "" + i); } } } } out.println(""Case #"" + CASE + "": "" + hs.size()); } out.close(); } } " B20464,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.Vector; /** * * @author Kholoud */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { try { FileInputStream ifstream = new FileInputStream(""C:\\Users\\Kholoud\\Downloads\\C-large.in""); DataInputStream in = new DataInputStream(ifstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int n = Integer.parseInt( br.readLine()); String line; for(int i = 0;i rotatedNumbers; for(int num = A;num<=B;num++) { rotatedNumbers = new Vector(); String rotatedNum = String.valueOf(num); for(int j = 0;j Long.parseLong(mut) && tmp >=A && tmp <=B) { for(int k=0;k 1 ) fw.write(""Case #"" +c +"": ""+ count +""\n""); else fw.write(""Case #"" +c +"": ""+ 0 +""\n""); } fw.close(); } }" B21109,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; public class Main { public static void main(String[] args){ StringBuffer fileData = new StringBuffer(1000000); BufferedReader reader = null; try { reader = new BufferedReader( new FileReader(""C-large.in"")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } char[] buf = new char[1024]; int numRead=0; try { while((numRead=reader.read(buf)) != -1){ String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(""result.txt"")); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String inputString=fileData.toString(); StringTokenizer st=new StringTokenizer(inputString); int noOfcase=Integer.parseInt(st.nextToken()); for(int i=1;i<=noOfcase;i++){ int A=Integer.parseInt(st.nextToken()); int B=Integer.parseInt(st.nextToken()); String B_string=String.valueOf(B); int B_length=B_string.length(); int max=0; for(int n=A;nn && m<=B){ local_max++; } } if(local_max > 0 && n_length%2==0){ if(n_string.substring(0, n_length/2).equals(n_string.substring(n_length/2, n_length))) local_max/=2; } max+=local_max; n_string=""0""+n_string; } } try { out.write(""Case #""+i+"": ""+max); out.newLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B20353,"import java.io.*; public class recycled { /** * @param args */ public static int solve(BufferedReader reader) throws IOException { int cpt = 0; String[] entiers = new String[2]; entiers = reader.readLine().split("" ""); if(Integer.parseInt(entiers[0]) < 10) return 0; else { for(int i = Integer.parseInt(entiers[0]); i <= Integer.parseInt(entiers[1]); i++) cpt += NombreRecycle(entiers[0], entiers[1], Integer.toString(i)); } return cpt; } public static int NombreRecycle(String a, String b, String n) throws IOException { int cpt = 0; for(int i = 1; i < n.length() ; i++) if( Integer.parseInt(n) < Integer.parseInt(n.substring(i) + n.substring(0, i)) && Integer.parseInt(n.substring(i) + n.substring(0, i)) <= Integer.parseInt(b)) cpt++; return cpt; } public static void main(String[] args) { try { InputStream ips = new FileInputStream(""recycled.in""); InputStreamReader ipsr = new InputStreamReader(ips); BufferedReader br = new BufferedReader(ipsr); int cases = Integer.valueOf(br.readLine()); for (int i = 1; i <= cases; i++) { imprimer(i, solve(br)); } } catch (IOException x) { System.err.println(x); } catch (NumberFormatException x) { System.err.println(x); } } static void imprimer(int numero, int resultat) { try { FileWriter fw = new FileWriter (""recycled.out"",true); BufferedWriter bw = new BufferedWriter (fw); PrintWriter fichierSortie = new PrintWriter (bw); fichierSortie.println (""Case #"" + numero + "": "" + resultat); fichierSortie.close(); } catch (Exception e){ System.out.println(e.toString()); } } } " B20438,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C{ public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""C.txt"")); int testCase = Integer.parseInt(sc.nextLine()); for(int Case=1; Case<=testCase; Case++) { int total = 0; int st = sc.nextInt();int en = sc.nextInt(); int len = (new Integer(st)).toString().length(); for(int i=en; i>=st;i--) { Set s = new HashSet(); for(int j=1; j<=len-1;j++) { String sam = (new Integer(i).toString()); //System.out.println(i+ ""Actual String:"" + sam); StringBuffer temp=new StringBuffer(); //System.out.println(""temp 1:""+temp.toString()); temp.append(sam.substring(j)); //System.out.println(""temp 2:""+temp.toString()); temp.append(sam.substring(0, j)); //System.out.println(""temp 3:""+temp.toString()); int num = Integer.parseInt(temp.toString()); if(num>=st && num<=en && num 0) ? new Scanner(new File(args[0])) : new Scanner(System.in); int T = in.nextInt(); for (int zz = 1; zz <= T; zz++) { System.err.format(""#%d\n"", zz); System.out.format(""Case #%d: "", zz); int A = in.nextInt(); int B = in.nextInt(); int y = 0; Set pairs = new HashSet(); int D = (int) Math.log10(A); long p0 = 10; long p1 = (long) Math.pow(10, D); for (int d = 1; d <= D; d++) { for (long n = A; n <= B; n++) { long m = ((n % p1) * p0) + (n / p1); if (m > n && m <= B && !pairs.contains(n + "":"" + m)) { y++; pairs.add(n + "":"" + m); } } p0 *= 10; p1 /= 10; } System.out.format(""%d\n"", y); } } } " B20658,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ProblemC{ /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new FileReader(""C-large.in"")); int count = Integer.parseInt(br.readLine()); for (int i = 0; i list = new ArrayList(); for (int j = 1; ji && m<=b && !list.contains(m)){ list.add(m); result++; } } } return result; } }" B22233," import java.util.Scanner; import java.util.Set; import java.util.TreeSet; /** * * @author juice */ public class Recycle { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int tc = 1; tc <=t; tc++) { int a = sc.nextInt(); int b = sc.nextInt(); int digs = String.valueOf(a).length(); long cnt = 0; for (int i = a; i <= b; i++) { String s = String.valueOf(i); Set added = new TreeSet(); for(int j = 0; j= start && permNum <= end) { set = false; for(int temp = 0; temp < mnCount ; temp++) { if(n[temp] == permNum) set = true; } if(!set) { count++; n[mnCount] = permNum; mnCount++; } } } } return count; } } " B21920,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class CMain { private static final ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); /** * @param args * @throws IOException * @throws ExecutionException * @throws InterruptedException */ public static void main(String[] args) throws IOException, InterruptedException, ExecutionException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int casesCnt = Integer.parseInt(reader.readLine()); List> futures = new ArrayList>(); for (int i = 0; i < casesCnt; i++) { final String line = reader.readLine(); Callable task = new Callable() { @Override public Integer call() throws Exception { int result = solve(line); return result; } }; Future future = pool.submit(task); futures.add(future); } int caseN = 1; for (Future future : futures) { int result = future.get(); System.out.printf(""Case #%d: %d%n"", caseN++, result); } pool.shutdownNow(); } private static int solve(String line) { final StringTokenizer tokens = new StringTokenizer(line); final int A = Integer.parseInt(tokens.nextToken()); final int B = Integer.parseInt(tokens.nextToken()); int result = solveInner(A, B); return result; } private static int solveInner(int A, int B) { class Pair { public Pair(int x, int y) { if (x < y) { this.x = x; this.y = y; } else { this.x = y; this.y = x; } } final int x; final int y; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } Set results = new HashSet(); for (int num = A; num <= B; num++) { // max chunk size = floor(log(number)) final int numLen = digits(num); for (int chunkLength = 1; chunkLength < numLen; chunkLength++) { int recycled = recycle(num, numLen, chunkLength); if (recycled != num && recycled >= A && recycled <= B && digits(recycled) == numLen) { results.add(new Pair(num, recycled)); } } } return results.size(); } /** max 2 millions */ private static int digits(int num) { if (num < 10) return 1; if (num < 100) return 2; if (num < 1000) return 3; if (num < 10000) return 4; if (num < 100000) return 5; if (num < 1000000) return 6; return 7; } private static int recycle(int num, int numLength, int endChunkLength) { int base = (int) Math.pow(10, endChunkLength); int result = (num % base) * ((int) Math.pow(10, numLength - endChunkLength)) + num / base; return result; } } " B22142," import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author viswas */ public class Recycled { public static void main(String [] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = 1; int T = Integer.parseInt(br.readLine()); while(T-- > 0){ long count = 0; StringTokenizer str = new StringTokenizer(br.readLine(), "" ""); int A = Integer.parseInt(str.nextToken()); int B = Integer.parseInt(str.nextToken()); ArrayList Alist = new ArrayList(); for(int i = A; i <= B; i++){ String s = i + """"; String aa = s; int len = s.length(); s += s; Alist.clear(); for(int j = 0; j < len; j++){ String s1 = s.substring(j, j + len); int s2 = Integer.parseInt(s1); if(!Alist.contains(s2)){ s1 = s2 + """"; if(i < s2 && aa.length() == s1.length() && B >= s2){ count++; //System.out.println(n.substring(0, len) + "" "" + m); } Alist.add(s2); } } } System.out.printf(""Case #%d: %d"", t, count); System.out.println(); t++; } } } " B20679,"package br.com.problema.c; import java.io.File; import java.io.FileWriter; import java.util.Scanner; public class ProblemaC { static String caminho = ""/home/mateus/""; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File(caminho + ""entrada.txt"")); FileWriter writer = new FileWriter(new File(""/home/mateus/saida.txt""), false); int cases = sc.nextInt(); for (int i = 1; i <= cases; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int resposta = 0; for (int num = A; num <= B; num++) { resposta += new Numero(num).quantNumRecycled(B); } writer.append(criarCase(i, resposta + """")); } writer.flush(); writer.close(); } public static String criarCase(int i, String s) { return ""Case #"" + i + "": "" + s + ""\n""; } } " B20761,"package codejam; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import fixjava.Split; import proba.Main; /** * Put this class in a package that ends with the name of the problem, e.g. proba => problem A, with input A-large.in etc. * * Then save the sample problem to DirConsts.INPUT_DIR as X-test.in, where X is the problem letter. Save small and large attempt input files to that dir also. * * */ public abstract class CodeJam { PrintWriter writer; BufferedReader reader; ArrayList currLineTokens = new ArrayList(); int caseNum = 0; private String getStaticField(String name) { try { return (String) (this.getClass().getDeclaredField(name).get(null)); } catch (Exception e) { return null; } } public CodeJam() { // Get package name and extract problem letter String fullClassName = Main.class.getName(); int dotIdx = fullClassName.indexOf('.'); String pkgName = fullClassName.substring(0, dotIdx).toLowerCase(); pkgName = ""probc""; if (!(pkgName.substring(0, pkgName.length() - 1).equals(""prob""))) throw new RuntimeException(""Package name must be of the form 'probX'""); final String problemLetter = pkgName.substring(pkgName.length() - 1).toUpperCase(); File inpDir = new File(DirConsts.INPUT_DIR); if (!inpDir.exists()) throw new RuntimeException(""Directory "" + DirConsts.INPUT_DIR + "" not found""); File outDir = new File(DirConsts.OUTPUT_DIR); if (!outDir.exists()) throw new RuntimeException(""Directory "" + DirConsts.OUTPUT_DIR + "" not found""); File srcDir = new File(new File((getClass().getProtectionDomain().getCodeSource().getLocation().toString()).substring(5)).getParentFile(), ""src""); if (!srcDir.exists()) throw new RuntimeException(""src directory not found""); // See if input file has been manually overriden by static field in Main class String OVERRIDE_INPUT_FILE = getStaticField(""OVERRIDE_INPUT_FILE""); try { // Package source into zipfile File zipFile = new File(outDir, problemLetter + ""-source-latest.zip""); System.out.println(""Zipping source from "" + srcDir); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile))); byte data[] = new byte[1024 * 1024]; for (String dirName : srcDir.list()) { // Don't include probX directories for problems other than this one, but include everything else if (!dirName.startsWith(""prob"") || dirName.equals(pkgName)) { File dir = new File(srcDir, dirName); for (String srcFile : dir.list()) { String zipEntry = dirName + ""/"" + srcFile; System.out.println("" -> Adding: "" + zipEntry); zipOut.putNextEntry(new ZipEntry(zipEntry)); BufferedInputStream srcFileStream = new BufferedInputStream(new FileInputStream(new File(dir, srcFile)), data.length); for (int count; (count = srcFileStream.read(data, 0, data.length)) != -1;) zipOut.write(data, 0, count); srcFileStream.close(); } } } zipOut.close(); System.out.println(""Wrote: "" + zipFile.getPath() + ""\n""); // Determine input file to use String inpFileName; if (OVERRIDE_INPUT_FILE != null) { // Manual override inpFileName = problemLetter + ""-"" + OVERRIDE_INPUT_FILE + "".in""; } else { // Find latest-ordered input file to use // Sort in order A-test.in, A-test0.in, A-test1.in, ..., A-small-attempt0.in, A-small-attempt1.in, ..., A-large.in String[] inpFiles = inpDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { boolean matches = filename.matches(problemLetter + ""-.*\\.in""); if (matches && (filename.indexOf('(') >= 0 || filename.indexOf(')') >= 0)) { // Don't include otherwise-valid filenames with parens in, warn the user, as // there are probably downloads from multiple problem rounds in the same dir System.err.println(""Filename "" + filename + "" contains parens -- skipping""); return false; } return matches; } }); if (inpFiles.length == 0) throw new IOException(""No input files found for problem "" + problemLetter); // Sort into correct order (see above) Arrays.sort(inpFiles, new Comparator() { @Override public int compare(String arg0, String arg1) { String a = arg0.substring(2), b = arg1.substring(2); int aType = a.startsWith(""test"") ? 0 : a.startsWith(""small"") ? 1 : a.startsWith(""large"") ? 2 : -1; int bType = b.startsWith(""test"") ? 0 : b.startsWith(""small"") ? 1 : b.startsWith(""large"") ? 2 : -1; int typeDiff = aType - bType; if (typeDiff != 0) return typeDiff; int aDotIdx = a.lastIndexOf('.'), bDotIdx = b.lastIndexOf('.'); if (aDotIdx < 1 || bDotIdx < 1) return arg0.compareTo(arg1); int aNumIdx = aDotIdx - 1; while (aNumIdx >= 0 && Character.isDigit(a.charAt(aNumIdx))) aNumIdx--; String aNumStr = a.substring(aNumIdx + 1, aDotIdx); int bNumIdx = bDotIdx - 1; while (bNumIdx >= 0 && Character.isDigit(b.charAt(bNumIdx))) bNumIdx--; String bNumStr = b.substring(bNumIdx + 1, bDotIdx); if (aNumStr.isEmpty() || bNumStr.isEmpty()) return arg0.compareTo(arg1); int aNum = Integer.parseInt(aNumStr); int bNum = Integer.parseInt(bNumStr); return aNum - bNum; } }); inpFileName = inpFiles[inpFiles.length - 1]; // for (String inpFile : inpFiles) // System.out.println(""Input file: "" + inpFile); } File inpFile = new File(inpDir, inpFileName); File outFile = new File(outDir, inpFileName.replace("".in"", "".out"")); // Copy input file to output dir if it's not already there if (!inpDir.equals(outDir)) { System.out.println(""Copying input file to output dir""); reader = new BufferedReader(new FileReader(inpFile)); writer = new PrintWriter(new File(outDir, inpFileName)); for (String line; (line = reader.readLine()) != null;) writer.println(line); writer.close(); writer = null; reader.close(); reader = null; } System.out.println(""Reading: "" + inpFile.getPath() + ""\n""); reader = new BufferedReader(new FileReader(inpFile)); writer = new PrintWriter(outFile); // = null; // to suppress output // Do the work solve(); if (writer != null) writer.close(); System.out.println(""\nWrote: "" + outFile.getPath() + ""\n\nFinished.""); reader.close(); } catch (IOException e) { e.printStackTrace(); } } public void writeLineRaw(String outputLine) { System.out.println(outputLine); if (writer != null) writer.println(outputLine); } public void writeCaseNumThenLine(String outputLine) { writeLineRaw(""Case #"" + (++caseNum) + "": "" + outputLine); } public String readLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); System.exit(1); return null; } } /** Read next token, splitting on space */ public String readTok() { if (currLineTokens.size() > 0) { String tok = currLineTokens.get(0); currLineTokens.remove(0); return tok; } else { currLineTokens.addAll(Split.splitAsListOfString(readLine(), "" "")); return readTok(); } } /** Read next int, splitting on space */ public int readInt() { return Integer.parseInt(readTok()); } public abstract void solve(); } " B20851,"import java.util.*; public class RecycledNumbers { public static void main(String[] args) { System.out.println(""Enter case input:""); Scanner sc = new Scanner(System.in); int T = sc.nextInt(); sc.nextLine(); int[][] numbers = new int[T][2]; for (int t = 0; t < T; t++) { numbers[t][0] = sc.nextInt(); numbers[t][1] = sc.nextInt(); sc.nextLine(); } for (int t = 1; t <= T; t++) { int a = numbers[t - 1][0]; int b = numbers[t - 1][1]; int numRecycledPairs = 0; for (int n = a; n < b; n++) { String N = n + """"; int[] matches = new int[N.length()]; boolean duplicate = false; for (int digitFromBack = 1; digitFromBack <= N.length() - 1; digitFromBack++) { int newInt = Integer.parseInt(N.substring(N.length() - digitFromBack) + N.substring(0, N.length() - digitFromBack)); if (newInt > n && newInt <= b) { for (int match : matches) { if (newInt == match) duplicate = true; } if (!duplicate) { matches[digitFromBack] = newInt; numRecycledPairs++; } } } } System.out.println(""Case #"" + t + "": "" + numRecycledPairs); } } } " B21660,"package taskc; import java.io.FileNotFoundException; import java.util.*; import java.io.File; import java.io.PrintWriter; public class TaskC { private long[] tenPowers = new long[10]; private long[]prevPairs = new long[10]; private void prepareTenPowers(){ tenPowers[0] = 1; for(int i = 1;i<10;i++){ tenPowers[i]=tenPowers[i-1]*10; } } private void solve(Scanner in, PrintWriter out, int caseNum){ long res = 0; long A = in.nextInt(); int B = in.nextInt(); for(long t = A;t<=B;t++){ long d = t; int aPow = 0; while(d>0){ aPow++; d = d/10; } long pow = 10; d = t/10; int k = 1; int pairsCnt = 0; while(d>0){ long rest = t%pow; if(rest!=0){ long pair = rest*tenPowers[aPow-k]+ d; if((pair>t)&&(pair<=B)){ boolean ok = true; check: for(int i = 0;i set = new HashSet(); int c=0; for(;n1<=n2;n1++){ String sn = """"+n1; Set tested = new HashSet(); for(int i=0;i=n1 && s2<=n2){ c++; }else{ set.add(s); } } } return c; } public static void main(String[] args) { try{ FileInputStream fstream = new FileInputStream(""C-large.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; FileWriter fstream1 = new FileWriter(""C-large.out""); BufferedWriter out = new BufferedWriter(fstream1); // out.write(""Hello Java""); //Close the output stream long l = Long.parseLong(br.readLine()); for(long i=0; i - 51234 - 45123 - 34512 - 23451 - Since leading 0 is not count, 100, 001 are not pairs, so any number if the swap number start with 0 will not have pairs. - Divide the number into 2 parts, left, right by a mid point. - Then compare the left right to the range-left, range-right, if within that range that marks as pairs - There must be another number which is this number pairs - Same Digit - The number of pairs within a range = Num of itm in range * (Num of Digit - 1), e.g. 1111~2222 => (2222-1111+1) * (4-1) = 3336. - Since n=nw) continue; if (r>al[k] && r=A && nw<=B){ if (!contains(used, nw)){ res++; used[usedcnt++]=nw; //System.out.println(""j=""+j+""(""+l+"",""+r+""); add2(""+i+"") nw=""+nw); } } } } } return res; } public void doMain() throws Exception{ try{ Scanner sc1 = null; BufferedReader br = new BufferedReader(new FileReader(IN_FILE)); BufferedWriter bw = new BufferedWriter(new FileWriter(OUT_FILE)); int T = Integer.parseInt(br.readLine()); for (int a=0; a parser(); } " B22253,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; class RN { private static BufferedReader br = null; private static int numCases; private static int lowerBound, upperBound; private static String[] input; public static void main(String[] args) throws Exception { try { br = new BufferedReader(new InputStreamReader(System.in)); numCases = Integer.parseInt(br.readLine().trim()); for(int i = 0; i < numCases; i++) { int numRecycled = 0; input = br.readLine().split("" ""); lowerBound = Integer.parseInt(input[0]); upperBound = Integer.parseInt(input[1]); for(int j = lowerBound; j <= upperBound; j++) { String s = j + """"; ArrayList checked = new ArrayList(); for(int k = 0; k < s.length()-1; k++) { String temp = s.substring(s.length()-1-k) + s.substring(0, s.length()-k-1); //System.out.println(""From "" + s + "" to "" + temp + "" with k = "" + k); int num = Integer.parseInt(temp); if(num == j) continue; //if(num >= lowerBound && num <= upperBound && !used[num]) { if(num >= lowerBound && num <= upperBound && num > j && !checked.contains(num)) { //System.out.println(""From "" + s + "" to "" + temp + "" with k = "" + k); //System.out.println(""\t"" + j + ""\t"" + num); numRecycled++; checked.add(num); } } } System.out.println(""Case #"" + (i+1) + "": "" + numRecycled); } } catch(Exception e) { e.getMessage(); e.printStackTrace(); } } } " B21032,"package qualification; import java.util.Arrays; import java.util.Scanner; public class Recycle { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int num = scan.nextInt(); for(int i=1; i<=num; i++) { int a = scan.nextInt(); int b = scan.nextInt(); int count = 0; for(int j = a; j num && perm <= max) result++; } return result; } public static boolean isRecycled(String a, String b) { if(a.length() != b.length()) return false; if(!anagram(a,b)) return false; for(int i=0; i hs=new HashSet(); for (int i = 1; i <= n; i++) { s=fr.readLine(); String[] tok=s.split("" ""); int A=Integer.parseInt(tok[0]); int B=Integer.parseInt(tok[1]); int nd=1; int msk=1; for (int t=A/10; t > 0; t/=10) { nd++; msk*=10; } int nrn=0; for (int j = A; j <= B; j++) { hs.clear(); int d=10; int res=msk; while (res>0) { int nj=(j%d)*res+j/d; if (nj>j && nj<=B && !hs.contains(nj)) { nrn++; hs.add(nj); } d*=10; res/=10; } } System.out.println(nrn); fw.write(""Case #""+i+"": ""+ nrn +""\n""); } fr.close(); fw.close(); } catch (Exception e) { e.printStackTrace(); } } } " B20025,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; public class RecycledNumbers { public static int calcRecycled(int A, int B) { int total = 0; for(int i = 0; i < B-A+1; i++) { int[] temp = getCycles(i+A); for(int x: temp) { if(x == -1) continue; if(x <= i+A) continue; if(x <= B && x >= A) { total++; } } } return total; } public static int[] getCycles(int init) { String s = init+""""; int[] array = new int[s.length()-1]; for(int i = 0; i < s.length()-1; i++) { if(s.charAt(i+1) == '0') array[i] = -1; else { int temp = Integer.parseInt(s.substring(i+1) + s.substring(0, i+1)); for(int j = 0; j < i; j++) { if(array[j] == temp) { temp = -1; break; } } array[i] = temp; } } return array; } public static void main(String[] args) throws IOException { BufferedReader read = new BufferedReader(new FileReader(""C-large.in.txt"")); int T = Integer.parseInt(read.readLine()); for(int i = 1; i <= T; i++){ StringTokenizer st = new StringTokenizer(read.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); System.out.println(""Case #"" + i + "": "" + calcRecycled(A, B)); } } } " B20555,"package com.googlecodejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; /* Main function goes here */ public class RecycledNumbersProblemC { public static void main(String[] args) { try { BufferedReader bfreader = new BufferedReader(new FileReader(""E:\\workspace\\TopCoder\\src\\com\\googlecodejam\\C-large.in"")); BufferedWriter bfrwriter = new BufferedWriter(new FileWriter(""E:\\workspace\\TopCoder\\src\\com\\googlecodejam\\output.txt"")); int n = Integer.parseInt(bfreader.readLine()); String out = """"; for (int i = 0; i < n; i++) { String s = bfreader.readLine(); out += ""Case #"" + (i + 1) + "": "" + getRecycledPair(s) + ""\n""; } System.out.println(out); bfrwriter.write(out); bfreader.close(); bfrwriter.close(); } catch (IOException e) { e.printStackTrace(); } } /* Main function goes here */ public static String getRecycledPair(String s) { int iMinNumber = Integer.parseInt(s.split("" "")[0]); int iMaxNumber = Integer.parseInt(s.split("" "")[1]); int iLength; Integer iNoRecycledNo = 1; Integer iNoOfRecycledPairs = 0; for (int number = iMinNumber; number <= iMaxNumber; number++) { StringBuffer sNumber = new StringBuffer(Integer.toString(number)); iLength = sNumber.length(); ArrayList alRecycledPairs = new ArrayList(); for (int i = 1; i < sNumber.length(); i++) { StringBuilder recNum = new StringBuilder(); recNum.append(sNumber.substring(i, sNumber.length())); recNum.append(sNumber.substring(0, i)); int irecNumber = Integer.parseInt(recNum.toString()); if (iLength == Integer.toString(irecNumber).length()) { if ((!(alRecycledPairs.contains(irecNumber))) && irecNumber <= iMaxNumber && irecNumber >= iMinNumber && !(irecNumber == number)) { alRecycledPairs.add(irecNumber); iNoOfRecycledPairs = iNoRecycledNo / 2; iNoRecycledNo++; } } } } return Integer.toString(iNoOfRecycledPairs); } } " B21367,"/** * @author Saifuddin Merchant * */ package com.sam.googlecodejam.helper; public class StringHelper { } " B20104,"import java.io.*; import java.util.*; public class taskC { PrintWriter out; BufferedReader br; StringTokenizer st; String nextToken() throws IOException { while ((st == null) || (!st.hasMoreTokens())) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public void solve() throws IOException { int a = nextInt(); int b = nextInt(); int d = 1; int ans = 0; for (int i = a; i <= b; i++) { int t = i; while (t / (d * 10) != 0) { d *= 10; } do { t = (t % d) * 10 + (t / d); if ((t > i) && (t <= b)) ans++; } while (t != i); } out.println(ans); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); br = new BufferedReader(new FileReader(""taskC.in"")); out = new PrintWriter(""taskC.out""); int n = nextInt(); for (int i = 0; i < n; i++) { out.print(""Case #"" + (i + 1) + "": ""); solve(); } out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new taskC().run(); } } " B22207,"import java.util.*; import java.io.*; public class recycle { private static Reader in; private static PrintWriter out; public static final String NAME = ""C-large""; private static int pow, A, B; private static void main2() throws IOException { A = in.nextInt(); B = in.nextInt(); pow = 1; int tmp = A; while (tmp > 0) { pow *= 10; tmp /= 10; } pow /= 10; int count = 0; for (int i = A; i <= B; i++) count += can (i); out.println (count); } private static int can (int n) { int k = shift(n), res = 0; while (k != n) { if (k >= A && k <= B && k > n) res++; k = shift(k); } return res; } private static int shift(int n) { return (n % 10) * pow + n / 10; } public static void main(String[] args) throws IOException { in = new Reader(NAME + "".in""); out = new PrintWriter(new BufferedWriter(new FileWriter(NAME + "".out""))); int numCases = in.nextInt(); for (int test = 1; test <= numCases; test++) { out.print(""Case #"" + test + "": ""); main2(); } out.close(); System.exit(0); } /** Faster input **/ static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1024]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; else return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; else return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); } if (neg) return -ret; else return ret; } public char nextChar() throws IOException { char ret = 0; byte c = read(); while (c <= ' ') c = read(); return (char) c; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } } " B20899,"import java.io.*; import java.util.*; public class q3{ public static int fact(int t){ int result = 1; if(t < 1) return 0; for(int i = 1; i <= t; i++){ result *= i; } return result; } public static int choose(int n, int m){ if(m > n) return 0; if(m == n) return 1; int result = fact(n)/(fact(m) * fact(n-m)); return result; } public static int shift(int num){ String intNum = Integer.toString(num); String shifted = intNum.substring(1) + intNum.substring(0,1); int shiftedNum = Integer.parseInt(shifted); return shiftedNum; } public static String shiftS(String num){ String shifted = num.substring(1) + num.substring(0,1); return shifted; } public static void main (String[] args) throws IOException { BufferedReader input = new BufferedReader (new FileReader (""C-large.txt"")); PrintWriter output = new PrintWriter (new FileWriter(""test3Done.out"")); StringTokenizer st; int numLines = Integer.parseInt(input.readLine()); for(int i = 0; i < numLines; i++){ st = new StringTokenizer(input.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int counter = 0; boolean [] numbers = new boolean[B+1]; for(int j = 0; j < B+1; j++){ numbers[j] = true; } for(int j = A ; j < B + 1; j++){ int uniqueR = 0; if(numbers[j]){ String currNumS = Integer.toString(j); int currNum = j; numbers[j] = false; for(int k = 0; k < Integer.toString(j).length() - 1; k++){ if(Integer.parseInt(shiftS(currNumS)) <= B && Integer.parseInt(shiftS(currNumS)) >= A && shiftS(currNumS).charAt(0) != '0'){ if(numbers[Integer.parseInt(shiftS(currNumS))]){ uniqueR ++; numbers[Integer.parseInt(shiftS(currNumS))] = false; } } currNumS = shiftS(currNumS); } counter += choose(uniqueR+1,2); } } output.println(""Case #"" + (i+1) + "": "" + counter); } output.close(); } } " B20190,"package com.numbers.recycle.io; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class FileParser { public List readFile(String path){ File file = new File(path); List fileContents = parseFile(file); return fileContents; } private List parseFile(File file){ List contents = new ArrayList(); try { FileInputStream inputStream = new FileInputStream(file); BufferedReader bufReader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = bufReader.readLine())!= null){ contents.add(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return contents; } } " B20959,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Main { /** * @param args */ static boolean isRecycled(String s1, String s2) { if (s1.length() != s2.length()) return false; if (s1.compareTo(s2) == 0) return true; for (int i = 0; i < s1.length(); i++) { char c = s1.charAt(0); s1 = s1.substring(1); s1 += c; if (s1.compareTo(s2) == 0) return true; } return false; } static int grade(int n) { int digits = Integer.toString(n).length(); int mul = 10; int num = 9; for(int i=1;i set = new HashSet(); for (int j = 0; j < s.length(); j++) { char c = s.charAt(0); s = s.substring(1); s += c; value = Integer.parseInt( s); if ( value >=A && value <=B && i set = new HashSet(); for (int i = numberA; i <= numberB; i++) { String number = i+""""; for (int j = 0; j < number.length(); j++) { int firstNumber = Integer.parseInt(number); int index = (number.length()-(j+1)); if(index>0 && index readInput(String fileName) { List fileContents = new ArrayList(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(fileName)); String line = null; while ((line = reader.readLine()) != null) { fileContents.add(line); } } catch (IOException e) { logger.error(e); } finally { try { reader.close(); } catch (IOException e) { logger.error(e); } } Integer noTestCases = Integer.valueOf(fileContents.remove(0)); System.out.println(""No. of test cases ["" + noTestCases + ""]""); return fileContents; } public static void writeOutput(List outputList, String fileName) { List finalList = new ArrayList(); int i = 1; for (String output : outputList) { finalList.add(""Case #"" + i + "": "" + output); i++; } BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(fileName)); for (String line : finalList) { out.write(line); out.newLine(); } } catch (IOException e) { logger.error(e); } finally { try { out.close(); } catch (IOException e) { logger.error(e); } } } } " B21309,"import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileOut { /** * コンストラクタ. * @param filename 書き出すファイル名 * @param s 書き出す文字列 */ public FileOut(String filename, String s) { File f = new File(filename); FileWriter fw = null; try { fw = new FileWriter(f); fw.write(s); } catch (IOException e) { e.printStackTrace(); } finally { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } }" B21066,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class Main { /** * @param args */ public static void main(String[] args) { FileInputStream fstream = null; try { fstream = new FileInputStream(args[0]); //fstream = new FileInputStream(""input.txt""); } catch (FileNotFoundException e) { // TODO Auto-generated catch block System.out.println(""Input File Not Found.""); System.exit(1); } DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int lines = 0; try { lines = Integer.parseInt(br.readLine()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } BufferedWriter out = null; try { // Create file FileWriter outstream = new FileWriter(""output.txt""); out = new BufferedWriter(outstream); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } String line[] = null; Integer numberA; Integer numberB; String sN; String sM; int m; for (int i = 1; i <= lines; i++) { try { line = br.readLine().split(""\\s+""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } numberA = Integer.parseInt(line[0]); numberB = Integer.parseInt(line[1]); String parte1; String parte2; //System.out.println(""Number A is "" + numberA + "" and number B is "" // + numberB); int counter = 0; for (int n = numberA; n < numberB; n++) { sN = Integer.toString(n); // Aqui temos o número n (n,m) HashSet respostas = new HashSet(); for (int pos = (sN.length() - 1); pos >= 0; pos--) { parte1 = sN.substring(pos); parte2 = sN.substring(0, pos); sM = parte1.concat(parte2); // Transformado m = Integer.parseInt(sM); if (numberA <= n && n < m && m <= numberB) { // System.out.println(sNumberA + "" <= "" + n + "" < "" + m // + "" <= "" + sNumberB); // counter++; respostas.add(m); } } counter += respostas.size(); } System.out.println(""Case #"" + i + "": "" + counter); try { out.write(""Case #"" + i + "": "" + counter + ""\n""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B21772,"package c; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; public class RecycledNumbers { public static int getDistinctRecycleCount(int min, int max) { HashSet distinctCollection = new HashSet(); for(int i = min; i <= max; i++) { distinctCollection.addAll(getThePossiblePair(i, max)); } return distinctCollection.size(); } private static HashSet getThePossiblePair(int theNum, int max) { HashSet ret = new HashSet(); String theNumStr = Integer.toString(theNum); for(int n = 1; n < theNumStr.length(); n++) { //roll the number 1 time to the left char firstChar = theNumStr.charAt(0); theNumStr = theNumStr.substring(1) + firstChar; int theRolledNum = Integer.parseInt(theNumStr); //check if the rolled number is possible if((theNum < theRolledNum) && (theRolledNum <= max)) ret.add(Integer.toString(Math.min(theNum, theRolledNum)) + ""-"" + Integer.toString(Math.max(theNum, theRolledNum))); } return ret; } public static void main(String[] args) throws Exception { //initial reader by args[0] BufferedReader r = new BufferedReader(new FileReader(args[0])); int cases = Integer.parseInt(r.readLine()); //initial writer by args[1] PrintWriter w = new PrintWriter(args[1]); //do for(int i = 1; i <= cases; i++) { String[] ab = r.readLine().split("" ""); System.out.println(""Case #"" + i + "": "" + getDistinctRecycleCount(Integer.parseInt(ab[0]), Integer.parseInt(ab[1]))); w.println(""Case #"" + i + "": "" + getDistinctRecycleCount(Integer.parseInt(ab[0]), Integer.parseInt(ab[1]))); } //close file handles w.close(); r.close(); } }" B22188,"import java.io.*; import java.util.*; public class C { static final int maxn = 2000010; static int A, B; static boolean was[] = new boolean[maxn]; static long ans; static void examine(int x) { String s = """" + x; int n = s.length(); int num = 1; was[x] = true; for (int i = 1; i < n; i++) { s = s.substring(1) + s.charAt(0); if (s.charAt(0) == '0') continue; int y = Integer.parseInt(s); if (y >= A && y <= B) { if (was[y]) break; was[y] = true; num++; } } ans += num * (num - 1) / 2; } public static void main(String[] args) { Scanner in = new Scanner(new InputStreamReader(System.in)); int T = in.nextInt(); for (int q = 1; q <= T; q++) { Arrays.fill(was, false); ans = 0; A = in.nextInt(); B = in.nextInt(); for (int i = A; i <= B; i++) { if (was[i]) continue; examine(i); } System.out.printf(""Case #%d: %d\n"", q, ans); } } } " B21334,"import java.util.HashMap; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String line = scanner.nextLine().trim(); int totalCase = Integer.parseInt(line); for (int i = 1; i <= totalCase; i++) { line = scanner.nextLine().trim(); String parts[] = line.split("" +""); int min = Integer.parseInt(parts[0]); int max = Integer.parseInt(parts[1]); int numOfDigits = ("""" + min).length(); int total = 0; HashMap map = new HashMap(); for (int num = min; num <= max; num++) { String numString = """" + num; for (int index = 1; index < numOfDigits; index++) { String numPart1 = numString.substring(0, index); String numPart2 = numString.substring(index); String newNumString = numPart2 + numPart1; int newNum = Integer.parseInt(newNumString); if (newNum > num && newNum <= max && num >= min) { String key = ""("" + num +"","" + newNum + "")""; map.put(key, 0); // total++; } } } total = map.size(); String output = ""Case #"" + i + "": "" + total; System.out.println(output); } System.exit(0); } } " B21641,"import java.io.*; import java.util.*; public class Main { public static void main(String... args) throws Exception { int t, a, b, T; Scanner in = new Scanner(new File(""recycled.in"")); //PrintStream out = System.out; PrintStream out = new PrintStream(new File(""recycled.out"")); T = in.nextInt(); for (t = 1; t <= T; t++) { a = in.nextInt(); b = in.nextInt(); int rez = 0; int i, j; int n = (a + """").length(); String B = b + """"; for (i = a; i <= b; i++) { String I = i + """"; Set s = new TreeSet(); s.add(I); for (j = 1; j < n; j++) { String x = I.substring(j) + I.substring(0, j); if (I.compareTo(x) < 0 && x.compareTo(B) <= 0 && s.add(x)) { rez++; } } } out.println(""Case #"" + t + "": "" + rez); } } } " B21120,"package recyclednumbers; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Input { List cases = null; public List getCases() { return cases; } String path = """"; public String getPath() { return path; } public Input(String path) { this.path = path; } public void setInputData() { try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(this.path); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line int lineNumber = 0; cases = new ArrayList(); while ((strLine = br.readLine()) != null) { // Print the content on the console lineNumber++; if(lineNumber == 1){continue;} cases.add(new TestCase(Integer.parseInt(strLine.split("" "")[0]), Integer.parseInt(strLine.split("" "")[1]))); } // Close the input stream in.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B21681,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner scan = new Scanner(new File(""input"")); PrintWriter out = new PrintWriter(new BufferedWriter (new FileWriter(""output""))); int T = scan.nextInt(); int compteur =1; while(T-->0){ int A = scan.nextInt(); int B=scan.nextInt(); int nbDig = (A+"""").length(); int pui = 1; for(int i=0;ii&&u<=B&&deja){ rec++; } } } out.println(""Case #""+compteur+"": ""+rec); compteur++; } out.close(); } } " B21179,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycled; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.TreeSet; /** * * @author Alfred */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(""C-large.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter outFile = new FileWriter(""out.txt""); PrintWriter out = new PrintWriter(outFile); String line; line = br.readLine(); int cases = Integer.parseInt(line); for (int i=1; i<=cases;i++){ line = br.readLine(); String[] values = line.split("" ""); int A = Integer.parseInt(values[0]); int B = Integer.parseInt(values[1]); int total=0; for (int n=A; n<=B;n++){ TreeSet solutions = new TreeSet(); for (int k=1;k n && !m.startsWith(""0"") && m.length()==Integer.toString(n).length() ) { solutions.add(m); } } total+=solutions.size(); } out.println(""Case #""+i+"": ""+total); } in.close(); out.close(); } catch (Exception e) {//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private static String circshift(int n, int k) { String nString=Integer.toString(n); int len=nString.length(); String m = nString.substring(len-k)+nString.subSequence(0, len-k); //System.out.println(n+"" ""+m); return m; } } " B21466,"package com.renoux.gael.codejam.utils; import java.util.Date; public class Timer { private static long timestamp; public static void start() { timestamp = new Date().getTime(); } public static String check() { long delay = (new Date().getTime() - timestamp); long seconds = delay / 1000; long millis = delay - 1000 * seconds; long minutes = seconds / 60; seconds = seconds % 60; return new StringBuilder().append(minutes).append("" min "") .append(seconds).append("" s "").append(millis).append("" ms "") .toString(); } } " B21029,"import java.io.File; import java.util.HashMap; import java.util.Scanner; public class ProblemC { /** * @param args */ public static void main(String[] args) throws Exception { Scanner leitor = new Scanner(new File(""problemC.in"")); int n = leitor.nextInt(); leitor.nextLine(); for (int caso = 0 ; caso < n; caso++) { int a = leitor.nextInt(); int b = leitor.nextInt(); leitor.nextLine(); /* A ≤ n < m ≤ B. */ if (b > 10) { int resultado[] = new int[b+1]; for (int i = 0; i < 11; i++) { resultado[i] = 0; } for (int i = a; i <= b; i++) { String number = Integer.toString(i); int resultadoParcial = resultado[i-1]; String numberToChange = Integer.toString(i); HashMap tiraRepetidos = new HashMap(); for (int j = 0; j < number.length()-1; j++) { String novoNumeroString = numberToChange.substring(j+1) + numberToChange.substring(0,j+1); while (novoNumeroString.startsWith(""0"")) novoNumeroString = novoNumeroString.substring(1); int novoNumero = new Integer( novoNumeroString); //System.out.println(i + "" -> "" + novoNumero); if (!tiraRepetidos.containsKey(novoNumero)) { if ((a <= i ) && (i < novoNumero) && (novoNumero <= b)) { resultadoParcial += 1; } tiraRepetidos.put(novoNumero, novoNumero); } } resultado[i] = resultadoParcial; } System.out.println(""Case #""+ (caso+1) + "": "" + (resultado[b])); } else { System.out.println(""Case #""+ (caso+1) + "": 0""); } } } } " B20681,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class TestB { private final static String DAT_PATH = ""/Users/ttsurumi/Downloads/""; // private final static String dat = ""A-sample-practice.in""; // private final static String dat = ""A-small-practice.in""; // private final static String dat = ""B-sample.in""; private final static String dat = ""C-large.in""; public static String datPath = DAT_PATH + dat; public static String ansPath = DAT_PATH + dat + "".ans""; /** * @param args */ public static void main(String[] args) { try{ BufferedReader br = new BufferedReader(new FileReader(datPath)); BufferedWriter bw = new BufferedWriter(new FileWriter(ansPath)); String[] movCounts = br.readLine().split("" ""); String tmp_str; int count = 1; while((tmp_str = br.readLine()) != null){ String[] row = tmp_str.split("" ""); long min = Long.parseLong(row[0]); long max = Long.parseLong(row[1]); int width = row[0].length(); bw.write(""Case #"" + count + "": "" ); long ans = 0; // System.out.println(""min = "" + min + "", max = "" + max + "", width"" + width); for(long i = min; i < max; i++){ long t= check(i,min,max,width); ans += t; // if(t != 0)System.out.println(""ans = "" + ans + "", t = "" + t); } bw.write(ans+""""); bw.newLine(); count++; } bw.flush(); }catch(IOException e){ System.err.println(e); } } private static long check(long l,long min, long max, int width){ long count = 0; long next = (long)Math.pow(10, width-1); long t = l % 10; long h = l / 10; long shift = h + t * next; if(shift == l )return 0; shift=l; for(int i = 0; i < width - 1; i++){ t = shift % 10; h = shift / 10; shift = h + t * next; if(min < shift && l < shift && shift <= max ){ // System.out.println(""l = "" + l + "", ans"" + shift); count++; } } return count; } } " B22255," package com.google.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { String input = null; String outputFileLocation = ""C:\\google-code-jam\\output\\C-large-output.txt""; //String outputFileLocation = ""C:\\google-code-jam\\output\\C-small-output.txt""; String inputFileLocation = ""C:\\google-code-jam\\input\\C-large-practice.in""; //String inputFileLocation = ""C:\\google-code-jam\\input\\C-small-practice.in""; File outputFile = new File(outputFileLocation); BufferedWriter outputWriter = null; DataInputStream in = null; int caseNum = 1; int count = 0; String appCount = """"; try { outputWriter = new BufferedWriter(new FileWriter(outputFile)); // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(inputFileLocation); // Get the object of DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = null; int numtestCases = 1; int credit = 0; int numItemsinStore = 0; String[] arrItems = null; int [] arrSoln = null; long startNum = 0; long endNum = 0; int answer = 0; numtestCases = new Integer(br.readLine()).intValue(); // Read File Line By Line for (int i = 1; i <= numtestCases; i++) { //get credit from file input = br.readLine(); String[] a = input.split(""\\s""); answer = 0; startNum = Integer.parseInt(a[0]); endNum = Integer.parseInt(a[1]); for (long j = startNum; j < endNum; j++) { answer = answer + getString(String.valueOf(j), startNum, endNum); } // System.out.println(""Case #"" + i + "": "" + answer); outputWriter.write(""Case #"" + i + "": "" + answer); outputWriter.newLine(); } System.out.println(""Done""); // Close the input stream in.close(); // Close the output stream outputWriter.close(); } catch (IOException e) // Catch exception if any { System.err.println(""IO Error: "" + e.getMessage()); } catch (Exception e) // Catch exception if any { System.err.println(""Error: "" + e.getMessage()); } } public static int getString(String inputString, long startNum, long endNum) { //System.out.println(""Input string is "" + inputString); int length = inputString.length(); int varLength = length; int tempLength = 0; boolean flag = true; int answer = 0; for (int i = 0; i < inputString.length() - 1; i++) { if (inputString.charAt(i) != inputString.charAt(i + 1)) { flag = false; } } if (flag == true) { //System.out.println(""found same digit number""); return 0; } String temp1 = null; String temp2 = null; String newString = null; for (int i = 0; i < length; i++) { tempLength = length - (i + 1); //System.out.println(""varLEnth = "" + varLength + "" tempLength = "" //+ tempLength); if (varLength > tempLength && tempLength != 0) { temp1 = inputString.substring(varLength - 1, length); //System.out.println(""1 = "" + temp1); temp2 = inputString.substring(0, varLength - 1); //System.out.println(""2 = "" + temp2); varLength--; if (temp1.charAt(0) != '0') { newString = temp1 + temp2; } else { //System.out.println(""found leading 0""); newString = null; } //System.out.println(""input string is "" + inputString); //System.out.println(""new string is "" + newString); if (newString != null && Long.valueOf(newString) <= endNum && Long.valueOf(newString) > Long.valueOf(inputString)) { answer++; //System.out.println(""answer incremented by one "" + answer); } } } return answer; } } " B20567,"import java.math.*; import java.io.*; import java.util.*; public class Recycle { public static void main(String[] args) { Recycle r = new Recycle(); writeOutput(r.countRecycleds(readInput())); } // Count all recycleds for all the inputs public String countRecycleds(ArrayList lines) { String line; StringBuffer out = new StringBuffer(); for (int i = 1; i < lines.size(); i++) { line = lines.get(i); String[] args = line.split("" ""); out.append(""Case #"" + i + "": ""); out.append(countRecycleds(Integer.parseInt(args[0]), Integer.parseInt(args[1]))); out.append(""\n""); } return out.toString(); } // Count all recycleds between A and B public int countRecycleds(int A, int B) { int count = 0; for (int n = A; n <= B; n++) { count += countRecycledsForN(n, B); } return count; } // Count recycleds for one n (ie, number of ms) public int countRecycledsForN(int n, int B) { int digits = countDigits(n); int count = 0; Map used = new HashMap(); // For each number of digits we're swapping for(int swap = 1; swap < digits; swap++) { // The base 10 number to swap int swapper = (int)Math.pow(10, swap); // The digits being swapped int swappedDigits = n % swapper; // n without the digits being swapped int swappedN = n / swapper; int m = (swappedDigits * (int)Math.pow(10, digits - swap)) + swappedN; // If m is valid, count it if (n < m && m <= B && !used.containsKey(m)) { count++; used.put(m, true); } } return count; } // Count the number of digits in n (base 10) public int countDigits(int n) { return (int)Math.log10(n) + 1; } public static void writeOutput(String s) { try{ BufferedWriter out = new BufferedWriter(new FileWriter(""./Output.txt"")); out.write(s); out.close(); }catch (Exception e){ System.out.println(s); throw new RuntimeException(""Oops, couldn't write""); } } public static ArrayList readInput() { ArrayList lines = new ArrayList(); try { FileInputStream fstream = new FileInputStream(""./Input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String str; while ((str = br.readLine()) != null) { lines.add(str); } br.close(); return lines; } catch (Exception e) { throw new RuntimeException(""Couldn't read""); } } }" B21265,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) throws IOException { File file = new File(""in.txt""); Scanner scanner = new Scanner(file); FileWriter outFile = new FileWriter(""out.txt""); PrintWriter out = new PrintWriter(outFile); int N = scanner.nextInt(); for (int i = 0; i < N; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); Set set = new HashSet(); for (int n = A; n <= B; n++) { char[] c = Integer.toString(n).toCharArray(); for (int k = 0; k < c.length - 1; k++) { char temp = c[c.length - 1]; for (int l = c.length - 1; l > 0; l--) { c[l] = c[l - 1]; } c[0] = temp; StringBuilder s = new StringBuilder(); for (int l = 0; l < c.length; l++) { s.append(c[l]); } String m = s.toString(); if (A <= Integer.parseInt(m) && Integer.parseInt(m) <= B && n < Integer.parseInt(m)) { set.add(Integer.toString(n).concat(m)); } } } out.println(""Case #"" + (i + 1) + "": "" + set.size()); } out.close(); System.out.println(""kla\n""); } } " B21129,"import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class WriteFile { public static void write(String path, String content) throws IOException { //BufferedWriter bw = new BufferedWriter(new FileWriter(""C:\\test\\output.txt"",false)); BufferedWriter bw = new BufferedWriter(new FileWriter(path,false)); bw.write(content); bw.flush(); bw.close(); } } " B20364,"package dom.zar.jam.qualifications; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); int inputLines = in.nextInt(); for (int i = 0; i < inputLines;) { int a = in.nextInt(); int b = in.nextInt(); System.out.println(""Case #"" + ++i + "": "" + result(a, b)); } } private static int result(int a, int b) { int size = b - a + 1; int[] nums = new int[size]; for (int i = 0; i < size; ++i) nums[i] = a + i; int counter = 0; for (int i = 0; i < size; ++i) { if (nums[i] > -1) { counter += rotate(nums[i], a, b, nums); nums[i] = -1; } } return counter; } private static int rotate(Integer n, int a, int b, int[] nums) { String valString = n.toString(); int length = valString.length(); valString = valString + valString; int counter = 0; for (int i = 1; i < length; ++i) { int rotated = Integer.parseInt( valString.substring(i, i + length)); if (rotated > n && rotated <= b && nums[rotated - a] != -1) { counter++; nums[rotated - a] = -1; } } return (counter * (counter + 1)) >> 1; } } " B20589,"package be.mokarea.gcj.common; import java.io.PrintWriter; public abstract class Transformation { private TestCaseReader caseReader; private final PrintWriter outputWriter; public Transformation(TestCaseReader caseReader, PrintWriter outputWriter) { this.caseReader = caseReader; this.outputWriter = outputWriter; } public void transformAll() throws Exception { T testCase = caseReader.nextCase(); while (testCase != null) { outputWriter.println(transform(testCase)); testCase = caseReader.nextCase(); }; } protected abstract String transform(T testCase); } " B21625,"package gcj.main; import gcj.cases.competition.qualification_round_2012.CaseC; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class Main { public static final void main (String[] args) throws Exception{ // doTask(""taskTeszt0"", ""/home/dev/Letöltések/0-teszt-practice.in"", ""/home/dev/Letöltések/0-teszt-practice.out"", new Case0()); // doTask(""taskSmall0"", ""/home/dev/Letöltések/A-small-attempt0.in"", ""/home/dev/Letöltések/A-small-attempt0.out"", new Case0()); // doTask(""taskTesztB"", ""/home/dev/Letöltések/B-teszt-practice.in"", ""/home/dev/Letöltések/B-teszt-practice.out"", new CaseB()); // doTask(""taskSmallB"", ""/home/dev/Letöltések/B-small-practice.in"", ""/home/dev/Letöltések/B-small-practice.out"", new CaseB()); // doTask(""taskLargeB"", ""/home/dev/Letöltések/B-large-practice.in"", ""/home/dev/Letöltések/B-large-practice.out"", new CaseB()); // doTask(""taskTesztC"", ""/home/dev/Letöltések/C-teszt-practice.in"", ""/home/dev/Letöltések/C-teszt-practice.out"", new CaseC()); // doTask(""taskSmallC"", ""/home/dev/Letöltések/C-small-attempt0.in"", ""/home/dev/Letöltések/C-small-attempt0.out"", new CaseC()); doTask(""taskLargeC"", ""/home/dev/Letöltések/C-large.in"", ""/home/dev/Letöltések/C-large.out"", new CaseC()); doTask(null, null, null, null); //because i hate the 'never used locally' warning... } private static final void doTask(String taskID, String inpFilePath, String outFilePath, Case c) throws Exception { if(taskID == null) return; BufferedReader br = null; BufferedWriter bw = null; String strLine; int caseNum = 0; System.out.println(taskID + "" strated...""); try{ { //open files br = new BufferedReader(new FileReader(new File(inpFilePath))); bw = new BufferedWriter(new FileWriter(new File(outFilePath))); } { //read caseNum value if ((strLine = br.readLine()) != null){ caseNum = Integer.parseInt(strLine); } System.out.println(""CaseNum: ""+caseNum); } for(int i=0; i 0) { ++ans; n /= 10; } return ans; } static int rotate(int n, int len) { int d = n % 10; n /= 10; n = p[len - 1] * d + n; return n; } static void redirect() throws FileNotFoundException { System.setIn(new FileInputStream(""c.in"")); System.setOut(new PrintStream(""c.out"")); } public static void main(String[] args) throws FileNotFoundException { redirect(); Scanner in = new Scanner(System.in); int tc; tc = in.nextInt(); for (int t = 1; t <= tc; t++) { int a, b, n, x, y; a = in.nextInt(); b = in.nextInt(); Set s = new TreeSet(); int ans ; int len = length(a); for (int i = a; i <= b; i++) { n = i; if (i == p[len]) len++; while (true) { n = rotate(n, len); if (n == i) break; if (a <= n && n <= b) { x = i; y = n; if (x > y) { int tmp = x; x = y; y = tmp; } s.add(new Pair(x, y)); } } } ans = s.size(); System.out.printf(""Case #%d: %d\n"", t, ans); } } } class Pair implements Comparable { int x,y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair p) { if (x != p.x) return x - p.x; else return y - p.y; } } " B21449,"import java.io.IOException; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""module/src/C.in""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""module/src/C.txt""); } catch (IOException e) { throw new RuntimeException(e); } MyScanner in = new MyScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); ProblemC solver = new ProblemC(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } class ProblemC { public void solve(int testNumber, MyScanner in, PrintWriter out) { int A = in.nextInt(),B = in.nextInt(); boolean[] visited=new boolean[B+1]; long res = 0; for(int i=A;i<=B;i++){ if(visited[i])continue; int num = i; String str = num+""""; int cnt = 0; for(int j=0;j= start && pairMI > number && pairMI <= end) { total++; // System.out.print(""Pair("" + pairN + "", "" + pairM + "")""); // System.out.print("", Ture""); // System.out.println(""""); } } } // System.out.println(""Total: "" + total); return total; } public static void main(String[] args) { // ProblemC.solve(1111, 2222); // List smallLinesIn = CodeHelper.loadInputLines(SMALL_IN_FILE_NAME); // List smallOuts = new ArrayList(); // for (int i = 1; i < smallLinesIn.size(); i++) { // String[] numbers = smallLinesIn.get(i).split("" ""); // int start = Integer.parseInt(numbers[0]); // int end = Integer.parseInt(numbers[1]); // smallOuts.add(""Case #"" + i + "": "" + ProblemC.solve(start, end)); // } // CodeHelper.writeOutputs(SMALL_OUT_FILE_NAME, smallOuts); List largeLinesIn = CodeHelper.loadInputLines(LARGE_IN_FILE_NAME); List largeOuts = new ArrayList(); for (int i = 1; i < largeLinesIn.size(); i++) { String[] numbers = largeLinesIn.get(i).split("" ""); int start = Integer.parseInt(numbers[0]); int end = Integer.parseInt(numbers[1]); largeOuts.add(""Case #"" + i + "": "" + ProblemC.solve(start, end)); } CodeHelper.writeOutputs(LARGE_OUT_FILE_NAME, largeOuts); } } " B20990,"import java.util.*; public class Recycle { public static void main(String args[]) { int uBound, lBound, count=0, caseNo=1; Scanner input = new Scanner(System.in); input.nextLine(); while(true) { lBound = input.nextInt(); uBound = input.nextInt(); for(int i=lBound; i<=uBound; i++) { int numDigits = new Integer(i).toString().length(); int[] pastPairs = new int[numDigits-1]; for(int j=1; ji && rotatedInt<=uBound) { for(int k=0; k out.txt " B21172,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.recyclednumbers; import uk.co.epii.codejam.common.AbstractMain; /** * * @author jim */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { AbstractMain.main(args, new RecycledNumbersProcessor()); } } " B20942,"import java.io.*; import java.util.*; public class recycle { public static int findList(int n, int a) { String s = Integer.toString(n); int count = 0; int len = s.length() - 1; for(int i = len; i >= 1; i--) { String st = s.substring(i) + s.substring(0, i); if(st.charAt(0) == '0') continue; int x = Integer.parseInt(st); if(x < n && x >= a) count++; } return count; } public static void main(String[] args)throws Exception { BufferedReader br = new BufferedReader(new FileReader(""recycle.in"")); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(""recycle.out""))); int n = Integer.parseInt(br.readLine()); for(int i = 0; i < n; i++) { StringTokenizer st = new StringTokenizer(br.readLine() + "" ""); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int count = 0; for(int j = a; j <= b; j++) count += findList(j, a); pw.println(""Case #"" + (i+1) + "": "" + count); } pw.close(); } } " B20580,"import java.util.ArrayList; import java.util.Scanner; public class C { public static void main(String[] argv){ Scanner in = new Scanner ( System.in ); int T=in.nextInt(); for(int i=0; i temp=new ArrayList(); for(int p=1; px else{ if(y<=B & !temp.contains(y)){ temp.add(y); Rep++; //System.out.println( x+"" ""+y); } } } } System.out.println(""Case #""+(i+1)+"": ""+Rep); } } } " B21796,"import java.awt.Point; import java.io.File; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static Set set; public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File(""input.in"")); int n, a, b; n = in.nextInt(); for (int tc = 1; tc <= n; tc++) { a = in.nextInt(); b = in.nextInt(); set = new HashSet(); finder(a, b); System.out.println(""Case #"" + tc + "": "" + set.size() / 2); } } public static void finder(int a, int b) { int temp; int ans = 0; for (int i = a; i <= b; i++) { for (int j = 1;; j++) { temp = moveDigits(i, j); if (temp == -1) break; if (temp != i && temp >= a && temp <= b) { // System.out.println(""Output :"" + i + "" "" + temp); set.add(new Point(i, temp)); ans++; } } } } public static int moveDigits(int num, int moveBy) { String s = Integer.toString(num); int size = s.length(); if (moveBy >= s.length()) return -1; s = s.substring(moveBy) + s.substring(0, moveBy); if (Integer.toString((Integer.parseInt(s))).length() != size) return 0; return Integer.parseInt(s); } } " B21337,"package com.google.codejam; import java.util.HashSet; import java.util.Set; import com.google.codejam.util.CodeJamInputFile; import com.google.codejam.util.CodeJamOutputFile; public class Recycle { /** * @param args */ public static void main(String[] args) { Integer count; CodeJamInputFile f = new CodeJamInputFile(""in/C-large.in""); CodeJamOutputFile fo = new CodeJamOutputFile(""out/C-large.out""); for(int c = 0; c < f.getCases(); c++){ count = 0; Set tested = new HashSet(); String[] range = f.getLine().split("" ""); Integer a = Integer.valueOf(range[0]); Integer b = Integer.valueOf(range[1]); for(Integer i = a; i < (b + 1); i++){ String str = i.toString(); tested.add(str.concat(str)); for(int j = 1; j= a && testval <= b){ //System.out.println(str + "" - "" + newstr); count++; } } } fo.writeCase(c, count.toString()); } f.close(); fo.close(); } } " B21878,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args){ Scanner in; try { in = new Scanner(new File(""C-large.in"")); solve(in); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void solve(Scanner in){ int cases =in.nextInt(); for(int i = 1; i<=cases; i++){ int min = in.nextInt(); int max = in.nextInt(); int ans = 0; for(int j =min; j<=max; j++){ ans+=combos(j, min, max); } System.out.println(""Case #"" +i+"": ""+(ans/2)); } } public static int combos(int num, int min, int max){ if(num<10){ return 0; } HashSet diffNums = new HashSet(); diffNums.add(num); int ans = 0; String numString = num+""""; for(int i =0; i< numString.length(); i++){ numString = numString.substring(1)+numString.charAt(0); int numTest = Integer.parseInt(numString); if(numTest<=max&&numTest>=min&&diffNums.add(numTest)){ ans++; } } return ans; } } " B20228,"/* * Anand Oza * Apr 14, 2012 */ import java.util.*; import java.io.*; public class C_RecycledNumbers { public static void main(String[] args) throws IOException { long startTime = System.nanoTime(); BufferedReader reader = new BufferedReader(new FileReader(""C_RecycledNumbers.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C_RecycledNumbers.out""))); StreamTokenizer in = new StreamTokenizer(reader); in.nextToken(); int T = (int) in.nval; for (int testcase = 1; testcase <= T; testcase++) { in.nextToken(); int A = (int) in.nval; in.nextToken(); int B = (int) in.nval; int ans = 0; for (int n = A; n <= B; n++) { String s = String.valueOf(n); Set mvalues = new HashSet(); for (int i = 0; i < s.length(); i++) { int m = Integer.parseInt(s.substring(i) + s.substring(0, i)); if (m > n && m <= B && m >= A) mvalues.add(m); } ans += mvalues.size(); } out.format(""Case #%d: %d%n"", testcase, ans); } out.close(); System.out.println(""Time (ms): "" + (double) (System.nanoTime() - startTime) / 1000000); System.exit(0); } } " B20924,"import java.util.*; import java.io.*; import java.lang.*; import static java.lang.System.*; public class RecycledNumbers{ static HashSet set; static int ctr, low, high; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(in)); int ii = Integer.parseInt(br.readLine()); for(int jj=0; jj(); ctr = 0; for(int i=low; i<=high; i++){ if(!set.contains(i)){ generate(i+""""); } } out.printf(""Case #%d: %d\n"", jj+1, ctr); } } static void generate(String s){ String ss = s+s; int tmp = 0; for(int i=0; i=low && x<=high && !set.contains(x)){ // out.println(x); set.add(x); tmp++; } } // out.println(); ctr+=(tmp*(tmp-1)/2); } }" B21269,"import java.text.*; import java.io.*; import java.util.*; import java.lang.Math; public class C { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; int T = Integer.parseInt(br.readLine()); for(int t = 1; t <= T; t++) { System.out.print(""Case #"" + t + "": ""); String[] star = br.readLine().split("" ""); int A = Integer.parseInt(star[0]); int B = Integer.parseInt(star[1]); String up = star[1]; int count = 0; LinkedList list = new LinkedList(); for(int i = A; i <= B; i++) { String current = Integer.toString(i); String next = current; list.clear(); for(int a = 0; a < current.length() - 1; a++) { next = next.charAt(next.length() - 1) + next.substring(0, next.length() - 1); //System.out.println(next); if(!list.contains(next)) { list.add(next); if(current.compareTo(next) < 0 && next.compareTo(up) <= 0) count++; } } } System.out.println(count); } } }" B21654,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; public class Prob1C { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int t = Integer.parseInt(br.readLine()); for(int x = 1; x <= t; x++) { int res = 0; String[] strs = br.readLine().split("" ""); int a = Integer.parseInt(strs[0]); int b = Integer.parseInt(strs[1]); if(a < 10 && b == 2000000) { pw.println(""Case #"" + x + "": 2498454""); continue; } for(int i = a; i <= b; i++) { HashSet set = new HashSet(); String as = """" + i; for(int j = 1; j < as.length(); j++) { String ns = as.substring(j) + as.substring(0, j); int nn = Integer.parseInt(ns); if(nn > i && nn <= b) { set.add(ns); } } res += set.size(); } pw.println(""Case #"" + x + "": "" + res); } br.close(); pw.close(); } } " B20708,"import java.io.File; import java.io.FileWriter; import java.util.Scanner; public class B { /** * @param args */ public static void main(String[] args) throws Exception { Scanner a = new Scanner(new File(""/Users/anurag/Dev/Java/workspace/CodeJam/src/input"")); FileWriter w = new FileWriter(new File(""/Users/anurag/Dev/Java/workspace/CodeJam/src/output"")); int T = a.nextInt(); for (int t = 1; t <= T; ++t) { int lower = a.nextInt(); int upper = a.nextInt(); int numInversions = 0; for (int i = lower; i <= upper; ++i) { int maxPower = (int) Math.log10(i); int rotatedNumber = i; do { int lastDigit = rotatedNumber % 10; rotatedNumber = ((int) (rotatedNumber/10)) + (int) (lastDigit * Math.pow(10, maxPower)); if (rotatedNumber >= lower && rotatedNumber <= upper && rotatedNumber != i) { ++numInversions; } } while (rotatedNumber != i); } w.write(String.format(""Case #%d: %d\n"", t, numInversions/2)); } w.close(); } } " B20301,"import java.io.File; import java.io.FileWriter; import java.util.Arrays; import java.util.Scanner; /** * Author: Andriy Gusyev * Date: 14.04.12 */ public class Task2 { static private int[] multiplers = {0, 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 10000000}; static private int cases; static private int[] lowerBounds; static private int[] upperBounds; static private int[] results; private static void readBounds(String s, int index) { s = s.trim(); String[] arr = s.split("" ""); lowerBounds[index] = Integer.parseInt(arr[0]); upperBounds[index] = Integer.parseInt(arr[1]); } public static void main(String args[]) throws Exception { Scanner sc = new Scanner(new File(""d:/codejam/2/large""), ""UTF-8""); cases = Integer.parseInt(sc.nextLine()); lowerBounds = new int[cases]; upperBounds = new int[cases]; results = new int[cases]; for (int i = 0; i < cases; i++) { readBounds(sc.nextLine(), i); } System.out.println(cases); System.out.println(Arrays.toString(lowerBounds)); System.out.println(Arrays.toString(upperBounds)); for (int i = 0; i < cases; i++) { results[i] = calcRecycled(i); } System.out.println(Arrays.toString(results)); FileWriter fw = new FileWriter(new File(""d:/codejam/2/large_out"")); int k = 0; for (int i : results) { k++; fw.write(String.format(""Case #%s: %s\n"", String.valueOf(k), String.valueOf(i))); } fw.close(); } private static int calcRecycled(int index) { int result = 0; int lower = lowerBounds[index]; int upper = upperBounds[index]; for (int i = lower; i <= upper; i++) { System.out.println(i); int[] possibles = getPossibleRecycled(i); for (int j : possibles) { if (i < j && j <= upper && areRecycled(i, j)) { result++; } } } return result; } private static boolean areRecycled(int i, int j) { // if (!Arrays.equals(toSortedChars(i), toSortedChars(j))) { // return false; // } int digits = String.valueOf(i).length(); int initialI = i; int initialJ = j; for (int p = 0; p < digits; p++) { i = changeValue(i, digits); if (i == j) { return true; } } ; return false; } private static int[] getPossibleRecycled(int i) { // if (!Arrays.equals(toSortedChars(i), toSortedChars(j))) { // return false; // } int digits = String.valueOf(i).length(); int possibles[] = new int[digits]; for (int p = 0; p < digits; p++) { int candidate = changeValue(i, digits); i = candidate; if (isInArray(candidate, possibles)) { possibles[p] = 0; } else { possibles[p] = candidate; } } return possibles; } private static boolean isInArray(int c, int[] array) { for (int i : array) { if (i == c) { return true; } } return false; } private static int changeValue(int i, int digits) { if (i < 10) { return i; } else { //get last digit int last = i % 10; //cut last digit i = i / 10; // add last digit to the front i = multiplers[digits] * last + i; return i; } } private static char[] toSortedChars(int i) { char[] chars = String.valueOf(i).toCharArray(); Arrays.sort(chars); return chars; } }" B21544,"import java.io.*; import java.util.*; public class QualiC_Naive { static void sop(String str) { System.out.println(str); } static void sop1(String str) { System.out.print(str); } public static void main(String args[]) { long tstart = System.currentTimeMillis(); if(args.length < 1) { System.out.println(""You have not given input file!""); System.exit(0); } File f1 = null; Scanner sc = null; try { f1 = new File(args[0]); sc = new Scanner(f1); } catch(Exception e) { System.out.println(""Error opening the input file "" + e); } /* int nCases, i, j, k, m, n; sc.next(); sc.nextInt(); sc.nextLine(); sc.nextDouble(); */ int nCases, i, j, k, m, n; nCases = sc.nextInt(); // sc.nextLine(); for(i=1; i<=nCases; ++i) { int a = sc.nextInt(); int b = sc.nextInt(); int ans = 0; String strn = """" + a; // String strm = """" + b; int len = strn.length(); int mult=0; switch(len) { case 2: mult = 10; break; case 3: mult = 100; break; case 4: mult = 1000; break; case 5: mult = 10000; break; case 6: mult = 100000; break; case 7: mult = 1000000; break; } if(len == 1) ans = 0; else { /* try { FileWriter tempf = new FileWriter(""temp.dat""); BufferedWriter buff = new BufferedWriter(tempf); buff.write(""Case "" + i + "":-------------------------------------------\n""); */ int c[] = new int[len]; for(j=a; j<=b; j++) { c[0] = j; HashSet x = new HashSet(); for(k=1; k Integer.parseInt(number)) { count ++; //System.out.println(""Number "" + number + "" New number "" + newNumber + ""counter"" + count); } } } } System.out.printf(""Case #%d: %d\n"",(i+1), count); } } } } " B20465,"import java.io.*; import java.util.*; class Problems { public static void main (String [] args) throws Exception { BufferedReader f = new BufferedReader(new FileReader(""input.java"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""output.java""))); StringTokenizer st = new StringTokenizer(f.readLine()); int T=Integer.parseInt(st.nextToken()); for(int t=0;ti&&curr<=B) { ans++; } } } System.err.println((t+1)+""""); out.println(""Case #""+(t+1)+"": ""+ans); } out.close(); System.exit(0); } } " B20730,"package fixjava; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.Map.Entry; public class HashMapDualKey extends HashMap> { private static final long serialVersionUID = 1L; /** Returns whether the dual map contains the given key in the K1 space */ @Override public boolean containsKey(Object key) { return this.containsKey(key); } public boolean containsKey(K1 key1, K2 key2) { HashMap map2 = this.get(key1); if (map2 == null) return false; else return map2.containsKey(key2); } /** Searches all (K1, K2) pairs to see if any of them map to the value. Runs in O(K1) time. */ public boolean containsValueAll(Object value) { for (HashMap map2 : this.values()) if (map2 != null && map2.containsValue(value)) return true; return false; } public V get(K1 key1, K2 key2) { HashMap map2 = this.get(key1); if (map2 == null) return null; else return map2.get(key2); } public Set keySet(K1 key1) { HashMap map2 = this.get(key1); if (map2 == null) return null; else return map2.keySet(); } public V put(K1 key1, K2 key2, V value) { HashMap map2 = this.get(key1); if (map2 == null) this.put(key1, map2 = new HashMap()); return map2.put(key2, value); } public void putAll(ArrayList> items) { for (Tuple3 item : items) put(item.getField0(), item.getField1(), item.getField2()); } public void putAllListOfLists(ArrayList>>> listOfLists) { for (Pair>> pair1 : listOfLists) { K1 k1 = pair1.getLeft(); for (Pair pair2 : pair1.getRight()) put(k1, pair2.getLeft(), pair2.getRight()); } } @Override public HashMap remove(Object key1) { return this.remove(key1); } public V remove(K1 key1, K2 key2) { HashMap map2 = this.get(key1); if (map2 == null) return null; V ret = map2.remove(key2); if (map2.isEmpty()) this.remove(key1); return ret; } /** Returns size across all (K1, K2) pairs. Runs in O(K1) time. */ public int sizeAll() { int size = 0; for (HashMap map2 : this.values()) if (map2 != null) size += map2.size(); return size; } /** Returns union of values across all (K1, K2) pairs. Runs in O(N) time. */ public HashSet valuesAll() { HashSet values = new HashSet(); for (HashMap map2 : this.values()) if (map2 != null) values.addAll(map2.values()); return values; } /** Returns the map as a list of Tuple3. Runs in O(N) time. */ public ArrayList> getAsList() { ArrayList> result = new ArrayList>(); for (Entry> ent1 : this.entrySet()) { K1 k1 = ent1.getKey(); HashMap map2 = ent1.getValue(); if (map2 != null) { for (Entry ent2 : map2.entrySet()) { K2 k2 = ent2.getKey(); V v = ent2.getValue(); result.add(Tuple3.make(k1, k2, v)); } } } return result; } /** Returns the map as a list of Pair>>. Runs in O(N) time. */ public ArrayList>>> getAsListOfLists() { ArrayList>>> result = new ArrayList>>>(this.size()); for (Entry> ent1 : this.entrySet()) { K1 k1 = ent1.getKey(); HashMap map2 = ent1.getValue(); if (map2 != null) { ArrayList> listOfK2VPairs = new ArrayList>(map2.size()); for (Entry ent2 : map2.entrySet()) { K2 k2 = ent2.getKey(); V v = ent2.getValue(); listOfK2VPairs.add(Pair.make(k2, v)); } result.add(Pair.make(k1, listOfK2VPairs)); } } return result; } } " B22204,"package com.irabin.google.codejam.problem3; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNumber { private Scanner scanner; private PrintWriter writer; public RecycledNumber(InputStream in, OutputStream os) { scanner = new Scanner(in); writer = new PrintWriter(os); } public void solve() { int n = Integer.parseInt(scanner.nextLine()); for (int i = 1; i <= n; i++) { writer.print(""Case #"" + i + "": ""); String output = """"; Long A = scanner.nextLong(); Long B = scanner.nextLong(); int total = 0; for (Long j = A; j <= B; j++) { String str = String.valueOf(j); if (str.length() < 2) { continue; } int startIndex = 1; int endIndex = str.length(); while (startIndex < endIndex) { String notSubStr = str.substring(0, startIndex); String substr = str.substring(startIndex); String newValue = substr.concat(notSubStr); Long C = Long.valueOf(newValue); String strJ = String.valueOf(j); String strC = String.valueOf(C); if (A<=j && j < C && C <= B && strJ.length()==strC.length()) { total = total + 1; } startIndex = startIndex + 1; } } output = String.valueOf(total); writer.println(output); writer.flush(); } writer.close(); } public static void main(String args[]) { InputStream input = null; input = RecycledNumber.class.getResourceAsStream(args[0]); OutputStream output = null; try { output = new FileOutputStream(args[1]); } catch (FileNotFoundException e) { e.printStackTrace(); } RecycledNumber practise1 = new RecycledNumber(input, output); practise1.solve(); } } " B21590,"package com.mohit.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class RecycledNumbers { public static void main(String[] args) { try { int noOfTests = 0; FileInputStream fis = new FileInputStream(""C-large.txt""); DataInputStream din = new DataInputStream(fis); BufferedReader br = new BufferedReader(new InputStreamReader(din)); FileWriter fstream = new FileWriter(""output_large.txt""); BufferedWriter out = new BufferedWriter(fstream); String strLine; strLine = br.readLine(); if (strLine == null || strLine == """") return; strLine = strLine.trim(); noOfTests = Integer.parseInt(strLine); int testNumber = 1; while (noOfTests > 0) { strLine = br.readLine(); if (strLine == null || strLine == """" || strLine == ""\n"") break; strLine = strLine.trim().toLowerCase(); String[] nums = strLine.split("" ""); int A = Integer.parseInt(nums[0].trim()); int B = Integer.parseInt(nums[1].trim()); int firstCharB = Integer.parseInt(String.valueOf(B).charAt(0) +""""); int recycledNum = 0; for (int i = A; i <= B; i++) { String n = String.valueOf(i); if (Integer.parseInt(n.substring(n.length() - 1)) > firstCharB) { int check = i; while(check>0) { int nexti = check % 10; if(nexti < firstCharB) break; else check = check/10; } if(check == 0) { i = i + (10 - i%10); continue; } } { int condition = 0; if (n.length() % 2 == 0 && n.substring(0, n.length() / 2).equals( n.substring(n.length() / 2))) { condition = n.length() / 2; } else { condition = n.length(); } for (int j = 1; j < condition; j++) { String m = n.substring(j) + n.substring(0, j); int mi = Integer.parseInt(m); if (mi <= i || mi > B) continue; recycledNum++; } } } out.write(""Case #"" + testNumber + "": "" + recycledNum + ""\n""); testNumber ++; } br.close(); out.close(); } catch (Exception e) { System.out.print(e.getMessage()); } } } " B20562,"import java.io.*; import java.util.*; public class C2012 { public static void main(String[] args) throws IOException { PrintWriter out; BufferedReader f; try { f = new BufferedReader(new FileReader(""C2012.in"")); out = new PrintWriter(new BufferedWriter(new FileWriter( ""C2012.out""))); } catch (Exception e) { f = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } int n=Integer.parseInt(f.readLine()); for(int i=1;i<=n;i++){ StringTokenizer token = new StringTokenizer(f.readLine()); int a=Integer.parseInt(token.nextToken()); int b=Integer.parseInt(token.nextToken()); int numDigits=numDigits(a); int answer=0; int last=0; for(int j=a;j<=b;j++){ int hm=j; int hm2=hm; int tenmultiply=0; for(int k=1;khm&&last!=hm2){ last=hm2; answer++; } } } out.print(""Case #""); out.print(i+"": ""); out.println(answer); } out.close(); System.exit(0); } public static int numDigits(int x){ if (x >= 10000) { if (x >= 10000000) { if (x >= 100000000) { if (x >= 1000000000) return 10; return 9; } return 8; } if (x >= 100000) { if (x >= 1000000) return 7; return 6; } return 5; } if (x >= 100) { if (x >= 1000) return 4; return 3; } if (x >= 10) return 2; return 1; } }" B21710," import java.io.*; import java.util.ArrayList; import java.util.StringTokenizer; /* * To change this template, choose Tools | Templates and open the template in the editor. */ /** * * @author doda */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here BufferedReader R = new BufferedReader(new FileReader(""C:\\Users\\doda\\Desktop\\C-large.in"")); PrintWriter P = new PrintWriter(new FileWriter(""C:\\Users\\doda\\Desktop\\large.txt"")); while (R.ready()) { int t = Integer.parseInt(R.readLine()); for (int i = 0; i < t; ++i) { StringTokenizer s = new StringTokenizer(R.readLine()); int out = 0; String O = ""Case #"" + (i + 1) + "":""; int n = Integer.parseInt(s.nextToken()); int m = Integer.parseInt(s.nextToken()); for (int j = n; j <= m; ++j) { int l[] = diffOrder(j); for (int k = 0; k < l.length; ++k) { if (l[k] > j && l[k] <= m) { ++out; } } } O += "" "" + out; P.println(O); } } P.close(); } public static int[] diffOrder(int num) { String s = """" + num; ArrayList in = new ArrayList(); int re[]; for (int i = 0; i < s.length() - 1; ++i) { s = s.charAt(s.length() - 1) + """" + s.substring(0, s.length() - 1); int y = Integer.parseInt(s); String h = """" + y; if (h.length() < s.length()) { y = 0; } if (!in.contains(y) && y != 0) { in.add(y); } } re = new int[in.size()]; for (int i = 0; i < in.size(); ++i) { re[i] = in.get(i); } return re; } }" B20350,"import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Hossam Yasseen */ public class ProblemC { /** * @param args */ static Integer startEdge , endEdge ; public static void main(String[] args) { int numberOfRecycledNumbers = 0; String[] result = null ; for (int counter0 = 1; counter0 < args.length; counter0++) { result = args[counter0].split(""\\s""); startEdge = Integer.parseInt(result[0]); endEdge = Integer.parseInt(result[1]); numberOfRecycledNumbers=0 ; for (int counterA = startEdge; counterA < endEdge; counterA++) { List recycledNumber = recycledNumbers(counterA); for (int counter = 0; counter < recycledNumber.size(); counter++) { if (recycledNumber.get(counter) <= endEdge ) numberOfRecycledNumbers++; } } System.out.println(""Case #"" + counter0 + "": "" + numberOfRecycledNumbers); } } private static List recycledNumbers(Integer number) { Map map = new HashMap(); String dummyValue = null ; String candidateNumber = """"; char[] characters = number.toString().toCharArray(); int index; for (int counter = 0; counter < characters.length; counter++) { index = counter ; int loops = 0 ; candidateNumber=""""; for ( ; loops < characters.length; index++) { candidateNumber += characters[index % characters.length]; loops++ ; } if(Integer.parseInt(candidateNumber)>number.intValue()) map.put(Integer.parseInt(candidateNumber),dummyValue); } List recycledNumber = new ArrayList( map.keySet()); return recycledNumber; } } " B21145,"import java.util.*; import java.io.*; import java.math.BigInteger; import static java.lang.Math.*; public class B implements Runnable { final String fileName = ""C-large""; private void solution() throws IOException { if (!fileName.isEmpty()) { in = new Scanner(new FileReader(fileName + "".in"")); out = new PrintWriter(fileName + "".out""); } int n = in.nextInt(); for (int cas = 1; cas <= n; ++cas) { out.printf(""Case #%d: %s\n"", cas, solve(in.nextInt(), in.nextInt())); } } private long solve(int left, int right) { int length = ("""" + left).length(); int p10 = (int) (Math.pow(10, length - 1) + 0.5); long res = 0; int[] used = new int[right + 1]; for (int cur = left; cur <= right; ++cur) { int value = cur; for (int step = 0; step < length - 1; ++step) { value = (value % 10) * p10 + (value / 10); if (left <= value && value <= right && value != cur) { if (used[value] != cur) { used[value] = cur; ++res; } } } } return res / 2; } public void run() { try { solution(); in.reader.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } private void debug(Object... objects) { System.out.println(Arrays.toString(objects)); } private static class Scanner { private BufferedReader reader; private StringTokenizer tokenizer; public Scanner(Reader reader) { this.reader = new BufferedReader(reader); this.tokenizer = new StringTokenizer(""""); } public boolean hasNext() throws IOException { while (!tokenizer.hasMoreTokens()) { String line = reader.readLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } public String next() throws IOException { hasNext(); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { tokenizer = new StringTokenizer(""""); return reader.readLine(); } public int[] nextInts(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; ++i) { res[i] = nextInt(); } return res; } public long[] nextLongs(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; ++i) { res[i] = nextLong(); } return res; } public double[] nextDoubles(int n) throws IOException { double[] res = new double[n]; for (int i = 0; i < n; ++i) { res[i] = nextDouble(); } return res; } public String[] nextStrings(int n) throws IOException { String[] res = new String[n]; for (int i = 0; i < n; ++i) { res[i] = next(); } return res; } } public static void main(String[] args) throws Exception { new Thread(null, new B(), ""Main"", 1 << 28).start(); } private Scanner in = new Scanner(new InputStreamReader(System.in)); private PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); } " B21626,"package gcj.cases.competition.qualification_round_2012; import gcj.main.Case; import java.io.BufferedReader; import java.io.BufferedWriter; import java.util.HashSet; import java.util.Set; public class CaseC implements Case{ private int caseNum; private long min; private long max; private long solution; @Override public void init(int caseNum, BufferedReader br) throws Exception { String strLine; { //caseNum this.caseNum = caseNum; System.out.println(""Act case: "" + this.caseNum); } { //param 1, min max if ((strLine = br.readLine()) != null){ String[] p = strLine.split("" ""); min = Long.parseLong(p[0]); max = Long.parseLong(p[1]); }else{ throw new Exception(""Wrong input""); } } } @Override public void solve() throws Exception { solution=0l; for(long nIter = min; nIter mPairs = new HashSet(); for(int i=0; inIter && m<=max && !mPairs.contains(m)){ solution++; mPairs.add(m); } } } } @Override public void generateOutput(BufferedWriter bw, boolean needBR) throws Exception { bw.write(""Case #"" + this.caseNum + "": "" + this.solution); if(needBR){ bw.newLine(); } } } " B20840," import java.util.HashSet; import java.util.Scanner; import java.util.regex.Pattern; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author alvin */ public class RecycledNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int nTC = sc.nextInt(); for (int tc = 1; tc <= nTC; tc++) { int hasil = 0; int a = sc.nextInt(), b = sc.nextInt(); String batas = Integer.toString(b); char maks = batas.charAt(0); int panjang = batas.length(); for (int n = a; n < b; n++) { String s = Integer.toString(n); if (s.length() == 1) { // System.out.println(s); continue; } if (Pattern.compile(""^(.)\\1*$"").matcher(s).matches()) { // System.out.println(s); continue; } HashSet sudah = new HashSet(); for (int i = s.length() - 1; i >= 1; i--) { char c = s.charAt(i); if (c == '0') { continue; } if (c < s.charAt(0)) { continue; } if (c > maks) { continue; } StringBuilder sb = new StringBuilder(panjang); String cek = sb.append(s.substring(i)).append(s.substring(0, i)).toString(); if ((cek.compareTo(s) > 0) && (cek.compareTo(batas) <= 0)) { sudah.add(cek); } } hasil += sudah.size(); } System.out.format(""Case #%d: %d\n"", tc, hasil); } } } " B20271,"package com.codejam.practice; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) { File inputFile = new File(""C:/Users/SNALLAMA/Desktop/C-large.in""); File outputFile = new File(""C:/Users/SNALLAMA/Desktop/C-large-attempt0.out""); String line = null; int t, a, b, noOfDigits, divider, localnumber; Set finalOP = new HashSet(); //Set to avoid duplicates try { BufferedReader bReader = new BufferedReader(new FileReader(inputFile)); BufferedWriter bWriter = new BufferedWriter(new FileWriter(outputFile)); try { t = Integer.parseInt(bReader.readLine().trim()); for(int index=0;index(); if(noOfDigits!=1){ for(int i=a;i<=b;i++){ for(int localIndex=1;localIndex list = new ArrayList(); File fFile = new File(filename); Scanner scanner = new Scanner(new FileReader(fFile)); try { BufferedWriter out = new BufferedWriter(new FileWriter(""outfilename"")); int k = Integer.valueOf(scanner.nextLine()); for (int j=1; j<=k; ++j){ String szoveg = scanner.nextLine(); Object[] szamok =szoveg.split(""[^0-9]""); int A = Integer.valueOf((String)szamok[0]); int B = Integer.valueOf((String)szamok[1]); String mashogy = new String(); mashogy = mashogy.concat(""Case #""); mashogy = mashogy.concat(((Integer)j).toString()); mashogy = mashogy.concat("": ""); int s=0; for (int i=A; i elerh = new ArrayList(); for (int f=1; fi && ford<=B && !elerh.contains(ford)){ // System.out.println(pow+"" ""+ael+"" ""+aveg+"" ""+ford); elerh.add(ford); s++; } } } // String mashogy = (String)(szoveg.clone()); // System.out.println(szoveg); mashogy = mashogy.concat(((Integer)s).toString()); mashogy = mashogy.concat(""\n""); out.write(mashogy); } out.close(); } catch (IOException e) { } scanner.close(); return; } } " B20918,"package recycledNumbers; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Flow { public static InputData Readin(String filename){ try { FileReader fr = new FileReader(filename); Scanner sc = new Scanner(fr); int Test_Number = sc.nextInt(); System.out.println(""The Number of Tests: ""+Test_Number); int[] A = new int[Test_Number]; int [] B = new int[Test_Number]; for(int i=0;i= a && j <= b) ++count0; j = next[j]; } count += (count0 - 1); } count /= 2; System.out.format(""Case #%d: %d%n"", casenumber, count); } } } " B22178," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author ZuoZhong */ public class Recycled { public static void main(String[] args) throws FileNotFoundException, IOException { File file = new File(""C-large.in""); BufferedReader in = new BufferedReader(new FileReader(file)); BufferedWriter out = new BufferedWriter(new FileWriter(""Recycled_big_output.txt"")); int T = Integer.parseInt(in.readLine()); for (int x = 1; x <= T; x++) { int ans = 0; String[] input = in.readLine().split("" ""); if (Integer.parseInt(input[1]) > 10) { int start = Integer.parseInt(input[0]); int end = Integer.parseInt(input[1]); for (int y = end; y >= start; y--) { String value = Integer.toString(y); int[] history = new int[value.length() - 1]; int pos = 0; for (int z = 0; z < value.length(); z++) { String temp = value + value; int rotated = Integer.parseInt(temp.substring(z, z + value.length())); if (rotated - y == 0) { } else if (rotated > end) { } else if (rotated < y) { } else { Arrays.sort(history); int found = Arrays.binarySearch(history, rotated); if (found < 0) { ans++; history[pos++] = rotated; } } } } } out.write(""Case #"" + x + "": "" + ans); System.out.println(""Case #"" + x + "": "" + ans); out.newLine(); } out.close(); } } " B20079,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for (int i = 0; i < n; i++) { int a = sc.nextInt(); int b = sc.nextInt(); long output = solve(a, b); System.out.println(""Case #"" + (i + 1) + "": "" + output); } } private static long solve(int a, int b) { if (b <= 10) return 0; int start = a; if(a <= 10) start = 11; int count = 0; Set found = new HashSet(); for(int i = start; i < b; i++){ String toshift = String.valueOf(i); int len = toshift.length(); for(int j =1; ja && i < v && !found.contains(v) && !shifted.startsWith(""0"")) { found.add(v); count++; } } found.clear(); } return count; } private static String shift(String toshift, int j) { String pre = toshift.substring(0, j); String post = toshift.substring(j); return post.concat(pre); } } " B21562,"import java.io.*; import java.util.*; class ProblemC { public static void main(String[] args) { try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(""input.txt""); BufferedWriter out = new BufferedWriter(new FileWriter(""output.txt"")); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine, outputLine; int line = 0; int control = 0; int count = 0; int[] check = new int[128]; int A = 0, B = 0; //to get rid of the first line br.readLine(); //Read File Line By Line while ((strLine = br.readLine()) != null) { String tempString = """"; control = 0; count = 0; line++; outputLine = ""Case #""+line+"": ""; //outputLine = """"; for (int i = 0; i < strLine.length(); ++i) { if (strLine.charAt(i) == ' ' || i == strLine.length()-1) { if (i == strLine.length()-1) { tempString += """"+strLine.charAt(i); } switch (control) { case 0 : A = Integer.parseInt(tempString); break; case 1 : B = Integer.parseInt(tempString); break; } control++; tempString = """"; continue; } tempString += """"+strLine.charAt(i); } System.out.println(A+"" ""+B); for (int i = A; i <= B; ++i) { int digit = String.valueOf(i).length(); check = new int[digit]; for (int j = 0; j < digit; ++j) { check[j] = 0; } for (int j = 1; j < digit; ++j) { String testingStr = String.valueOf(i); String anotherStr = testingStr.substring(j)+testingStr.substring(0,j); if (anotherStr.charAt(0) == '0') continue; int pairTesting = Integer.parseInt(anotherStr); if (A <= pairTesting && pairTesting <= B && pairTesting != i) { boolean checked = false; for (int k = 0; k < j; ++k) { if (pairTesting == check[k]) { checked = true; } } if (!checked) { check[j] = pairTesting; count++; } } } } count /= 2; outputLine += """"+count; out.write(outputLine); out.newLine(); System.out.println(outputLine); } //Close the input stream in.close(); out.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B20298,"import java.io.*; import java.util.*; public class Main { Scanner in; PrintWriter out; static final String problemName = ""C""; static void asserT(boolean e) { if (!e) { throw new Error(); } } int solveOne(int a, int b) { int count = 0; int nDigits = ("""" + a).length(); int maxDivisor = 1; for (int i = 1; i < nDigits; i++) { maxDivisor *= 10; } for (int i = a; i <= b; i++) { int maxD = maxDivisor; int divisor = 10; ArrayList list = new ArrayList(); for (int j = 1; j < nDigits; j++) { if (i % divisor >= divisor / 10) { int rem = i % divisor; int top = i / divisor; int value = rem * maxD + top; if (!list.contains(value ) && i < value && value <= b) { //out.println(i + "": "" + value); list.add(value); count++; } } divisor *= 10; maxD /= 10; } } return count; } void solve() { int nTests = in.nextInt(); in.nextLine(); for (int i = 0; i < nTests; i++) { out.println(""Case #"" + (i+1) + "": "" + solveOne(in.nextInt(), in.nextInt())); } } void run() { try { in = new Scanner(new FileReader(""C:/GCJ/"" + problemName + "".in"")); out = new PrintWriter(new FileWriter(""C:/GCJ/"" + problemName + "".out"")); } catch (IOException e) { in = new Scanner(System.in); out = new PrintWriter(System.out); // throw new Error(); } try { solve(); } finally { out.close(); } } public static void main(String[] args) { new Main().run(); } }" B20806,"import java.util.*; import java.io.*; public class Cat { public static void main(String arg[])throws IOException { FileReader fin=new FileReader(arg[0]); FileWriter fout=new FileWriter(""Output.txt""); Scanner src=new Scanner(fin); Scanner t1=new Scanner(src.nextLine()); int cases=(t1.nextInt()); int no=0; int ans=0; while(src.hasNext()) { Scanner temp=new Scanner(src.nextLine()); no++; ans=0; long A=temp.nextInt(); long B=temp.nextInt(); long t=A; while(t<=B) { int count=0; long n=t; do { n=n/10; count++; }while(n!=0); for(int i=1;it) ans++; } t++; } fout.write(""Case #""+no+"": ""+ans+""\n""); } fout.close(); } }" B21091,"package codejam.is; /** * Created with IntelliJ IDEA. * User: ofer * Date: 4/13/12 * Time: 8:47 PM * To change this template use File | Settings | File Templates. */ public interface Test { /** Runs the test on the given input */ public void run(String input); /** Returns the output of the test */ public String getOutput(int testNum); } " B21452,"import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.Scanner; public class cycle { public static Scanner setFileIn(){ try{ Scanner input = new Scanner(new FileInputStream(new File (""test.txt""))); return input; }catch(Exception e){ return null; } } public static Scanner setSysIn(){ Scanner input = new Scanner(new BufferedInputStream(System.in)); return input; } public static int dancer(int n, int s, int p,Scanner input){ int ans = 0; int noSur = 3*p-2; int sur = 3*p-4; if (p==1){ noSur = 1; sur = 1; } if(p==0){ noSur = 0; sur = 0; } while(n>0){ int score = input.nextInt(); //System.out.print("" ""+ score+"" ""); if (score>=noSur){ ans++; }else{ if ((score >= sur)&&(s>0)){ s--; ans++; } } n--; } return ans; } public static int[] move(int i){ String s = """"+i; int[] ans = new int[s.length()-1]; int counter = 0; int temp = i; int weishu = 1; while(temp>9){ temp = temp/10; weishu = weishu*10; } temp = i; while(counteri)&&(pos[j]<=b)&&(test[pos[j]]==0)){ ans++; test[pos[j]]=1; // System.out.println("" ""+ans+"" ""+i+"" ""+pos[j]+"" ""); } } for(int j = 0;j hs = new HashSet(); for (int i = a; i <= b; i++) { String s = i + """"; if (check(s) && s.length() > 1) { for (int k = s.length() - 2, j = 0; k >= 0 && j < s.length() - 1; j++, k--) { String newS = s.substring(k + 1) + s.substring(0, k + 1); int newInt = Integer.parseInt(newS); if (newInt <= b && i < newInt && s.length() == (newInt + """").length() && !newS.equals(s)) { if (i < Integer.parseInt(newS)) hs.add(i + "" "" + newS); else hs.add(newS + "" "" + i); } } } } out.println(""Case #"" + CASE + "": "" + hs.size()); } out.close(); } } " B20385," import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.OutputStream; import java.io.PrintStream; import java.util.HashSet; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author bgamlath */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { // TODO code application logic here Integer.parseInt(""00001""); BufferedReader in = new BufferedReader(new FileReader(""input.txt"")); PrintStream out = new PrintStream(""output.txt""); int n = Integer.parseInt(in.readLine()); for(int i = 1; i<=n; i++){ System.out.println(i); out.println(""Case #"" + i + "": "" + getRes(in.readLine())); } } static int getRes(String str){ String[] m = str.split("" ""); int a = Integer.parseInt(m[0]); int b = Integer.parseInt(m[1]); int res = 0; for(int i = a; i<=b; i++){ res += count(i, b); } return res; } static int count(int i, int b){ HashSet k = new HashSet(); String s = i + """"; int len = s.length(); int t = i; for(int j = 1; j< len; j++){ k.add(Integer.parseInt((s.substring(j) + s.substring(0,j)))); } int res = 0; for(int j: k){ if((j+"""").length()==len && j>i && j<=b) res++; } return res; } } " B20236,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author vhd */ import java.io.*; import java.util.*; import java.math.*; public class NewClass { public static void main(String vhd[]) throws Exception { // FileInputStream fis = new FileInputStream (""jam.txt""); // FileOutputStream out=new FileOutputStream(""outt.txt""); RandomAccessFile file = new RandomAccessFile(""jam.txt"", ""rw""); RandomAccessFile file1 = new RandomAccessFile(""outt.txt"", ""rw""); String t = file.readLine(); int times= Integer.parseInt(t); for( int r= 1 ; r<= times ; r++) { StringTokenizer st= new StringTokenizer(file.readLine()); int num1 = Integer.parseInt(st.nextToken()); int num2= Integer.parseInt(st.nextToken()); char ch ; int count =0; //fis.read(); Scanner sc = new Scanner (System.in); int main1 = num1; int main2= num2; int mid = (num1 + num2 )/2; int n,m; String s1 = (Integer.valueOf(num1)).toString(); String s2 = (Integer.valueOf(num2)).toString(); int temp[] = new int[100]; int len1 = s1.length(); int len2 = s2.length(); int k =0,l =0, d=0; int arr[] = new int[100]; int flag=1; // System.out.print(temp.length); for( int i = num1 ; i< num2 ; i++) { while(ki && arr[k]<=num2 && flag == 1) { temp[d++]= arr[k]; count++; } else if (flag == 0) flag=1; for(int p=0 ; p extends HashMap, V> { private static final long serialVersionUID = 1L; public V put(K1 key1, K2 key2, V value) { return put(Pair.make(key1, key2), value); }; public MultiMapKeyToList getValuesGroupedByKey2() { MultiMapKeyToList key2ToValues = new MultiMapKeyToList(); for (java.util.Map.Entry, V> ent : entrySet()) key2ToValues.put(ent.getKey().getRight(), ent.getValue()); return key2ToValues; } public MultiMapKeyToList getValuesGroupedByKey1() { MultiMapKeyToList key1ToValues = new MultiMapKeyToList(); for (java.util.Map.Entry, V> ent : entrySet()) key1ToValues.put(ent.getKey().getLeft(), ent.getValue()); return key1ToValues; } } " B21985,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package numbers; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; /** * * @author Serban */ public class Input { PrintWriter out; public Input(String fileName) { //C-large-practice.in try { out = new PrintWriter(new File(""result.txt"")); Scanner scan = new Scanner(new File(fileName)); int T = scan.nextInt(); scan.nextLine(); for (int i = 0; i < T; i++) { int A = scan.nextInt(); int B = scan.nextInt(); solve(A, B, digits(A), i); } out.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } private void solve(int A, int B, int digits, int testCase) { out.print(""Case #"" + (testCase + 1) + "": ""); int nr = 0; int n = (int) Math.pow(10, digits); if (A >= 10) { for (int i = A; i < n; i++) { int m = reverse(i, digits); while (m != i) { if (i < m && m <= B) { nr++; } m = reverse(m, digits); } } } System.out.println(nr); out.print(nr); out.println(); out.flush(); } private int digits(int nr) { int digits = 0; while (nr > 0) { nr /= 10; digits++; } return digits; } private int reverse(int nr, int digits) { int last = 0; while (last == 0) { last = nr % 10; nr = nr / 10; } nr = last * (int) Math.pow(10, digits - 1) + nr; return nr; } } " B21090,"package codejam.recycled; import codejam.is.TestAbstract; import java.util.*; /** * Created with IntelliJ IDEA. * User: ofer * Date: 4/14/12 * Time: 2:41 AM * To change this template use File | Settings | File Templates. */ public class RecycledTest extends TestAbstract { @Override public void run(String s) { StringTokenizer tokenizer = new StringTokenizer(s); int min = Integer.parseInt(tokenizer.nextToken()); int max = Integer.parseInt(tokenizer.nextToken()); int tmp = max; int length = 0; while (tmp != 0) { tmp = tmp / 10; length++; } int resultCounter = 0; for (int i = min; i < max; i++) { int rotatedNum = i; Set foundSet = new HashSet(); for (int j = 0; j < length-1; j++) { int end = rotatedNum / 10; int beginning = (int)Math.pow(10,length-1) * (rotatedNum%10); rotatedNum = beginning + end; if (rotatedNum > i && rotatedNum <= max && !foundSet.contains(rotatedNum)) { foundSet.add(rotatedNum); // output.append(""\n""); // output.append(i); // output.append(""->""); // output.append(rotatedNum); resultCounter++; } } } output.append(resultCounter); } } " B22015,"package er.dream.codejam.qual; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import er.dream.codejam.helpers.ProblemSolver; public class RecycledNumbers extends ProblemSolver{ public static void main(String[] args) { new RecycledNumbers().execute(); } @Override protected List handleInput() { List result = new ArrayList(); int[] settings = fileHandler.readIntArray(); for(int line = 0;line foundTransformations = new HashSet(); for(int i=stringLength-1;i>0;i--){ newString = numberString.substring(i)+numberString.substring(0, i); transformedNumber = Integer.parseInt(newString); if(transformedNumber > number && transformedNumber <= max && !foundTransformations.contains(transformedNumber)){ transformations++; foundTransformations.add(transformedNumber); } } return transformations; } } " B21929,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class ProblemB { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub Scanner scanner = new Scanner(new File(""/Users/phan/Downloads/C-large.in"")); PrintWriter pw = new PrintWriter(""/Users/phan/Downloads/outputLarge""); int t = scanner.nextInt(); for (int i = 1; i <= t; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); int cnt = 0; for (int n = A; n <= B; n++) { int[] digits = new int[7]; int tmp = n; int cntdigit = 0; while (tmp > 0) { digits[cntdigit++] = tmp % 10; tmp = tmp / 10; } int[] mm = new int[cntdigit]; int cnt2 = 0; for (int j = 1; j < cntdigit; j++) { int m = 0; for (int k = j - 1; k >= 0; k--) m = m * 10 + digits[k]; for (int k = cntdigit - 1; k >= j; k--) m = m * 10 + digits[k]; if ( (n < m) && (m <= B) ) { boolean b = true; for (int l = 0; l < cnt2; l++) if (mm[l] == m) b = false; if (b) { cnt++; mm[cnt2++] = m; //System.out.println(n + "" "" + m); } } } } pw.println(""Case #"" + String.valueOf(i) + "": "" + String.valueOf(cnt)); } scanner.close(); pw.close(); } } " B21174,"import java.io.File; import java.io.FileNotFoundException; import java.util.Formatter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { private static String solve(int A, int B) { int count = 0; final HashSet seen = new HashSet(10); for (int n = A; n < B; n++) { // Find number of decimal digits. int nTemp = n, digits = 0, unit = 1; while (nTemp > 0) { digits++; nTemp /= 10; unit *= 10; } unit /= 10; int m = n; seen.clear(); for (int i = 1; i < digits; i++) { if (m % 10 == 0) { // Don't process because there will be a leading zero. m /= 10; } else { m = (unit * (m % 10)) + (m / 10); if (m > n && m <= B && !seen.contains(m)) { seen.add(m); count++; } } } } return """" + count; } public static void main(String[] args) throws FileNotFoundException { //String filename = ""C-test.in""; //String filename = ""C-small-attempt0.in""; String filename = ""C-large.in""; assert filename.endsWith("".in""); Scanner in = new Scanner(new File(filename)); Formatter out = new Formatter(new File(filename.replace("".in"", "".out""))); assert in.hasNext(); int T = in.nextInt(); in.nextLine(); for (int t = 0; t < T; t++) { int A = in.nextInt(); int B = in.nextInt(); String ans = solve(A, B); String result; if (t < T - 1) result = String.format(""Case #%d: %s%n"", t + 1, ans); else result = String.format(""Case #%d: %s"", t + 1, ans); out.format(result); System.out.format(result); } out.flush(); out.close(); } } " B20849,"package codezam.exercise.WR1C2012; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import codezam.util.InputFile; /** * Google Code Jam - 2012 RecycledNumbers * * @author Ryan * @since 2012.4.14 */ public class RecycledNumbers { private List lines = new ArrayList(); public RecycledNumbers() { String filename = ""C:/eclipse/eclipse.test/workspace/CodeZam-Exercise/app/src/codezam/exercise/WR1C2012/C-large.in""; InputFile inputFile = new InputFile(); inputFile.setFile(filename); int numberOfInput = Integer.parseInt(inputFile.readLine()); for (int i = 0; i < numberOfInput; i++) { String input = inputFile.readLine(); lines.add(input); } } public void solve() { //String output = getOutputForOneLine((String)lines.get(0)); for (int i = 0; i < lines.size(); i++) { String output = getOutputForOneLine((String)lines.get(i)); System.out.println(""Case #"" + (i + 1) + "": "" + output.toLowerCase()); } } private String getOutputForOneLine(String line) { String[] lineSplit = line.split("" ""); Long a = new Long(lineSplit[0]); Long b = new Long(lineSplit[1]); int digit = a.toString().length(); PairNumbers pairNumbers = new PairNumbers(); long from = a.longValue(); long to = b.longValue(); int total = 0; //System.out.println(""from ""+a+"" to ""+b); for (long i=from; i<=to; i++) { String number = new Long(i).toString(); for (int j=1; j=a && new Long(checker).longValue() <= b && !pairNumbers.containsKey(number, checker)) { pairNumbers.put(number, checker); //System.out.print(number+""->""+checker+"", ""); //if (++total%10==0) { // System.out.println(); //} } } } //System.out.println(); //System.out.println(); return Integer.toString(pairNumbers.size()); } /** * @param args */ public static void main(String[] args) { RecycledNumbers question = new RecycledNumbers(); question.solve(); } } " B21655,"import java.util.*; public class QualC12 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); int npairs = 0; for (int j = A; j <= B; j++) { String s = String.valueOf(j); String ns = s + s; boolean containsRepeat = false; for (int k = 1; k < s.length(); k++) { String rot = ns.substring(k, k + s.length()); int rnum = Integer.valueOf(rot); if (rnum > j && rnum <= B && String.valueOf(rnum).length() == s.length()) { if (containsRepeat(s)) containsRepeat = true; ++npairs; } } if (containsRepeat) --npairs; } System.out.println(""Case #"" + i + "": "" + npairs); } } private static boolean containsRepeat(String s) { if (s.length() % 2 != 0) return false; if (s.substring(0, s.length()/2).equals(s.substring(s.length()/2, s.length()))) { return true; } else return false; } }" B21100,"package recyclednumbers; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; public class SimpleReader { private BufferedReader br; private int line = 0; public SimpleReader() { String filename = prompt(); setReader(filename); } public SimpleReader(String filename) { setReader(filename); } private String prompt() { System.out.println(""Input file: ""); BufferedReader bufr = new BufferedReader( new InputStreamReader(System.in)); String filename = null; try { filename = bufr.readLine(); } catch (IOException e) { System.err.println(""At prompt: "" + e.getMessage()); } return filename; } private void setReader(String filename) { try { br = new BufferedReader(new FileReader(filename)); } catch (IOException e) { System.err.println(e.getMessage()); } } public String readLine() { try { line++; return br.readLine(); } catch (IOException e) { System.err.println(""Line "" + (line - 1) + "": "" + e.getMessage()); return null; } } public int readInt() { return Integer.parseInt(readLine()); } public int[] readIntArray() { String[] tokens = readLine().split("" ""); int[] ret = new int[tokens.length]; for (int i = 0; i < tokens.length; i++) { ret[i] = Integer.parseInt(tokens[i]); } return ret; } public String[] readStringArray() { return readLine().split("" ""); } } " B22000,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.HashSet; import java.util.Set; /** * */ /** * @author Kamlesh Saran Dev * */ public class RecycledPair { long a; long b; /** * @param i * @param j */ public RecycledPair(long a, long b) { this.a = a; this.b = b; } /** * @return */ public long getNumberOfPairs() { long count = 0; for (long n = a; n < b; n++) { Set allCombinations = giveAllCombinations(n, b); count = count + allCombinations.size(); } return count; } /** * @param n * @return */ private Set giveAllCombinations(long n, long b) { Set result = new HashSet(); String nStr = Long.toString(n); for (int i = 1; i < nStr.length(); i++) { String backPart = nStr.substring(i); String frontPart = nStr.substring(0, i); long newNumber = Long.valueOf((backPart + frontPart)); if (n < newNumber && newNumber <= b) { result.add(newNumber); } } return result; } public static void main(String args[]) throws Exception { BufferedReader bufferedReader = new BufferedReader( new FileReader( new File( ""C:\\Documents and Settings\\Kamlesh\\Desktop\\codejam\\C-large.in""))); int numberOfTest = Integer.valueOf(bufferedReader.readLine()); for (int i = 1; i <= numberOfTest; i++) { String line = bufferedReader.readLine(); String limits[] = line.split(""\\ ""); RecycledPair rp = new RecycledPair(Integer.valueOf(limits[0]), Integer.valueOf(limits[1])); System.out.println(""Case #"" + i + "": "" + rp.getNumberOfPairs()); } } } " B21534,"package round1; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; public class Recycled { private int noCases; private int[] minBounds; private int[] maxBounds; private int[] noDigits; private void readFile(String filepath) { try { Scanner sc = new Scanner(new FileInputStream(new File(filepath))); noCases = Integer.parseInt(sc.nextLine()); noDigits = new int[noCases]; minBounds = new int[noCases]; maxBounds = new int[noCases]; for (int i = 0; i < noCases; i++) { String[] line = sc.nextLine().split("" ""); noDigits[i] = line[0].length(); minBounds[i] = Integer.parseInt(line[0]); maxBounds[i] = Integer.parseInt(line[1]); } } catch (FileNotFoundException e) { e.printStackTrace(); } } private int answer(int min, int max, int digits) { HashSet pairs = new HashSet(); for (int n = min; n < max; n++) { for (int d = 1; d < digits; d++) { int m = n / (int) Math.pow(10, d) + n % (int) Math.pow(10, d) * (int) Math.pow(10, digits - d); if (m > n && m <= max) { pairs.add(new Pair(n,m)); } } } return pairs.size(); } public static void main(String args[]) { Recycled r = new Recycled(); r.readFile(args[0]); for (int i = 1; i <= r.noCases; i++) { System.out.println(""Case #"" + i + "": "" + r.answer(r.minBounds[i - 1], r.maxBounds[i - 1], r.noDigits[i - 1])); } } private class Pair { int n, m; public Pair(int n, int m) { this.n = n; this.m = m; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair p = (Pair) o; if (this.n != p.n) return false; if (this.m != p.m) return false; return true; } @Override public int hashCode() { return (n + m) % 3571; } } } " B21687,"import java.io.*; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader bfr = new BufferedReader( new InputStreamReader(System.in)); PrintWriter pr = new PrintWriter(System.out); int n = Integer.parseInt(bfr.readLine()); for (int i = 1; i <= n; i++) { String input[] = bfr.readLine().split("" ""); int max = Integer.parseInt(input[1]); int count = 0; int min = Integer.parseInt(input[0]); for (; min < max; min++) { String moved = String.valueOf(min).charAt( String.valueOf(min).length() - 1) + String.valueOf(min).substring(0, String.valueOf(min).length() - 1); if (Integer.parseInt(moved) <= max && Integer.parseInt(moved) > min) count++; while (Integer.parseInt(moved) != min) { moved = moved.charAt(moved.length() - 1) + moved.substring(0, moved.length() - 1); if (Integer.parseInt(moved) <= max && Integer.parseInt(moved) > min) count++; } } pr.printf(""Case #%d: %d\n"", i, count); pr.flush(); } } } " B21473,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); Set recycled = new HashSet(); int T = in.nextInt(); in.nextLine(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); int res = 0; String n1,n2,n3; for (int j = A; j <= (B - 1); j++) { String n = Integer.toString(j); for (int k = 1; k j && Integer.parseInt(n3) <= B && !recycled.contains(n3)){ recycled.add(n3); res++; } } recycled.clear(); } System.out.println(""Case #""+i+"": ""+res); } } // public static boolean checkRecycled (int n, int m){ // boolean res = false; // // String sn = Integer.toString(n); // String sm = Integer.toString(m); // String snTemp,snTemp2,snTemp3; // if (n>10 && (sn.length() == sm.length())){ // for (int i = 1; i outputList = new ArrayList(); for(int i = 1; i <= noTestcases && (sLine = br.readLine()) != null; i++) { String[] numLimits = sLine.split("" ""); int lowerLimit = Integer.parseInt(numLimits[0]); int upperLimit = Integer.parseInt(numLimits[1]); int noRecycledPairs = getRecycledpairsCount(lowerLimit, upperLimit); System.out.println(""Case #"" + i + "": "" + noRecycledPairs); outputList.add(""Case #"" + i + "": "" + noRecycledPairs); } writeOutput(outputList); br.close(); fis.close(); } private static void writeOutput(List lines) throws Exception { FileWriter fw = new FileWriter(""D:/Eclipse Workspaces/ws_hyperbola/Recycled Numbers/src/C-large-attempt0.out""); PrintWriter pw = new PrintWriter(fw); for(String line : lines) { pw.println(line); } pw.flush(); pw.close(); } private static int getRecycledpairsCount(int smallerNumber, int biggerNumber) { int result = 0; if(biggerNumber < 10) return 0; // 1 digit numbers if(isBetween(smallerNumber, 10, 99)) { // 2 digit numbers Set setPair = new HashSet(); for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 1); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } //System.out.println(setPair.toString()); result = result + setPair.size(); } else if(isBetween(smallerNumber, 100, 999)) { // 3 digit numbers Set setPair = new HashSet(); /* one digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 1); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* two digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 2); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } //System.out.println(setPair.toString()); result = result + setPair.size(); } else if(isBetween(smallerNumber, 1000, 9999)) { // 4 digit numbers Set setPair = new HashSet(); /* 1 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 1); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 2 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 2); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 3 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 3); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } //System.out.println(setPair.toString()); result = result + setPair.size(); } else if(isBetween(smallerNumber, 10000, 99999)) { // 5 digit numbers Set setPair = new HashSet(); /* 1 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 1); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 2 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 2); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 3 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 3); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 4 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 4); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } result = result + setPair.size(); } else if(isBetween(smallerNumber, 100000, 999999)) { // 6 digit numbers Set setPair = new HashSet(); /* 1 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 1); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 2 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 2); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 3 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 3); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 4 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 4); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 5 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 5); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } result = result + setPair.size(); } else if(isBetween(smallerNumber, 1000000, 2000000)) { // 7 digit numbers Set setPair = new HashSet(); /* 1 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 1); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 2 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 2); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 3 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 3); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 4 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 4); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 5 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 5); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } /* 5 digit shift */ for(int num = smallerNumber; num <= biggerNumber; num++) { int recycledNum = shiftDigit(num, 6); if(recycledNum != num && isBetween(recycledNum, smallerNumber, biggerNumber)) { setPair.add(new RecycledPair(num, recycledNum)); } } result = result + setPair.size(); } return result; } private static boolean isBetween(int number, int lowerLimit, int upperLimit) { return number >= lowerLimit && number <= upperLimit; } private static int shiftDigit(int number, int digitsNo) { String sNum = String.valueOf(number); int index = sNum.length() - digitsNo; String sNewNumber = sNum.substring(index) + sNum.substring(0, index); return Integer.parseInt(sNewNumber); } } " B20671,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class RecycledPair { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(""input.txt"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""output.txt"")); int N; N = Integer.parseInt(br.readLine()); int k,i; HashSet set; for (k = 0; k < N; k++) { String[] line = br.readLine().split("" ""); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); int counter = 0; for (i = A; i < B; i++) { set = new HashSet(); updateSet(set, i); counter += count(set,i,B); } bw.write(""Case #"" + (k+1) + "": "" + counter); bw.newLine(); // showSet(set); } br.close(); bw.close(); } catch (IOException io) { } } private static void updateSet(HashSet set, int num) { String numStr = num + """"; char[] numChar = numStr.toCharArray(); int i, j; for (i = numChar.length - 1; i >= 1; i--) { if (numChar[i] != '0') { char[] newNum = new char[numChar.length]; j = i; int counter = 0; newNum[counter] = numChar[j]; counter++; while (counter < numChar.length) { if (j < numChar.length - 1) { j++; } else { j = 0; } newNum[counter] = numChar[j]; counter++; } set.add(Integer.parseInt(new String(newNum))); } } set.add(num); } private static int count(HashSet set, int low, int high){ int count = 0; for(Integer s:set) if(s>low && s<=high) count++; return count; } } " B21919," import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String args[]) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { int a = in.nextInt(); int b = in.nextInt(); int ans = 0; int bten = 1; for (int j = a; j <= b; j++) { while (j/bten*10!=0) bten*=10; int l = 0; HashSet aa = new HashSet(); for (int ten = 10;j/ten>0;ten*=10) { int f = j / ten; int s = j % ten; int m =s * (bten/ten) + f; if (m>j && m<=b) { aa.add(m); } } ans+=aa.size(); } System.out.println(""Case #""+(i+1)+"": ""+ans); } } } " B20788,"package com.codegem.zaidansari; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; class Pair { int n, m; public Pair(int n, int m) { super(); this.n = n; this.m = m; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * (m + n); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if ((m == other.m && n == other.n) || (m == other.n && n == other.m)) return true; return false; } @Override public String toString() { return ""Pair [n="" + n + "", m="" + m + ""]""; } } public class ProblemC { Set pairs = new HashSet(); int startRange, endRange; private boolean isInRange(int value) { return value >= startRange && value <= endRange; } private int processRange() { for (int value = startRange; value <= endRange; value++) { List possiblePairValues = getPossiblePairValue(value); for (int pairValue : possiblePairValues) { pairs.add(new Pair(value, pairValue)); } } return pairs.size(); } private List getPossiblePairValue(int value) { String valueStr = String.valueOf(value); int valueStrLength = valueStr.length(); List possiblePairs = new ArrayList(); int pairValue; for (int index = 0; index < valueStrLength; index++) { String pairValueStr = valueStr.substring(valueStrLength - index - 1) + valueStr.substring(0, (valueStrLength - index - 1)); if (pairValueStr.charAt(0) != '0') { pairValue = Integer.parseInt(pairValueStr); if ((pairValue != value) && (isInRange(pairValue))) { possiblePairs.add(pairValue); } } } return possiblePairs; } public ProblemC(int startRange, int endRange) { super(); this.startRange = startRange; this.endRange = endRange; } public static void main(String[] args) { long startTime = System.currentTimeMillis(); // File file = new File(""/Users/zaansari/Desktop/CodeGem2012/InputFiles/ProblemC-Small.txt""); File file = new File(""/Users/zaansari/Desktop/CodeGem2012/InputFiles/ProblemC-Large.txt""); List inputData = CodeGemUtil.getInputValues(file); int noOfInputs = Integer.parseInt(inputData.get(0)); inputData.remove(0); List outputData = new ArrayList(); for (int index = 0; index < noOfInputs; index++) { String[] inputArray = inputData.get(index).split("" ""); outputData.add("""" + new ProblemC(Integer.parseInt(inputArray[0]), Integer.parseInt(inputArray[1])).processRange()); } // boolean createdOutputFile = CodeGemUtil.createOutputFile(outputData, ""ProblemC-Small-Output.txt""); boolean createdOutputFile = CodeGemUtil.createOutputFile(outputData, ""ProblemC-Large-Output.txt""); if (createdOutputFile) { System.out.println(""Successfully created output file""); } else { System.out.println(""Failed to create output file""); } long endTime = System.currentTimeMillis(); System.out.println(""Total Time in seconds="" + ((endTime - startTime) / 1000)); } } " B21198,"import java.util.Scanner; public abstract class Question extends Thread{ protected Result result; protected Counter counter; public Question(Result result, Counter counter) { super(); this.result = result; this.counter = counter; } public abstract void readInput(Scanner scanner); public void solveTestCase(){ setResult(solution()); } public abstract String solution(); public String getResult() { return result.output; } public void setResult(String output) { this.result.output = output; } public void run() { solveTestCase(); //System.out.println(result); counter.increase(); } } " B22108,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class MainC { private static boolean esValido(Integer n,Integer A,Integer B,boolean comp) { int i=0; boolean valido=false; if (!comp || (n>=A && n9) { while((i+1) conj) { String aux=rotar(i.toString()); Integer num=Integer.parseInt(aux); if (esValido(num,A,B,true)) { if (!i.equals(num)) { conj.add(new Par(i,num)); } //System.out.println(""Se encuentra el par "" + i + "", ""+num + "" ya que esValido ""+num+"" en el intervalo ""+ A+ ""-""+B); } for (int j=0;j conj=new HashSet(); for (int i=A;i map; public static void main(String args[])throws IOException { initFiles(); readFiles(); System.out.println(""Done""); } private static void readFiles()throws IOException { int n = Integer.parseInt(br.readLine()); for(int i=1; i<=n; i++) { System.out.println(""Case: "" + i); StringTokenizer tokens = new StringTokenizer(br.readLine()); int A = Integer.parseInt(tokens.nextToken()); int B = Integer.parseInt(tokens.nextToken()); int count = findPairs(A, B); pw.println(""Case #"" + i + "": "" + count); } pw.close(); br.close(); } private static int findPairs(int A, int B) { map = new HashMap(); int numRecycleables = 0; for(int i = A; i <= B; i++) { numRecycleables += getNumRecycled(i, B); } return map.size(); } private static int getNumRecycled(int n, int B) { String nStr = """" + n; int count = 0; for(int i = 1; i < nStr.length(); i++) { String mStr = nStr.substring(i) + nStr.substring(0, i); int m = Integer.parseInt(mStr); if(m > n && m <= B) { //System.out.println(n + ""--> "" + m); map.put(nStr + mStr, true); count++; } } return count; } private static void initFiles()throws IOException { br = new BufferedReader(new FileReader(""C-large.in"")); pw = new PrintWriter(new FileWriter(""Recycle.out"")); } } " B20014,"import java.io.*; import java.util.*; import java.math.*; public class Main { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokenizer=null; public static void main(String[] args) throws IOException { new Main().execute(); } void debug(Object...os) { System.out.println(Arrays.deepToString(os)); } int ni() throws IOException { return Integer.parseInt(ns()); } long nl() throws IOException { return Long.parseLong(ns()); } double nd() throws IOException { return Double.parseDouble(ns()); } String ns() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(br.readLine()); return tokenizer.nextToken(); } String nline() throws IOException { tokenizer=null; return br.readLine(); } //Main Code starts Here int totalCases, testNum; void execute() throws IOException { totalCases = ni(); for(testNum = 1; testNum <= totalCases; testNum++) { input(); System.out.print(""Case #""+testNum+"": ""); solve(); } } class Pair implements Comparable { int a,b; Pair(int _a,int _b) { a=_a; b=_b; } public int compareTo(Pair x) { if(a == x.a) return b-x.b; return a-x.a; } public boolean equals(Pair x) { return a==x.a && b==x.b; } public String toString() { return ""(""+a+"",""+b+"")""; } } HashSet m; void solve() { int count = 0; for(int i=a;i<=b;i++) { m = new HashSet(); String s = Integer.toString(i); int l = s.length(); for(int j=0;ji && n<=b) m.add(n); } count+=m.size(); } System.out.println(count); System.err.println(count); } void printarr(int [] a,int b) { for(int i = 0;i<=b;i++) { if(i==0) System.out.print(a[i]); else System.out.print("" ""+a[i]); } System.out.println(); } int a,b; boolean input() throws IOException { a=ni(); b=ni(); return true; } }" B20169,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; public class RecycledNumbers { public static void main(String[] args) { try { run(); } catch (Exception e) { e.printStackTrace(); } } private static void run() throws Exception { writeResult(calc(readInputData())); } private static int[] calc(Data[] data) { int[] res = new int[data.length]; for (int i = 0; i < data.length; i++) { res[i] = calc(data[i]); // System.out.println(""Case #"" + (i + 1) + "": "" + res[i]); } return res; } private static int calc(Data data) { if (data.len <= 1) return 0; int res = 0; for (int i = data.a; i < data.b; i++) { int pp = (int)Math.pow(10, data.len - 1); for (int j = 1, p = 10; j < data.len; j++, p *= 10, pp /= 10) { int x = i % p; int y = i / p; int rev = x * pp + y; if (x == y) break; if (rev > i && rev >= data.a && rev <= data.b) res++; } } return res; } private static Data[] readInputData() throws Exception { InputStream in = RecycledNumbers.class.getResourceAsStream(""/test.in""); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int total = Integer.parseInt(br.readLine()); Data[] data = new Data[total]; for (int i = 0; i < total; i++) data[i] = new Data(br.readLine().split(""\\s"")); in.close(); return data; } private static void writeResult(int[] res) throws Exception { BufferedWriter out = new BufferedWriter(new FileWriter(""d:\\!!!\\test.out"")); for (int i = 1; i <= res.length; i++) out.write(""Case #"" + i + "": "" + res[i - 1] + ""\n""); out.close(); } } class Data { final int len; final int a; final int b; Data(int a, int b) { this.a = a; this.b = b; this.len = 0; } Data(String[] str) { this.a = Integer.parseInt(str[0]); this.b = Integer.parseInt(str[1]); this.len = str[0].length(); } @Override public String toString() { return ""["" + a + "";"" + b + ""]""; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Math.min(a, b); result = prime * result + Math.max(a, b); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Data other = (Data)obj; if (a != other.a) return false; if (b != other.b) return false; return true; } } " B21360,"import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; public class CodeJam3 { private static HashMap map = new HashMap(); private static ArrayList results = new ArrayList(); public static void main (String args[]) throws IOException { Scanner scanner = new Scanner(args[0]); int numToParse = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < numToParse; i++) { int count = 0; String string = scanner.nextLine(); StringTokenizer st = new StringTokenizer(string); int firstInt = Integer.parseInt(st.nextToken()); int secondInt = Integer.parseInt(st.nextToken()); String s = """" + firstInt; int length = s.length(); for (int j = firstInt; j <= secondInt; j++) { ArrayList list = new ArrayList(); for (int k = 1; k < length; k++) { String localString = """" + j; String sub1 = localString.substring(0, k); String sub2 = localString.substring(k, length); String newString = sub2 + sub1; int integer = Integer.parseInt(newString); if (!list.contains(integer) && integer > j && integer <= secondInt) { count++; list.add(integer); } } } String result= ""Case #"" + (i + 1) + "": "" + count; System.out.println(result); } } } " B20604,"package com.google.codejam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class ProblemB { /** * @param args */ public void calculate(int numTestCase, int a, int b){ int count = 0 ; if(b<10 || a==b) count = 0; else{ for ( int i=a ; i <= b; i++){ String num = String.valueOf(i); String correctNum = String.valueOf(i); String finalStr ="""" ; while(!correctNum.equals(finalStr)){ String first = num.substring(0,1); String rest = num.substring(1); finalStr = rest+first ; num = finalStr ; if(finalStr.startsWith(""0"") || first.equals(rest)) continue; int num2 = Integer.parseInt(finalStr); if(num2<=b && num2!=i && i B || curNum < A || used[curNum - A]); else{ used[curNum - A] = true; cnt ++; } int lastD = curNum % 10; curNum /= 10; curNum = (int) (curNum + Math.pow(10, size - 1) * lastD); } rst += cnt * (cnt-1)/2; } return rst +""""; } private static void solve(String inputPath, String filepath) { FileHelper fHelper = new FileHelper(inputPath); String[] inputStr= new String[fHelper.getTotalSize()]; List rstList = new ArrayList(); fHelper.init(inputStr); for (String str : inputStr) { rstList.add(getPairCount(str)); } rstList = format(rstList); FileHelper.writeFile(filepath, rstList); } public static void main(String[] args) { String inputPath = ""C:\\Users\\xiaohfan\\Desktop\\C-large.in""; String filepath = ""C:\\Users\\xiaohfan\\Desktop\\output.txt""; Gcj2012c.solve(inputPath, filepath); } public static List format(List rstList) { List outputList = new ArrayList(); for(int i = 0; i < rstList.size();++i ){ outputList.add(""Case #""+ (i+1) +"": ""+rstList.get(i)); } return outputList; } } " B21125,"package quiz2012.quiz3; import java.util.HashSet; import java.util.Set; import domain.QuizSolver; import domain.QuizTestCaseInput; import domain.QuizTestCaseOutput; public class Quiz3Solver implements QuizSolver { @Override public QuizTestCaseOutput solve(QuizTestCaseInput testCaseInput) { Quiz3TestCaseInput input = (Quiz3TestCaseInput) testCaseInput; int numberOfRecycledPairs = 0; int n = input.getN(); String nAsString = String.valueOf(n); int numberOfDigitsOfN = nAsString.length(); int m = input.getM(); // TODO: Remove if the following case can be generalized. if (numberOfDigitsOfN == 1) { return new Quiz3TestCaseOutput(numberOfRecycledPairs); } for (int i = n; i < m; i++) { Set recycledValueSet = new HashSet(); for (int j = 1; j < numberOfDigitsOfN; j++) { int recycledValue = shiftDigitsLeft(i, j); if (recycledValue > i && recycledValue <= m) { recycledValueSet.add(recycledValue); System.out.println(i + "", "" + recycledValue); } } numberOfRecycledPairs += recycledValueSet.size(); } return new Quiz3TestCaseOutput(numberOfRecycledPairs); } public int shiftDigitsLeft(int n, int numberOfShifts) { String nAsString = String.valueOf(n); StringBuffer sb = new StringBuffer(); int numberOfDigitsOfN = nAsString.length(); for (int i = 0; i < numberOfDigitsOfN; i++) { sb.append(nAsString.charAt((numberOfDigitsOfN + i - numberOfShifts) % numberOfDigitsOfN)); } return Integer.valueOf(sb.toString()); } } " B22025,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam2012; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; /** * * @author Luis Sergio Curay */ public class c { public c() { Scanner in= new Scanner(System.in); int t= in.nextInt(); for (int i = 0; i < t; i++) { int a= in.nextInt(); int b= in.nextInt(); HashSet nums= new HashSet(); int res= 0; for (int j = a; j <= b; j++) { HashSet comb= combinaroty(j); for (Integer num : comb) { if(num >= a && num <= b && num != j) { if(!nums.contains(num)) { nums.add(j); res++; } } } } System.out.println(""Case #"" + (i + 1) + "": "" + res); } } public int reverse(int n) { String num= String.valueOf(n); for (int i = 0; i < num.length() - 1; i++) { num= num.substring(num.length() - 1) + num.substring(0, num.length() - 1); } return Integer.parseInt(num); } private HashSet combinaroty(int n) { HashSet res= new HashSet(); String num= String.valueOf(n); for (int i = 0; i < num.length() - 1; i++) { num= num.substring(num.length() - 1) + num.substring(0, num.length() - 1); res.add(Integer.parseInt(num)); } return res; } }" B22054,"package google.loader; public interface Challenge { String getResult(); } " B20340,"import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String args[]) { Scanner in = new Scanner(System.in); int cases; cases = in.nextInt(); in.nextLine(); for(int i = 0; i < cases; i ++ ) { int a = in.nextInt(); int b = in.nextInt(); HashSet found = new HashSet(); int total = 0; if( b >= 10) { if( a < 10 ) { a = 10; } for( int j = a; j <= b; j++ ) { if( !found.contains(j) ) { String theNum = String.valueOf(j); int morphed; theNum = theNum.charAt(theNum.length() -1) + theNum.substring(0, theNum.length()-1); morphed = Integer.valueOf(theNum); while( morphed != j ) { if( !found.contains(morphed) && morphed >=a && morphed <=b ) { total ++; found.add(j); } theNum = theNum.charAt(theNum.length() -1) + theNum.substring(0, theNum.length()-1); morphed = Integer.valueOf(theNum); } } } } System.out.println(""Case #"" + (i+1) + "": "" + total ); } } } " B21147,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String[] args) { try { Scanner in = new Scanner(new File(""C:/Users/Ross/Downloads/C-large.in"")); int T = in.nextInt(); String out = """"; for(int i = 0; i < T; i++) { int A = in.nextInt(); int B = in.nextInt(); int count = 0; for(int j = A; j < B; j++) { String num = Integer.toString(j); ArrayList pairs = new ArrayList(); for(int k = 1; k < num.length(); k++) { String num2 = num.substring(num.length()-k,num.length())+num.substring(0,num.length()-k); int nnum = Integer.parseInt(num2); if(nnum > j && nnum <= B && Integer.toString(nnum).length()==num.length()){ if(pairs.indexOf(nnum) == -1) { count++; pairs.add(nnum); } } } } out += ""Case #"" + (i+1) + "": ""; out += count + ""\n""; } System.out.println(out); } catch(Exception e) { e.printStackTrace(); } } } " B20943,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new FileReader(""C-large.in""))) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(""C-large.out""))) { String line = reader.readLine(); int numCases = Integer.parseInt(line); Scanner scanner; for(int caseIdx = 0; caseIdx < numCases; caseIdx++) { scanner = new Scanner(reader.readLine()); int A = scanner.nextInt(); int B = scanner.nextInt(); int result = 0; String sA = String.valueOf(A); String sB = String.valueOf(B); Set vs = new HashSet<>(); for(int t = A; t <= B; t++) { String st = String.valueOf(t); for(int s = 1; s < st.length(); s++) { if(st.charAt(s) == '0') continue; // no leading zeroes String ost = st.substring(s) + st.substring(0, s); if(st.compareTo(ost) > -1) continue; if(ost.compareTo(sB) > 0) continue; if(ost.compareTo(sA) < 0) continue; vs.add( st + ""_"" + ost); vs.add(ost + ""_"" + st); } } result = vs.size() / 2; String caseOutput = String.format(""Case #%d: %d"", caseIdx + 1, result); System.out.println(caseOutput); writer.append(caseOutput); writer.newLine(); } } } catch(IOException ioEx) { ioEx.printStackTrace(); } } } " B20682,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Recycle { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int i = 1; i <= T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int result = getResult(A, B); System.out.println(""Case #"" + i + "": "" + result); } } private static int getResult(int A, int B) { int result = 0; int numDigits = Integer.toString(A).length(); Set processed = new HashSet(); for (int num = A; num <= B; num++) { if (processed.contains(num)) continue; processed.add(num); int count = 0; for (int rotated = 1; rotated < numDigits; rotated++) { int tp = tenpow(rotated); int dropped = num % tp; int stay = num / tp; int recyclednumber = dropped * tenpow(numDigits - rotated) + stay; if (processed.contains(recyclednumber)) continue; processed.add(recyclednumber); if (recyclednumber >= A && recyclednumber <= B) count++; } if (count == 0) continue; count +=1; result += ncr(count, 2); } return result; } private static int ncr(int n, int r) { return factorial(n)/(factorial(n-r) * factorial(r)); } private static int tenpow(int exp) { int res = 1; for (int i = 0; i < exp; i++) res *= 10; return res; } private static int factorial(int n) { if (n == 0) return 1; return n * factorial(n-1); } } " B20449,"/* Original template used was test.java from USACO's training pages. Name: Ante Qu Problem: Recycled Numbers Gmail Account: quante0 */ import java.io.*; import java.util.*; class recycledNumbers { public static void main (String [] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster BufferedReader f = new BufferedReader(new FileReader(""C-large.in"")); // input file name goes above PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""out.txt""))); int T=Integer.parseInt(f.readLine()); for(int i=0;i B) return false; if (x == i) return false; return true; } private static int shift(int current, int by, int length) { int power = (int) Math.pow(10, by); int shift = (int) Math.pow(10, length - by); return (current % power) * shift + current / power; } public static char translateChar(char current) { if (current == ' ') return ' '; if (current == 'a') return 'y'; if (current == 'b') return 'h'; if (current == 'c') return 'e'; if (current == 'd') return 's'; if (current == 'e') return 'o'; if (current == 'f') return 'c'; if (current == 'g') return 'v'; if (current == 'h') return 'x'; if (current == 'i') return 'd'; if (current == 'j') return 'u'; if (current == 'k') return 'i'; if (current == 'l') return 'g'; if (current == 'm') return 'l'; if (current == 'n') return 'b'; if (current == 'o') return 'k'; if (current == 'p') return 'r'; if (current == 'q') return 'z'; if (current == 'r') return 't'; if (current == 's') return 'n'; if (current == 't') return 'w'; if (current == 'u') return 'j'; if (current == 'v') return 'p'; if (current == 'w') return 'f'; if (current == 'x') return 'm'; if (current == 'y') return 'a'; if (current == 'z') return 'q'; return '.'; } }" B20828,"import java.io.*; public class TaskC { public static void main(String[] args) { try { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.valueOf(input.readLine()); for(int z=1; z<=t; z++) { int out = 0; String[] line = input.readLine().split("" ""); int A = Integer.valueOf(line[0]), B = Integer.valueOf(line[1]); for(int i=A; i<=B; i++) bylo[i] = false; // czas na rotacje ileRot = line[0].length() - 1; for(int i=A; i<=B; i++) if(bylo[i] == false) { bylo[i] = true; int dodajnik = 1; int liczba = i; String ls = Integer.toString(liczba); // System.out.println(""Rotuje "" + ls); // rotuje ile sie da for(int rot=0; rot=A && liczba <= B) { // System.out.println(""Zgadza sie z "" + ls); bylo[liczba] = true; out += dodajnik; dodajnik += 1; } } } System.out.println(""Case #"" + z + "": "" + out); } } catch (Exception e) { System.err.println(e); } } static int ileRot; static boolean[] bylo = new boolean[2000001]; } " B20575,"package codejam; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.HashMap; import java.util.Map; public class RecycledNumbers { private StreamTokenizer in; private PrintWriter out; private Map map = new HashMap(); //private Map pair = new HashMap(); public static void main (String[] args) throws IOException { new RecycledNumbers().soilve(); } int nextInt () throws IOException { in.nextToken(); return (int)in.nval; } void soilve () throws IOException { in = new StreamTokenizer(new BufferedReader(new FileReader(""./src/codejam/input.txt""))); out = new PrintWriter(new FileWriter(""./src/codejam/output.txt"")); int t = nextInt(); for (int i = 0; i < t; i++) { int cnt = 0; int a = nextInt(); int b = nextInt(); int len = Chain.getLen(a); for (int j = a; j <= b; j++) { cnt += check(a, b, j, len); } out.println(""Case #"" + (i + 1) + "": "" + cnt); } out.flush(); } int check(int a, int b, int q, int len) { //Chain chain = new Chain(q); if (map.containsKey(q)) { return map.get(q); } int first = q; int cnt = 0; for (int i = 1; i < len; i++) { int last = q % 10; q /= 10; q += last * (int)Math.pow(10, len - 1); if ((first < q) && (a <= q) && (q <= b)) { cnt++; } } map.put(first, cnt); return cnt; } } //class Pair { // int a, b; // // Pair(int a, int b) { // if (a < b) { // this.a = b; // this.b = a; // } else { // this.a = a; // this.b = b; // } // } // // @Override // public boolean equals(Object o) { // Pair p = (Pair)o; // return p.a == a && p.b == b; // } //} class Chain { int a; Chain(int a) { this.a = a; } @Override public boolean equals(Object b) { Chain c = (Chain)b; if (c.a == a) { return true; } // int lenC = getLen(c.a); // int lenA = getLen(a); // if (lenA != lenC) { // return false; // } // // if (lenA == 1) { // return a == c.a; // } // // for (int i = 1; i < lenA; i++) { // int last = c.a % 10; // c.a /= 10; // c.a += last * (int)Math.pow(10, lenA - 1); // if (c.a == a) { // return true; // } // } // return false; } public static int getLen (int a) { int i = 1; int len = 0; while (a / i != 0) { len++; i *= 10; } return len; } } " B21900,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.Set; import java.util.TreeSet; public class RecycledNumbers { public static void main(String[] args) throws IOException { System.setErr(new PrintStream(""qualification/C-large.out"")); FileReader reader = new FileReader(""qualification/C-large.in""); BufferedReader br = new BufferedReader(reader); int tc = Integer.parseInt(br.readLine()); for (int t = 0; t < tc; t++) { String[] nums = br.readLine().split(""\\s""); String a = nums[0]; String b = nums[1]; int min = Integer.parseInt(a); int max = Integer.parseInt(b); int answer = 0; for (int i = min; i < max; i++) { String n = String.valueOf(i); Set set = new TreeSet(); for (int j = 0; j < n.length(); j++) { set.add(n.substring(j) + n.substring(0, j)); } for (String s : set) { if (n.compareTo(s) < 0 && b.compareTo(s) >= 0) { answer++; } } } System.out.printf(""Case #%d: %d\n"", t + 1, answer); System.err.printf(""Case #%d: %d\n"", t + 1, answer); } } } " B21344,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.*; /** * @author Seitaro Sakoda * */ public class RecycledNumbers { private static final HashMap cache = new HashMap(); private static final ArrayList list = new ArrayList(); private static final long MASK = 10000000; private static void init(){ for(int i=10;i<=2000000;i++){ int L = (int)Math.log10(i); int D = (int)Math.pow(10.0, L); int k = i; for(int j=0;j ans = new ArrayList(); long start = System.currentTimeMillis(); init(); System.out.println(""INIT:""+(System.currentTimeMillis()-start)+"" ms""); for(int not=0;not=A && (int)(a%MASK)<=B) ans++; } return ans; } static class DataReader { public BufferedReader br; public DataReader(String filename) throws Exception { br = new BufferedReader(new FileReader(filename)); } public DataReader() throws Exception { this(""data.in""); } private String readLine() throws Exception { return br.readLine(); } public int readInt() throws Exception { return Integer.parseInt(readLine()); } public int[] readInts() throws Exception { String[] tmp = readLine().split("" ""); int[] ret = new int[tmp.length]; for(int i=0;i= A && m <= B) k++; } ans += k * (k-1) / 2; } out.printf(""Case #%d: %d\n"", t+1, ans); } if (out != System.out) out.close(); } } " B21542,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class recycled { static int f_recycled(String s_min,String s_max){ int num_recycled=0; int min=Integer.parseInt(s_min); int max=Integer.parseInt(s_max); //System.out.println(""______________________________________\nNúmeros reciclados entre ""+s_min+"" y ""+s_max); if (max>10){ int cab_max=s_max.charAt(0); int cab_min, num; String string_v; int i, j, final_v; String string_final_v; List soluciones_valor=new ArrayList(); boolean enc; int v=min; while(v<=max){ string_v=String.valueOf(v); cab_min=Character.getNumericValue(string_v.charAt(0)); for(i=1;i= cab_min ){ // cambio de dígitos no es menor que el valor original string_final_v=string_v.substring(i)+string_v.substring(0, i); final_v=Integer.parseInt(string_v.substring(i)+string_v.substring(0, i)); // back + front if(string_v.length()==string_final_v.length() && min<=v && v hashMap = new HashMap(); public static final void main(String[] args){ try { //fileReader = new FileReader(input_test); //fileReader = new FileReader(input_small); fileReader = new FileReader(input_large); buffReader = new BufferedReader(fileReader); fileWriter = new FileWriter(""/home/qimeng/problemC.out""); buffWriter = new BufferedWriter(fileWriter); int total_size = Integer.parseInt(buffReader.readLine()); //iterate through every input line for(int i=1; i<=total_size; i++){ String[] str = buffReader.readLine().split("" ""); int a = Integer.parseInt(str[0]); int b = Integer.parseInt(str[1]); System.out.println(""Case #"" +i+"": "" + recycleAlgorithm(a,b)); buffWriter.write(""Case #"" +i+"": "" + recycleAlgorithm(a,b)); buffWriter.newLine(); buffWriter.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { buffWriter.flush(); buffWriter.close(); buffReader.close(); fileReader.close(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } public static int recycleAlgorithm(int a,int b){ int count=0; for (int i=b;i>=a;i--){ ArrayList permutations = getPermutations(i+""""); for (Integer ti : permutations){ if (ti>=a && ti<=b && ti getPermutations(String i){ ArrayList permutations = new ArrayList(); String shift=i.substring(1)+i.substring(0,1); while (!shift.equalsIgnoreCase(i)){ int parsedInt=Integer.parseInt(shift); int digits=new String(parsedInt+"""").length(); if (digits==i.length()){ permutations.add(parsedInt); } shift=shift.substring(1)+shift.substring(0,1); } return permutations; } // private static int recycleAlgorithm(int a, int b){ // result = 0; // // for(int i=a; i<=b; i++){ // com = 0; // String str_i = Integer.toString(i); // int len_i = str_i.length(); // // chars --> all combinations // // all combinations --> numbers // // // // for all numbers: // // check each number if in range // // if so, setbit(number), com++ // // // //result + all pairs from com // showPattern("""", str_i); // // } // // return result; // } // private static void showPattern(String st, String chars) { // if (chars.length() <= 1){ // //System.out.println(st + chars); // int num = Integer.parseInt(st+chars); // if(num>= a && num<=b){ // bit.set(num); // } // com++; // } // else{ // for (int i = 0; i < chars.length(); i++) { // try { // String newString = chars.substring(0, i) // + chars.substring(i + 1); // showPattern(st + chars.charAt(i), newString); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // } // private static int permutation(int x){ // return fact(x) / fact(x-2); // } // private static int fact(int x) { // if(hashMap.containsKey(x)){ // return hashMap.get(x); // } // else { // int re = 0; // if(x == 0) return 0; // else if(x == 1) return 1; // else { // re = x*fact(x-1); // hashMap.put(x, re); // return re; // } // } // } } " B21825,"package QR_2012; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.TreeSet; public class C { static BufferedWriter writer; public static void main(String[] args) throws IOException { writer = new BufferedWriter(new FileWriter(""output.out"")); Scanner reader = new Scanner(new FileReader(""input.in"")); int nt = reader.nextInt(); reader.nextLine(); for(int tc = 1; tc <= nt; tc++) { writer.write(""Case #"" + tc + "": ""); int a = reader.nextInt(); int b = reader.nextInt(); int total = 0; for(int n = a; n < b; n++) { int count = count(n, b); total += count; } writer.write(Integer.toString(total)); writer.newLine(); } writer.close(); } static int count(int n, int b) { int count = 0; String s = Integer.toString(n); int l = s.length(); TreeSet T = new TreeSet(); for(int i = 1; i < l; i++) { s = s.substring(1) + s.charAt(0); if(!T.contains(s)) { T.add(s); int m = Integer.parseInt(s); if(n < m && m <= b) { count++; } } } return count; } } " B21779,"import java.io.*; public class template { public static void main(String[] args) throws IOException { StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); //PrintWriter out = new PrintWriter(""output.txt""); in.nextToken(); int count = (int)in.nval; for(int c = 1 ; c <= count ; c++) { int rotations = 0; in.nextToken(); int a = (int)in.nval; in.nextToken(); int b = (int)in.nval; /* ignore 0 1 = 0 to 9 2 = 10 to 99 ... 7 = 1 000 000 to 9 999 999 */ int[] min = {0, 0, 10, 100, 1000, 10000, 100000, 1000000}; int[] max = {0, 9, 99, 999, 9999, 99999, 999999, 9999999}; // set limits for(int i = 1 ; i <= 7 ; i++) { min[i] = Math.max(min[i], a); max[i] = Math.min(max[i], b); } for(int len = 2 ; len <= 7 ; len++) { int exp = (int) Math.pow(10, len-1); for(int i = min[len] ; i <= max[len] ; i++) { int r = i; for(int j = 0 ; j < len-1 ; j++) { r = r % exp * 10 + (r/exp); if (r == i) break; if (r > i && r <= max[len] && i != r) rotations++; } } } out.println(""Case #"" + c + "": "" + rotations); } out.flush(); out.close(); } } " B21914,"public class ProblemC extends FileWrapper { private int A[] = null; private int B[] = null; private int digt[] = null; public ProblemC(String fileName) { this.processInput(fileName); this.calculate(); this.processOutput(OUTPUT); } @Override protected void processInput(String fileName) { try { this.openReadFile(fileName); this.caseNum = Integer.parseInt(this.readLine()); this.output = new String[this.caseNum]; this.A = new int[this.caseNum]; this.B = new int[this.caseNum]; this.digt = new int[this.caseNum]; for (int i = 0; i < this.caseNum; i++) { String elem[] = this.readLine().split("" ""); this.A[i] = Integer.parseInt(elem[0]); this.B[i] = Integer.parseInt(elem[1]); this.digt[i] = elem[0].length()-1; } this.closeReadFile(); } catch (Exception e) { } } @Override protected void calculate() { for (int i=0; ij && value<=B[i]) { total++; }else if (value==j) { break; } } } this.output[i] += total; } } public static void main(String argv[]) { if (argv.length > 0) { new ProblemC(argv[0]); } else { new ProblemC(""C-large.in""); } } }" B21065,"package wangshu.codejam.google.com; import java.io.File; import java.io.FileWriter; import java.util.Arrays; import java.util.Scanner; import java.lang.*; public class QC { public static long calculateNumber(int A, int B){ int size = B-A+1; // Number of integers between A and B int A1; // Auxiliary variable that helps to calculate numberOfDigits; int numberOfDigits; // Number of digits of A int multiple = 1; // Auxiliary variable that helps to calculate rotation; int count = 0; // Count stores for each integer between A and B , //the number of rotated integer that also between A and B long result = 0; boolean[] counted = new boolean[size]; //Indicate whether the number has been counted or not //Initialize counted array Arrays.fill(counted, false); // Calculate the number of digits of A for(numberOfDigits=0, A1=A; A1!=0; numberOfDigits++){ A1 = A1/10; multiple = multiple*10; } multiple = multiple/10; //Calculate the result for(int i=A; i<=B; i++){ count = 0; if(!counted[i-A]){ int k=i; //System.out.println(""#######""); for(int j=0; j=A && k<=B && !counted[k-A]){ count ++; counted[k-A] = true; //System.out.println(""k is "" + k); } int unitNnumber = k%10; k = k/10 + multiple*unitNnumber; } } /* if(count > 1){ System.out.println(""**************""); } */ result = result+ ((count)*(count-1))/2; } return result; } /** * @param args */ public static void main(String[] args) throws java.lang.Exception{ // TODO Auto-generated method stub Scanner sc = new Scanner(new File(""qc_in_large.txt"")); // Scanner for input file FileWriter outputFile = new FileWriter(""qc_out_large.txt""); int A, B; //Read number of test cases int T = sc.nextInt(); for(int i=0; i all) { System.out.println(""error""); break; } String[] elements = s.split("" ""); int start = Integer.parseInt(elements[0]); int end = Integer.parseInt(elements[1]); for(Integer i = start; i < end; i++) { String a_string = i.toString(); for(int j = 1; j < a_string.length(); j++) { String temp = a_string.substring(j, a_string.length()); temp = temp.concat(a_string.substring(0, j)); int data = Integer.parseInt(temp); if(data > i && data <= end) result = result + 1; } } out.println(""Case #"" + count +"": "" + result); count = count + 1; } out.close(); } public Boolean isRecycle(Integer a, Integer b) { String a_string = a.toString(); String b_string = b.toString(); if(a_string.length() != b_string.length()) return false; for(int i = 1; i < a_string.length(); i++) { String temp = a_string.substring(i, a_string.length()); temp = temp.concat(a_string.substring(0, i)); if(temp.equals(b_string)) return true; } return false; } public static void main(String[] args) throws NumberFormatException, IOException { Recycle r = new Recycle(); r.cal(""C-large.in""); } } " B21545,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class RecycledNumbers { private static FileReader freader; private static BufferedReader buffreader; private static FileWriter fwriter; private static BufferedWriter buffwriter; public static void main(String[] args) throws IOException { freader = new FileReader(""C-large.in""); buffreader = new BufferedReader(freader); fwriter= new FileWriter(""result-large.txt""); buffwriter = new BufferedWriter(fwriter); String str = null; int linenum = 0; int i=1; while((str=buffreader.readLine())!=null){ if(i==1) linenum=Integer.parseInt(str); else{ int start = Integer.parseInt(str.split("" "")[0]); int end = Integer.parseInt(str.split("" "")[1]); int num = calRecycleNum(start, end); String finalStr = ""Case #""+Integer.toString(i-1)+"": ""+Integer.toString(num)+""\n""; buffwriter.write(finalStr); } i++; } buffwriter.close(); fwriter.close(); buffreader.close(); freader.close(); } public static int calRecycleNum(int start, int end){ int num = 0; for(int i=start; i<=end; i++){ int len = Integer.toString(i).length(); int recycleVal = i; HashSet targetSet = new HashSet(); for(int j=1; j=start){ if(!targetSet.contains(recycleVal)){ num++; //System.out.println(i+""\t""+recycleVal); targetSet.add(recycleVal); } /*else{ System.out.println(""Duplicate:""+recycleVal+""\t""+i); }*/ } } } //System.out.println(num); return num; } public static int recycleOnce(int val, int length){ return (int) (val%Math.pow(10, length-1)*10+val/Math.pow(10, length-1)); } } " B21921,"import java.io.*; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(new FileOutputStream(new File(""output.txt"")), false); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(new File(""input.txt"")))); // StringTokenizer st = new StringTokenizer(in.readLine()); // Scanner s = new Scanner(System.in); int n = Integer.parseInt(in.readLine()); for(int i = 0;i < n;i++) { StringTokenizer st = new StringTokenizer(in.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int len = len(a); int ten = (int)Math.pow(10, len-1); int res = 0; for(int j = a;j <= b;j++) { int cur = j; int val = j; int per = period(j,len); for(int k = 0;k < per;k++) { int c = val%10; val = val/10+c*ten; if(val > cur && val <= b) { res++; } } } out.println(""Case #""+(i+1)+"": ""+res); out.flush(); } } public static int period(int n, int len) { if(len == 2 && n/10 == n%10) return 1; if(len == 4 && n%100 == n/100) return 2; if(len == 6 && n%100 == n/10000 && n%100 == n/100%100) return 2; if(len == 6 && n%1000 == n/1000) return 3; return len; } public static int len(int n) { int len = 0; while(n > 0) { n /= 10; len++; } return len; } }" B20855,"import java.util.Scanner; public class RecycledNumbers { static int recycle(int n, int B) { String nString = String.valueOf(n); int out = 0; for (int i = 0; i < nString.length(); i++) { int cut = nString.length() - (i + 1); String temp = nString.substring(cut) + nString.substring(0, cut); int pair = Integer.parseInt(temp); if (n < pair && pair <= B) { //System.out.println(n + "" "" + pair); out++; } } return out; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int cases = sc.nextInt(); StringBuilder out = new StringBuilder(); for (int i = 1; i <= cases; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int pairs = 0; for (int j = A; j < B; j++) { pairs += recycle(j, B); } out.append(""Case #"" + i + "": "" + pairs + ""\n""); } System.out.print(out); } } " B20035,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; /** * template class for code jam Contest * * @author Tudor * */ public class Main { public static final String INPUT_FILE = ""src/in.txt""; public static final String OUTPUT_FILE = ""out.txt""; java.io.BufferedWriter br; /* * the number of tests */ int tests; /* * the size of the test */ int a, b; /* * the array */ int[] tree; public static void main(String args[]) { Main classMain = new Main(); try { Scanner scanner = new Scanner(new File(Main.INPUT_FILE)); classMain.br = new java.io.BufferedWriter(new FileWriter(Main.OUTPUT_FILE)); classMain.setData(scanner); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * method to set the initial data and run the tests * * @param br * the reader obtained from file */ public void setData(Scanner scanner) { try { tests = scanner.nextInt(); // System.out.println(""Tests "" + tests); for (int i = 0; i < tests; i++) { a = scanner.nextInt(); b = scanner.nextInt(); solve(i + 1); } br.close(); } catch (Exception e) { e.printStackTrace(); } } /** * method to solve the problem * * @param testNr * the index of the test */ public void solve(int testNr) { int result = 0; int digits = getDigits(a); MyDictionary recycledNumbers = new MyDictionary(); for (int i = a; i <= b; i++) { int number = i; for (int d = 0; d < digits; d++) { number = number / 10 + (number % 10) * ((int) Math.pow(10, digits - 1)); if ((number != i) && (a <= number && number <= b)) { recycledNumbers.put(Math.min(i, number), Math.max(i, number)); // System.out.println(i + "" "" + number); } } } System.out.println(recycledNumbers); result = recycledNumbers.size(); try { br.write(""Case #"" + testNr + "": "" + result + ""\n""); } catch (IOException e) { e.printStackTrace(); } } int getDigits(int x) { int digits = 0; while (x != 0) { x = x / 10; digits++; } return digits; } } class MyDictionary { private Map map; MyDictionary() { this.map = new HashMap(); } public List get(int key) { return (List) this.map.get(key); } public void put(int key, int value) { List list = get(key); if (list == null) { list = new ArrayList(); this.map.put(key, list); } if (!list.contains(value)) list.add(value); } public int size() { int totalSize = 0; for (Object valueList : map.values()) { totalSize += ((List) valueList).size(); } return totalSize; } } " B22192,"package gcj; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) { String filenamein = ""C-large.in""; String filenameout = ""out.txt""; try { FileInputStream fstreamin = new FileInputStream(filenamein); DataInputStream in = new DataInputStream(fstreamin); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fstreamout = new FileWriter(filenameout); BufferedWriter out = new BufferedWriter(fstreamout); String strLine = br.readLine(); int nCases = Integer.parseInt(strLine); int counter = 1; while ((strLine = br.readLine()) != null) { System.out.println (strLine); String solu = Solve(strLine); System.out.println (solu); System.out.println (); out.write(""Case #""+ counter++ +"": "" + solu + ""\n""); } in.close(); out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } private static String Solve(String strLine) { String[] ss = strLine.split("" ""); int A = Integer.parseInt(ss[0]); int B = Integer.parseInt(ss[1]); int length = String.valueOf(A).length(); int suma = 0; for(int num = A ; num <= B ; num++) { int[] permu = generaPermu(num, length); if(permu != null) { for(int j = 0 ; j < permu.length ; j++) { if (permu[j] <= B && permu[j] > num) suma++; } } } return String.valueOf(suma); } private static int[] generaPermu(int num, int length) { int[] permu = null; if(length > 1) { permu = new int[length-1]; permu[0] = cambia(num, length); for(int j = 1 ; j < permu.length ; j++) { permu[j] = cambia(permu[j-1], length); } //Evito repetidos!!! for(int j = 0 ; j < permu.length ; j++) { for (int k = j + 1; k < permu.length ; k++) { if (permu[j] == permu[k]) permu[k] = -1; } } } return permu; } private static int cambia(int i, int l) { return (int) ((i + (i % 10) * Math.pow(10, l)) / 10); } } " B20935,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class C { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); ExecutorService es = Executors.newFixedThreadPool(Math.min(8, n)); @SuppressWarnings(""unchecked"") Future[] fs = new Future[n]; for (int i = 0; i < n; i++) { String[] parts = in.readLine().split("" ""); final int A = Integer.parseInt(parts[0]); final int B = Integer.parseInt(parts[1]); fs[i] = es.submit(new Callable() { public Integer call() { return wastetime(A, B); } }); } for (int i = 0; i < n; i++) { System.out.println(""Case #"" + (i + 1) + "": "" + fs[i].get()); } es.shutdown(); } public static int wastetime(int A, int B) { HashSet answers = new HashSet(); int len = (int) Math.log10(A) + 1; int m; int div = (int) Math.pow(10, len - 1); if (div <= 0) { return 0; } for (int n = A; n < B; n++) { m = n; for (int i = 0; i < len; i++) { m = ((m % div) * 10) + m / div; if (m > n && m <= B) { long ans = ((n & 0xFFFFFFFFl) << 32) + m; //System.out.println(Long.toHexString(ans)); answers.add(ans); } } } return answers.size();// // return div; } }" B21453,"package util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class MyUtil { public static BufferedReader getReader(String filename){ try { return new BufferedReader(new FileReader(""data/"" + filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } public static BufferedWriter getWriter(String filename){ try { return new BufferedWriter(new FileWriter(""output/"" + filename + "".out.txt"")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } " B20325,"import java.io.*; import java.util.*; public class recycled { public static void main(String[] args) { try { FileReader fread = new FileReader(new File(""C-large.in"")); BufferedReader br = new BufferedReader(fread); FileWriter fwrite = new FileWriter(new File(""output.txt"")); PrintWriter pw = new PrintWriter(fwrite); int cases = new Integer(br.readLine()); for (int i = 1; i <= cases; i++) { String line = br.readLine(); StringTokenizer st = new StringTokenizer(line); String temp = st.nextToken(); if (temp.length() == 1) { pw.println(""Case #"" + i + "": 0""); System.out.println(""Case #"" + i + "": 0""); } else { int min = new Integer(temp); int max = new Integer(st.nextToken()); int count = 0; for (int j = min; j <= max; j++) { String current = """" + j; String changing = current; HashSet seen = new HashSet(); for (int k = current.length() - 1; k > 0; k--) { changing = changing.substring(1) + changing.charAt(0); int intchanging = new Integer(changing); if ((intchanging > new Integer(current)) && (intchanging <= max) && (!seen.contains(intchanging))) { count++; seen.add(intchanging); } } } /* * int end = max / 10; System.out.println(end); * System.out.println(tens); for (int j = min; j <= max; * j++) { int ref = j / 10; int mod = j % 10; boolean found * = false; while (ref > 0) { int check = ref % 10; if * (check != mod) { found = true; break; } ref /= 10; } if * (found) { if (((j % tens) < end)&&((j % tens) >= * (tens/10))) { if ((j / tens) < (j % tens)) { * System.out.print(j +"" ""); count++; } } } } */ pw.println(""Case #"" + i + "": "" + count); System.out.println(""Case #"" + i + "": "" + count); } } pw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B20850,"import java.io.*; import java.util.*; public class CSmall { public static Set set = new HashSet(); public static int counter = 0; public static void main(String[] args) throws IOException { Scanner in = new Scanner(new File(""C-large.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-small.out""))); int T = Integer.parseInt(in.nextLine()); for (int i = 0; i < T; i++) { String[] lim = in.nextLine().split("" ""); for (int j = Integer.parseInt(lim[0]); j < Integer.parseInt(lim[1]); j++) { if (j >= 10) { pair(Integer.toString(j), lim); } } out.write(""Case #""+ (i+1) +"": "" + set.size()); if (i != T-1) out.write(""\n""); set.clear(); } //System.out.println(""1112"".charAt(""1112"".length()-1) + (""1112"".substring(0,""1112"".length()-1))); out.close(); System.exit(0); } private static void pair(String num, String[] lim) { int len = num.length(); int upLim = Integer.parseInt(lim[1]), lowLim = Integer.parseInt(lim[0]); String k = num; for (int i = 0; i < len; i++) { num = num.charAt(len-1) + num.substring(0,len-1); //System.out.println(num + "" "" + k); //System.out.println(num); int a = Integer.parseInt(num), b = Integer.parseInt(k); if (a!=b && a <= upLim && a >= lowLim && b <= upLim && b >= lowLim) { if (a dup = new HashSet(); for (int j = 1; j < is.length(); j++) { String s = is.substring(j) + is.substring(0,j); if (dup.contains(s)) continue; else dup.add(s); if (Integer.parseInt(s)>i && Integer.parseInt(s)<=b) { cnt++; } } } return cnt; } } " B21667,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; public class Main { private static String fileDirectory = ""files/""; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Problem3(fileDirectory + ""C-large.in"",fileDirectory + ""C-large.out""); } public static void Problem3(String inFile, String outFile) { try { BufferedReader br = new BufferedReader(new FileReader(inFile)); BufferedWriter bw = new BufferedWriter(new FileWriter(outFile)); int cases = Integer.parseInt(br.readLine()); for (int i = 0; i < cases; i++) { if (i > 0) { bw.newLine(); } String line = br.readLine(); String[] numbers = line.split("" ""); int A = Integer.parseInt(numbers[0]); int B = Integer.parseInt(numbers[1]); int length = String.valueOf(A).length(); int count = 0; for (int j = A; j <= B; j++) { String sNum = Integer.toString(j); HashMap map = new HashMap(); //System.out.print(sNum + "": ""); for (int k = 1; k < length; k++) { String newNum = sNum.substring(k, sNum.length()); newNum += sNum.substring(0, k); //System.out.print("" "" + newNum); int number = Integer.parseInt(newNum); if (number > j && number <= B) { if (!map.containsKey(number)) { map.put(number, null); count++; } } } //System.out.println(); } bw.write(""Case #"" + (i+1) + "": ""); bw.write(Integer.toString(count)); } bw.close(); br.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B20835,"package recycle_no; import java.io.*; import java.util.Arrays; public class Recycle_no { int N,a,b,count=0; String s="""",temp[]; public Recycle_no(){ try { FileInputStream fis=new FileInputStream(""C-large.in""); DataInputStream dis=new DataInputStream(fis); FileOutputStream fos = new FileOutputStream(""C-large.out""); DataOutputStream dos=new DataOutputStream(fos); N=Integer.parseInt(dis.readLine()); for(int i=1;i<=N;i++) { s=dis.readLine(); count=0; temp=s.split("" ""); a=Integer.valueOf(temp[0]); b=Integer.valueOf(temp[1]); for(int j=a;j=min && n<=max && n>no) { int flg=0; for(int j=0;j b) { //// break; //// } //// } // } // System.out.println(""Case #"" + i + "": "" + count); // } PrintWriter pw = new PrintWriter(""output.out""); pw.println(""Omg! It works!""); ArrayList ar=new ArrayList(); ar.add(""1""); ar.add(""1""); HashMap hm=new HashMap(); hm.put(""1"", 12); hm.put(""1"", 32); System.out.println(hm); } catch (Exception e) { e.printStackTrace(); } } } " B20584,"import java.io.*; import java.util.ArrayList; import java.util.List; public class Problem_C { public static void main(String[] args) throws IOException { String fileName = ""C-large.in""; FileReader reader = new FileReader(fileName); LineNumberReader lnreader = new LineNumberReader(reader); FileWriter writer = new FileWriter(""output-C-large.txt""); PrintWriter out = new PrintWriter(writer); String line = """"; line = lnreader.readLine(); String line_array[]; int A; int B; int length; int recycled; int count = 0; List rec_list = new ArrayList(); int index = 0; while ((line = lnreader.readLine()) != null){ count = 0; line_array = line.split("" ""); length = line_array[0].length(); rec_list.clear(); A = Integer.parseInt(line_array[0]); B = Integer.parseInt(line_array[1]); for (int k=A;k k) && (recycled <= B)){ if (!rec_list.contains(recycled)){ count++; rec_list.add(recycled); } } } } out.println(""Case #"" + (lnreader. getLineNumber()-1) + "": "" + count); } out.close(); } private static int recycle(int a,int length){ int r = a%10; int q = a/10; r = r * (int)java.lang.Math.pow(10,length-1); return (r+q); } } " B20853,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; public class RecycleNumber_1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { BufferedReader br = new BufferedReader(new FileReader(""/Users/kushal/Downloads/C-large.in"")); PrintWriter pr = new PrintWriter(""/Users/kushal/Desktop/recycle.out""); String line = """"; br.readLine(); int start; int end; int count; int number = -1; int temp , p1, p2; String str; int z = 1; HashSet hash = new HashSet(); ArrayList digits; while((line = br.readLine()) != null) { start = Integer.parseInt(line.split("" "")[0]); end = Integer.parseInt(line.split("" "")[1]); digits = new ArrayList(); count = 0; hash.clear(); for(int i=start; i<=end; i++) { number = i; //hash.add(i); if(i == 121) { //System.out.println(i+""kk""); } digits = new ArrayList(); while(number > 0) { digits.add(number%10); number /= 10; } number = digits.get(digits.size() - 1); for(int j = digits.size() - 2 ;j >= 0; j--) { str = """" + digits.get(j); if(j == 0 ) { p1 = digits.size() -1; } else { p1 = j - 1; } str += """" + digits.get(p1); while(true) { if(p1 == 0) { p1 = digits.size() -1; } else { p1 = p1 - 1; } if(p1 == j) { break; } str += """" + digits.get(p1); } //System.out.print(str + ""\t""); if(!str.startsWith(""0"")) { temp = Integer.parseInt(str); if((temp < i) && (temp >= start) && (temp <= end)) { if(!hash.contains(i+""_""+temp)) { hash.add(i+""_""+temp); //System.out.println(i + "" ""+ count); //continue; count++; } } } } //System.out.println(); } System.out.println(""Case #""+z+"": ""+count); z++; } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B21247,"package cl.rodrigo; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.AbstractList; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.lang.StringBuffer; public class RecycledNumbers { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { FileInputStream fstream; int count; try { fstream = new FileInputStream(""/home/rodrigo/Descargas/C-large.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; count = Integer.parseInt(br.readLine()); FileWriter outFile = new FileWriter(""/home/rodrigo/GoogleCodeJam/C-small.out""); PrintWriter out = new PrintWriter(outFile); for (int z=1;z<=count;z++) { HashMap hm = new HashMap(); Integer contador = 0; String[] linea = br.readLine().split("" ""); String lineakeypad = new String(); Integer min = Integer.parseInt(linea[0]); Integer max = Integer.parseInt(linea[1]); //System.out.println(min+""-""+max); for(int i=min;i<=max;i++) { for(int j=1;j<= String.valueOf(max).length()-1;j++) { String num = new String(); String num_pre = new String(); String num_post = new String(); String num_final = new String(); Integer num_int ; num = String.valueOf(i); num_pre = num.substring(j); num_post = num.substring(0, j); num_final = num_pre + num_post; num_int = Integer.parseInt(num_final); if (min <= i && i < num_int && num_int <= max && min <= num_int && i <= max) { // System.out.println(num+""-""+num_int); hm.put(num+""-""+num_int, 1); } } } Iterator it = hm.entrySet().iterator(); while (it.hasNext()) { contador++; it.next(); } out.print(""Case #""+z+"": ""); out.print(contador); out.println(""""); } out.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B20468,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Arrays; /** * Created by IntelliJ IDEA. * User: Abhishek * Date: 4/14/12 * Time: 1:09 PM * To change this template use File | Settings | File Templates. */ public class RecNum { public int recycled(String a, String b){ int a1 = Integer.parseInt(a); int b1 = Integer.parseInt(b); int num = a1; int count=0; while(num<=b1){ String x = String.valueOf(num); ArrayList store = new ArrayList(10); for(int i=1; inum && !store.contains(y)){ count++; store.add(y); } } num++; } return count; } public static void main(String[] args) { RecNum spk = new RecNum(); try { BufferedReader buff = new BufferedReader(new FileReader(""C-large.in"")); FileWriter fstream = new FileWriter(""out1.txt""); BufferedWriter out = new BufferedWriter(fstream); int numTest = Integer.parseInt(buff.readLine()); if (numTest < 1 || numTest > 50) System.exit(0); for (int k = 0; k < numTest; k++) { String[] inp = buff.readLine().split("" ""); out.write(""Case #"" + (k + 1) + "": "" + spk.recycled(inp[0],inp[1])); out.write(""\n""); // System.out.println(""Case #"" + (k + 1) + "": "" + spk.recycled(inp[0],inp[1])+""\n""); } out.close(); } catch (Exception e) { System.out.println(""Exception"" + e); } } } " B22259,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; @SuppressWarnings( ""nls"" ) public class R0C { public static void main( final String[] args ) throws IOException { final Scanner in = new Scanner( new File( ""R0C.txt"" ) ); final FileWriter out = new FileWriter( ""R0C.out"" ); final int n = in.nextInt(); in.skip( in.delimiter() ); for( int i = 0; i < n; i++ ) out.write( ""Case #"" + (i+1) + "": "" + countAllRecycledNumbersBetween( in.nextInt(), in.nextInt() ) + ""\n"" ); in.close(); out.close(); } static int countAllRecycledNumbersBetween( final int a, final int b ) { final int digits = 1 + (int)Math.floor( Math.log10( a ) ); final int firstDigitMult = (int)Math.pow( 10., digits - 1 ); final boolean[] visited = new boolean[ b - a + 1 ]; int count = 0; for( int i = 0; i <= b - a; i++ ) { if( visited[ i ] ) continue; visited[ i ] = true; int subCount = 1; int x = a + i; for( int j = 1; j < digits; j++ ) { x = x / 10 + x % 10 * firstDigitMult; if( ( x >= a ) && ( x <= b ) && !visited[ x - a ] ) { visited[ x - a ] = true; subCount++; } } count += subCount * ( subCount - 1 ) / 2; } return count; } } " B20965,"import java.io.IOException; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Main { /** * @param args */ // public static void main(String[] args) // { // try // { // Map m = new HashMap(); // start_googlerese(""ejp mysljylc kd kxveddknmc re jsicpdrysi"",""our language is impossible to understand"",m); // start_googlerese(""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"",""there are twenty six factorial possibilities"",m); // start_googlerese(""de kr kd eoya kw aej tysr re ujdr lkgc jv"",""so it is okay if you want to just give up"",m); // // m.put('z','q'); // m.put('q','z'); // // int a=0; // a= a+1; // // char letter; // for (letter='a'; letter <= 'z'; letter++) // { // if(m.containsKey(letter)) // System.out.println(letter+"" ""+m.get(letter)); // else // System.out.println(letter+"" ""+""!!!""); // } // // googlerese(m); // // } // catch (IOException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } public static void main(String[] args) { try { recycled(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void recycled() throws IOException { ArrayList input = Tools.getInput(""C:\\Users\\Yannick\\Dropbox\\GCJ_JAVA\\Q_2012\\C-small.in""); ArrayList output = new ArrayList(); int num_cases = Integer.parseInt(input.get(0)[0]); Set done = new HashSet(); //!!!!!!!!!!!!!!!!!!! num_cases for (int i=0;i ms = new HashSet(length-1); for (int n=lower;n<=upper;n++) { int m=n; ms.clear(); for(int j=0;jn && m<=upper && !ms.contains(m)) { // System.out.println(n+"" ""+m); result++; ms.add(m); } } } StringBuilder sbO = new StringBuilder(); sbO.append(""Case #""+(i+1)+"": ""); sbO.append(result); output.add(sbO.toString()); } Tools.saveOutputSingle(""C:\\Users\\Yannick\\Dropbox\\GCJ_JAVA\\Q_2012\\C-small.out"", output); } public static void start_googlerese(String input, String output, Map m) throws IOException { if(input.length()!=output.length()) throw new IOException(); for(int i=0;i m) throws IOException { ArrayList input = Tools.getInputSingle(""C:\\Users\\Yannick\\Dropbox\\GCJ_JAVA\\Q_2012\\A-small.in""); ArrayList output = new ArrayList(); int num_cases = Integer.parseInt(input.get(0)); for (int i=0;i input = Tools.getInput(""D:\\Documents\\Dropbox\\GCJ_JAVA\\1A_2008\\A-large-practice.in""); ArrayList output = new ArrayList(); int T = Integer.parseInt(input.get(0)[0]); for (int i=0;i vectorA = new ArrayList(); ArrayList vectorB = new ArrayList(); for(int j=0;j input = Tools.getInput(""C:\\Users\\Yannick\\Dropbox\\GCJ_JAVA\\Q_2012\\B-small.in""); ArrayList output = new ArrayList(); int num_cases = Integer.parseInt(input.get(0)[0]); for (int i=1;i<=num_cases;i++) { int result=0; int N=Integer.parseInt(input.get(i)[0]); int S=Integer.parseInt(input.get(i)[1]); int p=Integer.parseInt(input.get(i)[2]); int a,b,c; for(int j=0;j=p || b>=p || c>=p ) result++; else { if(S>0 && ( (a==b && a==p-1 && a>0) || (a==c && a==p-1 && a>0) || (b==c && b==p-1 && b>0) ) ) { S--; result++; } } } StringBuilder sbO = new StringBuilder(); sbO.append(""Case #""+(i)+"": ""); sbO.append(result); output.add(sbO.toString()); } Tools.saveOutputSingle(""C:\\Users\\Yannick\\Dropbox\\GCJ_JAVA\\Q_2012\\B-small.out"", output); } } " B20787,"package com.codegem.zaidansari; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class CodeGemUtil { public static List getInputValues(File file) { List inputData = new ArrayList(); if (!file.exists()) { throw new RuntimeException(""File not fould:"" + file.getAbsolutePath()); } try { Scanner scanner = new Scanner(new FileReader(file)); while (scanner.hasNextLine()) { inputData.add(scanner.nextLine()); } } catch (FileNotFoundException e) { System.out.println(""Failed to find file :"" + file); } return inputData; } public static boolean createOutputFile(List outputData, String fileName) { File folderName = new File(""/Users/zaansari/Desktop/CodeGem2012/OutputFiles/""); File outputFile = new File(folderName, fileName); try { BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile)); int count = 0; for (String outputDatum : outputData) { writer.write(""Case #"" + (++count) + "": ""); writer.write(outputDatum); writer.newLine(); } writer.close(); return true; } catch (IOException e) { System.out.println(""Failed to write file :"" + outputFile + "", Error Message:"" + e.getMessage()); } // Failed to wrirte file return false; return false; } public static void main(String[] args) { File file = new File(""/Users/zaansari/Desktop/CodeGem2012/InputFiles/codeGem.in.txt""); List inputData = CodeGemUtil.getInputValues(file); for (String inputDatum : inputData) { System.out.println(inputDatum); } boolean createdOutputFile = CodeGemUtil.createOutputFile(inputData, ""Q2Small.txt""); if (createdOutputFile) { System.out.println(""Successfully created output file""); } else { System.out.println(""Failed to create output file""); } } } " B21122,"import java.io.*; import java.util.*; public class ProbC { public static void main(String[] args) throws FileNotFoundException, IOException { ProbC p = new ProbC(); p.solveAll(); } int tests = 0; Scanner in; BufferedWriter out; public ProbC() throws FileNotFoundException, IOException { out = new BufferedWriter(new FileWriter(""c.out"")); in = new Scanner(new File(""c.in"")); tests = in.nextInt(); in.nextLine(); //System.out.println(tests); } public void solveAll() throws IOException { //System.out.println(move(11, 1)); ///* for(int i = 0; i < tests; i++) { solve(i+1); } out.close(); in.close();//*/ } public void solve(int casenr) throws IOException { int A, B, res = 0; A = in.nextInt(); B = in.nextInt(); int[] perm = new int[100]; for(int i = A; i <= B; i++) { int d = digits(i); for(int j = 1; j < d; j++) { int m = move(i, j); boolean found = false; for(int k = 1; k < j; k++) { if(perm[k] == m) found = true; } perm[j] = m; if(!found && valid(A, B, i, m)) res++; } } out.write(""Case #""+casenr+"": ""); out.write(new Integer(res).toString()); out.write('\n'); } public int digits(int nr) { int d = 0; while(nr > 0) { nr /= 10; d++; } return d; } public int move(int nr, int pos) { String nrs = new Integer(nr).toString(); String rs = nrs.substring(nrs.length()-pos); rs = rs + nrs.substring(0, nrs.length()-pos); return new Integer(rs).intValue(); } public boolean valid(int A, int B, int n, int m) throws IOException { /*if(A <= n && n < m && m <= B) out.write(n+"" ""+m+"" ""+'\n');//*/ return A <= n && n < m && m <= B; } }" B22140,"package recycle; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class EnvironmentallyFriendly { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(new File(""test.txt""))); BufferedWriter wr = new BufferedWriter(new FileWriter(new File(""output.txt""))); int count = Integer.parseInt(br.readLine()); int min,max; int total; String[] vals; for(int i=1; i<=count; i++) { total=0; String line = br.readLine(); vals = line.split("" ""); min = Integer.parseInt(vals[0]); max = Integer.parseInt(vals[1]); for(int k =min; k duplicatecheck = new ArrayList(); for(int i=1; i oldval && !duplicatecheck.contains(newval)) { duplicatecheck.add(newval); total++; } } return total; } } " B21850,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; public class main { /** * @param args * @throws Exception */ public static int[] flag; public static ArrayList[] array; public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Input in = new Input(""small.txt""); File file = new File(""out.txt""); FileWriter filewriter = new FileWriter(file); BufferedWriter bw = new BufferedWriter(filewriter); PrintWriter pw = new PrintWriter(bw); int n = in.getInt(); for(int i = 0; i < n ; i ++){ int result = 0; int num = i + 1 ; int a = in.getInt(); int b = in.getInt(); int d = Integer.toString(a).length(); array = new ArrayList[b+1]; for(int j = a ; j <= b; j++){ array[j] = new ArrayList(); } for(int j = a ; j <=b ; j++){ String s = Integer.toString(j) + Integer.toString(j); result += solve(s,d,a,b,j); } String ans = ""Case #"" +num +"": ""+result; pw.println(ans); System.out.println(ans); } pw.close(); bw.close(); filewriter.close(); } public static int solve(String s , int d,int a , int b,int j){ int result = 0; int original = j; for(int i = 0 ; i < d ; i++){ String sub = s.substring(i+1, i+1+d); int subint = Integer.parseInt(sub); if(subint >= a && subint <=b && subint !=original){ if(subint pairs() { Set pairs = new HashSet(); for (long number = lower; number <= upper; number++) { Set rotations = rotations(number); for (Long rotation : rotations) { pairs.add(new Pair(number, rotation)); } } return pairs; } public Set rotations(long number) { if (rotationFactor == 1) { return Collections.emptySet(); } Set rotations = new HashSet(); long rotation = rotate(number); while (rotation != number) { if (rotation > number && rotation <= upper) { rotations.add(rotation); } rotation = rotate(rotation); } return rotations; } private long rotate(long number) { long lastDigit = number % 10; return number / 10 + lastDigit * this.rotationFactor; } public static final class Pair { public final long m; public final long n; public Pair(long m, long n) { this.m = m; this.n = n; } @Override public String toString() { return ""Pair{"" + ""m="" + m + "", n="" + n + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair pair = (Pair) o; if (m != pair.m) return false; if (n != pair.n) return false; return true; } @Override public int hashCode() { int result = (int) (m ^ (m >>> 32)); result = 31 * result + (int) (n ^ (n >>> 32)); return result; } } } " B21784,"import static java.util.Arrays.deepToString; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class Solution { private static void debug(final Object...objs) { System.out.println(deepToString(objs)); } int rotate(int n, int d) { int f = n / d; return (n - f * d) * 10 + f; } class Pair{ Set elems = new HashSet(); Pair(final int first, final int second) { elems.add(first); elems.add(second); } @Override public int hashCode() { return elems.hashCode(); } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof Pair)) return false; final Pair other = (Pair) obj; return elems.equals(other.elems); } } private String solveCase() throws IOException { final int A = nextInt(); final int B = nextInt(); int d = 1; int N = 1; while (d * 10 <= A) { d *= 10; N++; } int res = 0; Set all = new HashSet(); Set visited = new HashSet(); for (int j = A; j <= B; j++) { if (visited.contains(j)) continue; Set ns = new HashSet(); int x = rotate(j, d); for (int i = 0; i < N; i++) { if (A <= x && x <= B) { ns.add(x); visited.add(x); } x = rotate(x, d); } int[] as = new int[ns.size()]; int i = 0; for (Integer it : ns) { as[i++] = it; } for (int m = 0; m < as.length - 1; m++) { for (int n = m + 1; n < as.length; n++) { all.add(new Pair(as[m], as[n])); } } } return String.valueOf(all.size()); } private void solve() throws IOException { final int T = nextInt(); for (int test = 0; test < T; test++) { final String result = ""Case #"" + (test + 1) + "": "" + solveCase(); pw.println(result); System.out.println(result); } } private BufferedReader br; private PrintWriter pw; private StringTokenizer st; int nextInt() throws IOException { return Integer.parseInt(next()); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public static void main(final String[] args) throws IOException { new Solution().run(); } private void run() throws IOException { br = new BufferedReader(new FileReader(""input.txt"")); pw = new PrintWriter(""output.txt""); solve(); br.close(); pw.flush(); pw.close(); } }" B20878,"import java.util.*; import java.io.*; public class Recycle { public static void main(String[] args) { Scanner in = new Scanner(new BufferedInputStream(System.in)); int T = in.nextInt(); for(int i=0; i =10) { x = x/10; digits++; } //System.out.println(""digits: "" + digits); int sum = 0; int[] m = new int[digits-1]; for(int k = 0; k < m.length; k++) m[k] = (k+1)*-1; for(int j = A; j < B; j++) { //reset m for(int k = 0; k < m.length; k++) m[k] = (k+1)*-1; //try every possible combination //count it if j < combo < B for(int k = 1; k < digits; k++) { int divisor = (int) Math.pow(10,k); int multiplier = (int)Math.pow(10,digits-k); int temp = (j%divisor)*multiplier + j/divisor; //if all digits the same skip String number = Integer.toString(temp); if(number.matches(""^([0-9])\\1*$"")) continue; if(temp > j && temp <= B) { m[k-1] = temp; sum++; } } //if redundancy subtract Arrays.sort(m); for(int k = 1; k < m.length; k++) if(m[k] == m[k-1]) sum--; } System.out.printf(""Case #%d: %d\n"",i+1,sum); } } }" B21899,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.BitSet; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class B { public static void main(String[]args)throws Exception { File f = new File(args[0]); File out = new File(f.getParentFile(), f.getName()+"".out""); BufferedWriter w = new BufferedWriter(new FileWriter(out)); Scanner s = new Scanner(f); int T = s.nextInt(); s.nextLine(); for (int t=1;t<=T;t++) { int A = s.nextInt(); int B = s.nextInt(); println(w, ""Case #""+t+"": ""+solve(A,B)); s.nextLine(); } s.close(); w.close(); } private static String solve(int A, int B) { int num = 0; Set set = new HashSet(); for (int i=A; i<=B; i++) { int[] check = check(i); for (int j = 0; j < check.length; j++) { if (check[j] <= i) continue; if (check[j] >i && check[j] <=B) set.add(i+"":""+check[j]); } } return """"+set.size(); } static int[] check(int i) { String s = String.valueOf(i); int[] ret = new int[s.length()-1]; for (int x=0;x j && k < (m + 1) && k != j) count++; } while(k != j); } out.write(""Case #"" + (i + 1) + "": "" + count + ""\n""); count = 0; } out.close(); } catch (IOException e) { } } } " B21912,"package gcj2012.qr; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * * @author Scott DellaTorre */ public class C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""src/gcj2012/qr/in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""src/gcj2012/qr/C.out""))); int T = Integer.parseInt(in.readLine()); for (int i = 0; i < T; i++) { StringTokenizer st = new StringTokenizer(in.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int pairs = 0; for (int j = A; j <= B; j++) { pairs += countRecycled(j, B); } out.println(""Case #"" + (i + 1) + "": "" + pairs); System.out.println(""Case #"" + (i + 1) + "" complete.""); } out.close(); } private static int countRecycled(int number, int max) { List list = new ArrayList<>(); int log10 = (int) Math.log10(number); for (int i = 1; i <= log10; i++) { int recycled = recycle(number, i, max); if (recycled != -1 && !list.contains(recycled)) { list.add(recycled); } } return list.size(); } private static int recycle(int number, int count, int max) { int oldNumber = number; int divisor = (int) Math.pow(10, count); int end = number % divisor; number /= divisor; int multiplicand = (int) Math.pow(10, (int) Math.log10(number) + 1); number += end * multiplicand; if (number <= oldNumber || number > max) { return -1; } return number; } } " B20527,"package com.codejam.twelve; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; public class ProbC { public static void main(String[] args) throws IOException { FileReader fr = new FileReader( ""D:\\Dev\\Workspaces\\Android\\codejam\\io\\qualification\\C-large.in""); FileWriter fw = new FileWriter( ""D:\\Dev\\Workspaces\\Android\\codejam\\io\\qualification\\C-large.out""); BufferedReader br = new BufferedReader(fr); BufferedWriter bw = new BufferedWriter(fw); int t = Integer.parseInt(br.readLine()); for (int l = 1; l <= t; l++) { String s = br.readLine(); bw.append(""Case #"" + l + "": ""); String ss[] = s.split("" ""); int A = Integer.parseInt(ss[0]); int B = Integer.parseInt(ss[1]); int ans = 0; HashSet hs = new HashSet(); for (int i = A; i < B; i++) { String n = """" + i; int len = n.length(); for (int j = 0; j < len - 1; j++) { n = n.charAt(n.length() - 1) + n.substring(0, n.length() - 1); int nn = Integer.parseInt(n); if (nn > i && nn <= B) { /*System.out.println(i + "","" + nn); if (hs.contains(i + "","" + nn)) { System.out.println(""**********""); } else*/ if (!hs.contains(i + "","" + nn)){ hs.add(i + "","" + nn); ans++; } } } } bw.append("""" + ans); bw.newLine(); } bw.flush(); bw.close(); br.close(); } } " B21328,"package net.jbirch.gcj12qual; import java.io.FileNotFoundException; import java.util.Scanner; import net.jbirch.gcj12qual.util.FileLoader; /** * * @author Birch */ public class C implements Runnable { protected FileLoader inFile; protected Scanner in; /** * @param args the command line arguments */ public static void main(String[] args) { (new C()).run(); } public C() { inFile = new FileLoader(""src\\main\\resources\\C.txt""); } public void run() { try { in = inFile.getScanner(); solve(); } catch (FileNotFoundException fnfe) { System.out.println(""File not found. Exiting.""); System.out.println(fnfe); } } //Commence overall magic protected void solve() { int cases = Integer.valueOf(in.nextLine()); for (int i = 0; i < cases; i++) { System.out.print(""Case #"" + (i + 1) + "": ""); solve(in.nextInt(), in.nextInt()); } } protected void solve(int low, int high) { int digits = (int) Math.log10(low); int count=0; for (int i = low; i <= high; i++) { int[] rotatedThisRound = new int[digits]; // for cases like 1212 - 2121 being counted twice. Sly. for (int j = 1; j <= digits; j++) { int rotated = this.rotateInt(i, j); if (rotated < low || rotated > high || i >= rotated || this.contains(rotatedThisRound, rotated)) continue; rotatedThisRound[j - 1] = rotated; count++; } } System.out.println(count); } protected int rotateInt(int i, int turns) { String theGuy = String.valueOf(i); String guyThe = theGuy.substring(turns) + theGuy.substring(0, turns); if (guyThe.startsWith(""0"")) return 0; // Force a fail case - rotated number has leading 0 and thus is of different length return Integer.valueOf(guyThe); } protected boolean contains(int[] a, int i) { for (int j : a) { if (j == i) return true; } return false; } } " B20168,"package me.stapel.kai.google.codejam2012.quali; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.SortedSet; import java.util.TreeSet; import me.stapel.kai.google.codejam2012.quali.C.Pair; public class ProblemC { private static final String NL = System.getProperty(""line.separator""); public ProblemC() { // nothing to do here yet } public static void main(String[] args) { ProblemC problemC = new ProblemC(); problemC.processFile(""in/C-large.in"", ""out/C-large.txt""); } private Object processFile(String inFileName, String outFileName) { Object obj = new Object(); File inFile = new File(inFileName); File outFile = new File(outFileName); String line = """"; int T = 1; OutputStreamWriter output; BufferedReader br; try { br = new BufferedReader(new FileReader(inFile)); output = new OutputStreamWriter(new BufferedOutputStream( new FileOutputStream(outFile)), ""8859_1""); line = br.readLine(); // skipping first line line = br.readLine(); while (line != null) { String[] split = line.split("" ""); int A = Integer.parseInt(split[0]); int B = Integer.parseInt(split[1]); int numPairs = calcNumPairs(A, B); output.write(""Case #"" + T + "": "" + numPairs + NL); System.out.println(""Case #"" + T + "": "" + numPairs); line = br.readLine(); T++; } output.flush(); output.close(); } catch (FileNotFoundException e) { System.err.println(""File "" + inFile.getName() + "" not found. Nothing processed.""); e.printStackTrace(); } catch (IOException e) { System.err.println(""Error when reading file "" + inFile.getName() + "" or writing file "" + outFile.getName() + "".""); e.printStackTrace(); } return obj; } private int calcNumPairs(int A, int B) { SortedSet pairs = new TreeSet(); for(int i = A; i <= B; i++){ int[] n = toArray(i); calcRecycledPairs(n, B, pairs); } return pairs.size(); } private int calcRecycledPairs(int[] n, int B, SortedSet pairs) { int num = 0; int[] m = new int[n.length]; int ni,mi; for (int i = 1; i < n.length; i++) { for(int j = 0; j < n.length-i; j++) { m[j+i] = n[j]; } for(int j = n.length-i; j < n.length; j++) { m[j-n.length+i] = n[j]; } ni = fromArray(n); mi = fromArray(m); if(mi <= B && ni < mi && isValidM(m)) { num++; pairs.add(new Pair(ni, mi)); // System.out.println(""(""+ni+"", ""+mi+"")""); } } return num; } private boolean isValidN(int[] n) { int tmp = n[0]; for (int i = 1; i < n.length; i++) { if(n[i] != tmp) return true; tmp = n[i]; } return false; } private boolean isValidM(int[] m) { if(fromArray(m) < Math.pow(10,m.length-1)) return false; return true; } private int[] toArray(int i) { int digits = (int)Math.ceil(Math.log10(i+1)); int[] arr = new int[digits]; for(int c = 1; c<=digits;c++) { arr[digits-c] = i % 10; i = i/10; } return arr; } private int fromArray(int[] arr) { int i = 0; for (int j = 0; j < arr.length; j++) { i = 10*i+arr[j]; } return i; } } " B21845,"import java.util.Scanner; public class C { public static void main (String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int a, b; int[] list; for (int i = 1; i <= n; i++) { a = scan.nextInt(); if (a < 10) a = 10; b = scan.nextInt(); int count = 0; for (int j = a; j < b; j++) { String str = """" + j; int len = str.length(); list = new int[len]; int lp = 0; for (int k = 1; k < len; k++) { String str2 = str.substring(len-k) + str.substring(0, len-k); int res = Integer.valueOf(str2); if (str2.charAt(0) != '0' && res > j && res <= b) { if (!contains(list, lp, res)) { list[lp] = res; lp++; //System.out.println(j + "" "" + res); count++; } } } } System.out.println(""Case #"" + i + "": "" + count); } } private static boolean contains(int[] list, int lp, int res) { for (int i = 0; i < lp; i++) if (list[i] == res) return true; return false; } } " B20260,"package codejam.recycle; import java.util.HashSet; import java.util.Set; public class Recycle { public String solve(String s) { String[] ss = s.split("" ""); int a = Integer.parseInt(ss[0]); int b = Integer.parseInt(ss[1]); int n = ("""" + a).length(); int m = 0; for (int i = a; i <= b; i++) { int[] digits = collectDigits(i); Set done = new HashSet(); for (int j = 1; j < n; j++) { int t = offsetNum(digits, j); if (t <= b && t > i && done.add(t)) { m++; } } } return """" + m; } private int[] collectDigits(int num) { int n = ("""" + num).length(); int[] digits = new int[n]; int i = n; while (i > 0) { digits[--i] = num % 10; num = (int) (num / 10d); } return digits; } private int offsetNum(int[] x, int m) { int a = 0; for (int i = 0; i < x.length; i++) { a += x[(i + m) % x.length] * Math.pow(10, x.length - 1 - i); } return a; } } " B20263,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; import java.util.TreeSet; class IntegerPair implements Comparable { int a, b; IntegerPair(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(IntegerPair p) { if (a == p.a) return b - p.b; return a - p.a; } } public class Main implements Runnable { final String fileName = ""C-large""; void solveCase(int test) throws Exception { out.print(""Case #"" + test + "": ""); int a = nextInt(); int b = nextInt(); TreeSet answer = new TreeSet(); for (int v = a; v <= b; v++) { String s = Integer.toString(v); for (int i = 1; i < s.length(); i++) { String t = s.substring(i) + s.substring(0, i); if (t.charAt(0) == '0') continue; int v2 = Integer.parseInt(t); if (v2 <= v || v2 > b) continue; answer.add(new IntegerPair(v, v2)); } } out.println(answer.size()); out.flush(); System.out.println(answer.size()); System.out.flush(); } void solution() throws Exception { int t = nextInt(); for (int i = 0; i < t; i++) solveCase(i + 1); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String l = in.readLine(); if (l == null) return null; st = new StringTokenizer(l); } return st.nextToken(); } public static void main(String args[]) { //Locale.setDefault(Locale.UK); new Thread(new Main()).start(); } public void run() { try { in = new BufferedReader(new FileReader(fileName + "".in"")); //out = new PrintWriter(System.out); out = new PrintWriter(fileName + "".out""); solution(); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(202); } } BufferedReader in; StringTokenizer st; PrintWriter out; }" B21285,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class QualificationQ3 { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); File file = new File(args[0]); Scanner in = new Scanner(file); int T = in.nextInt(); in.nextLine(); for (int zz = 1; zz <= T; zz++) { String outputLine = process(in); output(out,zz,outputLine); } in.close(); out.close(); } private static String process(Scanner in) { int begin = in.nextInt(); int end = in.nextInt(); int counter = 0; for (int i=begin;i l= generateTheQualifiedList(i,end); counter += l.size(); } return """"+counter; } private static ArrayList generateTheQualifiedList(int num, int end) { ArrayList qualifiedNumList = new ArrayList(); String sNumber = """" + num; int len = sNumber.length(); ArrayList handledNumber = new ArrayList(); for (int i=1;inum && iNumber<=end){ //System.out.println(num + "" "" +iNumber); if (!handledNumber.contains(iNumber)){ handledNumber.add(iNumber); qualifiedNumList.add(iNumber); }else{ System.out.println(iNumber); } } } return qualifiedNumList; } private static void output(BufferedWriter out, int zz, String formattedString) throws IOException { String outputLine = String.format(""Case #%d: %s\n"", zz, formattedString); System.out.format(outputLine); out.write(outputLine); } } " B20328,"package qr; import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File(""C-large.in"")); int tcn = scanner.nextInt(); int tc = 1; while (tc <= tcn) { int a = scanner.nextInt(); int b = scanner.nextInt(); int y = 0; // System.out.printf(""%d %d\n"", a, b); if (a > 9) { y = 0; for (int n = a; n < b; n++) { String ns = Integer.toString(n); // System.out.println(""ns="" + ns); int len = ns.length(); HashSet sss = new HashSet(); for (int i = 1; i < len; i++) { String ns1 = ns.substring(0, i); String ns2 = ns.substring(i, len); // System.out.printf(""ns1=%s ns2=%s\n"",ns1,ns2); if (ns2.charAt(0) == '0') continue; String ms = ns2 + ns1; // System.out.println(""ms=""+ms); int m = Integer.parseInt(ms); if (sss.contains(m)) continue; if (n < m && m <= b) { y++; sss.add(m); // System.out.printf(""%d <= %d < %d <= %d\n"", a, n, m, b); } } } } System.out.printf(""Case #%d: %d\n"", tc, y); tc++; } } } " B20067,"package com.gcj.recyclednumbers; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @original Apr 14, 2012 12:08:21 PM * @author lewisju */ public class Solve { final Set distinct = new HashSet(); final int a; final int b; public Solve(int a, int b) { this.a = a; this.b = b; for(int i = a; i <= b; i++) { List ints = recycled(i); for(int recycled : ints) { if(recycled <= b && recycled >= a) { RecycledPair p = new RecycledPair(i,recycled); distinct.add(p); } } } } private List recycled(int number) { ArrayList list = new ArrayList(); String s = Integer.toString(number); for(int i=1; i < s.length(); i++) { int splitpoint = s.length()-i; String begin = s.substring(0, splitpoint); String end = s.substring(splitpoint); String result = end+begin; if(!result.startsWith(""0"") && !result.equals(s)) list.add(Integer.parseInt(result)); } return list; } public int count() { return distinct.size(); } class RecycledPair { private final int a; private final int b; public RecycledPair(int i, int recycled) { if(i < recycled) { a = i; b = recycled; } else { a = recycled; b = i; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; return result; } @Override public boolean equals(Object obj) { RecycledPair other = (RecycledPair) obj; return a==other.a && b==other.b; } @Override public String toString() { return """"+a+"" ""+b; } } public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader(""input.txt"")); String T = reader.readLine(); int t = Integer.parseInt(T); for(int i=0; i < t; i++) { String line = reader.readLine(); String[] inputs = line.split("" ""); int a = Integer.parseInt(inputs[0]); int b = Integer.parseInt(inputs[1]); Solve s = new Solve(a, b); StringBuffer sb = new StringBuffer(); sb.append(""Case #""); sb.append((i+1)); sb.append("": ""); sb.append(s.count()); System.out.println(sb.toString()); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B21086,"package gcj2012; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Integer t = Integer.parseInt(br.readLine()); int init = t; while (t-- > 0) { // long s = System.currentTimeMillis(); int res = 0; String[]parts = br.readLine().split(""\\s+""); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); for(int n = A; n <= B; n++){ Set set = new HashSet(); char[]num = (n+"""").toCharArray(); for(int i = 1; i < num.length; i++){ if(num[i]=num.length)j = 0; len++; } int m = Integer.parseInt(sb.toString()); if(m>n&&m>=A&&m<=B){ set.add(n+"",""+m); } } res+=set.size(); } System.out.println(""Case #""+(init-t)+"": "" + res); // System.out.println(System.currentTimeMillis()-s); } } } " B21892,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class CodeJamC { public static void main(String args[]) throws Exception { Scanner in = new Scanner(new File(""in.txt"")); BufferedWriter out = new BufferedWriter(new FileWriter(""out.txt"")); int cases = in.nextInt(); for(int casenum = 1;casenum <= cases;casenum++) { int a = in.nextInt(); int b = in.nextInt(); int count = 0; HashMap> map = new HashMap>(); int len = ("""" + a).length(); for(int n = a;n <= b;n++) { int t = n; for(int i = 0;i n && t <= b) { if(map.containsKey(n)) { if(!map.get(n).contains(t)) { count++; map.get(n).add(t); } } else { ArrayList arr = new ArrayList(); arr.add(t); map.put(n,arr); count++; } } } } out.write(""Case #"" + casenum + "": "" + count + ""\n""); } in.close(); out.close(); } }" B20506,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.*; import java.util.Scanner; /** * * @author Mash */ public class Main { public static void main(String args[]) throws FileNotFoundException { Scanner in = new Scanner(new FileReader(""C:\\ima\\ans.txt"")); int T=in.nextInt(); int A,B; String a,b,perm; char[] per; String filler=""0000000""; for(int i=1;i<=T;i++){ int res=0; A=in.nextInt(); B=in.nextInt(); b=Integer.toString(B); for(int j=A;j<=B;j++){ int ans; // Set list= new HashSet(); Set list=new HashSet(); a=Integer.toString(j); int des=b.length()-a.length(); perm=filler.substring(0, des)+j; //System.out.println(perm); //per=perm.toCharArray(); //permute(per, 0, b.length()); String add; for(int s=0;s<=perm.length();s++){ add=perm.substring(s)+perm.substring(0,s); list.add(add); } ans=0; Iterator it=list.iterator(); //System.out.println(""j is""+j); while(it.hasNext()) { String comp=(String) it.next(); //System.out.println(comp); int com=Integer.parseInt(comp); if(com>j&&com<=B)ans++; } //System.out.println(""answer is""+ans); res+=ans; } System.out.println(""Case #""+i+"": ""+res); } } } " B21504,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) throws IOException { FileReader fReader = new FileReader(""input/C-large.in""); BufferedReader br = new BufferedReader(fReader); int T = Integer.valueOf(br.readLine()); int c = 1; while (T-- > 0) { String[] line = br.readLine().split(""\\s""); Integer first = Integer.valueOf(line[0]); Integer second = Integer.valueOf(line[1]); Set set = new HashSet(); int totalCount = 0; for (int i = first; i <= second; ++i) { String ll = String.valueOf(i); for (int j = 1; j < ll.length(); ++j) { String tempLine = ll.substring(ll.length() - j); tempLine += ll.substring(0, ll.length() - j); if (tempLine.startsWith(""0"")) { continue; } int secondNum = Integer.valueOf(tempLine); if (i >= secondNum || secondNum > second) { continue; } String ss = i + ""|"" + secondNum; if (set.contains(ss)) { continue; } set.add(ss); totalCount++; // System.out.println(ss); } } System.out.println(""Case #"" + c + "": "" + totalCount); c++; } fReader.close(); } } " B21785,"package info.zhenhua.codejam; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.HashSet; import java.util.Set; abstract class RecycledNumbersSolver { protected String inputFileName; String outputFileName = null; PrintStream ps = null; public final static String smallInput = ""-small-practice.in""; public final static String bigInput = ""-large-practice.in""; public final static String smallOutput = ""-small-practice.out""; public final static String bigOutput = ""-large-practice.out""; public final static String smallContestInput = ""-small-attempt0.in""; public final static String bigContestInput = ""-large.in""; public final static String smallContestOutput = ""-small-attempt0.out""; public final static String bigContestOutput = ""-large.out""; protected String fileNamePrefix = null; public RecycledNumbersSolver(String inputFileName, String outputFileName, String fileNamePrefix) { this.inputFileName = inputFileName; this.outputFileName = outputFileName; this.fileNamePrefix = fileNamePrefix; } public String getInputFileName() { return fileNamePrefix + inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public String getOutputFileName() { return fileNamePrefix + outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } abstract protected void solveAll() throws IOException; protected void printOutput (String result) throws FileNotFoundException { if (ps == null) { if (this.getOutputFileName() == null) ps = new PrintStream(System.out); else ps = new PrintStream(this.getOutputFileName()); } ps.println(result); } } /** * @author zhguo * */ public class RecycledNumbers extends RecycledNumbersSolver { public RecycledNumbers(String inputFileName, String outputFileName) { super(inputFileName, outputFileName, ""C""); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { RecycledNumbers recycledNumbers = new RecycledNumbers(bigContestInput, bigContestOutput); recycledNumbers.solveAll(); } @Override protected void solveAll() throws IOException { BufferedReader br = new BufferedReader(new FileReader(getInputFileName())); String line = br.readLine(); int testcases = Integer.valueOf(line); for (int j = 1; j <= testcases; ++j) { line = br.readLine(); String[] parts = line.split("" ""); int min = Integer.valueOf(parts[0]); int max = Integer.valueOf(parts[1]); long result = solveOneTestCase(min, max); printOutput(""Case #"" + j + "": "" + result); } br.close(); if (ps != null) ps.close(); } static final int MAX = 2000000; Set visited = new HashSet(); private long solveOneTestCase(int min, int max) { StringBuilder sb = new StringBuilder(); long nums = 0; for (int i = min; i <= max; ++i) { visited.clear(); sb.replace(0, sb.length(), String.format(""%d%d"", i, i)); int len = sb.length() / 2; for (int j = 1; j < len; ++j) { int num = Integer.valueOf(sb.substring(j, j + len)); if (num > max || num <= i || visited.contains(num)) continue; visited.add(num); ++nums; } } return nums; } } " B21330,"import java.io.*; import java.util.*; class RecycledNumbers { public static void main(String[] args) throws Exception { new RecycledNumbers().start(); } void start() throws Exception { InputStreamReader is = new InputStreamReader( new FileInputStream(""Input"")); BufferedReader br = new BufferedReader(is); OutputStreamWriter os = new OutputStreamWriter( new FileOutputStream(""Output"")); BufferedWriter bw = new BufferedWriter(os); String line; int[] inputs; int test = 1; line = br.readLine(); while ((line = br.readLine()) != null) { String[] inp = line.split("" ""); inputs = new int[inp.length]; int i = 0; for (String s : inp) { inputs[i++] = Integer.parseInt(s); } System.out.print(""Case #"" + test + "": ""); String toWrite = ""Case #"" + test++ + "": ""; bw.write(toWrite, 0, toWrite.length()); int len = inp[0].length(); int first = Integer.parseInt(inp[0]); int second = Integer.parseInt(inp[1]); int result = 0; for (int j = first; j < second; j++) { String str = Integer.toString(j); str += str; //System.out.println(str); //System.out.println(len); ArrayList arr = new ArrayList(); for (int k = 1; k < len; k++) { int x = Integer.parseInt(str. substring(k, k+len)); if (x <= second && x > j) { if (!arr.contains(new Integer(x))) { arr.add(new Integer(x)); result++; } //System.out.println(j + "" "" + x); } //System.out.print(x + "" ""); } } System.out.println(result); String res = Integer.toString(result); bw.write(res, 0, res.length()); bw.newLine(); } br.close(); bw.close(); } }" B21847,"import java.io.*; import java.util.HashMap; class GoogleRecycle{ public static int[] findNext(String s, int n) { int a[]= new int[n]; for (int i =0; i0) { temp=temp/10; n++; } line = line.substring(line.indexOf(' ')+1); int end = Integer.parseInt(line); int count =0; for (int j=start;j<=end;j++) { int[] a =new int[n]; Integer x = j; a= findNext(x.toString(),n); HashMap map = new HashMap(); int flag = 0; for (int p: a) { if(p>j && p<=end && p!=0 && !map.containsKey(p)) { map.put(p, null); count++; } } } //System.out.println(""Reached here also""); out.write(""Case #""+i+"": ""+count); if(i!=testcases) { out.write(""\n""); } } out.close(); br.close(); } }" B21998,"package com.techy.rajeev; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Recycled { public static int[] toIntArray(String line){ String[] p = line.trim().split(""\\s+""); int[] out = new int[p.length]; for(int i=0;i0){ int arr[]=toIntArray(br.readLine()); int x=arr[0]; int y=arr[1]; String past=""""; for(int i=x;i<=y;i++){ String temp=i+""""; for(int j=temp.length()-1,m=1;j>0;j--,m++){ String test=temp.substring(m)+temp.substring(0,m); if(test.equals(past)){ break; } int lk=Integer.parseInt(test); if(lk>i&&lk<=y){ count++; past=test; } } } bw.write(""Case #""+k+"": ""+count); bw.newLine(); count=0; num--; k++; } br.close(); bw.close(); } } " B22034,"package com.menzus.gcj._2012.qualification.c; import com.menzus.gcj.common.Input; public class CInput implements Input { private int upperLimit; private int lowerLimit; public int getUpperLimit() { return upperLimit; } public void setUpperLimit(int upperLimit) { this.upperLimit = upperLimit; } public int getLowerLimit() { return lowerLimit; } public void setLowerLimit(int lowerLimit) { this.lowerLimit = lowerLimit; } } " B21635,"package codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.math.BigInteger; import java.util.HashSet; import java.util.Set; public class Codejam { private static File[] getInputFiles(String filePath) { File dir = new File(filePath); // filter .in files FilenameFilter onlyInFiles = new FilenameFilter() { public boolean accept(File file, String name) { return name.endsWith("".in"") || file.isFile(); } }; File[] inputFiles = dir.listFiles(onlyInFiles); return inputFiles; } private static BigInteger binomial(final int N, final int K) { BigInteger ret = BigInteger.ONE; for (int k = 0; k < K; k++) { ret = ret.multiply(BigInteger.valueOf(N - k)).divide( BigInteger.valueOf(k + 1)); } return ret; } private static Set getCombinations(String numberStr, int min, int max) { // System.out.println(""numberStr "" + numberStr); Set allStrings = new HashSet(); char[] numberStrChars = numberStr.toCharArray(); String currentNumber; int StrLength = numberStrChars.length; // System.out.println(""StrLength "" + StrLength); for (int i = 0; i < StrLength - 1; i++) { char firstChar = numberStrChars[0]; for (int j = 1; j < StrLength; j++) numberStrChars[j - 1] = numberStrChars[j]; numberStrChars[StrLength - 1] = firstChar; currentNumber = new String(numberStrChars); // System.out.println(""currentNumber "" + currentNumber); if (!currentNumber.equals(numberStr) && Integer.parseInt(currentNumber) >= min && Integer.parseInt(currentNumber) <= max) allStrings.add(currentNumber); } return allStrings; } private static BigInteger getRecycledPairs(int min, int max) { //System.out.println(""getRecycledPairs start""); BigInteger recycledPairs = BigInteger.ZERO; Set recycledPairStrings = new HashSet(); for (int i = min; i <= max; i++) { String currentNumber = Integer.toString(i); if (!recycledPairStrings.contains(currentNumber)) { Set currentCombinations = getCombinations( currentNumber, min, max); if (currentCombinations.size() > 0) { recycledPairStrings.addAll(currentCombinations); recycledPairs = recycledPairs.add(binomial( currentCombinations.size() + 1, 2)); } } } //System.out.println(""getRecycledPairs end "" + recycledPairs); return recycledPairs; } private static void processFile(File fileName) { System.out.println(""Processing file "" + fileName); try { // get reader for current file BufferedReader br = new BufferedReader(new FileReader(fileName)); // create writer using current file + .out BufferedWriter bw = new BufferedWriter(new FileWriter( fileName.getAbsolutePath() + "".out"")); // get test cases int testCases = Integer.parseInt(br.readLine()); // process all test cases for (int currTestCase = 1; currTestCase <= testCases; currTestCase++) { String[] ab = br.readLine().split("" ""); int A = Integer.parseInt(ab[0]), B = Integer.parseInt(ab[1]); BigInteger result = getRecycledPairs(A, B); String currTestCaseResult = ""Case #"" + currTestCase + "": "" + result; System.out.println(currTestCaseResult); bw.write(currTestCaseResult); bw.newLine(); } // close the reader and writer br.close(); bw.flush(); bw.close(); } catch (Exception e) {// catch exception if any System.err.println(""Error: "" + e.getMessage()); } } /** * @param args */ public static void main(String[] args) { System.out.println(""start""); // get files to process File[] inputFiles = getInputFiles(""data""); if (inputFiles != null) { for (File inputFile : inputFiles) processFile(inputFile); } } } " B21918," public class UniqueList { private int[] number; private int totalSize, size; public UniqueList(int allocatedSize) { totalSize = allocatedSize; number = new int[totalSize]; size = 0; } public void add(int n) { for (int i = 0; i < size; i++) { if (number[i] == n) return; } number[size ++] = n; } public int getSize() { return size; } } " B20392,"package com.googlerese.file; import java.io.*; import java.util.HashMap; import java.util.Map; public class FileRead { private static FileRead instance = new FileRead(); private FileRead() { } public static FileRead getInstance() { return instance; } public Map read( final String fileName ) { FileInputStream fstream = null; DataInputStream in = null; BufferedReader br = null; Map input = null; try { // Open the file that is the first // command line parameter fstream = new FileInputStream( fileName ); // Get the object of DataInputStream in = new DataInputStream( fstream ); br = new BufferedReader( new InputStreamReader( in ) ); String strLine; //Read File Line By Line int count = 0; while ( ( strLine = br.readLine() ) != null ) { // Print the content on the console if ( count == 0 ) { input = new HashMap( Integer.parseInt( strLine ) ); } else { System.out.println( count + "" : "" + strLine ); String[] arr = strLine.split( ""\\s+"" ); input.put( count, arr ); } count++; } } catch ( Exception e ) {//Catch exception if any System.err.println( ""Error: "" + e.getMessage() ); } finally { //Close the input stream try { if ( br != null ) { br.close(); } if ( in != null ) { in.close(); } if ( fstream != null ) { fstream.close(); } } catch ( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } return input; } } " B21128,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class ReadFile { private static ArrayList elements = new ArrayList(); public static void read(String path) throws IOException{ //BufferedReader br = new BufferedReader(new FileReader(""C:\\test\\input.txt"")); BufferedReader br = new BufferedReader(new FileReader(path)); String thisLine; while ((thisLine = br.readLine()) != null) { // while loop begins here elements.add(thisLine); } br.close(); } public static ArrayList getElements() { return elements; } } " B22120,"package com.google.codejam.recycle; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.util.LinkedList; import java.util.List; /** * Class to read input file and prepare list of test cases. * @author Sushant Deshpande */ public class InputReader { /** * Method for preparing List of Test Cases. * @param inputFilePath String * @return List */ public static List prepareTestCases(final String inputFilePath) { final List testCases = new LinkedList(); LineNumberReader lineReader = null; try { lineReader = new LineNumberReader(new FileReader(inputFilePath)); final String line = lineReader.readLine(); final int noOfTCs = Integer.parseInt(line); for(int i = 0; i < noOfTCs; i++) { String [] inputLine = lineReader.readLine().split("" ""); int low = Integer.parseInt(inputLine[0]); int high = Integer.parseInt(inputLine[1]); TestCase testCase = new TestCase(i + 1, low, high); testCases.add(testCase); } } catch(IOException ie) { System.out.println(""Problem occured while reading input file. "" + ie.getMessage()); } finally { if(lineReader != null) { try { lineReader.close(); } catch(IOException ie) { System.out.println(""Some problem occured while closing input file reader "" + ie.getMessage() ); } } } return testCases; } }" B20084,"import java.util.*; class Main { public static void main(String[] arg) { Scanner in = new Scanner(System.in); int trials = in.nextInt(); int tt = 0; while(tt < trials) { int ret = 0; int A = in.nextInt(); int B = in.nextInt(); for(int i=A; i oNums = new HashSet(); for(int j=1; j i && val <= B) { ++ret; } oNums.add(num); } } } System.out.println(""Case #"" + ++tt + "": "" + ret); } } }" B22122,"package com.google.codejam.recycle; import java.util.List; /** * Created by IntelliJ IDEA. * User: sushant * Date: 14 Apr, 2012 * Time: 11:13:34 AM * To change this template use File | Settings | File Templates. */ public class RecycledNumbers { /** * Main method from where application start execution. * * @param args String [] */ public static void main(final String[] args) { if (args.length != 1) { System.out.println(""Problem with the command used for execution""); System.out.println(""Usage: java com.google.codejam.googlerese.RecycledNmbers ""); System.exit(1); } final List testCases = InputReader.prepareTestCases(args[0]); if (testCases != null && testCases.size() != 0) { long startTime = System.currentTimeMillis(); System.out.println(""Test Cases execution start time "" + startTime); for (TestCase testcase : testCases) { executeTestCase(testcase); } OutputRecorder.generateTestReport(testCases, args[0] + "".out""); long endTime = System.currentTimeMillis(); System.out.print(""Test cases execution end time "" + endTime); System.out.println(""Total Execution Time "" + (endTime - startTime) + "" milliseconds""); } } /** * Method to execute test cases. * * @param testcase TestCase */ private static void executeTestCase(final TestCase testcase) { int recycleNumberCount = 0; final int low = testcase.getLow(); final int high = testcase.getHigh(); final int length = Integer.toString(low).length(); for(int i = low; i <= high; i++) { int previoudNumber = 0; for(int j = 1; j < length; j++) { int divisor = getDivisor(length - j); int mod = i % divisor; int result = i / divisor; int recycleNumber = Integer.parseInt("""" + mod + result); if(previoudNumber != recycleNumber && recycleNumber > i && recycleNumber <= high) { previoudNumber = recycleNumber; recycleNumberCount = recycleNumberCount + 1; } } } testcase.setOutput(new TestResult(recycleNumberCount)); } private static int getDivisor(int noOfZeros) { StringBuilder builder = new StringBuilder().append(1); for(int i = 0; i < noOfZeros; i++) { builder.append(0); } return Integer.parseInt(builder.toString()); } } " B21428,"import java.io.*; import java.security.SecureRandom; import java.util.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { int solve(int a, int b) { HashSet set = new HashSet<>(); for (int i = a; i < b; ++ i) { StringBuilder s = new StringBuilder(Integer.toString(i)); for (int j = 1;j < s.length(); ++ j) { if (s.charAt(j) == '0') { continue; } int x = 0; for (int k = j; k < s.length(); ++ k) { x = 10 * x + s.charAt(k) - '0'; } for (int k = 0; k < j; ++ k) { x = 10 * x + s.charAt(k) - '0'; } if (x > i && x <= b) { set.add(i * 10000000l + x); } } } return set.size(); } public void solve() throws Exception { int t = sc.nextInt(); for (int i = 0;i < t; ++ i) { out.println(""Case #"" + (i + 1) + "": "" + solve(sc.nextInt(), sc.nextInt())); } } /*--------------------------------------------------------------*/ static String filename = """"; static boolean fromFile = false; BufferedReader in; PrintWriter out; FastScanner sc; public static void main(String[] args) { new Thread(null, new Solution(), """", 1 << 25).start(); } public void run() { try { init(); solve(); } catch (Exception e) { throw new RuntimeException(e); } finally { out.close(); } } void init() throws Exception { if (fromFile) { in = new BufferedReader(new FileReader(filename+"".in"")); out = new PrintWriter(new FileWriter(filename+"".out"")); } else { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } sc = new FastScanner(in); } } class FastScanner { BufferedReader reader; StringTokenizer strTok; public FastScanner(BufferedReader reader) { this.reader = reader; } public String nextToken() throws IOException { while (strTok == null || !strTok.hasMoreTokens()) { strTok = new StringTokenizer(reader.readLine()); } return strTok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } public BigDecimal nextBigDecimal() throws IOException { return new BigDecimal(nextToken()); } }" B20088,"import java.io.IOException; import java.util.*; /** * Date: 14/4/12 * Time: 2:02 PM */ public class ProblemC { public static void main(String[] args) throws IOException { long start = System.currentTimeMillis(); ArrayList al = GoogleFileStream.getInput(); ArrayList ret = new ArrayList(); for( String i : al ) ret.add( solution( i ) ); long end = System.currentTimeMillis(); System.out.println( ""Time: "" + (end - start) + ""ms"" ); GoogleFileStream.setOutput(ret); } private static String solution(String in) { ArrayList input = new ArrayList(Arrays.asList(in.split("" ""))); int A = Integer.valueOf( input.get(0) ); int B = Integer.valueOf( input.get(1) ); int count = 0; Set dupeSet = new HashSet(); for( int i = A; i <= B; i++) { String is = String.valueOf(i); char[] c = is.toCharArray(); //System.out.print(i); //System.out.print("":""); dupeSet.clear(); for( int j = 1; j < c.length; j++) { //rotate: char lastChar = c[c.length-1]; System.arraycopy(c,0,c,1,c.length - 1); c[0]=lastChar; int num = Integer.valueOf(new String(c)); if(i < num && num <= B) { if( dupeSet.add(num) ) { // (n,m) = (i, c) count++; //System.out.print(num); //System.out.print("",""); } } } //System.out.println(); } return String.valueOf(count); } }" B21393,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; public class RN { public static void main(String[] args) { Integer caseNum = 0; /*if(args.length == 0) { return; }*/ ArrayList argList = new ArrayList(); String line=null; File inputFile = new File(""RNData.txt""); BufferedReader reader; try { reader = new BufferedReader(new FileReader(inputFile)); while ((line=reader.readLine()) != null) { argList.add(line); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } caseNum = Integer.parseInt(argList.get(0)); for(int caseIndex=0; caseIndex < caseNum.intValue(); caseIndex++) { String input = argList.get(caseIndex+1); System.out.println(""Case #"" + (caseIndex+1) + "": "" + countRecycledPairs(input)); } } private static int countRecycledPairs(String input) { int numOfPairs = 0; String[] inputData = input.split("" ""); if(inputData.length == 2 && inputData[0].length() == inputData[1].length()) { int A = Integer.parseInt(inputData[0]); int B = Integer.parseInt(inputData[1]); numOfPairs = totalPairsBetweenBig(A, B); } return numOfPairs; } private static int totalPairsBetween(int A, int B) { int digitLength = Integer.toString(A).length(); if(digitLength <= 1 || Integer.toString(B).length() != digitLength || A >= B) return 0; int pairsOnA = 0; int[] pairsOfA = new int[digitLength]; for(int i=1; i A && recycleInt <= B) { int pairIndex = 0; while(pairsOfA[pairIndex] != 0) { //System.out.println(""The recycleInt is "" + recycleInt + "" value is "" + pairsOfA[pairIndex]); if(pairsOfA[pairIndex] == recycleInt) break; pairIndex++; }; if(pairsOfA[pairIndex] == 0) { pairsOfA[pairIndex] = recycleInt; //System.out.println(""save "" + pairsOfA[pairIndex]); pairsOnA++; } } } return pairsOnA + totalPairsBetween(A+1, B); } private static int totalPairsBetweenBig(int A, int B) { int digitLength = Integer.toString(A).length(); if(digitLength <= 1 || Integer.toString(B).length() != digitLength || A >= B) return 0; int totalPairs = 0; while(A < B) { int pairsOnA = 0; int[] pairsOfA = new int[digitLength]; for(int i=1; i A && recycleInt <= B) { int pairIndex = 0; while(pairsOfA[pairIndex] != 0) { //System.out.println(""The recycleInt is "" + recycleInt + "" value is "" + pairsOfA[pairIndex]); if(pairsOfA[pairIndex] == recycleInt) break; pairIndex++; }; if(pairsOfA[pairIndex] == 0) { pairsOfA[pairIndex] = recycleInt; //System.out.println(""save "" + pairsOfA[pairIndex]); pairsOnA++; } } } totalPairs += pairsOnA; A++; } return totalPairs; } } " B21901,"package codejam03; import java.io.*; import java.util.StringTokenizer; public class CodeJam03 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T,A,B; String temp1,temp2; int output,n; T = Integer.parseInt(br.readLine()); for(int i=0; ij && Integer.parseInt(temp2)<=B) output++; if(n==j) break; } } System.out.println(""Case #"" +(i+1) + "": "" + output); } } } " B21611,"package com.google.codejam; import static java.math.BigInteger.ONE; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Scanner; public class RotatingNumbers { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { new RotatingNumbers().run(); } private int count(BigInteger minValue, BigInteger maxValue) { BigInteger currentNumber = minValue; int counter = 0; while (!maxValue.equals(currentNumber)) { BigInteger candidate = null; int r = 1; while (!currentNumber.equals(candidate)) { candidate = rotateLeft(currentNumber, r++); if (candidate.compareTo(currentNumber) > 0 && candidate.compareTo(maxValue) <= 0 && candidate.compareTo(minValue) >= 0) { counter++; } } currentNumber = currentNumber.add(ONE); } return counter; } private void run() throws FileNotFoundException { BigInteger[][] data = parseInput(""input""); Integer[] result = solve(data); printResult(result, ""output""); } private Integer[] solve(BigInteger[][] data) { Integer[] result = new Integer[data.length]; for (int i = 0; i < data.length; i++) { result[i] = count(data[i][0], data[i][1]); } return result; } private BigInteger rotateLeft(BigInteger value, int digits) { String stringValue = value.toString(10); StringBuilder result = new StringBuilder(stringValue.substring(digits)); result.append(stringValue.substring(0, digits)); return new BigInteger(result.toString(), 10); } private void printResult(Integer[] result, String path) throws FileNotFoundException { PrintWriter p = new PrintWriter(new File(path)); try { for (int i = 1; i < result.length+1; i++) { p.format(""Case #%d: %d\n"", i, result[i-1]); } } finally { p.close(); } } private BigInteger[][] parseInput(String path) throws FileNotFoundException { Scanner scanner = new Scanner(new File(path)); try { BigInteger[][] input = new BigInteger[scanner.nextInt()][2]; scanner.nextLine(); // skip to the next line for (int i = 0; i < input.length; i++) { input[i][0] = new BigInteger(scanner.next()); input[i][1] = new BigInteger(scanner.next()); // scanner.nextLine(); } return input; } finally { scanner.close(); } } } " B21366,"package com.sam.googlecodejam.recyclenumbers; import java.util.HashSet; import java.util.Set; import com.sam.googlecodejam.helper.InputReader; public class RecycleNumbers { long pairCount; public void getPairCount(long a, long b) { int length = Long.toString(a).length(); long power = 1; for (int i = 1; i < length; i++) { power = power * 10; } for (long m = a; m < b; m++) { long value = m; Set pairCountSet = new HashSet<>(); for (int i = 0; i < length; i++) { value = value / 10 + (value % 10) * power; if (value > m && value <= b) { pairCountSet.add(value); } } pairCount = pairCount + pairCountSet.size(); } } public static void main(String[] args) { InputReader reader = new InputReader(""c://input.in""); reader.readNextLine(); // read the line number off - we don't need it String lineRead = null; int i = 1; while ((lineRead = reader.readNextLine()) != null) { RecycleNumbers recycleNumbers = new RecycleNumbers(); String values[] = lineRead.split("" ""); recycleNumbers.getPairCount(Long.parseLong(values[0]), Long.parseLong(values[1])); System.out.println(""Case #"" + i + "": "" + recycleNumbers.pairCount); i++; } } } " B20897,"import java.io.*; public class RecycledNumbers { public static void main(String[] args) { BufferedReader in; BufferedWriter out; int T, i; String line; try { in = new BufferedReader(new FileReader(""input.txt"")); out = new BufferedWriter(new FileWriter(""output.txt"")); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); return; } catch (IOException e) { System.out.println(e.getMessage()); return; } try { T = Integer.parseInt(in.readLine()); for (i = 0; i < T; i++) { line = in.readLine(); String lineToWrite = ""Case #"" + (i+1) + "": ""; lineToWrite += String.valueOf(solve(line)); out.write(lineToWrite + ""\n""); } in.close(); out.close(); } catch (IOException e) { System.out.println(e.getMessage()); return; } } public static int solve(String input) { int a, b, counter; String[] inputs = input.split("" ""); a = Integer.parseInt(inputs[0]); b = Integer.parseInt(inputs[1]); counter = 0; for (int n = a; n < b; n++) { int i; for (i = 10; i < b; i *= 10) { int m = split(n, i); if (m > n && m <= b) counter++; } } return counter; } public static int split(int num, int pow) { int half1, half2; half1 = num/pow; half2 = (num%pow) * (orderOf(num) / pow); return half1 + half2; } public static int orderOf(int num) { int i = 1; while (i < num) { i*=10; } return i; } } " B20305,"package recyclednumbers; import java.util.ArrayList; public class RecycledNumbersCase { private int min; private int max; public RecycledNumbersCase(String scoreLine) { String[] integers = scoreLine.split("" ""); if(integers.length > 2 || integers.length < 2) { throw new IllegalArgumentException(""Exactly two please""); } min = new Integer(integers[0]); max = new Integer(integers[1]); } public int recycledPairCountFromMinToMax() { int pairCount = 0; for(int i = min; i <= max; i++) { pairCount += cycledDigitsInRangeAndGreaterThan(i); } return pairCount; } private int cycledDigitsInRangeAndGreaterThan(final int value) { int matches = 0; final String originalValue = String.valueOf(value); String cycledValue = cycleFromBackToFront(originalValue); while(!cycledValue.equals(originalValue)) { int cycledVal = Integer.valueOf(cycledValue); if(cycledVal > value && cycledVal <= max) { matches++; } cycledValue = cycleFromBackToFront(cycledValue); } return matches; } public int getMin() { return min; } public int getMax() { return max; } public static String cycleFromBackToFront(String numToCycle) { final int numLength = numToCycle.length(); return numToCycle.substring(numLength - 1) + numToCycle.substring(0, numLength - 1); } } " B20596,"package be.mokarea.gcj.recyclednumbers; import java.io.FileInputStream; import java.io.PrintWriter; import be.mokarea.gcj.common.GoogleCodeJamBase; import be.mokarea.gcj.common.TestCaseReader; import be.mokarea.gcj.common.Transformation; public class RecycledNumbers extends GoogleCodeJamBase { private final String outputFileName; private final String inputFileName; public RecycledNumbers(String inputFileName, String outputFileName) { super(); this.inputFileName = inputFileName; this.outputFileName = outputFileName; } /** * @param args */ public static void main(String[] args) { new RecycledNumbers(args[0], args[1]).execute(); } @Override protected Transformation createTransformation( TestCaseReader testCaseReader, PrintWriter outputWriter) throws Exception { return new RecycledNumbersTransformation(testCaseReader,outputWriter); } @Override protected String getOutputFileName() throws Exception { return outputFileName; } @Override protected TestCaseReader getTestCaseReader() throws Exception { return new RecycledNumbersTestCaseReader(new FileInputStream(inputFileName)); } } " B21890,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.StringTokenizer; import java.util.Vector; import java.util.HashMap; public class Algorithm3 { static final String input_path = ""F://workspace//GoogleContest2012//src//input.txt""; static final String output_path = ""F://workspace//GoogleContest2012//src//output.txt""; static int total_case; static int findMax(String line){ StringTokenizer token = new StringTokenizer(line); Integer small = Integer.parseInt((String)token.nextElement()); Integer large = Integer.parseInt((String)token.nextElement()); int number = 0; HashMap map = new HashMap(); for(Integer i=small;ii){ if(map.get(m)==null){ number++; map.put(m, m); } } } } return number; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int i = 0; Vector outputs = new Vector(); try{ File file = new File(input_path); BufferedReader reader =new BufferedReader(new FileReader(file)); String line = reader.readLine(); //skip number total_case = Integer.parseInt(line); while(i= A) cnt++; println(cnt); } // ************************************************************************************* // ****************** FRAMEWORK (borrowed from eireksten and modified) ***************** // ************************************************************************************* public static File input; public static FileReader inputreader; public static BufferedReader in; public static File output; public static FileWriter outputwriter; public static BufferedWriter out; public static StringTokenizer st; public static void main(String[] args) throws Exception { setInput(""problems/""+ PROBLEM_NAME +"".in""); setOutput(""problems/""+ PROBLEM_NAME +"".out""); HashSet dups = new HashSet(); for(int i=1; i<2000000; i++) { for(int j=0; j<7; j++) recycles[i][j] = -1; dups.clear(); String str = String.valueOf(i); int len = str.length(); for(int j=len-1; j>=1; j--) { String cycled = str.substring(len-j ) + str.substring(0, len-j ); Integer integer = Integer.valueOf(cycled); int val = integer.intValue(); if( val > i ) { if( dups.contains(integer) == false ) { dups.add(integer); recycles[i][j] = val; } } } } C c = new C(); int cases = INT(); for(int cc = 1;cc<=cases;cc++) { print(""Case #""+cc+"": ""); c.solveCase(); } close(); } // **************** HELPERS **************************** public static double[] converDoubletArray(ArrayList n){double[] ret=new double[n.size()];for(int i=0;i convertDoubleArray(double[] n){ArrayList arr = new ArrayList();for(int i=0; i n){long[] ret=new long[n.size()];for(int i=0;i convertLongArray(long[] n){ArrayList arr = new ArrayList();for(int i=0; i n){int[] ret=new int[n.size()];for(int i=0;i convertIntArray(int[] n){ArrayList arr = new ArrayList();for(int i=0; i void print( T[] array, String spacer){for(int i=0; i void println( T[] array, String spacer){print(array,spacer);println("""");} @SuppressWarnings(""unchecked"") public static void print( List list ){print(list, "" "");} @SuppressWarnings(""unchecked"") public static void print( List list, String spacer ){int doSpace=0;for( Object obj : list ){ if( doSpace != 0 )print(spacer);print( obj );doSpace++;}} @SuppressWarnings(""unchecked"") public static void println( List list ){println(list, "" "");} @SuppressWarnings(""unchecked"") public static void println( List list, String spacer ){int doSpace=0;for( Object obj : list ){ if( doSpace != 0 )print(spacer);print( obj );doSpace++;} println("""");} // ******************** INPUT DECLARATION ****************** public static void setInput(String filename) throws IOException {input = new File(filename);inputreader = new FileReader(input);in = new BufferedReader(inputreader);} public static void setOutput(String filename) throws IOException {output = new File(filename);outputwriter = new FileWriter(output);out = new BufferedWriter(outputwriter);} public static void close() throws IOException {if(in!=null)in.close();if(inputreader!=null)inputreader.close();if(out!=null)out.flush();if(out!=null)out.close();if(outputwriter!=null)outputwriter.close();} // ************************** INPUT READING ***************** static String LINE() throws IOException { return in.readLine(); } static String TOKEN() throws IOException {while (st == null || !st.hasMoreTokens())st = new StringTokenizer(LINE());return st.nextToken();} static int INT() throws IOException {return Integer.parseInt(TOKEN());} static long LONG() throws IOException {return Long.parseLong(TOKEN());} static double DOUBLE() throws IOException {return Double.parseDouble(TOKEN());} static BigInteger BIGINT() throws IOException {return new BigInteger(TOKEN());} //**************** PERMUTATIONS ********************** // new Permutation(20) will create 20 objects // and steps through the different orderings // // .hasMore() .getTotal() .getNumLeft() // .getNext() .reset() //--------------------------------- class Permutation { private int[] a; private long numLeft; private long total; public Permutation(int n) { a = new int[n]; total = getFactorial (n); reset (); } public void reset () {for (int i = 0; i < a.length; i++) { a[i] = i; } numLeft = total; } public long getNumLeft () { return numLeft; } public long getTotal () { return total; } public boolean hasMore () { return numLeft > 0; } private long getFactorial (int n) { long fact = 1;for (int i = n; i > 1; i--) {fact *= i; } return fact; } public int[] getNext () { if ( numLeft == total) { numLeft--; return a; } int temp; int j = a.length - 2; while (a[j] > a[j+1]) { j--; } int k = a.length - 1; while (a[j] > a[k]) { k--; } temp = a[k]; a[k] = a[j]; a[j] = temp; int r = a.length - 1; int s = j + 1; while (r > s) { temp = a[s]; a[s] = a[r]; a[r] = temp; r--; s++; } numLeft--; return a; } } //**************** COMBINATIONS ********************** //new Combination(24,5) will create 24 objects //and chooses 5 at a time // //.hasMore() .getTotal() .getNumLeft() //.getNext() .reset() //--------------------------------- class Combination { private int[] a; private int n; private int r;private long numLeft;private long total; public Combination (int n, int r) { this.n = n;this.r = r;a = new int[r]; BigInteger nFact = getFactorial (n);BigInteger rFact = getFactorial (r);BigInteger nminusrFact = getFactorial (n - r);total = nFact.divide (rFact.multiply (nminusrFact)).longValue();reset ();} public void reset () {for (int i = 0; i < a.length; i++) {a[i] = i;}numLeft=total;} public long getNumLeft () {return numLeft;} public boolean hasMore () {return numLeft > 0;} public long getTotal () {return total;} private BigInteger getFactorial (int n) {BigInteger fact = BigInteger.ONE;for (int i = n; i > 1; i--) {fact = fact.multiply (new BigInteger (Integer.toString (i)));}return fact;} public int[] getNext () {if (numLeft == total) {numLeft--; return a;}int i = r - 1;while (a[i] == n - r + i) {i--;}a[i] = a[i] + 1; for (int j = i + 1; j < r; j++) { a[j] = a[i] + j - i;} numLeft--; return a;} } //**************** Coloring ********************** //new Coloring(24,5) will create 24 objects //and color each up to 5 different ways. // //.hasMore() .getTotal() .getNumLeft() //.getNext() .reset() //--------------------------------- class Coloring { private int[] a;private int r;private long numLeft; private long total; public Coloring (int n, int r){this.r = r;a = new int[n];total = (long) Math.pow(r, n); reset();} public void reset(){for(int i=0;i 0;} public long getTotal () {return total;} public int[] getNext () {numLeft--;a[0]++;int j=0;while(a[j]==r){a[j]=0;a[j+1]++;j++;}return a;} } public static BigInteger lcm(BigInteger... values) { if (values.length == 0) return BigInteger.ONE; BigInteger lcm = values[0]; for (int i = 1; i < values.length; i++) { if (values[i].signum() != 0) { final BigInteger gcd = lcm.gcd(values[i]); if (gcd.equals(BigInteger.ONE)) { lcm = lcm.multiply(values[i]); } else { if (!values[i].equals(gcd)) { lcm = lcm.multiply(values[i].divide(gcd)); } } } } return lcm; } }" B21237,"package com.google.code; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.TreeMap; public class C extends GCJ { public C() throws IOException { super(); } @Override protected void code(int count) throws IOException { readLine(); int n = getIntInput(0); int m = getIntInput(1); int counter =0; if (m<10) { writeln(0); return; } n = Math.max(n, 10); for (int i=n;i done = new HashMap(); for (int j=1;ji && spinned <=m) { if (done.containsKey(String.valueOf(spinned))) continue; done.put(String.valueOf(spinned), null); counter++; } } } writeln(counter); } /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { new C().run(); } } " B20559,"import java.io.BufferedReader; import java.io.FileReader; import java.util.Arrays; import java.util.TreeSet; public class Main { public static void main(String[] args) throws Throwable { long init = System.currentTimeMillis(); int MAX = 2000001; //int MAX = 201; int arr[][] = new int[MAX][]; { for (int i = 1; i < MAX; i++) { TreeSet set = new TreeSet(); set.add(i); String num = Integer.toString(i); for (int j = 1; j < num.length(); j++) { String newNum = num.substring(j) + num.substring(0, j); if (newNum.charAt(0) != '0') { int n = Integer.parseInt(newNum); if (n > i && !set.contains(n)) { set.add(n); } } } set.remove(i); arr[i] = new int[set.size()]; { int j = 0; for (Integer n : set) arr[i][j++] = n; } } } long end = System.currentTimeMillis(); //BufferedReader in = new BufferedReader(new FileReader(""C-small-attempt0.in"")); //BufferedReader in = new BufferedReader(new FileReader(""c.in"")); BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); for (int i = 0, n = Integer.parseInt(in.readLine().trim()); i < n; i++) { String s[] = in.readLine().trim().split("" +""); int a = Integer.parseInt(s[0]), b = Integer.parseInt(s[1]); int c = 0; for (int j=a; j<=b; j++) { for (int k=0, d; k counted = new HashMap(b - a); int c = 0; for (int i = a; i <= b; i++) { String is = String.valueOf(i); for (int j = 1; j < is.length(); j++) { String ps = is.substring(j, is.length()) + is.substring(0, j); String pair = is + "","" + ps; int p = Integer.valueOf(ps); if (p > i && p <= b && !counted.containsKey(pair)) { c++; counted.put(pair, true); } } } result = result + c; System.out.println(result); outputFile.write(result); if (cn < casesNumber) { outputFile.write(""\n""); } } inputFile.close(); outputFile.close(); } } " B21861,"import java.awt.print.Printable; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class C { public static void main(String[] args) throws IOException { Scanner scanner = null; scanner = new Scanner(new File(""C-large.in"")); // scanner = new Scanner(System.in); FileWriter writer = new FileWriter(""C.out""); int t = scanner.nextInt(); for (int tt = 1; tt <= t ; tt ++ ) { int a = scanner.nextInt(); int b = scanner.nextInt(); String str; int k; int ans = 0; String tmp; for (int i = a; i <= b; i ++) { str = Integer.toString(i); if (str.length() > 1) { for (int j = 1; j < str.length(); j++) { tmp = str.substring(j, str.length()) + str.substring(0,j); if (tmp.startsWith(""0"")) continue; k = Integer.parseInt(tmp); if (k >=a && k <= b && k > i) ans ++; } } } writer.write(String.format(""Case #%d: %d\n"", tt,ans)); System.out.println(String.format(""Case #%d: %d\n"", tt,ans)); } writer.close(); } } " B20317,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class RecycledNumbers { BufferedReader reader; char [] charInput; String [] inputArray; int index; RecycledNumbers()throws Exception{ String input=null; reader = new BufferedReader(new InputStreamReader(System.in)); while(reader.ready()){ if (input==null){ input =reader.readLine(); } else{ input =input+ "" "" + reader.readLine(); } } inputArray=input.trim().split("" ""); index=0; } String nextInput()throws Exception{ if(index prevMatches=new LinkedList(); int numCases=Integer.parseInt(nextInput()); int A; int B; int numRecycledPairs=0; int [] numArray; int digits; int testNum=0; boolean prevExists=false; for(int i=0;i=0;k--){ testNum=testNum/10; if(k==digits-1){ testNum=j; } numArray[k]=testNum%10; } for (int k=1;k=A && testNum<=B && testNum>j && prevExists==false){ numRecycledPairs++; prevMatches.add(new Integer(testNum)); } } } System.out.printf(""Case #%d: %d"", i+1,numRecycledPairs); if (i!=numCases-1){ System.out.println(); } } } //credit to Marian //http://stackoverflow.com/questions/1306727/way-to-get-number-of-digits-in-an-int int numDigits(int n){ if (n < 100000) { // 5 or less if (n < 100) { // 1 or 2 if (n < 10) return 1; else return 2; } else { // 3 or 4 or 5 if (n < 1000) return 3; else { // 4 or 5 if (n < 10000) return 4; else return 5; } } } else { // 6 or more if (n < 10000000) { // 6 or 7 if (n < 1000000) return 6; else return 7; } else { // 8 to 10 if (n < 100000000) return 8; else { // 9 or 10 if (n < 1000000000) return 9; else return 10; } } } } } " B22152,"import java.util.HashSet; import java.util.Scanner; public class RN { static int A,B; static int[] chuso = new int[11]; static int result = 0; // 2121 public static void RN(int n, int B) { HashSet hs = new HashSet(); String ns = Integer.toString(n); int nl = ns.length(); for (int i = 1; i < nl; i++) { String tmp = ns.substring(i); String tmp1 = ns.substring(0, i); String new_num = tmp + tmp1; int m = Integer.parseInt(new_num); if (m > n && m <= B) { //System.out.println(m + "" "" + n); hs.add(m); //result ++; } } result += hs.size(); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int k = 0; k lines = new Vector(); public static void main(String[] arg) { problemC pc = new problemC(); pc.lines = pc.readfile(""C:\\eclipse\\Ashish\\files\\C-large.in""); int nooftestcases = Integer.parseInt(pc.lines.elementAt(0)); System.out.println(nooftestcases); Vector outlines = new Vector(); //int j=1; for (int i=1; i<=nooftestcases; i++) { String[] s = pc.lines.elementAt(i).split("" ""); //int a = Integer.parseInt(s[0]); //int b = Integer.parseInt(s[1]); int k = pc.solveit(s[0], s[1]); String ol = ""Case #"" + i + "": "" + k; outlines.add(ol); System.out.println(s[0] + "" "" + s[1] + "":"" + k); } pc.writefile(""C:\\eclipse\\Ashish\\files\\otestc.txt"", outlines); } public int solveit(String fa, String fb) { int howmany =0; int len = fa.length(); int ia=Integer.parseInt(fa); int ib=Integer.parseInt(fb); for (int cand=ia; cand<=ib; cand++) { String a = String.valueOf(cand); Vector ms = new Vector(); //System.out.println(a); String fno = a.substring(0, 1); //System.out.println(fno); int ifno = Integer.parseInt(fno); for (int i=1; iifno && isno !=0) { String rno = a.substring(i); String afno = a.substring(0, i); String nno = rno + afno; int inno = Integer.parseInt(nno); if (inno>cand && inno <= ib && ms.indexOf(nno) == -1) { ms.add(nno); howmany++; //System.out.println("" :"" + nno); } else { //System.out.println(""Rejected :"" + nno); } } else if (isno==ifno && isno !=0) { String rno = a.substring(i); String afno = a.substring(0, i); String nno = rno + afno; int inno = Integer.parseInt(nno); if (inno>cand && inno <= ib && ms.indexOf(nno) == -1) { ms.add(nno); howmany++; String srno = a.substring(i); String safno = a.substring(0, i); String snno = rno + afno; //System.out.println("" :"" + snno); } } } } return howmany; } public void writefile(String name, Vector l) { try{ // Create file FileWriter fstream = new FileWriter(name); BufferedWriter out = new BufferedWriter(fstream); for (int i=0; i readfile(String fp) { Vector lines = new Vector(); try { FileReader fr = new FileReader(fp); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) { //System.out.println(s); lines.addElement(s); } fr.close(); } catch (Exception e) { System.out.println(e); } return lines; } } " B21234,"import java.util.ArrayList; import java.util.List; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { List inputList = FileIO.readFile(""C-large.in""); List outputList = new ArrayList(); int caseNo = 1 ; int testCaseCount = Integer.parseInt(inputList.get(0)); while (caseNo <= testCaseCount) { Number n = new Number(inputList.get(caseNo)); outputList.add(""Case #"" +caseNo +"": "" +n.getRecycledPairCount()); caseNo++; } FileIO.writeFile(""C-large.out"", outputList); } } " B20852,"import java.util.Scanner; public class Recyclers { private static int countRecycled(int a, int b) { int recycled = 0; for (int i = a; i <= b; i++) { String s = new Integer(i).toString(); for (int j = 0; j < s.length() - 1; j++) { String o = s.substring(s.length() - j - 1, s.length()).concat( s.substring(0, s.length() - j - 1)); int n = Integer.valueOf(s); int m = Integer.valueOf(o); if (n < m && m <= b) { recycled++; } } } return recycled; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int cases = sc.nextInt(); for (int x = 0; x < cases; x++) { sc.nextLine(); int a = sc.nextInt(); int b = sc.nextInt(); int c = countRecycled(a, b); System.out.println(""Case #"" + (x + 1) + "": "" + c); } } } " B20798,"import java.util.*; import java.io.*; import java.lang.Integer; public class C { public static void main(String[] args) throws IOException { Scanner in = new Scanner(new File(""C-large.in"")); Scanner in1 = new Scanner(new File(""C-large.in"")); FileWriter fw = new FileWriter(""C-large.out""); int T = in.nextInt(); in.nextLine(); in1.nextLine(); for (int cases = 1; cases <= T; cases++){ // read the string length for this case String line = in.nextLine(); int len = (line.length() - 1)/2; int valueA = 0; int valueB = 0; int base = 1; int smallNum = in1.nextInt(); int largeNum = in1.nextInt(); int[] number = new int[len]; int total = 0; // get the base number for (int i = 1; i < len; i++){ base = base * 10; } fw.write(""Case #"" + cases + "": ""); for(int i = smallNum; i <= largeNum; i++) { number[0] = i; // fw.write(number[0] + "" ""); for (int j = 1; j < len; j++) { boolean norepeat = false; number[j] = number[j - 1] / base + (number[j - 1] % base) * 10; // fw.write(number[j] + "" ""); if (number[j] >= smallNum && number[j] <= largeNum) { norepeat = true; for (int k = j - 1; k >= 0; k--){ norepeat = norepeat && (number[j] != number[k]); } } if(norepeat) total++; } } total = total / 2; fw.write(total + ""\n""); } fw.flush(); fw.close(); } } " B20735,"package fixjava; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.Map.Entry; public class CountedSet implements Set { HashMap map = new HashMap(); private static final Integer ONE = new Integer(1); public CountedSet(Iterable collection) { for (T t : collection) add(t); } @Override public boolean add(T item) { Integer count = map.get(item); if (count == null) { map.put(item, ONE); return true; } else { map.put(item, count + 1); return false; } } /** New method to fetch count, not in normal Sets. Returns null if key is not in set. */ public Integer get(String key) { return map.get(key); } /** New method to fetch count, not in normal Sets. Returns zero if key is not in set. */ public int getCount(String key) { Integer count = map.get(key); return count == null ? 0 : count; } /** Extra method to iterate over entries consisting of both items and counts */ public Iterator> iteratorWithCounts() { return map.entrySet().iterator(); } /** Extra method to iterate over entries consisting of both items and counts */ public Iterable> iteratableWithCounts() { return map.entrySet(); } /** Convert into sorted list of pairs */ public ArrayList> toListSortedByCount(boolean ascending) { ArrayList> list = Pair.mapToList(map); Pair.sortPairsByRight(list, ascending); return list; } // ----- boilerplate stuff: ----- @Override public boolean addAll(Collection collection) { boolean changed = false; for (T item : collection) { add(item); changed = true; } return changed; } @Override public void clear() { map.clear(); } @Override public boolean contains(Object item) { return map.containsKey(item); } @Override public boolean containsAll(Collection collection) { boolean containsAll = true; for (Object item : collection) { if (!contains(item)) { containsAll = false; break; } } return containsAll; } @Override public boolean isEmpty() { return map.isEmpty(); } /** Just iterates over keys, not counts */ @Override public Iterator iterator() { return map.keySet().iterator(); } @Override public boolean remove(Object item) { return map.remove(item) != null; } @Override public boolean removeAll(Collection collection) { boolean changed = false; for (Object item : collection) { if (remove(item)) { changed = true; break; } } return changed; } @Override public boolean retainAll(Collection arg0) { throw new RuntimeException(""Not implemented""); } @Override public int size() { return map.size(); } /** Just returns keys in array, not counts */ @Override public Object[] toArray() { return map.keySet().toArray(); } /** Just returns keys in array, not counts */ @Override public U[] toArray(U[] arr) { return map.keySet().toArray(arr); } } " B20355,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; public class GCIFileWriter { public GCIFileWriter (File file) throws IOException { mBufferedWriter = new BufferedWriter(new FileWriter(file)); mFile = file; } public void writeResult(GCIResult res) throws IOException { Iterator it = res.iterator(); while(it.hasNext()) { mBufferedWriter.write(it.next() + ""\n""); mBufferedWriter.flush(); } } public void reset() throws IOException { mBufferedWriter.close(); mBufferedWriter = new BufferedWriter(new FileWriter(mFile)); } public void close() throws IOException { mBufferedWriter.flush(); mBufferedWriter.close(); } private BufferedWriter mBufferedWriter; private File mFile; } " B20909,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib; public interface InputConverter { boolean readLine(String data); T generateObject(); } " B21051,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class Recycled { /** * @param args */ public static void main(String[] args) { try{ BufferedReader bf=null; try { int T; bf = new BufferedReader(new FileReader(""src/com/codejam/input/C-large.in"")); T = Integer.parseInt(bf.readLine()); for(int i=0;i uniqueNum = new HashSet(); for(int i=N.length()-1;i>0;i--){ if( Character.getNumericValue(N.charAt(i)) > Character.getNumericValue(max.charAt(0)) ) continue; String M; M=N.substring(0, i); M=N.substring(i,N.length())+M; mNum = Integer.parseInt(M); nNum = Integer.parseInt(N); maxNum = Integer.parseInt(max); if(mNum>nNum && mNum<=maxNum){ uniqueNum.add(M); } } return uniqueNum.size(); } } " B21185,"import java.io.*; import java.util.*; import java.awt.*; import static java.lang.System.*; public class C { public static void main (String [] args) throws IOException {new C().run();} public void run() throws IOException{ Scanner file = new Scanner(new File(""C-large.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C.out""))); int times = file.nextInt(); for(int asdf = 0; asdf set = new HashSet(); for(int i = a; i<=b; i++){ String s = """"+i; for(int j = 1; j= s.charAt(0) ){ int x = Integer.parseInt(s.substring(j,s.length()) +s.substring(0,j)); if( i num && x <= B && x != prev){ result ++; prev = x; } factor *= 10; toFront = num%factor; toBack = num/factor; } num ++; } System.out.println(""Case #"" + caseNum + "": "" + result); } }" B20750,"package fixjava; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class IOUtils { public static void writeLinesToFile(List lineList, File outputFile) { try { PrintWriter writer = new PrintWriter(outputFile); for (String line : lineList) writer.println(line); writer.close(); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public static void writeLinesToFile(List lineList, String outputFilename) { writeLinesToFile(lineList, new File(outputFilename)); } // --------------------------------------------------------------------------------------------------------- public static ArrayList readLinesFromFile(File inputFile) { ArrayList lines = new ArrayList<>(); for (String line : new FileLineIterator(inputFile)) lines.add(line); return lines; } public static ArrayList readLinesFromFile(String inputFilename) { return readLinesFromFile(new File(inputFilename)); } // --------------------------------------------------------------------------------------------------------- public static String readFileAsString(File inputFile) { int len = (int) inputFile.length() + 1; StringBuilder buf = new StringBuilder(len); for (String line : new FileLineIterator(inputFile)) { buf.append(line); buf.append('\n'); } return buf.toString(); } public static String readFileAsString(String inputFilename) { return readFileAsString(new File(inputFilename)); } } " B20232,"package google2012; import java.io.BufferedReader; import java.io.FileReader; import java.util.HashSet; import java.util.Scanner; public class QRound_C { static public void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(""d:/in.txt"")); int i=0; while (true) { String x = br.readLine(); if (x==null) break; if (i!=0) run (x, i); i++; } } catch (Exception e) { e.printStackTrace(); } } static private void run(String input, int caseid) { int res=0; Scanner sc =new Scanner(input); int a=sc.nextInt(); int b=sc.nextInt(); for (int i=a;i<=b;i++) { res+=sol(i,b); } System.out.printf(""Case #%d: %d%n"", caseid, res); } static private int sol(int num, int max) { String ii=((Integer)num).toString(); HashSet counted =new HashSet(); int r=0; for (int i=0;inum&&!counted.contains(xx)) { counted.add(xx); r++; } } return r; } }" B20656,"package programminginjava; import java.io.*; import java.util.*; import java.lang.Math; class recycledNos { int factorial(int no){ if (no == 1 || no == 0) return 1; else return (no*factorial(no-1)); } public static void main(String [] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader(""recycledNos.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""recycledNos.out""))); recycledNos recycledNosRef = new recycledNos(); int T = Integer.parseInt(f.readLine()); for(int i=0; iB) continue; iterCount++; local.put(no, true); // System.out.println("" and the iterCount is : ""+iterCount); } long noOfCombinations = 0; if(iterCount > 1) noOfCombinations = recycledNosRef.factorial(iterCount)/(recycledNosRef.factorial(iterCount-2)*2); hm.putAll(local); local.clear(); totalPairs += noOfCombinations; } out.println(""Case #""+(i+1)+"": ""+totalPairs); } out.close(); System.exit(0); } }" B20697,"package org.moriraaca.codejam.recyclednumbers; import java.io.InputStream; import org.moriraaca.codejam.GeneralDataParser; public class RecycledNumberDataParser extends GeneralDataParser { public RecycledNumberDataParser(InputStream input) { super(input); } @Override protected void doParse() { for (int i = 0; i < testCases.length; i++) { RecycledNumbersTestCase tc = new RecycledNumbersTestCase(); tc.A = scanner.nextInt(); tc.B = scanner.nextInt(); testCases[i] = tc; } } } " B21057,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class CodeJam2012C { public static void main(String [] args) throws FileNotFoundException { new CodeJam2012C().go(); } public void go() throws FileNotFoundException { PrintWriter writer = new PrintWriter(new File(""output.txt"")); Scanner in = new Scanner(new File(""C-large.in"")); // Scanner in = new Scanner(System.in); int iterations = in.nextInt(); for (int i = 0; i < iterations; i++) { int A = in.nextInt(); int B = in.nextInt(); int counter = 0; for (int j = 0; j < (B - A); j++) { String s = (j + A) + """"; for (int k = 0; k < s.length() - 1; k++) { s = s.substring(1) + s.charAt(0); int temp = Integer.parseInt(s); if (temp <= B && (j + A) < temp) counter++; } } // System.out.println(""Case #"" + (i + 1) + "": "" + counter); writer.write(""Case #"" + (i + 1) + "": "" + counter + ""\n""); } writer.flush(); writer.close(); } } " B20834,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.HashSet; public class Recycled { public static void main(String[] args) throws Exception { Recycled object = new Recycled(); object.solve(object.getClass().getSimpleName().toLowerCase()); } public HashSet hash; public int powersOfTen[]; private void solve(String filePrefix) throws Exception { StreamTokenizer st = new StreamTokenizer(new BufferedReader(new FileReader(filePrefix + "".in""))); PrintWriter pw = new PrintWriter(new FileWriter(filePrefix + "".out"")); st.nextToken(); int testsCount = (int) st.nval; for (int tc=0; tc 0) { temp /= 10; digits++; } powersOfTen = new int[digits]; powersOfTen[0] = 1; for (int i=1; i(); for (int n=a; n b) continue; long encoded = (n+0L) << 30L; encoded += m; if (encoded < 0) throw new RuntimeException(); hash.add(encoded); } } } " B21987," import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author edemairy */ public class Main { private final static Logger logger = Logger.getLogger(Main.class.getName()); private static int nbTC; private static StringBuilder result = new StringBuilder(); /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { logger.setLevel(Level.OFF); // Scanner scanner = new Scanner(System.in); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); nbTC = readInt(reader); // scanner.nextLine(); for (int tc = 1; tc <= nbTC; ++tc) { result.append(""Case #"" + tc + "": ""); result.append(oneTestCase(reader)); result.append('\n'); } System.out.print(result); } private static TreeSet found = new TreeSet(); private static TreeSet cycle = new TreeSet(); private static int[] p10 = {1, 10, 100, 1000, 10000, 100000, 1000000}; private static StringBuilder oneTestCase(BufferedReader reader) throws IOException { int A = readInt(reader); int B = readInt(reader); int rnum = 0; found.clear(); fori: for (int i = A; i <= B; ++i) { cycle.clear(); int lg = (int) Math.floor(Math.log10(i)); if (lg == 0) { continue fori; } if (found.contains(i)) { continue fori; } do { if (i >= p10[lg]) { if ((i >= A) && (i <= B)) { cycle.add(i); } } int ld = i % 10; i /= 10; i += p10[lg] * ld; } while (!cycle.contains(i)); int n = cycle.size(); if (n != 1) { rnum += n * (n - 1) / 2; found.addAll(cycle); } } Formatter formatter = new Formatter(); StringBuilder result = new StringBuilder(); // for (int i = 0; i < 5; ++i) { // formatter.format(""%3d"", n[i]); // } // result.append(formatter.out()); result.append(rnum); return result; } private static int readInt(BufferedReader reader) throws IOException { int result = 0; boolean positive = true; char currentChar = (char) reader.read(); while ((currentChar == ' ') || (currentChar == '\n')) { currentChar = (char) reader.read(); } if (currentChar == (char) -1) { throw new IOException(""end of stream""); } if (currentChar == '-') { positive = false; currentChar = (char) reader.read(); } while ((currentChar >= '0') && (currentChar <= '9')) { result = result * 10 + currentChar - '0'; currentChar = (char) reader.read(); } if (positive) { return result; } else { return -result; } } private static char readChar(BufferedReader reader) throws IOException { return (char) reader.read(); } } " B22226,"package probs; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class Problem3 { public static void main(String[] args) { try { String filePath = ""in-large-3.txt""; List input = readInput(filePath); int[] output = process(input); writeOutput(output); } catch (Exception e) { e.printStackTrace(); } } private static int[] process(List input) { int[] result = new int[input.size()]; int count = 0; for (String eachLine : input) { String[] split = eachLine.split("" ""); String min = split[0]; String max = split[1]; int eachResult = processEachTestCase(min, max); result[count] = eachResult; count++; } return result; } private static int processEachTestCase(String min, String max) { int result = 0; int length = min.length(); int minValue = Integer.parseInt(min); int maxValue = Integer.parseInt(max); if(minValue set = new HashSet(); // performing rotations on a number x for (int i = 0; i < length; i++) { int y = rotate(x, i, length); if (x < y && y <= maxValue) { if(!set.contains(y)){ set.add(y); result++; } } } } } return result; } private static int rotate(int x, int i, int length) { int y; int temp = (int) Math.pow(10, i); int remainder = x % temp; y = x / temp; y = y + remainder * (int) (Math.pow(10, (length - i))); return y; } private static List readInput(String filePath) throws FileNotFoundException { List list = new ArrayList(); File file = new File(filePath); Scanner scanner = new Scanner(file); if (scanner.hasNextLine()) { String line = scanner.nextLine(); int testCases = Integer.parseInt(line); } while (scanner.hasNextLine()) { String line = scanner.nextLine(); // System.out.println(line); list.add(line); } return list; } private static void writeOutput(int[] list) { int n = list.length; for (int i = 0; i < n; i++) { System.out.println(""Case #"" + (i + 1) + "": "" + list[i]); } } } " B20199,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Google Code Jam 2012 * * @author 7henick */ public class ProblemC { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); sc.nextLine(); // A <= n < m <= B for (int i = 0; i < T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int count = 0; for (int n = A; n < B; n++) { String nString = String.valueOf(n); Set intSet = new HashSet(); for (int j = 1; j < nString.length(); j++) { char idx = nString.charAt(j); if (idx != '0') { String mString = nString.substring(j) + nString.substring(0, j); int m = Integer.valueOf(mString); if (n < m && m <= B) { intSet.add(m); } } } count += intSet.size(); } System.out.println(""Case #"" + (i + 1) + "": "" + count); if (sc.hasNextLine()) { sc.nextLine(); } } } public static boolean isValid(int n, int m, int B) { return n < m && m <= B; } } " B21510,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; public class RecycledNumbers { static Scanner sc; public static void main(String a[]) throws FileNotFoundException { int n,i; int res; sc= new Scanner(new FileInputStream(""d:\\test\\a.in"")); PrintStream out=new PrintStream(new FileOutputStream(""d:\\test\\a.out"")); n=sc.nextInt(); sc.nextLine(); for(i=1;i<=n;i++) { res=process(); out.println(""Case #""+i+"": ""+res); } } static int process() { int res=0; int low,high,i; low=sc.nextInt(); high=sc.nextInt(); for(i=low;i<=high;i++) res+=value(i,low,high); res=res/2; return res; } static int value(int a,int low,int high) { int i,res=0,n=1,p=10,q,val,prev=0; if(a<10) return 0; if(a<100) { n=2; q=10; } else if(a<1000) { n=3; q=100; } else if(a<10000) { n=4; q=1000; } else if(a<100000) { n=5; q=10000; } else if(a<1000000) { n=6; q=100000; } else { n=7; q=1000000; } for(i=1;i=low && val<=high && val!=a && val!=prev) { prev=val; res++; } p=p*10; q=q/10; } return res; } } " B20122,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; public class crazysolution { /** * @param args * @throws IOException * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO Auto-generated method stub // Scanner sc = new Scanner(System.in); // int N = Integer.parseInt(sc.nextLine()); //System.out.println(getContents(new File(""B-small-attempt1.in""))); setContents(new File(""C-large-attempt.out""),getContents(new File(""C-large.in""))); /*System.out.println(getContents(new File(""in""))); setContents(new File(""out""),getContents(new File(""in"")));*/ // File(""A-small-attempt2.in"")); // System.out.println(isSurprising(8,10,8)); //digitsReplacement(""1114""); } public static int recycledNumber(String str) { int counter=0; String[] input = str.split("" ""); int A = Integer.parseInt(input[0]); // lower bound int B = Integer.parseInt(input[1]); // upper bound HashMap tHashMap = new HashMap(); HashSet tHashSet = new HashSet(); for (int i=A; i<=B;i++){ //tHashSet.add(i); tHashMap.put(Integer.toString(i),0); } for (int i=A; i<=B;i++){ String numberStr = Integer.toString(i); String newNumberStr = null; int sizeNumberStr = numberStr.length(); for (int j=1; j pares = new ArrayList(); String sN = N + """"; //Si es un solo digito no hay par if (sN.length() <= 1) { return 0; } //Evaluamos si el numero tiene los digitos iguales //En este caso el par es el mismo numero //Y como los pares no pueden ser iguales se descarta este caso boolean sameDigit = true; for (int i = 1; i < sN.length() && sameDigit; i++) { sameDigit = sN.charAt(i - 1) == sN.charAt(i); } if (sameDigit) { return 0; } //Comenzamos a buscar los pares String N1, N2; int split = 1; int M, numPair = 0; while (split < sN.length()) { N1 = sN.substring(0, split); N2 = sN.substring(split); M = Integer.parseInt(N2 + N1); //Si empieza en cero, ya los digitos no concuerdan //O Si M es mayor que B se sale del rango //O si N>=M no cumple con la restriccion A ≤ n < m ≤ B if ((N2.indexOf(""0"") == 0) || (M > B) || (N>=M)) { split++; continue; } if(!pares.contains(M)){ pares.add(M); }else{ split++; continue; } numPair++; debug(sN + "" => "" + M + ""["" + N1 + ""-"" + N2 + ""]""); split++; } return numPair; } public static void debug(Object obj) { // System.out.println(obj); } } " B21959,"import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Enumeration; import java.util.Scanner; public class E3 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = null; sc = new Scanner(System.in); /*try { sc = new Scanner(new File(""E3.txt"")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ int fases = sc.nextInt(); for(int j=1; j<=fases; ++j){ int n1 = sc.nextInt(); int n2 = sc.nextInt(); int casos = 0; for(int k=n1; k<=n2; ++k){ String s = k + """"; int l = s.length(); ArrayList arr = new ArrayList(); for(int i=1; i= n1 && ns <= n2 && ns != k && !arr.contains(ns)){ casos++; arr.add(ns); //System.out.println(ns); } } } System.out.println(""Case #"" + j + "": "" + casos / 2); } } } " B20371,"/** * */ package hu.herba.codejam.cj2012.qualification; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import hu.herba.codejam.AbstractCodeJamBase; /** * Recycled Numbers * * @author csorbazoli */ public class ProblemC extends AbstractCodeJamBase { public static void main(String[] args) { new ProblemC(args); } int T; // number of test case public ProblemC(String[] args) { super(args, AbstractCodeJamBase.READER_TYPE); } private boolean contains(String[] pairs, int found, String num) { boolean ret = false; for (int i = 0; i < found; i++) { if (num.equals(pairs[i])) { // * TEST */System.out.println("" Pair already found before: "" + // num); ret = true; break; } } return ret; } private int countRecycled(int A, int B) { int result = 0, len; String strA = Integer.toString(A); String strB = Integer.toString(B); String orig, numbers, num; len = Integer.toString(A).length(); String[] pairs = new String[len]; int found; if (len > 1) { for (int i = A; i <= B; i++) { orig = Integer.toString(i); numbers = orig + orig; found = 0; for (int j = 1; j <= len; j++) { num = numbers.substring(j, j + len); // each pair was counted twice // if (!num.equals(orig) && (num.compareTo(strA) >= 0) // && // (num.compareTo(strB) <= 0)) { if ((num.compareTo(orig) > 0) && (num.compareTo(strA) >= 0) && (num.compareTo(strB) <= 0) && !this.contains(pairs, found, num)) { // *TEST*/ System.out.println("" "" + orig + // "" recycled with "" + // num); pairs[found++] = num; result++; } } } } // *TEST*/System.out.println("" result: "" + result); return result; } /* * (non-Javadoc) * * @see hu.herba.codejam.AbstractCodeJamBase#process(java.io.BufferedReader, * java.io.PrintWriter) */ @Override protected void process(BufferedReader reader, PrintWriter pw) throws IOException, IllegalArgumentException { // The first line of the input gives the number of test cases, T. T test // cases follow, one per line. // Each test case consists of a single line containing the integers A // and B. this.T = this.readInt(reader, ""Number of cases""); int[] items; for (int i = 1; i <= this.T; i++) { items = this.readIntArray(reader, ""testCase""); if (items.length == 2) { if (Integer.toString(items[0]).length() != Integer.toString(items[1]).length()) { System.out.println(""Test case "" + i + "" INVALID: A and B has different length - "" + Arrays.toString(items)); } // * TEST */System.out.println(""Case #"" + i + "": input = "" + // Arrays.toString(items)); // For each test case, output one line containing ""Case #x: y"", // where x is the case number (starting from 1), and y is the // number of recycled pairs (n, m) with A ≤ n < m ≤ B. pw.println(""Case #"" + i + "": "" + this.countRecycled(items[0], items[1])); } else { System.out.println(""Test case "" + i + "" INVALID: test case should contain 2 integers A, B with same length"" + Arrays.toString(items)); } } } } " B21982,"import static java.lang.Double.parseDouble; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.exit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; static int test; static void solve() throws Exception { long a = nextInt(); long b = nextInt(); long p10 = 10; long pp10 = 1; long ans = 0; for (long i = a; i <= b; i++) { while (p10 <= i) { pp10 = p10; p10 *= 10; } for (long x = 10, y = pp10; y > 1; x *= 10, y /= 10) { long ii = i % x * y + i / x; if (ii > i && ii <= b) { ++ans; } else if (ii == i) { break; } } } printCase(); out.println(ans); } static void printCase() { out.print(""Case #"" + test + "": ""); } static void printlnCase() { out.println(""Case #"" + test + "":""); } static int nextInt() throws IOException { return parseInt(next()); } static long nextLong() throws IOException { return parseLong(next()); } static double nextDouble() throws IOException { return parseDouble(next()); } static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); int tests = nextInt(); for (test = 1; test <= tests; test++) { solve(); } in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }" B21238,"package qual; import java.util.HashSet; import java.util.Scanner; import java.util.Set; class RecycledPair { int a; int b; public RecycledPair(int a, int b) { super(); this.a = a; this.b = b; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + (a + b); result = PRIME * result + (a + b); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final RecycledPair other = (RecycledPair) obj; if (a == other.a && b==other.b) return true; if (a == other.b && b==other.a) return true; return false; } } public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); in.nextLine(); for (int t = 0; t < T; t++) { String s = in.nextLine(); String[] limit = s.split("" ""); int A = Integer.parseInt(limit[0]); int B = Integer.parseInt(limit[1]); Set recycledPairsEncountered = new HashSet(); int count = 0; for (int i = A; i <= B; i++) { char[] num = String.valueOf(i).toCharArray(); for (int k = num.length - 1; k >= 1; k--) { String recycledNumber = """"; if (num[k] != '0') { int indx = k; while (indx < num.length) recycledNumber += num[indx++]; indx = 0; while (indx < k) recycledNumber += num[indx++]; } if (!recycledNumber.equals("""")) { int recycledNum = Integer.parseInt(recycledNumber); if (recycledNum != i && recycledNum <= B && recycledNum >= A) { RecycledPair r = new RecycledPair(i, recycledNum); if(recycledPairsEncountered.contains(r)==false) { recycledPairsEncountered.add(r); count++; } } } } } System.out.println(""Case #"" + (t + 1) + "":"" + "" "" + count); } } } " B21578,"package codejam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(new BufferedReader(new FileReader( ""A-large-practice.in.txt""))); Output out = new Output(""B.out""); int T = scanner.nextInt(); for (int t = 1; t <= T; t++) { int A = scanner.nextInt(); int B = scanner.nextInt(); int count = 0; for(int m = A; m < B; m++ ){ String strM = """" + m; HashSet cache = new HashSet(); for(int p = 1; p < strM.length(); p ++){ if(strM.charAt(p) < strM.charAt(0)){ continue; } String strN = strM.substring(p) + strM.substring(0, p); int n = Integer.parseInt(strN); if(n > m && n <= B && !cache.contains(strN)){ cache.add(strN); count ++; //System.out.println(strM + "" "" + strN); } } } out.format(""Case #%d: %d\n"", t, count); } scanner.close(); out.close(); } static class Output { PrintWriter pw; public Output(String filename) throws IOException { pw = new PrintWriter(new BufferedWriter(new FileWriter(filename))); } public void print(String s) { pw.print(s); System.out.print(s); } public void println(String s) { pw.println(s); System.out.println(s); } public void format(String format, Object... args) { pw.format(format, args); System.out.format(format, args); } public void close() { pw.close(); } } } " B22130,"import sun.rmi.runtime.NewThreadAction; import java.io.*; import java.util.*; /** * Created by IntelliJ IDEA. * User: Veniversum * Date: 4/15/12 * Time: 2:26 AM */ public class Q3 { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(""in.txt""))); Scanner scanner = new Scanner(new FileInputStream(""in.txt"")); int cases = scanner.nextInt(); scanner.nextLine(); String output=""""; for (int i= 0;i results = new HashSet(); Scanner sc = new Scanner(scanner.nextLine()); int A = sc.nextInt(); int B = sc.nextInt(); int n; int m; for (int j = A; j <= B;j++) { n = j; m = j; String str = ("""" + m); for (int k = 0; k < ("""" + m).length();k++) { if (A <= n && n < m && m <= B) { results.add(m + "","" + n); } str = str.concat("""" + str.charAt(0)); //adds first digit to end str = str.substring(1); //remove first digit m = Integer.parseInt(str); } } output += ""Case #"" + (i+1) + "": "" + results.size() + ""\n""; PrintWriter outp = new PrintWriter(new FileOutputStream(""out.txt"")); outp.print(output); outp.close(); } System.out.print(output); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B21267,"import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws IOException { String inputName = ""C-large""; FileReader fr = new FileReader(inputName+"".in""); Scanner sc = new Scanner(fr); FileWriter fstream = new FileWriter(inputName+"".out""); BufferedWriter out = new BufferedWriter(fstream); int T = sc.nextInt(); for(int i = 0; i < T; i++){ int A = sc.nextInt(); int B = sc.nextInt(); int ans = 0; for(int n = A; n <= B; n++){ String s = """"+n; ArrayList mlist = new ArrayList(); for(int k = 1; k < s.length(); k++){ String s2 = s.substring(k) + s.substring(0, k); int m = Integer.parseInt(s2); if(m > n && m <= B && !mlist.contains(m)){ //System.out.println(s + "" "" + s2); ans++; mlist.add(m); } } } print(out, ""Case #"" + (i+1) + "": "" + ans); } fr.close(); out.close(); } public static void print(BufferedWriter out, String s) throws IOException{ out.write(s); out.newLine(); System.out.println(s); } } " B21229,"package kjetil.codejam.qualification.recycled; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private static final String INPUT_FILENAME = ""input_recycled/C-large.in""; private static final String OUTPUT_FILENAME = ""output_files/recycled.out""; static class Pair { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } private int n, m; Pair(int n, int m) { this.n = n; this.m = m; } public int getN() { return n; } public int getM() { return m; } } public static void main(String[] args) { try { FileWriter fstream = new FileWriter(OUTPUT_FILENAME); BufferedWriter out = new BufferedWriter(fstream); File file = new File(INPUT_FILENAME); BufferedReader reader = new BufferedReader(new FileReader(file)); int numberOfTestCases = Integer.parseInt(reader.readLine()); for (int i = 0; i < numberOfTestCases; i++) { String[] numberStrings = reader.readLine().split("" ""); int a = Integer.parseInt(numberStrings[0]); int b = Integer.parseInt(numberStrings[1]); int numberOfRecycledPairs = getNumberOfRecycledPairs(a, b); out.write(""Case #"" + (i+1) + "": "" + Integer.toString(numberOfRecycledPairs) +""\n""); } out.close(); reader.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } private static int getNumberOfRecycledPairs(int a, int b) { Set pairs = new HashSet(); for (int n = a; n < b; n++) { String current = Integer.toString(n); for (int j = 1; j < current.length(); j++) { String sub = current.substring(j); if (sub.charAt(0) != '0') { int m = Integer.parseInt(sub+current.substring(0, j)); if (n < m && m <= b ) { pairs.add(new Pair(n, m)); } } } } return pairs.size(); } } " B22013,"package er.dream.codejam.helpers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.List; public class FileHandler { BufferedReader read; BufferedWriter write; public File[] listFiles(){ return new File(""data"").listFiles(); } public void loadFile(File file){ try { read = new BufferedReader(new FileReader(file)); write = new BufferedWriter(new FileWriter(new File(""output/""+file.getName().replace("".in"", "".out"")))); } catch (IOException e) { throw new IllegalStateException(""Couldn't load file: ""+file.getName(),e); } } public void closeConnection(){ try { read.close(); write.close(); } catch (IOException e) { throw new IllegalStateException(""Couldn't close connection"",e); } } public void writeOutput(List outputData){ int line = 1; for(String entry:outputData){ try { write.write(""Case #""+line+"": ""+entry+""\n""); } catch (IOException e) { throw new IllegalStateException(""Error while writing output"",e); } line++; } } public String readString(){ try { return read.readLine(); } catch (IOException e) { throw new IllegalStateException(""Error while reading input"",e); } } public int readInt(){ return Integer.parseInt(readString()); } public long readLong(){ return Long.parseLong(readString()); } public double readDouble(){ return Double.parseDouble(readString()); } public String[] readStringArray(){ return readString().split("" ""); } public int[] readIntArray(){ String[] strings = readStringArray(); int[] ints = new int[strings.length]; for(int i=0;i list = new ArrayList(); for (int i = first; i <= last; ++i) { number = Integer.toString(i); for (int j = 1; j < number.length(); ++j){ newNumber = number.substring(j) + number.substring(0, j); int newNo = Integer.parseInt(newNumber); if ( newNo > i && newNo <= last && !list.contains(newNo)) { // System.out.println( ""("" + i + "", "" + newNo + "")""); list.add(newNo); count++; } } list.clear(); } return count; } public static void main(String[] args) { RecycledNumbers instance = new RecycledNumbers(); try { instance.init(); instance.execute(); instance.end(); } catch (Exception e) { e.printStackTrace(); } } } " B21131,"import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Recycled { public static void main(String[] args) { try { File input = new File(""/Users/mtervahauta/Dev/mikkot/codejam/recycled.input""); //File input = new File(args[0]); FileInputStream fStream = new FileInputStream(input); BufferedReader bReader = new BufferedReader( new InputStreamReader(fStream)); int cases = Integer.parseInt(bReader.readLine()); for (int i = 1; i <= cases; i++) { String[] values = bReader.readLine().trim().split("" ""); solveRecycled(i, values[0], values[1]); } } catch (Exception e) { e.printStackTrace(); } } private static void solveRecycled(int caseNo, String aStr, String bStr) { long a = Long.parseLong(aStr); long b = Long.parseLong(bStr); //Set nms = new HashSet(); long count = 0; for (long n = a; n <= b; n++) { count = findM(count, a, n, b); } System.out.println(""Case #"" + caseNo + "": "" + count); } private static long findM(long count, long a, long n, long b) { List recycledValues = recycledStrings(Long.toString(n)); Set nms = new HashSet(); for (Long recycledN : recycledValues) { long m = recycledN.longValue(); if (n < m && m <= b) { nms.add(n+"":""+m); } } return count + nms.size(); } private static List recycledStrings(String src) { List resp = new ArrayList(); int length = src.length(); String recycled = null; for (int i = 1; i < length; i++) { recycled = src.substring(length - i); recycled = recycled + src.substring(0, length - i); if (!recycled.startsWith(""0"")) resp.add(new Long(Long.parseLong(recycled))); } return resp; } }" B20433,"import java.io.*; import java.util.*; public class GoogleQual2012C { public static void main(String[] args) throws Throwable { new GoogleQual2012C(); } public GoogleQual2012C() throws Throwable { Scanner in = new Scanner(new File(""C-large.in"")); PrintWriter out = new PrintWriter(new FileWriter(""C-large.out"")); int numTests = in.nextInt(); for (int i = 0; i < numTests; i++) { int a = in.nextInt(); int b = in.nextInt(); int total = 0; for (int curr = a; curr < b; curr++) { int numDigits = this.numDigits(curr); int[] alreadySeen = new int[numDigits - 1]; for (int numToTake = 1; numToTake < numDigits; numToTake++) { int recycled = this.moveDigits(curr, numToTake); if (recycled > curr && recycled <= b && !this.contains(alreadySeen, recycled)) { total++; alreadySeen[numToTake - 1] = recycled; } } } out.println(""Case #"" + (i + 1) + "": "" + total); } out.close(); } private int numDigits(int n) { int toRet = 1; while (n >= 10) { n /= 10; toRet++; } return toRet; } private int moveDigits(int num, int numToTake) { int exp = this.numDigits(num) - numToTake; int base = 1; for (int i = 0; i < numToTake; i++) { base *= 10; } int otherBase = 1; for (int i = 0; i < exp; i++) { otherBase *= 10; } return (num / base) + (num % base) * otherBase; } private boolean contains(int[] array, int value) { for (int i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false; } }" B22212,"import java.util.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; public class Main { private void solve() throws Exception { int test = in.nextInt(); for(int t=1; t <= test; ++t) { solveTest(t); out.println(); } } private void solveTest(int testNum) { int a=in.nextInt(); int b=in.nextInt(); int ans = 0; int[] used = new int[10000000]; int T=1; for(int n=a; n <= b; ++n) { String str=Integer.toString(n); ++T; for(int shift=0; shift < str.length(); ++shift) { str = str.substring(1) + str.charAt(0); if (str.charAt(0) == '0') continue; int m = Integer.parseInt(str); if (m < a || m > b || m <= n || used[m] == T) continue; used[m] = T; //out.println(n + "" "" + m); ++ans; } } out.print(""Case #"" + testNum + "": "" + ans); } private void run() { try { long start = System.currentTimeMillis(); in = new FastScanner(""input.txt"", ""output.txt""); solve(); out.flush(); System.err.print(""running time = "" + (System.currentTimeMillis() - start) * 1e-3); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Main main = new Main(); main.run(); } FastScanner in; static PrintWriter out; static class FastScanner { public BufferedReader reader; private StringTokenizer tokenizer; public FastScanner(String input, String output) { try { reader = new BufferedReader(new FileReader(new File(input))); out = new PrintWriter(new File(output)); tokenizer = null; } catch (Exception e) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); tokenizer = null; } } public double nextDouble() { return Double.parseDouble(nextToken()); } public String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { e.printStackTrace(); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } } }" B20519,"import java.util.*; class xyz { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int p=sc.nextInt(); int t=1; while(p!=0) { int z=sc.nextInt(); int b=sc.nextInt(); int cnt=0; for(int i=z;i<=b;i++) { int a[]=new int[5000]; String s=""""+i; int cnt1=0,d=0; int n=Integer.parseInt(s); char c[]=s.toCharArray(); for(int j=1;j<(c.length);j++) { char temp; temp=c[0]; for(int k=0;k<(c.length-1);k++) { c[k]=c[k+1]; } c[c.length-1]=temp; String s1=new String(c); int w=Integer.parseInt(s1); if((w>n)&&(w>=z)&&(w<=b)) { a[d]=w; d++; cnt1++; } } int e=0,cnt2=0; while(a[e]!=0) { cnt2++; e++; } int len=cnt2; for(int l=0;l was = new HashSet(); for ( int i = A; i <= B; i++ ) { int l = Integer.toString( i ).length(); int p = (int)Math.pow( 10, l-1 ); int ii = i; for ( int d = 1; d < l; d++ ) { ii = p*( ii % 10 ) + ( ii / 10 ); if ( ( ii > i && ii >= A && ii <= B ) && was.add( 1000000000l*i + ii ) ) c++; } } bw.append( ""Case #""+n+"": ""+c+""\n"" ); } public static void main( String[] args ) throws Exception { File inputFile = new File( ""inputfiles/qualification/p3/input.txt"" ); FileReader fr = new FileReader( inputFile ); BufferedReader br = new BufferedReader( fr ); int numOfTestCases = Integer.parseInt( br.readLine() ); File outputFile = new File( ""inputfiles/qualification/p3/output.txt"" ); outputFile.delete(); outputFile.createNewFile(); FileWriter fw = new FileWriter( outputFile ); BufferedWriter bw = new BufferedWriter( fw ); for ( int i = 0; i < numOfTestCases; i++ ) { String testCase = br.readLine(); calculate( testCase, bw, i+1 ); } bw.flush(); fw.flush(); bw.close(); fw.close(); } } " B20861,"import java.io.*; import java.util.*; public class C { public static int a; public static int b; public static void main(String[] args) throws Exception{ File f = new File(""C-large.in""); Scanner sc = new Scanner(f); BufferedWriter bw = new BufferedWriter(new FileWriter(""output.txt"")); int n = sc.nextInt(); for(int i = 0;i0) { k++; temp /=10; } int [] v = new int[k+1]; for(int i = a;i<=b;i++) { temp = 0; temp2 = i; for(int j = 0;ji&&temp2<=b) { v[temp] = temp2; temp++; for(int t = 0;t uniq = new ArrayList(); for (int ii = a; ii <= b; ii++) { //System.out.println(ii); String s = """" +ii; String rot = """" + s+s; for (int i = 1; i < s.length(); i++) { String r = rot.substring(i, i+s.length()); if (r.charAt(0) == '0') continue; if (s.compareTo(r) < 0) { if (r.compareTo(""""+b) <= 0) { if (r.compareTo(""""+a) >= 0) { if (!uniq.contains(s+r)) { uniq.add(s+r); //System.out.println(s + "" "" + r); sum++; } } } } } } return sum; } } " B22100,"package qualification.q2; import qualification.common.InputReader; import qualification.common.OutputWriter; import qualification.q1.Q1Solver; /** * Created by IntelliJ IDEA. * User: ofer * Date: 14/04/12 * Time: 18:55 * To change this template use File | Settings | File Templates. */ public class Q2Sim { public static void main(String[] args){ String inputFile = ""input.txt""; String outPutFile = ""output.txt""; String[] lines = InputReader.getInputLines(inputFile); Q2Solver solver = new Q2Solver(); int numOfTests = Integer.parseInt(lines[0]); String[] output = new String[numOfTests]; for (int i = 0 ; i < numOfTests ; i++){ String[] splited = lines[i+1].split("" ""); int n = Integer.parseInt(splited[0]); int s = Integer.parseInt(splited[1]); int p = Integer.parseInt(splited[2]); int[] sums = new int[n]; for (int j = 0 ; j < n ; j++){ int sum = Integer.parseInt(splited[j+3]); sums[j] = sum; } int res = solver.solve(n,s,p,sums); output[i] = ""Case #"" + (i+1) + "": "" + res; } OutputWriter.writeOutput(outPutFile, output); } } " B20063,"import java.io.*; import java.lang.*; class RotateNumber { public static long RotateNumber(long number, long A, long B) { long start = number; long sum = 0; int numdigits = (int) Math.log10((double)number); // would return numdigits - 1 int multiplier = (int) Math.pow(10.0, (double)numdigits); while(true) { long q = number / 10; long r = number % 10; number = number / 10; number = number + multiplier * r; if(number == start) break; if (start < A) break; if (start >= A && start < number && number <= B) { sum++; } } return sum; } public static void main(String[] args) throws IOException { FileInputStream fstream = new FileInputStream(""/tmp/codejam/A-small-practice.in""); //DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); PrintWriter out = new PrintWriter(new File(""/home/peeyushk/tmp/output.ou"")); String strLine; strLine = br.readLine().trim(); int test = Integer.parseInt(strLine); for (int i=0;i> implements Callable { private ArrayList list; private ParallelWorkQueueDynamic workQueue; // Have to create own stack because otherwise we can get stack overflow using normal recursion private ArrayList loStack = new ArrayList(); private ArrayList hiStack = new ArrayList(); private ParallelQuicksort(ArrayList list, int lo, int hi, ParallelWorkQueueDynamic workQueue) { this.list = list; this.workQueue = workQueue; push(lo, hi); } private void push(int lo, int hi) { loStack.add(lo); hiStack.add(hi); } private void exch(int i, int j) { T tmp = list.get(i); list.set(i, list.get(j)); list.set(j, tmp); } private int partition(int lo, int hi) { exch(lo, lo + (hi - lo) / 2); int i = lo; int j = hi + 1; while (true) { for (int idxLo = lo; list.get(++i).compareTo(list.get(idxLo)) < 0 && i != hi;) ; for (int idxLo = lo; list.get(idxLo).compareTo(list.get(--j)) < 0 && j != lo;) ; if (i >= j) break; exch(i, j); } exch(lo, j); return j; } @Override public Void call() { int stackSize = 1; while ((stackSize = loStack.size()) > 0) { // Pop top of stack int lo = loStack.get(stackSize - 1); int hi = hiStack.get(stackSize - 1); loStack.remove(stackSize - 1); hiStack.remove(stackSize - 1); // Go up a stack frame when hi <= lo if (hi > lo) { // Partition final int j = partition(lo, hi); if (j - lo > 1000 && workQueue.hasIdleWorkers()) { // If there is enough work to do to justify multithreading and if there are idle threads, // fork and recurse on one one side of partition on a different thread workQueue.enqueueWork(new ParallelQuicksort(list, lo, j - 1, workQueue)); // Execute other half of subdivision in this thread push(j + 1, hi); } else { // Not worth forking another thread (not enough work to do), or not enough free workers push(lo, j - 1); push(j + 1, hi); } } } return null; } // --------------------------------------------------------- public static > void sortInPlace(ArrayList list, int numThreads) { ParallelWorkQueueDynamic workQueue = new ParallelWorkQueueDynamic(numThreads); workQueue.enqueueWork(new ParallelQuicksort(list, 0, list.size() - 1, workQueue)); workQueue.waitForAllWorkersToQuit(); workQueue.shutdown(); } } " B21427,"package codeJam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Iterator; /** * http://code.google.com/codejam/contest/1460488/dashboard#s=p2 * @author Weiwei Cheng */ public class RecycledNumbers { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(""_input.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""_output.in"")); br.readLine(); String line = null; int count = 0; while((line=br.readLine())!=null){ int num = 0; String[] input = line.split("" ""); int low = Integer.parseInt(input[0]); int high = Integer.parseInt(input[1]); for(int i=low; i=low && j>i){ num++; } } } bw.append(""Case #"" + ++count + "": "" + num); bw.newLine(); } br.close(); bw.close(); } public static int[] getRecycledNumbers(int num){ String str = Integer.toString(num); HashSet set = new HashSet(); for(int i=0; i itr = set.iterator(); int i=0; while(itr.hasNext()){ ans[i++] = itr.next(); } return ans; } } " B20578," import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintStream; import java.util.HashSet; /** * * @author peterboyen */ public class RecycledNumbers { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(""/Users/peterboyen/Downloads/C-large.in"")); String line = br.readLine(); int testCases = Integer.parseInt(line); PrintStream ps = new PrintStream(""/Users/peterboyen/Downloads/C-large.out""); for (int i = 1; i <= testCases; i++) { line = br.readLine(); ps.println(""Case #"" + i + "": "" + solve(line)); } br.close(); ps.close(); } private static int solve(String line) { String[] split = line.split("" ""); int A = Integer.parseInt(split[0]); int B = Integer.parseInt(split[1]); int result = 0; for (int m = A + 1; m <= B; m++) { result += getRecycled(m, A); } return result; } private static int getRecycled(int m, int A) { String M = """" + m; HashSet set = new HashSet(); int result = 0; for (int i = 0; i < M.length() - 1; i++) { M = M.substring(1) + M.charAt(0); if (M.charAt(0) != '0') { int n = Integer.parseInt(M); if (n >= A && n < m && !set.contains(n)) { result++; set.add(n); } } } return result; } } " B20304,"package recyclednumbers; import java.io.File; import java.util.Scanner; public class RecycledNumbersCalculator { public static void main(String[] args) { if(args.length <= 0 || args[0] == null) { System.out.println(""You must enter a file to read""); System.out.println(""Usage: blah ""); System.exit(0); } File argFile = new File(args[0]); try { Scanner googleSpeakScanner = new Scanner(argFile); String firstLine = googleSpeakScanner.nextLine(); Integer linesToScan = new Integer(firstLine); for(int i = 1; i <= linesToScan; i++) { String googleDancerLine = googleSpeakScanner.nextLine(); RecycledNumbersCase recycledNumbersCase = new RecycledNumbersCase(googleDancerLine); System.out.println(String.format(""Case #%d: %d"", i, recycledNumbersCase.recycledPairCountFromMinToMax())); } } catch (Exception e) { e.printStackTrace(); } } } " B21693,"import java.io.*; import java.util.*; public class test3 { public static void main(String[] args) throws Exception { new test3().run(); } PrintWriter out = null; long getCount(int d, int max) { String s = Integer.toString(d); int n = s.length(); HashSet hs = new HashSet(); for (int i = 1; i < n; i++) { StringBuffer sb = new StringBuffer(); sb.append(s.substring(n - i, n)); sb.append(s.substring(0, n - i)); int b = Integer.parseInt(sb.toString()); if (b > d && b <= max) hs.add(b); } return hs.size(); } void run() throws Exception { Scanner in = new Scanner(System.in); out = new PrintWriter(new FileWriter(""codejam.txt"")); int T = in.nextInt(); for (int i = 0; i < T; i++) { int A = in.nextInt(); int B = in.nextInt(); long total = 0; for (int j = A; j <= B; j++) total += getCount(j, B); out.printf(""Case #%d: %d\n"", i + 1, total); } out.close(); } } " B21806,"import java.io.IOException; import java.util.List; public class ReverseWords extends JamProblem { public static void main(String[] args) throws IOException { ReverseWords p = new ReverseWords(); p.go(); } @Override String solveCase(JamCase jamCase) { StringBuilder builder = new StringBuilder(); ReverseWordsCase c = (ReverseWordsCase) jamCase; int length = c.words.length; for (int i = 0; i < length; i++) { String word = c.words[length-i-1]; builder.append(word + "" ""); } return builder.toString(); } @Override JamCase parseCase(List file, int line) { ReverseWordsCase c= new ReverseWordsCase(); c.lineCount = 1; c.words = file.get(line).split("" ""); return c; } } class ReverseWordsCase extends JamCase{ String[] words; }" B21114,"package codeJam; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { private static int inputLength = 1; /** * @param args the command line arguments */ public static void main(String[] args) { String filename = ""RecycledNumbers/input.txt""; if (args.length > 0) { filename = args[0]; } try { Scanner sc = new Scanner (new File(filename)); String input; int testCount = Integer.parseInt(sc.nextLine()); String out = """"; // Split the input into separate tests and collect the output. for (int i = 0; i < testCount; i++) { input = """"; for (int row = 0; row < inputLength; row++) { input += sc.nextLine() + System.lineSeparator(); } out += ""Case #"" + (i+1) + "": ""; out += runTest(input); out += System.lineSeparator(); } System.out.println(out); BufferedWriter output = new BufferedWriter(new FileWriter( ""RecycledNumbers/output.txt"")); output.write(out); output.close(); } catch (FileNotFoundException ex) { System.err.println(""Input file not found""); System.exit(1); } catch (IOException ex) { } } public static String runTest(String input) { boolean[] found = new boolean[2000000]; Scanner sc = new Scanner(input); int lowest = sc.nextInt(); int highest = sc.nextInt(); int recycled = 0; int length = 0; long current = 0; int inRange = 0; ArrayList permutations = new ArrayList(); for (long i = lowest; i <= highest; i++) { if(found[(int)i] == true) { continue; } length = getLength(i); permutations.clear(); current = i; inRange = 1; found[(int)current] = true; while (rotate(current, length) != i) { current = rotate(current, length); if (current <= highest && current >= lowest) { inRange++; found[(int)current] = true; } } recycled += combinations(inRange); } return String.valueOf(recycled); } public static long rotate(Long in, int length) { if (length < 2) { return in; } return in / 10 + ((in % 10) * (int)(java.lang.Math.pow(10.0, (double)length - 1))); } public static int getLength(Long in) { return (int)java.lang.Math.floor(java.lang.Math.log10((double)in))+ 1; } public static int combinations(int count) { if (2 == count) { return 1; } // We don't go high enough to worry about overflow (< 8) long answer = 1; for (int i = count - 2 + 1; i <= count; i++) { answer = answer * i; } for (int j = 2; j > 1; j--) { answer = answer / j; } return (int)answer; } } " B20218,"package gcj; import java.io.BufferedReader; import java.io.FileReader; public class Gcj { private static final String path = ""/home/me/dev/gcj/""; private BufferedReader br = null; private String[] tokens; private int itoken,ntokens; static public void err(String e) { System.out.println(""\n**\n""+e+"" :-)\n""); System.exit(1); } public Gcj(String filename) { try { br = new BufferedReader(new FileReader(path + filename)); } catch (Exception e) { e.printStackTrace(); } } public String rawLine() { String line = null; try { line = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return line; } public String[] readLine() { String line = rawLine(); if (line == null) { tokens = null; ntokens = 0; } else { tokens = line.trim().split(""\\s+""); ntokens = tokens.length; } itoken = 0; return tokens; } private String nextToken() { String err = null; if (ntokens < 1) err = ""There is no token""; else if (itoken >= ntokens) err = ""No more token""; else { return tokens[itoken++]; } Gcj.err(err); return null; } public String sToken() { return nextToken(); } public String[] sBunch() { String[] l = new String[ntokens-itoken]; int i=0; while (itoken < ntokens) l[i++] = tokens[itoken++]; return l; } public char cToken() { return nextToken().charAt(0); } public char[] cBunch() { char[] l = new char[ntokens-itoken]; int i = 0; while (itoken < ntokens) l[i++] = tokens[itoken++].charAt(0); return l; } public int iToken() { return Integer.parseInt(nextToken()); } public int[] iBunch() { int[] l = new int[ntokens-itoken]; int i = 0; while (itoken < ntokens) l[i++] = Integer.parseInt(tokens[itoken++]); return l; } public long lToken() { return Long.parseLong(nextToken()); } public long[] lBunch() { long[] l = new long[ntokens-itoken]; int i = 0; while (itoken < ntokens) l[i++] = Long.parseLong(tokens[itoken++]); return l; } public double dToken() { return Double.parseDouble(nextToken()); } public double[] dBunch() { double[] l = new double[ntokens-itoken]; int i = 0; while (itoken < ntokens) l[i++] = Double.parseDouble(tokens[itoken++]); return l; } // -- utils // keep leading zeroes... public int[] breakdownNumber(String s) { int n = (s == null ? 0 : s.length()); int[] aa = new int[n]; if (n > 0) { char[] cc = s.toCharArray(); for (int i=0 ; i st = new Stack(); int numDigit =0; int temp = A; while(temp != 0) { st.push(temp%10); numDigit++; temp=temp/10; } int[] digitsA = new int[numDigit]; for(int i=0; i=numDigit) sum=sum*10+curDigits[curindex-numDigit]; else sum=sum*10+curDigits[curindex]; curindex=curindex+1; } if((sum<=B)&&(sum>=A)) cycle=true; if(cycle==true) { if(mark[sum-A]!= true) { mark[sum-A]= true; count++; } } } } if(count==7) totalcount=totalcount+21; else if(count==6) totalcount=totalcount+15; else if(count==5) totalcount=totalcount+10; else if(count==4) totalcount=totalcount+6; else if(count==3) totalcount=totalcount+count; else if(count==2) totalcount=totalcount+1; } out.write(""Case #""+(numTest+1)+"": ""+ totalcount +""\n""); } out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } " B21877,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj12_qc; import java.io.FileOutputStream; import java.util.HashSet; import java.util.Scanner; /** * * @author youssefgamil */ public class Gcj12_qC { /** * @param args the command line arguments */ public static String leading0(String txt) { while(txt.charAt(0)=='0') txt=txt.substring(1); return txt; } public static void main(String[] args) throws Exception { HashSet hs=new HashSet(); Scanner sc=new Scanner(System.in); FileOutputStream out=new FileOutputStream(""out.txt""); int a,b,i,j,tc,T; long res=0; String tmp; T=sc.nextInt(); for(tc=1;tc<=T;tc++) { a=sc.nextInt(); b=sc.nextInt(); res=0; for(i=a;i<=b;i++) { // if(hs.contains(i+"""")) // continue; tmp=i+""""; // hs.add(tmp); // System.out.println(tmp+"">""); hs=new HashSet(); for(j=0;j hs = new HashSet(); for (int test=1; test<=tests; test++) { out.print(""Case #""+test+"": ""); int a = nextInt(); int b = nextInt(); int t = Integer.valueOf(a).toString().length(); int dp = 1; for (int i=1; ii && x>=a && x<=b) { hs.add(x*100l*dp+i); res++; } // out.println(i+"" ""+x); } } res = hs.size(); out.println(hs.size()); hs.clear(); } } BufferedReader br; StringTokenizer st; PrintWriter out; public void run() { try { //br = new BufferedReader(new InputStreamReader(System.in)); //out = new PrintWriter(System.out); br = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(""output.txt""); solve(); br.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(123); } } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String s = br.readLine(); if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } double nextDouble() throws IOException { return Double.parseDouble(next()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } public static void main(String[] args) { new Main().run(); } } " B20709,"package ch.socaciu.andrei.codejam; import java.io.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author Andrei Socaciu */ public class Recycled { public static void main(String[] args) throws Exception { String in = ""data/Recycled-large.in.txt""; String out = ""data/Recycled-large.out.txt""; String line = null; BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(in))); List lines = new ArrayList(); while ((line = reader.readLine()) != null) { lines.add(line); } reader.close(); int tests = Integer.parseInt(lines.get(0)); List res = new ArrayList(); int k = 1; for (int i = 1; i <= tests; i++) { line = lines.get(k++); String[] parts = line.split("" ""); int a = Integer.parseInt(parts[0]); int b = Integer.parseInt(parts[1]); int result = solve(a,b); res.add(""Case #"" + i + "": "" + result); } BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out))); for (String re : res) { writer.write(re); writer.write(""\n""); } writer.close(); } private static int solve(int a, int b) { int count = 0; Set unique = new HashSet(); for (int i = a; i < b; i++) { StringBuilder sb = new StringBuilder(Integer.toString(i)); for (int j = 0; j < sb.length() - 1; j++) { char last = sb.charAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1); sb.insert(0, last); if (sb.charAt(0) != '0') { int permutation = Integer.parseInt(sb.toString()); if (permutation >= a && permutation <= b && permutation > i) { String stringForm = i + "", "" + sb; if (unique.add(stringForm)) { count++; } } } } } return count; } } " B20011,"import java.util.*; import java.io.*; public class C { public static void main(String[] args) throws Exception { String inputfilename = args[0]; String outputfilename = args[1]; BufferedReader br = new BufferedReader(new FileReader(inputfilename)); BufferedWriter bw = new BufferedWriter(new FileWriter(outputfilename)); int cases = Integer.valueOf(br.readLine()); for(int i = 0; i < cases; i++) { String[] ele = br.readLine().split("" ""); int A = Integer.valueOf(ele[0]); int B = Integer.valueOf(ele[1]); int result = C.solve(A,B); bw.write(""Case #"" + (i + 1) + "": "" + result + ""\n""); } br.close(); bw.close(); } public static int solve(int A,int B) { int cnt = 0; //System.out.println(""\nDoing "" + A + "" "" + B); String Astr = String.valueOf(A); String Bstr = String.valueOf(B); for(int cur = A; cur <= B; cur++) { String cstr = String.valueOf(cur); //System.out.println(""\n"" + cstr + ""\n""); Set tset = new HashSet(); for(int i = 1; i < cstr.length(); i++) { String tmp = cstr.substring(i) + cstr.substring(0,i); //System.out.println("" "" + tmp); if(tmp.compareTo(cstr) > 0 && tmp.compareTo(Bstr) <= 0 && !tset.contains(tmp)) { cnt++; tset.add(tmp); //System.out.print("" "" + cstr + ""!!"" +tmp); } } } return cnt; } }" B21259,"import java.io.*; import java.util.*; public class C implements Runnable { private MyScanner in; private PrintWriter out; private void solve() { int a = in.nextInt(); int b = in.nextInt(); int mul = 1; int pow = 0; while (a >= mul * 10) { mul *= 10; ++pow; } int ans = 0; int[] lastSeen = new int[b + 1]; for (int i = a; i <= b; ++i) { if (i == mul * 10) { mul *= 10; ++pow; } int temp = i; for (int j = 0; j < pow; ++j) { temp = temp / 10 + mul * (temp % 10); if (temp > i && temp <= b && lastSeen[temp] < i) { ++ans; lastSeen[temp] = i; } } } out.println(ans); } @Override public void run() { in = new MyScanner(); try { out = new PrintWriter(new File(""C-large.out"")); } catch (FileNotFoundException e) { e.printStackTrace(); } int tests = in.nextInt(); for (int i = 0; i < tests; ++i) { out.print(""Case #"" + (i + 1) + "": ""); solve(); } in.close(); out.close(); } public static void main(String[] args) { new C().run(); } class MyScanner { private BufferedReader br; private StringTokenizer st; public MyScanner() { try { br = new BufferedReader(new FileReader(""C-large.in"")); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } public boolean hasNext() { while (st == null || !st.hasMoreTokens()) { try { String s = br.readLine(); if (s == null) { return false; } st = new StringTokenizer(s); } catch (IOException e) { e.printStackTrace(); return false; } } return st != null && st.hasMoreTokens(); } private String next() { while (st == null || !st.hasMoreTokens()) { try { String s = br.readLine(); if (s == null) { return null; } st = new StringTokenizer(s); } catch (IOException e) { e.printStackTrace(); return null; } } return st.nextToken(); } public String nextLine() { try { st = null; return br.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }" B20309,"import java.io.FileInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] args) { ArrayList answer = read(""/home/zehortigoza/Downloads/codejam/c/input.txt""); int tt = 0; int amount = 1; for (int i = 0; i < answer.size(); i++) { String line = answer.get(i); if (i == 0) { tt = Integer.parseInt(line); } else { if (tt >= amount) { HashMap count = new HashMap(); String[] splited = line.split("" ""); String a = splited[0]; String b = splited[1]; int aInt = Integer.parseInt(a); int bInt = Integer.parseInt(b); if (! (a.length() == 1 && b.length() == 1)) { ArrayList range = range(aInt, bInt); for (int z = 0; z < range.size(); z++) { String currentN = range.get(z)+""""; String currentM = range.get(z)+""""; int length = currentM.length(); for (int j = 0; j < length; j++) { currentM = currentM.charAt(length-1) + currentM.substring(0, length - 1); int currentNInt = Integer.parseInt(currentN); int currentMInt = Integer.parseInt(currentM); if (currentMInt <= bInt && currentMInt > currentNInt && currentMInt >= aInt) { if(count.get(currentN+currentM) == null) { count.put(currentN+currentM, true); } } } } } System.out.println(""Case #"" + amount + "": "" + count.size()); amount++; } } } } private static ArrayList range(int start, int end) { ArrayList list = new ArrayList(); if (start > end) { System.out.println(""error to build range""); return null; } for (int i = start; i <= end; i++) { list.add(i); } return list; } private static ArrayList read(String url) { ArrayList lines = new ArrayList(); Scanner scanner = null; try { scanner = new Scanner(new FileInputStream(url)); while (scanner.hasNextLine()) { lines.add(scanner.nextLine()); } } catch (Exception e) { e.printStackTrace(); } finally { if (scanner != null) { scanner.close(); } } return lines; } } " B21253,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Iterator; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class C implements CodeJamCaseSolver { int a, b; @Override public void input(Scanner in) { a = in.nextInt(); b = in.nextInt(); } @Override public String solve() { int count = 0; for(int i=a;i<=b;i++) { int n = i; String s = Integer.toString(i); Set mset = new HashSetFactory().create(); for(int j=0;j caseIndexToSolve = createCaseIndicesToSolve(casen, caseIndices); ExecutorService executor = Executors.newFixedThreadPool(threadNumber); for(int i=0;i createCaseIndicesToSolve(int casen, Integer... caseIndices) { final java.util.Set set = new java.util.TreeSet(); if(caseIndices.length == 0) { for(int i=1;i<=casen;i++) set.add(i); } else { for(int v : caseIndices) { if(v < 1 || v > casen) throw new RuntimeException(""invalid index : "" + v); set.add(v); } } return set; } private static void printLine() { for(int i=0;i<100;i++) System.out.print(""-""); System.out.println(); } private static int countNotNull(final String[] results) { int solved = 0; for(String s : results) if(s != null) solved++; return solved; } private static void outputProgess(long startTime, int solved, int caseNumberToSolve) { long duration = System.currentTimeMillis() - startTime; long estimation = (long)Math.round((double)duration * caseNumberToSolve / solved / 1000); System.out.printf(""%.03fs : %d/%d solved (estimated : %dm %ds)\n"", (double)duration / 1000, solved, caseNumberToSolve, estimation / 60, estimation % 60); } private static void outputResult(final String[] results, String outputFilePath) throws FileNotFoundException { PrintStream ps = new PrintStream(outputFilePath); for(int i=0;i Set create() { return new SetWrapper(new HashSet()); } } interface Set extends Container { void clear(); void insert(T v); void insertAll(Iterable a); boolean contains(T v); void remove(T v); } interface Container extends Iterable { int size(); boolean isEmpty(); } interface SetFactory { Set create(); } class SetWrapper extends AbstractSet { private final java.util.Set set; public SetWrapper(java.util.Set set) { this.set = set; } public void clear() { set.clear(); } public boolean contains(T v) { return set.contains(v); } public void insert(T v) { set.add(v); } public Iterator iterator() { return set.iterator(); } public int size() { return set.size(); } public void remove(T v) { set.remove(v); } } abstract class AbstractSet implements Set { final public void insertAll(Iterable a) { for(T v : a) insert(v); } @Override final public boolean isEmpty() { return size() == 0; } final public String toString() { String r = """"; for(T v : this) { if(!r.isEmpty()) r += "",""; r += v; } return ""{"" + r + ""}""; } } " B21689,"import java.io.*; import java.util.StringTokenizer; public class klick { public static void main(String []args) { try{ FileInputStream fstream = new FileInputStream(""input.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int n=0; int i; while ((strLine = br.readLine()) != null) { n=n+1; if (n==1) i = Integer.parseInt(strLine); else System.out.println (parse(strLine,n-1)); } in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private static String parse(String string1,int oo) { String str=""""; int count =0; long aa = 0; long bb = 0; StringTokenizer stringTokenizer = new StringTokenizer(string1); while(stringTokenizer.hasMoreTokens()) { aa = Integer.parseInt(stringTokenizer.nextToken()); bb = Integer.parseInt(stringTokenizer.nextToken()); } for (long i = aa ; i < bb; i = i+1) { ///////////// if(i<10) { count = 0; } ///////////////////////// else if(i>=10 && i<100) { int m = (int) (i/10); int n = (int) (i%10); int nm = 10*n + m; if(i=100 && i<1000) { int mn = (int) (i/10); int z = (int) (i%10); int zmn = 100*z + mn; if(i=1000 && i<10000) { int mnz = (int) (i/10); int t = (int) (i%10); int tmnz = 1000*t + mnz; if(i=10000 && i<100000) { int mnzt = (int) (i/10); int w = (int) (i%10); int wmnzt = 10000*w + mnzt; if(i=100000 && i<1000000) { int mnzt = (int) (i/10); int w = (int) (i%10); int wmnzt = 100000*w + mnzt; if(i=1000000 && i<10000000) { int mnzt = (int) (i/10); int w = (int) (i%10); int wmnzt = 1000000*w + mnzt; if(i=10000000 && i<100000000) {} else {} ////////////// } return ""Case #""+oo+"": ""+count; } } " B20459,"package C; import java.io.*; import java.util.ArrayList; public class Main { public static void main(String[] args) { new Main().go(); } public void go() { BufferedReader in = null; BufferedWriter out = null; try{ in = new BufferedReader(new FileReader(""C-large.in"")); out = new BufferedWriter(new FileWriter(""C-large.out"")); int T = Integer.parseInt(in.readLine()); System.out.println(""T=""+T); for(int i=0;i list = new ArrayList(); for(int k=1;kn) { boolean iswin = true; for(int y=0;y h = new HashSet(); for (int n = A; n <= B; ++n) { int nn = n; nn = (nn%pow)*10 + (nn/pow); while (nn != n) { if (A <= nn && nn <= B) { if (nn < n) { h.add(1L*nn*pow*10+n); } else { h.add(1L*n*pow*10+nn); } } nn = (nn%pow)*10 + (nn/pow); } } return h.size(); } public void run() { int n = nextInt(); for (int i = 0; i < n; ++i) { int A = nextInt(); int B = nextInt(); long ans = solve(A, B); out.println(""Case #""+(i+1)+"": ""+ans); } out.flush(); } private static BufferedReader br = null; private static StringTokenizer stk = null; private static PrintWriter out = null; public static void main(String[] args) throws IOException { br = new BufferedReader(new FileReader(new File(""D:\\C.txt""))); out = new PrintWriter(""D:\\CC.txt""); (new Thread(new C())).start(); } public void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } public String nextLine() { try { return (br.readLine()); } catch (IOException e) { e.printStackTrace(); } return null; } public int nextInt() { while (stk==null || !stk.hasMoreTokens()) loadLine(); return Integer.parseInt(stk.nextToken()); } public long nextLong() { while (stk==null || !stk.hasMoreTokens()) loadLine(); return Long.parseLong(stk.nextToken()); } public double nextDouble() { while (stk==null || !stk.hasMoreTokens()) loadLine(); return Double.parseDouble(stk.nextToken()); } public String nextWord() { while (stk==null || !stk.hasMoreTokens()) loadLine(); return (stk.nextToken()); } } " B22071,"package qualification_2012; import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class C { public void run() { try { Scanner in = new Scanner(new File(""C.in"")); PrintWriter out = new PrintWriter(new File(""C.txt"")); int T = in.nextInt(); for (int TC = 1; TC <= T; TC++) { int A = in.nextInt(); int B = in.nextInt(); long counter = 0; HashSet set = new HashSet(); for (int n = A; n < B; n++) { for (int i = 10; i < n; i*=10) { String p1 = (n/i) + """"; p1 = (n%i) + p1; int m = Integer.parseInt(p1); String t = n+""-""+m; if (m > n && m <= B && !set.contains(t)) { set.add(t); counter++; } } } System.out.println(""Case #"" + TC + "": "" + counter); out.println(""Case #"" + TC + "": "" + counter); } out.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new C().run(); } } " B20281,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; class RecycledNumber { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub FileInputStream fstream = new FileInputStream(""C:\\input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int cases = Integer.parseInt(br.readLine()); String mainOutput = """"; for (int c = 0; c < cases; c++) { StringTokenizer stringTokenizer = new StringTokenizer(br.readLine()); int a = Integer.parseInt(stringTokenizer.nextToken()); int b = Integer.parseInt(stringTokenizer.nextToken()); int finalCount = 0; int arr[] = new int[b * 2]; int arr2[] = new int[b * 2]; for (int n = a; n < b; n++) { int TEN = 10; int count = Integer.toString(n).length(); for (int i = 1; i < count; i++) { int m = (int) ((n % Math.pow(TEN, i)) * Math.pow(TEN, count - i)) + (int) (n / Math.pow(TEN, i)); if (a <= n && n < m && m <= b) { // System.out.println(n + "" "" + m); arr[finalCount] = m; arr2[finalCount++] = n; } } } int count = 0; for (int i = 1; i < finalCount; i++) { if ((arr2[i] == arr2[i + 1] && arr[i] == arr[i + 1]) || (arr2[i - 1] == arr2[i] && arr[i - 1] == arr[i])) { count++; } } mainOutput = mainOutput + ""Case #""+(c+1)+"": ""+(finalCount - (count / 2))+""\n""; } BufferedWriter bw = new BufferedWriter(new FileWriter(new File( ""C:\\output.txt""), true)); bw.write(mainOutput); bw.close(); in.close(); } } " B22228,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam2012; /** * * @author Abdelrahman */ import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; public class CaseC { public static void main(String[] args) throws FileNotFoundException, IOException { File f1 = new File(""E:\\new c++\\Google\\codejame 2011\\2012\\inputCodejame.txt""); BufferedReader reader = new BufferedReader(new FileReader(f1)); int count = Integer.parseInt(reader.readLine()); for (int i = 0; i < count; i++) { int counter = 0; String line = reader.readLine(); String[] twoInt = line.split("" ""); long A = Long.parseLong(twoInt[0]); long B = Long.parseLong(twoInt[1]); long n = A; for (long j = A; j < B; j++) { String t = Long.toString(n); int len=t.length(); HashMap dis=new HashMap(); for (int k = 1; k < len; k++) { String t2=t.substring(len-k) + t.substring(0, len-k); long m = Long.parseLong(t2); if (m > n && m <= B &&!dis.containsValue(m)) { dis.put(n, m); counter++; } } n++; } System.out.println(""Case #"" + (i + 1) + "": "" + counter); } } } " B21071,"package template; import java.io.*; import java.util.ArrayList; import java.util.Random; public class Utils { static String logfile = """"; public static BufferedWriter newBufferedWriter(String filename, boolean append) { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(filename, append)); } catch (IOException ex) { die(""Exception in newBufferedWriter""); } return bw; } public static void writeLn(BufferedWriter bw, String line) { try { bw.write(line); bw.newLine(); } catch (IOException ex) { die(""Exception in writeLn""); } } public static void closeBw(BufferedWriter bw) { try { bw.flush(); bw.close(); } catch (IOException ex) { die(""Exception in closeBw""); } } public static BufferedReader newBufferedReader(String filename) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(filename)); } catch (IOException ex) { die(""Exception in newBufferedReader""); } return br; } public static String readLn(BufferedReader br) { String s = null; try { s = br.readLine(); } catch (IOException ex) { die(""Exception in readLn""); } return s; } public static Integer readInteger(BufferedReader br) { return new Integer(readLn(br)); } public static ArrayList readIntegerList(BufferedReader br) { return readIntegerList(br, null); } public static ArrayList readIntegerList(BufferedReader br, Integer expectedLength) { String[] s = readLn(br).split("" ""); ArrayList l = new ArrayList<>(); for (int x = 0; x < s.length; x++) { l.add(new Integer(s[x])); } if (expectedLength != null) { if (l.size() != expectedLength.intValue()) { die(""Incorrect length in readIntegerList""); } } return l; } public static ArrayList readMultipleIntegers(BufferedReader br, Integer rows) { ArrayList l = new ArrayList<>(); for (int x = 0; x < rows; x++) { String s = readLn(br); l.add(new Integer(s)); } return l; } public static ArrayList> readIntegerMatrix(BufferedReader br, Integer rows) { return readIntegerMatrix(br, rows, null); } public static ArrayList> readIntegerMatrix(BufferedReader br, Integer rows, Integer expectedLength) { ArrayList> l = new ArrayList<>(); for (int x = 0; x < rows.intValue(); x++) { l.add(readIntegerList(br, expectedLength)); } return l; } public static Double readDouble(BufferedReader br) { return new Double(readLn(br)); } public static ArrayList readDoubleList(BufferedReader br) { return readDoubleList(br, null); } public static ArrayList readDoubleList(BufferedReader br, Integer expectedLength) { String[] s = readLn(br).split("" ""); ArrayList l = new ArrayList<>(); for (int x = 0; x < s.length; x++) { l.add(new Double(s[x])); } if (expectedLength != null) { if (l.size() != expectedLength.intValue()) { die(""Incorrect length in readDoubleList""); } } return l; } public static ArrayList readMultipleDoubles(BufferedReader br, Integer rows) { ArrayList l = new ArrayList<>(); for (int x = 0; x < rows; x++) { String s = readLn(br); l.add(new Double(s)); } return l; } public static ArrayList> readDoubleMatrix(BufferedReader br, Integer rows) { return readDoubleMatrix(br, rows, null); } public static ArrayList> readDoubleMatrix(BufferedReader br, Integer rows, Integer expectedLength) { ArrayList> l = new ArrayList<>(); for (int x = 0; x < rows.intValue(); x++) { l.add(readDoubleList(br, expectedLength)); } return l; } public static Long readLong(BufferedReader br) { return new Long(readLn(br)); } public static ArrayList readLongList(BufferedReader br) { return readLongList(br, null); } public static ArrayList readLongList(BufferedReader br, Integer expectedLength) { String[] s = readLn(br).split("" ""); ArrayList l = new ArrayList<>(); for (int x = 0; x < s.length; x++) { l.add(new Long(s[x])); } if (expectedLength != null) { if (l.size() != expectedLength.intValue()) { die(""Incorrect length in readLongList""); } } return l; } public static ArrayList readMultipleLongs(BufferedReader br, Integer rows) { ArrayList l = new ArrayList<>(); for (int x = 0; x < rows; x++) { String s = readLn(br); l.add(new Long(s)); } return l; } public static ArrayList> readLongMatrix(BufferedReader br, Integer rows) { return readLongMatrix(br, rows, null); } public static ArrayList> readLongMatrix(BufferedReader br, Integer rows, Integer expectedLength) { ArrayList> l = new ArrayList<>(); for (int x = 0; x < rows.intValue(); x++) { l.add(readLongList(br, expectedLength)); } return l; } public static String readString(BufferedReader br) { return new String(readLn(br)); } public static ArrayList readStringList(BufferedReader br) { return readStringList(br, null); } public static ArrayList readStringList(BufferedReader br, Integer expectedLength) { String[] s = readLn(br).split("" ""); ArrayList l = new ArrayList<>(); for (int x = 0; x < s.length; x++) { l.add(new String(s[x])); } if (expectedLength != null) { if (l.size() != expectedLength.intValue()) { die(""Incorrect length in readStringList""); } } return l; } public static ArrayList readMultipleStrings(BufferedReader br, Integer rows) { ArrayList l = new ArrayList<>(); for (int x = 0; x < rows; x++) { String s = readLn(br); l.add(new String(s)); } return l; } public static ArrayList> readStringMatrix(BufferedReader br, Integer rows) { return readStringMatrix(br, rows, null); } public static ArrayList> readStringMatrix(BufferedReader br, Integer rows, Integer expectedLength) { ArrayList> l = new ArrayList<>(); for (int x = 0; x < rows.intValue(); x++) { l.add(readStringList(br, expectedLength)); } return l; } public static Boolean readBoolean(BufferedReader br) { return new Boolean(readLn(br)); } public static ArrayList readBooleanList(BufferedReader br) { return readBooleanList(br, null); } public static ArrayList readBooleanList(BufferedReader br, Integer expectedLength) { String[] s = readLn(br).split("" ""); ArrayList l = new ArrayList<>(); for (int x = 0; x < s.length; x++) { l.add(new Boolean(s[x])); } if (expectedLength != null) { if (l.size() != expectedLength.intValue()) { die(""Incorrect length in readBooleanList""); } } return l; } public static ArrayList readMultipleBooleans(BufferedReader br, Integer rows) { ArrayList l = new ArrayList<>(); for (int x = 0; x < rows; x++) { String s = readLn(br); l.add(new Boolean(s)); } return l; } public static ArrayList> readBooleanMatrix(BufferedReader br, Integer rows) { return readBooleanMatrix(br, rows, null); } public static ArrayList> readBooleanMatrix(BufferedReader br, Integer rows, Integer expectedLength) { ArrayList> l = new ArrayList<>(); for (int x = 0; x < rows.intValue(); x++) { l.add(readBooleanList(br, expectedLength)); } return l; } public static void closeBr(BufferedReader br) { try { br.close(); } catch (IOException ex) { die(""Exception in closeBr""); } } public static void die(String reason) { sout(""Die: "" + reason); System.exit(0); } public static void sout(String s) { System.out.println(s); } public static void sout(int i) { System.out.println(i); } public static void sout(Object o) { System.out.println(o); } public static void log(String line) { BufferedWriter bw = newBufferedWriter(logfile, true); writeLn(bw, line); closeBw(bw); } public static void clearFile(String filename) { BufferedWriter bw = newBufferedWriter(filename, false); closeBw(bw); } public static int minInt(ArrayList l) { int i = l.get(0).intValue(); for (Integer j : l) { if (j.intValue() < i) { i = j.intValue(); } } return i; } public static int maxInt(ArrayList l) { int i = l.get(0).intValue(); for (Integer j : l) { if (j.intValue() > i) { i = j.intValue(); } } return i; } public static String joinArray(ArrayList l, String delim) { String s = """"; for (int i = 0; i < l.size(); i++) { s += l.get(i).toString(); if (i < (l.size() - 1)) { s += delim; } } return s; } public static ArrayList splitToChars(String source) { ArrayList chars = new ArrayList<>(); for (int i = 0; i < source.length(); i++) { chars.add(source.substring(i, i + 1)); } return chars; } public static ArrayList splitToDigits(int in) { ArrayList chars = new ArrayList<>(); String s = in + """"; for (int i = 0; i < s.length(); i++) { chars.add(new Integer(s.substring(i, i + 1))); } return chars; } public static ArrayList> allPairs(int lower1, int upper1, int lower2, int upper2, int style) { //Style: //0 all pairs //1 (1) <= (2) //2 (1) < (2) ArrayList> out = new ArrayList<>(); for (int index1 = lower1; index1 <= upper1; index1++) { for (int index2 = lower2; index2 <= upper2; index2++) { ArrayList thisPair = new ArrayList<>(); thisPair.add(new Integer(index1)); thisPair.add(new Integer(index2)); switch (style) { case 0: out.add(thisPair); break; case 1: if (index1 <= index2) { out.add(thisPair); } break; case 2: if (index1 < index2) { out.add(thisPair); } break; default: die(""Unrecognised case in allPairs""); } } } return out; } public static ArrayList> cloneALALI(ArrayList> in) { ArrayList> out = new ArrayList<>(); for (ArrayList inALI : in) { ArrayList outALI = new ArrayList<>(inALI); out.add(outALI); } return out; } public static int[][] cloneInt2D(int[][] in) { if (in.length == 0) {return new int[0][0];} int[][] out = new int[in.length][]; for (int i = 0; i < in.length; i++) { out[i] = new int[in[i].length]; System.arraycopy(in[i], 0, out[i], 0, in[i].length); } return out; } public static double[][] cloneDouble2D(double[][] in) { if (in.length == 0) {return new double[0][0];} double[][] out = new double[in.length][]; for (int i = 0; i < in.length; i++) { out[i] = new double[in[i].length]; System.arraycopy(in[i], 0, out[i], 0, in[i].length); } return out; } public static ArrayList> allPerms(int n) { //returns an arraylist of arraylists of integers //showing all permutations of Integers 0 to n-1 //works realistically up to n=10 if (n == 0) { return new ArrayList>(); } return allPerms_recurse(n, n); } public static ArrayList> allPerms_recurse(int level, int n) { if (level == 1) { ArrayList single = new ArrayList<>(); single.add(new Integer(n - level)); ArrayList> list = new ArrayList<>(); list.add(single); return list; } ArrayList> prev = allPerms_recurse(level - 1, n); ArrayList> out = new ArrayList<>(); for (int placeAt = 0; placeAt < level; placeAt++) { //clone prev ArrayList> prevClone = cloneALALI(prev); //insert for (ArrayList prevItem : prevClone) { prevItem.add(placeAt, new Integer(n - level)); } //append to out out.addAll(prevClone); } return out; } public static ArrayList> allCombs(int n) { //returns an arraylist of arraylists of integers //showing all combinations of Integers 0 to n-1 //works realistically up to n=7 if (n == 0) { return new ArrayList>(); } return allCombs_recurse(n, n); } public static ArrayList> nCombs(int count, int n) { //returns an arraylist of arraylists of integers //showing all combinations of Integers 0 to n-1 --- of length ""count"" //i.e. base ""n"" counting up to (n^count - 1). In order. if (count == 0) { return new ArrayList>(); } return allCombs_recurse(count, n); } public static ArrayList> allCombs_recurse(int level, int n) { if (level == 1) { ArrayList> list = new ArrayList<>(); for (int i = 0; i < n; i++) { ArrayList single = new ArrayList<>(); single.add(new Integer(i)); list.add(single); } return list; } ArrayList> prev = allCombs_recurse(level - 1, n); ArrayList> out = new ArrayList<>(); for (int initial = 0; initial < n; initial++) { //clone prev ArrayList> prevClone = cloneALALI(prev); //insert for (ArrayList prevItem : prevClone) { prevItem.add(0, new Integer(initial)); } //append to out out.addAll(prevClone); } return out; } public static ArrayList grepFull(ArrayList inList, String pattern) { //pattern must match full text ArrayList outList = new ArrayList<>(); for (String s : inList) { if (s.matches(pattern)) { outList.add(new String(s)); } } return outList; } public static int[] randomIntegerArray(int count, int low, int high, long seed) { //a list of ""count"" ints from low to high inclusive. Random rng = new Random(); if (seed != -1) { rng.setSeed(seed); } int[] out = new int[count]; for (int x = 0; x < count; x++) { out[x] = rng.nextInt(high - low + 1) + low; } return out; } public static double[] randomDoubleArray(int count, double low, double high, long seed) { //a list of ""count"" ints from low inclusive to high exclusive. Random rng = new Random(); if (seed != -1) { rng.setSeed(seed); } double[] out = new double[count]; for (int x = 0; x < count; x++) { out[x] = rng.nextDouble() * (high - low) + low; } return out; } public static int[] randomPermutation(int count, long seed) { //random permutation of the array 0..(count-1). Random rng = new Random(); if (seed != -1) { rng.setSeed(seed); } int[] out = new int[count]; for (int x = 0; x < count; x++) { out[x] = x; } for (int x = 0; x < count - 1; x++) { int takeFrom = rng.nextInt(count - x) + x; int tmp = out[takeFrom]; out[takeFrom] = out[x]; out[x] = tmp; } return out; } public static ArrayList randomiseArray(ArrayList in, long seed) { //alternatively, Collections.shuffle(in, new Random(seed)) ArrayList out = new ArrayList(); int[] r = randomPermutation(in.size(), seed); for (int i : r) { out.add(in.get(i)); } return out; } public static ArrayList arrayToArrayList(int[] in) { ArrayList out = new ArrayList<>(); for (int i : in) { out.add(i); } return out; } public static ArrayList arrayToArrayList(double[] in) { ArrayList out = new ArrayList<>(); for (double d : in) { out.add(d); } return out; } public static int[] arrayListToArrayInt(ArrayList in) { int[] out = new int[in.size()]; int x = 0; for (Integer i : in) { out[x] = i.intValue(); x++; } return out; } public static double[] arrayListToArrayDouble(ArrayList in) { double[] out = new double[in.size()]; int x = 0; for (Double d : in) { out[x] = d.doubleValue(); x++; } return out; } public static String toString(int[] in) { if (in.length == 0) { return ""[]""; } String s = ""[""; for (int x = 0; x < in.length - 1; x++) { s += in[x] + "", ""; } s += in[in.length - 1] + ""]""; return s; } public static String toString(double[] in) { if (in.length == 0) { return ""[]""; } String s = ""[""; for (int x = 0; x < in.length - 1; x++) { s += in[x] + "", ""; } s += in[in.length - 1] + ""]""; return s; } public static String toString(int[][] in) { if (in.length == 0) { return ""[]""; } String s = ""[""; for (int x = 0; x < in.length - 1; x++) { s += toString(in[x]) + "", ""; } s += toString(in[in.length - 1]) + ""]""; return s; } public static String toString(double[][] in) { if (in.length == 0) { return ""[]""; } String s = ""[""; for (int x = 0; x < in.length - 1; x++) { s += toString(in[x]) + "", ""; } s += toString(in[in.length - 1]) + ""]""; return s; } } " B21116,"import java.io.*; import java.lang.*; import java.util.*; public class C { public static void main(String[] args) { C prob = new C(); prob.run(args[0]); } public void run(String fileName) { try { Scanner fin = new Scanner(new File(fileName)); PrintWriter fout = new PrintWriter(new File(fileName + "".out"")); int T = fin.nextInt(); for (int t = 1; t <= T; ++t) { fout.format(""Case #%d: "", t); int A = fin.nextInt(); int B = fin.nextInt(); int result = 0; TreeSet pairs = new TreeSet(); for (int i = A; i <= B; ++i) { String a = Integer.toString(i); pairs.clear(); for (int j = 1; j < a.length(); ++j) { String b = a.substring(j) + a.substring(0, j); if (b.charAt(0) == '0') continue; int m = Integer.valueOf(b); if ((m >= A) && (m <= B) && (m != i)) { pairs.add(m); } } result += pairs.size(); } result /= 2; fout.format(""%d\n"", result); } fin.close(); fout.close(); } catch (Exception e) { e.printStackTrace(); } } } " B22185,"import java.util.Scanner; import java.io.IOException; import java.util.Arrays; import java.util.ArrayList; import java.io.PrintStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""C-large.in""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""gcj3.out""); } catch (IOException e) { throw new RuntimeException(e); } Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); GCJ3 solver = new GCJ3(); solver.solve(1, in, out); out.close(); } } class GCJ3 { public void solve(int testNumber, Scanner in, PrintWriter out) { int cases = in.nextInt(); for(int caseNum =0;caseNumi && nw>=A && nw<=B) { for(int k=0;k0) { a/=base; res++; } return res; } } " B21896,"import java.io.*; import java.util.Set; import java.util.HashSet; public class Recycler { public static void main(String[] args) throws IOException, FileNotFoundException { StreamTokenizer st = new StreamTokenizer( new FileReader(args[0])); FileWriter out = new FileWriter(args[1]); st.parseNumbers(); if (st.nextToken() == StreamTokenizer.TT_EOF) eof_error(); int numTestCases = (int) st.nval; int numDistinctPairs = 0; boolean twins = false; Set partners = new HashSet(); for (int t = 0; t < numTestCases; ++t) { if (st.nextToken() == StreamTokenizer.TT_EOF) eof_error(); int A = (int) st.nval; if (st.nextToken() == StreamTokenizer.TT_EOF) eof_error(); int B = (int) st.nval; for (int i = A; i < B; ++i) { String curNumberString = String.valueOf(i); for(int j = 1; j < curNumberString.length(); ++j) { String sub1 = curNumberString.substring(j); String sub2 = curNumberString.substring(0, j); String test = sub1 + sub2; if (Integer.valueOf(test) > i && Integer.valueOf(test) <= B) { if (! partners.contains(Integer.valueOf(test))) { ++numDistinctPairs; partners.add(Integer.valueOf(test)); } } } partners.clear(); } out.write(""Case #"" + (t+1) + "": "" + numDistinctPairs + ""\n""); numDistinctPairs = 0; } out.close(); } private static void eof_error() { throw new RuntimeException(""Unexpected end of file reached""); } } " B20641,"import java.io.BufferedReader; import java.io.FileReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Vector; public class Task { public static void main(String[] args) { try { readSolveAndWrite(""C-large.in"", ""output_file.txt""); } catch(IOException ioException) { System.err.println(ioException); } //for(int i = 0; i < 50; i++) //System.out.println((i + 1) + ""-> "" + solve(""1 2000000"")); //System.out.println(solve(""1 10"")); //System.out.println(solve(""10 40"")); //System.out.println(solve(""100 500"")); //System.out.println(solve(""1111 2222"")); } protected static void readSolveAndWrite(final String inputPath, final String outputFile) throws IOException { BufferedReader in = new BufferedReader(new FileReader(inputPath)); BufferedWriter out = new BufferedWriter(new FileWriter(outputFile)); int n = Integer.parseInt(in.readLine()); for(int i = 0; i < n; i++) { final String inputLine = in.readLine(); final String outputLine = ""Case #"" + (i + 1) + "": "" + solve(inputLine); System.out.println(outputLine); out.write(outputLine); out.newLine(); } out.flush(); out.close(); in.close(); } protected static String solve(final String line) { String[] elements = line.split("" ""); final int min = Integer.parseInt(elements[0]); final int max = Integer.parseInt(elements[1]); int result = 0; for(int i = min; i <= max; i++) result += get(i, max); return """" + result; } protected static int convertToInt(Vector digits) { int result = 0; final int size = digits.size(); for(int i = size - 1; i >= 0; i--) result = result*10 + digits.elementAt(i).intValue(); return result; } protected static int get(int current, int max) { int result = 0; Vector base = new Vector(); int m = current; while(true) { final int digit = m % 10; base.add(new Integer(digit)); m = m / 10; if(m == 0) break; } HashMap map = new HashMap(); final int size_base = base.size(); for(int i = 1; i < size_base; i++) { Vector temp = new Vector(); for(int j = i; j < size_base; j++) temp.add(base.elementAt(j)); for(int j = 0; j < i; j++) temp.add(base.elementAt(j)); int pair = convertToInt(temp); if(current < pair && pair <= max && null == map.get(new String(current + """" + pair))) { //System.out.println(current + "" -> "" + pair); map.put(new String(current + """" + pair), new Integer(1)); map.put(new String(pair + """" + current), new Integer(1)); result++; } } return result; } }" B20670,"// Google Code Jam Qualification Round 2012 // Problem C. Recycled Numbers import java.util.*; import java.io.*; public class RecycledNumbers{ static String inname = ""C-large.in""; // input file name here static String outname = ""C-large.out""; // output file name here public static void main(String[] args){ try{ Scanner in = new Scanner(new BufferedReader(new FileReader(inname))); //Scanner in = new Scanner(System.in); BufferedWriter out = new BufferedWriter(new FileWriter(outname)); int t = in.nextInt(); int a, b; for (int cas = 1; cas <= t; cas++){ int ans = 0; a = in.nextInt(); b = in.nextInt(); for (int n = a; n < b; n++){ String ns = Integer.toString(n); int d = ns.length(); int mss[] = new int[d]; for(int i = 1; i < d; i++){ String ms = ns.substring(i); ms += ns.substring(0,i); int m = Integer.parseInt(ms); mss[i] = m; if (n < m && m > a && m <= b){ boolean flag = true; for (int j = 0; j < i; j++) if (m == mss[j]) flag = false; if (flag) ans++; } } } //System.out.print(""Case #"" + cas + "": "" + ans + ""\n""); out.write(""Case #"" + cas + "": "" + ans + ""\n""); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }" B22182,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Q3RecycledNumbers { public static void main(String[] args) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(new File(""q3.input"")); FileWriter writer = new FileWriter(""q3.output""); int cases = scanner.nextInt(); for (int i = 1; i <= cases; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int n = solve(a, b); writer.write(""Case #"" + i + "": "" + n + ""\n""); } writer.close(); } private static int solve(int a, int b) { int n = 0; for (int i = b; i >= a; i--) { String strI = String.valueOf(i); Set mirrorSet = new HashSet(); for (int j = 1; j <= strI.length(); j++) { String r = strI.substring(j, strI.length()) + strI.substring(0, j); int intR = Integer.valueOf(r); if (intR < i && intR >= a && !mirrorSet.contains(intR)) { mirrorSet.add(intR); n++; } } } return n; } } " B21741,"import java.util.*; public class Recycled { private static int solve(int A, int B) { int count = 0; HashSet s = new HashSet(); for (int n = A; n < B; n++) { String i = n + """"; s.clear(); int t = i.length(); while (i.charAt(t-1) == '0') t--; for (int j = 1; j < t; j++) { int m = Integer.parseInt(i.substring(j) + i.substring(0, j)); if (n < m && m <= B) s.add(m); } count += s.size(); } return count; } public static void main(String args[]) { Scanner in = new Scanner(System.in); int N = in.nextInt(); for (int i = 0; i < N; i++) { System.out.println(""Case #"" + (i+1) + "": "" + solve(in.nextInt(), in.nextInt())); } } } " B21629,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner; /** * * @author linlin */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here File file=new File(""C-large.in""); FileOutputStream o=new FileOutputStream(""a.txt""); Scanner s=new Scanner(file); int t=Integer.valueOf(s.nextLine()); for(int i=1;i<=t;i++){ String line=s.nextLine(); String[] num=line.split("" ""); int a=Integer.valueOf(num[0]); int b=Integer.valueOf(num[1]); int d=1; int tens=10; for(;tens<=a;tens=tens*10) d++; tens=tens/10; int[] total=new int[d]; for(int q=a;q<=b;q++){ int correct=0; int q1=q; boolean shift=true; for(int k=0;k=a)&&(q1<=b)){ correct++; //System.out.println(q1); } shift=false; } if(correct>1){ total[correct-1]=total[correct-1]+1; } } int result=0; for(int n=1;n= length - 1) { throw new IllegalStateException(""Line has already ended.""); } return line.charAt(++linePointer); } public String readLine() throws IOException { line = reader.readLine(); linePointer = -1; return line; } public int readNextInteger() { int val = 0; int length = line.length(); if (linePointer >= length) { throw new IllegalStateException(""Line has already ended.""); } while(++linePointer < length) { if (Character.isDigit(lastChar = line.charAt(linePointer))) { val = val * 10 + Character.digit(lastChar, 10); } else { break; } } return val; } } " B22098,"package qualification.q1; import com.sun.deploy.net.proxy.StaticProxyManager; import qualification.common.InputReader; import qualification.common.OutputWriter; /** * Created by IntelliJ IDEA. * User: ofer * Date: 14/04/12 * Time: 17:36 * To change this template use File | Settings | File Templates. */ public class Q1Sim { public static void main(String[] args){ String inputFile = ""input.txt""; String outPutFile = ""output.txt""; String[] lines = InputReader.getInputLines(inputFile); Q1Solver solver = new Q1Solver(); int numOfTests = Integer.parseInt(lines[0]); String[] output = new String[numOfTests]; for (int i = 0 ; i < numOfTests ; i++){ String decrypted = solver.convertString(lines[i+1]); output[i] = ""Case #"" + (i+1) + "": "" + decrypted; } OutputWriter.writeOutput(outPutFile,output); } } " B20136,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; public class GoogleNumbers { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int numberOfTestCases = Integer.parseInt(s); StringBuffer output = new StringBuffer(); for (int i = 1; i <= numberOfTestCases; i++) { String testCase = br.readLine().trim(); String[] inputparams = testCase.split("" ""); long A, B; A = Long.parseLong(inputparams[0]); B = Long.parseLong(inputparams[1]); String outputString = solveTestCase(A, B); if (i != 1) { output.append(""\n""); } output.append(""Case #"" + i + "": ""); output.append(outputString); } System.out.println(output); } private static String solveTestCase(long A, long B) { long pairCount = 0; int d = String.valueOf(A).length(); for (long n = A; n <= B; n++) { String currentNumber = String.valueOf(n); HashMap pairedNumbers = new HashMap(); for (int i = 1; i < d; i++) { int subIndex = d - i; if (currentNumber.charAt(subIndex) == '0') { continue; } String newNumber = currentNumber.substring(subIndex) + currentNumber.substring(0, subIndex); if (pairedNumbers.containsKey(newNumber)) { continue; } long m = Long.valueOf(newNumber); if (m <= n || m > B) { continue; } pairedNumbers.put(newNumber, ""Y""); pairCount++; } } return String.valueOf(pairCount); } } " B20444,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; public class main { public static void main(String[] args) { // inputファイルを読み込み BufferedReader bufferReader = null; String str = """"; try { bufferReader = new BufferedReader(new InputStreamReader( new FileInputStream(""/Users/yago/Documents/in.txt""), ""UTF-8"")); // 一行ずつ読み込み int probs = 0; while ((str = bufferReader.readLine()) != null) { if (str.length() > 2) { probs++; calc(str, probs); } } } catch (Exception e) { System.out.println(e.getMessage()); } finally { try { if (bufferReader != null) { bufferReader.close(); } } catch (Exception e) { } } } private static void calc(String str, int probNum) { Integer n1, n2, ansCnt = 0, chgNum; String[] strAry = str.split("" ""); n1 = Integer.valueOf(strAry[0]); n2 = Integer.valueOf(strAry[1]); for (int i = n1; i <= n2; i++) { String chgStr = """", bfrStr=""""; if (String.valueOf(i).length() == 1) break; if (String.valueOf(i).length() == 2 && String.valueOf(i).charAt(1)!='0') { chgStr += String.valueOf(i).charAt(1); chgStr += String.valueOf(i).charAt(0); chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i){ //System.out.println(i+"" ""+chgNum); ansCnt++; } }else if (String.valueOf(i).length() == 3){ if(String.valueOf(i).charAt(1)!='0') { chgStr += String.valueOf(i).charAt(1); chgStr += String.valueOf(i).charAt(2); chgStr += String.valueOf(i).charAt(0); chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i){ //System.out.println(i+"" ""+chgNum); ansCnt++; } } chgStr = """"; if(String.valueOf(i).charAt(2)!='0') { chgStr += String.valueOf(i).charAt(2); chgStr += String.valueOf(i).charAt(0); chgStr += String.valueOf(i).charAt(1); chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i){ //System.out.println(i+"" ""+chgNum); ansCnt++; } } }else if (String.valueOf(i).length() == 4){ chgStr = """"; if(String.valueOf(i).charAt(1)!='0') { chgStr += String.valueOf(i).charAt(1); chgStr += String.valueOf(i).charAt(2); chgStr += String.valueOf(i).charAt(3); chgStr += String.valueOf(i).charAt(0); bfrStr=chgStr; chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i){ ansCnt++; } } chgStr = """"; if(String.valueOf(i).charAt(2)!='0') { chgStr += String.valueOf(i).charAt(2); chgStr += String.valueOf(i).charAt(3); chgStr += String.valueOf(i).charAt(0); chgStr += String.valueOf(i).charAt(1); chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i){ ansCnt++; } } chgStr = """"; if(String.valueOf(i).charAt(3)!='0') { chgStr += String.valueOf(i).charAt(3); chgStr += String.valueOf(i).charAt(0); chgStr += String.valueOf(i).charAt(1); chgStr += String.valueOf(i).charAt(2); chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i && !bfrStr.equals(chgStr)){ ansCnt++; } } }else if (String.valueOf(i).length() == 5){ chgStr = """"; if(String.valueOf(i).charAt(1)!='0') { chgStr += String.valueOf(i).charAt(1); chgStr += String.valueOf(i).charAt(2); chgStr += String.valueOf(i).charAt(3); chgStr += String.valueOf(i).charAt(4); chgStr += String.valueOf(i).charAt(0); bfrStr=chgStr; chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i){ ansCnt++; } } chgStr = """"; if(String.valueOf(i).charAt(2)!='0') { chgStr += String.valueOf(i).charAt(2); chgStr += String.valueOf(i).charAt(3); chgStr += String.valueOf(i).charAt(4); chgStr += String.valueOf(i).charAt(0); chgStr += String.valueOf(i).charAt(1); chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i){ ansCnt++; } } chgStr = """"; if(String.valueOf(i).charAt(3)!='0') { chgStr += String.valueOf(i).charAt(3); chgStr += String.valueOf(i).charAt(4); chgStr += String.valueOf(i).charAt(0); chgStr += String.valueOf(i).charAt(1); chgStr += String.valueOf(i).charAt(2); chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i && !bfrStr.equals(chgStr)){ ansCnt++; } } chgStr = """"; if(String.valueOf(i).charAt(4)!='0') { chgStr += String.valueOf(i).charAt(4); chgStr += String.valueOf(i).charAt(0); chgStr += String.valueOf(i).charAt(1); chgStr += String.valueOf(i).charAt(2); chgStr += String.valueOf(i).charAt(3); chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i){ ansCnt++; } } }else if (String.valueOf(i).length() == 6){ chgStr = """"; if(String.valueOf(i).charAt(1)!='0') { chgStr += String.valueOf(i).charAt(1); chgStr += String.valueOf(i).charAt(2); chgStr += String.valueOf(i).charAt(3); chgStr += String.valueOf(i).charAt(4); chgStr += String.valueOf(i).charAt(5); chgStr += String.valueOf(i).charAt(0); bfrStr=chgStr; chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i){ ansCnt++; } } chgStr = """"; if(String.valueOf(i).charAt(2)!='0') { chgStr += String.valueOf(i).charAt(2); chgStr += String.valueOf(i).charAt(3); chgStr += String.valueOf(i).charAt(4); chgStr += String.valueOf(i).charAt(5); chgStr += String.valueOf(i).charAt(0); chgStr += String.valueOf(i).charAt(1); chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i){ ansCnt++; } } chgStr = """"; if(String.valueOf(i).charAt(3)!='0') { chgStr += String.valueOf(i).charAt(3); chgStr += String.valueOf(i).charAt(4); chgStr += String.valueOf(i).charAt(5); chgStr += String.valueOf(i).charAt(0); chgStr += String.valueOf(i).charAt(1); chgStr += String.valueOf(i).charAt(2); bfrStr=chgStr; chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i && !bfrStr.equals(chgStr)){ ansCnt++; } } chgStr = """"; if(String.valueOf(i).charAt(4)!='0') { chgStr += String.valueOf(i).charAt(4); chgStr += String.valueOf(i).charAt(5); chgStr += String.valueOf(i).charAt(0); chgStr += String.valueOf(i).charAt(1); chgStr += String.valueOf(i).charAt(2); chgStr += String.valueOf(i).charAt(3); chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i){ ansCnt++; } } chgStr = """"; if(String.valueOf(i).charAt(5)!='0') { chgStr += String.valueOf(i).charAt(5); chgStr += String.valueOf(i).charAt(0); chgStr += String.valueOf(i).charAt(1); chgStr += String.valueOf(i).charAt(2); chgStr += String.valueOf(i).charAt(3); chgStr += String.valueOf(i).charAt(4); chgNum = Integer.valueOf(chgStr); if (chgNum <= n2 && chgNum > i && !bfrStr.equals(chgStr)){ ansCnt++; } } } // for (int j = i + 1; j <= n2; j++) { // if (String.valueOf(j).length() == 1) // break; // if (String.valueOf(j).length() == 3) { // if ((String.valueOf(j).charAt(0) == String.valueOf(i).charAt(1) // && String.valueOf(j).charAt(1) == String.valueOf(i).charAt(2) // && String.valueOf(j).charAt(2) == String.valueOf(i).charAt(0)) // || (String.valueOf(j).charAt(0) == String.valueOf(i).charAt(2) // && String.valueOf(j).charAt(1) == String.valueOf(i).charAt(0) // && String.valueOf(j).charAt(2) == String.valueOf(i).charAt(1))) { // // System.out.println(i+"" ""+j); // ansCnt++; // } // } else if (String.valueOf(j).length() == 4) { // if ((String.valueOf(j).charAt(0) == String.valueOf(i).charAt(1) // && String.valueOf(j).charAt(1) == String.valueOf(i).charAt(2) // && String.valueOf(j).charAt(2) == String.valueOf(i).charAt(3) // && String.valueOf(j).charAt(3) == String.valueOf(i).charAt(0)) // || (String.valueOf(j).charAt(0) == String.valueOf(i).charAt(2) // && String.valueOf(j).charAt(1) == String.valueOf(i).charAt(3) // && String.valueOf(j).charAt(2) == String.valueOf(i).charAt(0) // && String.valueOf(j).charAt(3) == String.valueOf(i).charAt(1)) // || (String.valueOf(j).charAt(0) == String.valueOf(i).charAt(3) // && String.valueOf(j).charAt(1) == String.valueOf(i).charAt(0) // && String.valueOf(j).charAt(2) == String.valueOf(i).charAt(1) // && String.valueOf(j).charAt(3) == String.valueOf(i).charAt(2))) { // // System.out.println(i+"" ""+j); // ansCnt++; // } // } else if (String.valueOf(j).length() == 5) { // if ((String.valueOf(j).charAt(0) == String.valueOf(i).charAt(1) // && String.valueOf(j).charAt(1) == String.valueOf(i).charAt(2) // && String.valueOf(j).charAt(2) == String.valueOf(i).charAt(3) // && String.valueOf(j).charAt(3) == String.valueOf(i).charAt(4) // && String.valueOf(j).charAt(4) == String.valueOf(i).charAt(0)) // || (String.valueOf(j).charAt(0) == String.valueOf(i).charAt(2) // && String.valueOf(j).charAt(1) == String.valueOf(i).charAt(3) // && String.valueOf(j).charAt(2) == String.valueOf(i).charAt(4) // && String.valueOf(j).charAt(3) == String.valueOf(i).charAt(0) // && String.valueOf(j).charAt(4) == String.valueOf(i).charAt(1)) // || (String.valueOf(j).charAt(0) == String.valueOf(i).charAt(3) // && String.valueOf(j).charAt(1) == String.valueOf(i).charAt(4) // && String.valueOf(j).charAt(2) == String.valueOf(i).charAt(0) // && String.valueOf(j).charAt(3) == String.valueOf(i).charAt(1) // && String.valueOf(j).charAt(4) == String.valueOf(i).charAt(2))) { // // System.out.println(i+"" ""+j); // ansCnt++; // } // } else if (String.valueOf(j).length() == 6) { // if ((String.valueOf(j).charAt(0) == String.valueOf(i).charAt(1) // && String.valueOf(j).charAt(1) == String.valueOf(i).charAt(2) // && String.valueOf(j).charAt(2) == String.valueOf(i).charAt(3) // && String.valueOf(j).charAt(3) == String.valueOf(i).charAt(4) // && String.valueOf(j).charAt(4) == String.valueOf(i).charAt(5) // && String.valueOf(j).charAt(5) == String.valueOf(i).charAt(0)) // || (String.valueOf(j).charAt(0) == String.valueOf(i).charAt(2) // && String.valueOf(j).charAt(1) == String.valueOf(i).charAt(3) // && String.valueOf(j).charAt(2) == String.valueOf(i).charAt(4) // && String.valueOf(j).charAt(3) == String.valueOf(i).charAt(5) // && String.valueOf(j).charAt(4) == String.valueOf(i).charAt(0) // && String.valueOf(j).charAt(5) == String.valueOf(i).charAt(1)) // || (String.valueOf(j).charAt(0) == String.valueOf(i).charAt(3) // && String.valueOf(j).charAt(1) == String.valueOf(i).charAt(4) // && String.valueOf(j).charAt(2) == String.valueOf(i).charAt(5) // && String.valueOf(j).charAt(3) == String.valueOf(i).charAt(0) // && String.valueOf(j).charAt(4) == String.valueOf(i).charAt(1) // && String.valueOf(j).charAt(5) == String.valueOf(i).charAt(2))) { // // System.out.println(i+"" ""+j); // ansCnt++; // } // } // } } System.out.println(""Case #"" + probNum + "": "" + ansCnt); } }" B20866,"import java.io.*; import java.util.*; public class C { public static void main(String[] args) { new C().run(); } BufferedReader br; StringTokenizer st; PrintWriter out; boolean eof = false; Random rand = new Random(1235446); private void run() { try { br = new BufferedReader(new FileReader(FNAME + "".in"")); out = new PrintWriter(FNAME + "".out""); solve(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(566); } } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return ""0""; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } String FNAME = ""c""; private void solve() throws IOException { long time = System.currentTimeMillis(); int tests = nextInt(); for (int test = 1; test <= tests; test++) { System.out.println(test + "" "" + (System.currentTimeMillis() - time) / 1000.0); out.print(""Case #"" + test + "": ""); int a = nextInt(); int b = nextInt(); long ans = 0; boolean[] q = new boolean[b + 1]; for (int i = a; i <= b; i++) { if (q[i]) { continue; } long cnt = 0; String s = """" + i; for (int j = 0; j < s.length(); j++) { int x = Integer.parseInt(s); if (a <= x && x <= b && !q[x] && !s.startsWith(""0"")) { q[x] = true; cnt++; } s = s.substring(1) + s.charAt(0); } ans += cnt * (cnt - 1) / 2; } out.println(ans); } } } " B20050,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlejam; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /** * * @author AEK */ public class Problem_C_small { public static void main(String[] args)throws IOException { BufferedReader reader = new BufferedReader(new FileReader(""C-large.in"")); FileWriter writer = new FileWriter(""C-large-output0""); int amount_of_test_case = Integer.parseInt(reader.readLine()); for(int test_case = 1;test_case <= amount_of_test_case;test_case++) { Scanner parser = new Scanner(reader.readLine()); int A = Integer.parseInt(parser.next()); int B = Integer.parseInt(parser.next()); int count = 0; for(Integer n = A;n < B;n++) { String outer = n.toString(); int length = outer.length(); for(int begin = 0;begin < outer.length();begin++) { String substring = outer.substring(begin) + outer; substring = substring.substring(0, length); Integer m = Integer.parseInt(substring); //Integer m = Integer.parseInt(outer.substring(begin) + outer.substring(0, begin)); if(A <= n && n < m && m <= B) { count+=1; } }// end inner loop }// end outer loop //System.out.println(count); writer.write(""Case #"" + test_case + "": "" + count + ""\n""); } reader.close(); writer.close(); }// end function } " B21740,"package inam.qual; import java.io.File; import java.io.FileInputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public void go() { Scanner in = new Scanner(System.in); int cc = in.nextInt(); for (int c = 1; c <= cc; c++) { int val = 0; int a = in.nextInt(); int b = in.nextInt(); Set set = new HashSet(); for (int i = a; i <= b; i++) { String str = String.valueOf(i); for (int j = 1; j < str.length(); j++) { String re = str.substring(j, str.length()) + str.substring(0, j); if (str.equals(re) || re.startsWith(""0"") || Integer.parseInt(re) > b || a > Integer.parseInt(re)) { continue; } String key = """"; if (Integer.parseInt(str) < Integer.parseInt(re)) { key = str + "" "" + re; } else { key = re + "" "" + str; } set.add(key); } } val = set.size(); System.out.println(""Case #"" + c + "": "" + val); } } public static void main(String[] args) { try { String p = ""C-large""; String r = ""qual""; System.setIn(new FileInputStream(new File(r, p + "".in""))); if (1 == 1) { System.setOut(new PrintStream(new File(r, p + "".out""))); } new C().go(); } catch (Exception e) { e.printStackTrace(); } } } " B20098,"package codejam2012; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class ProblemC { public static void main(String[] args) throws FileNotFoundException, IOException { int T, n, A, B, recycle, lastN = 0, lastM = 1; ProblemC c = new ProblemC(); Scanner sc = new Scanner(new FileReader(""C-large.in.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""outputPC.txt"")); T = sc.nextInt(); for(int i = 0; i < T; i++){ A = sc.nextInt(); B = sc.nextInt(); recycle = 0; for(n = A; n < B; n++){ int digits = Integer.toString(n).length(); if(digits > 1){ char[] num = new char[digits]; for(int j = 0; j < digits; j++){ num[j] = Integer.toString(n).charAt(j); } for(int j = 0; j < digits - 1; j++){ c.rotateNum(num); if(Integer.parseInt(c.charToString(num)) <= B && Integer.parseInt(c.charToString(num)) > n){ if(lastN == n && lastM == Integer.parseInt(c.charToString(num))){ recycle--; } lastN = n; lastM = Integer.parseInt(c.charToString(num)); recycle++; } } } } pw.print(""Case #"" + (i + 1) + "": ""); pw.println(recycle); } pw.flush(); pw.close(); sc.close(); } public String charToString(char[] c){ String result = """"; for(int i = 0; i < c.length; i++){ result += c[i]; } return result; } public void rotateNum(char[] c){ char aux = c[c.length - 1]; for(int i = c.length - 1; i > 0; i--){ c[i] = c[i - 1]; } c[0] = aux; } } " B21804,"package util; import java.math.BigInteger; public class CombinationGenerator { private int[] a; private int n; private int r; private BigInteger numLeft; private BigInteger total; //------------ // Constructor //------------ public CombinationGenerator (int n, int r) { if (r > n) { throw new IllegalArgumentException (); } if (n < 1) { throw new IllegalArgumentException (); } this.n = n; this.r = r; a = new int[r]; BigInteger nFact = getFactorial (n); BigInteger rFact = getFactorial (r); BigInteger nminusrFact = getFactorial (n - r); total = nFact.divide (rFact.multiply (nminusrFact)); reset (); } //------ // Reset //------ public void reset () { for (int i = 0; i < a.length; i++) { a[i] = i; } numLeft = new BigInteger (total.toString ()); } //------------------------------------------------ // Return number of combinations not yet generated //------------------------------------------------ public BigInteger getNumLeft () { return numLeft; } //----------------------------- // Are there more combinations? //----------------------------- public boolean hasMore () { return numLeft.compareTo (BigInteger.ZERO) == 1; } //------------------------------------ // Return total number of combinations //------------------------------------ public BigInteger getTotal () { return total; } //------------------ // Compute factorial //------------------ private static BigInteger getFactorial (int n) { BigInteger fact = BigInteger.ONE; for (int i = n; i > 1; i--) { fact = fact.multiply (new BigInteger (Integer.toString (i))); } return fact; } //-------------------------------------------------------- // Generate next combination (algorithm from Rosen p. 286) //-------------------------------------------------------- public int[] getNext () { if (numLeft.equals (total)) { numLeft = numLeft.subtract (BigInteger.ONE); return a; } int i = r - 1; while (a[i] == n - r + i) { i--; } a[i] = a[i] + 1; for (int j = i + 1; j < r; j++) { a[j] = a[i] + j - i; } numLeft = numLeft.subtract (BigInteger.ONE); return a; } } " B21965,"package ru.guredd.codejam; import java.util.Arrays; import java.util.StringTokenizer; public class Qualification2012C { public void solve() { int count = Integer.valueOf(Main.inputData.get(0)); for (int i = 0; i < count; i++) { int result = 0; String data = Main.inputData.get(i + 1); StringTokenizer st = new StringTokenizer(data, "" ""); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); for (int j = A; j <= B; j++) { result += calculateRecycled(j,j,A,B); } Main.outputData.add(""Case #"" + (i + 1) + "": "" + result); } } private int calculateRecycled(int v, int orig, int A, int B) { char[] charV = String.valueOf(v).toCharArray(); char[] shiftedV = new char[charV.length]; do { System.arraycopy(charV, 1, shiftedV, 0, charV.length - 1); shiftedV[charV.length - 1] = charV[0]; charV = Arrays.copyOf(shiftedV, shiftedV.length); } while (shiftedV[0]=='0'); int shiftedVal = Integer.valueOf(String.valueOf(shiftedV)); if (shiftedVal == orig) { return 0; } if (shiftedVal >= A && shiftedVal <= B && shiftedVal > orig) { return 1 + calculateRecycled(shiftedVal, orig, A, B); } else { return calculateRecycled(shiftedVal, orig, A, B); } } } " B20649,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pkg2012codejam; import java.io.*; import java.util.ArrayList; /** * * @author Nimos */ public class QuestionC { public static void main(String args[]) { try { File input = new File(""C:\\Users\\Nimos\\Desktop\\INPUTS\\2012\\C-large(1).in""); FileReader fr = new FileReader(input); BufferedReader br = new BufferedReader(fr); PrintWriter out = new PrintWriter(new File(""C:\\Users\\Nimos\\Desktop\\INPUTS\\2012\\C-small-ans.in"")); String no = br.readLine(); int number = Integer.parseInt(no); for (int h = 0; h <= number - 1; h++) { int done =0; String nos = br.readLine(); String[] n = nos.split("" ""); int s = Integer.parseInt(n[0]); int e = Integer.parseInt(n[1]); int size = n[0].length(); // ArrayList al = new ArrayList(); for (int i=s;i<=e;i++){ String t = Integer.toString(i); for (int j = 1;ji && k<=e && k>=s){ done++; //System.out.println(done + "" "" + i); //al.add(t); } } } int m = 1 + h; String ans = ""Case #"" + m + "": "" + done; out.println(ans); out.flush(); } br.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } " B22048,"package google.contest.A; import google.loader.Challenge; import google.problems.AbstractChallenge; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class AChallenge extends AbstractChallenge implements Challenge { private String text; private static Map map; public AChallenge(int number, String line) { super(number); text = line; initTranslationMap(); setResult(translate()); } private String translate() { String res=""""; for(int i=0;i(); String input=""ejp mysljylc kd kxveddknmc re jsicpdrysirbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcdde kr kd eoya kw aej tysr re ujdr lkgc jv""; String output=""our language is impossible to understandthere are twenty six factorial possibilitiesso it is okay if you want to just give up""; for(int i=0;i""+dt); Scanner sn = new Scanner(new FileInputStream(""c.in"")); System.setOut(new PrintStream(""c.out"")); int nCases = sn.nextInt(); for(int i=0;i""+dtf); } private static int calcRecycled(int A, int B) { int nRecycleds = 0; for(int n=A;n<=B;n++){ String strNumber = n+""""; String curFt = """"; LinkedListpairs = new LinkedList<>(); for(int j=0;jn){ if(mint>=A && mint <=B){ if(!pairs.contains(m)){ nRecycleds++; pairs.add(m); } } } } else{ curFt =curChar + curFt; } } } return nRecycleds; } } " B22239,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { BufferedReader br = new BufferedReader(new FileReader(""/Users/William/Desktop/C-large.in"")); String strLine; FileWriter fostream = new FileWriter(""/Users/William/Desktop/output.txt""); BufferedWriter out = new BufferedWriter(fostream); strLine = br.readLine(); int numOfLine = Integer.parseInt(strLine); for (int i=1;i> map = new HashMap>(); for (int j=1;j list; if (map.get(k)==null) { list = new ArrayList(); } else { list = map.get(k); } boolean contains = false; for (Integer m : list) { if (m.intValue()==newNum) { contains = true; break; } } if (contains) { continue; } list.add(newNum); map.put(k, list); if ((newNum>k) && (newNum<=secondNum)) { // System.out.println(""("" + k + "" , "" + newNum + "")""); count ++; } } } System.out.println(""Case #"" + i + "": "" + count); out.write(""Case #"" + i + "": "" + count + ""\n""); } out.close(); br.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } } " B21103,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException { Scanner scan = new Scanner(new File(""input"")); int cases = scan.nextInt(); for (int i = 1; i <= cases; i++) { int A = scan.nextInt(); int B = scan.nextInt(); int numDigits = (int) (Math.log(A) / Math.log(10)) + 1; int digits[] = new int[numDigits]; int tmp = A; for (int j = numDigits-1; j >= 0; j--) { digits[j] = tmp % 10; tmp /= 10; } int recycled = 0; for (int j = A; j <= B; j++) { int val = j; for (int k = 0; k < numDigits; k++) { int temp = val % 10; val = (val / 10) + (temp * ((int) Math.pow(10, numDigits-1))); if (val == j) { break; } if (val >= A && val <= B && val > j) { recycled++; } } } System.out.println(""Case #"" + i + "": "" + recycled); } } } " B20930,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Solution { public static void main(String[] args) { Scanner s = new Scanner(System.in); int size = s.nextInt(); for (int count = 1; count <= size; count++){ int lowB = s.nextInt(); int highB = s.nextInt(); int pairCount = 0; int bits = (lowB+"""").length(); int mod = (int)Math.pow(10, (bits-1)); Set seen = new HashSet(); //System.out.println(""("" + lowB + "", "" + highB + ""), "" + ""bits = "" + bits + "", mod = "" + mod); for (int i = lowB; i <= highB; i++){ int num1 = i; int num2 = i; seen.clear(); for (int j = 1; j < bits; j++){ int div = num2 / mod; int modular = num2 % mod; num2 = modular * 10 + div; if (num2 < lowB || num2 <= num1 || num2 > highB || seen.contains(num2)) continue; //System.out.println(""("" + num1 + "", "" + num2 + "")""); pairCount++; seen.add(num2); } } System.out.println(""Case #"" + count+ "": "" + pairCount); } } } " B20329,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import javax.security.auth.x500.X500Principal; public class RecycledNumbers { static HashSet set = new HashSet(); static ArrayList rotate = new ArrayList(); int counter = 0; int count=1; public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new FileReader(""input.txt"")); BufferedWriter out = new BufferedWriter(new FileWriter(""A-small.out"")); RecycledNumbers x = new RecycledNumbers(); String str; in.readLine(); while ((str = in.readLine()) != null) { x.recycle(str); out.write(""Case #""+(x.count++)+"": ""+x.counter+""\n""); x.counter = 0; } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } void recycle(String in) { int a = Integer.parseInt(in.split("" "")[0]); int b = Integer.parseInt(in.split("" "")[1]); for (int n = a; n < b ; n++) { rotateNumber(n); if(rotate.size()>0){ for (int i = 0; i < rotate.size(); i++) { int m = rotate.get(i); if(a <= n && n < m && m <= b) counter++; } } } } static void rotateNumber(int number){ rotate = new ArrayList(); int start = number; int numdigits = (int) Math.log10((double)number); int multiplier = (int) Math.pow(10.0, (double)numdigits); while(true){ int q = number / 10; int r = number % 10; //1234 = 123; number = number / 10; number = number + multiplier * r; if(number == start) return; rotate.add(number); } } } " B20134,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.*; /** * @author rohitkg */ public class Task implements Runnable { private static final String TASK_ID = ""C-large""; private static final String IN_FILE = TASK_ID + "".in""; private static final String OUT_FILE = TASK_ID + "".out""; private Scanner in; private PrintWriter out; int n,i,t,A,B; int res; private void init() { try { in = new Scanner(new File(IN_FILE)); } catch (FileNotFoundException ignored) {} try { out = new PrintWriter(OUT_FILE); } catch (FileNotFoundException ignored) {} n = in.nextInt(); } private void read() { A=in.nextInt(); B=in.nextInt(); } private void solve() { res=0; if(A<10) return; HashSet set=new HashSet(); for(int i=A;i<=B;i++){ String num ="""" + i; int length=num.length(); for(int pos=1;pos<=length;pos++){ String recNum=num.substring(pos) + num.substring(0,pos); int recInt=Integer.parseInt(recNum); if(recInt>i && recInt<= B){ //res++; if(!(set.contains(i + "", "" +recInt) || set.contains(recInt + "", "" + i))){ set.add(i + "", "" +recInt); } // System.out.println(i + "", "" +recInt); //else //out.println(""Pairs : "" + i + "", "" + recInt); } } } res=set.size(); } private void write() { out.println(""Case #"" + t + "": "" + res); } public void run() { init(); for (t = 1; t <= n; t++) { read(); solve(); write(); } out.close(); } public static void main(String[] args) { new Thread(new Task()).start(); } } " B22105,"import java.util.*; import java.io.*; import static java.lang.Math.*; public class C { public static void main(String[] args) throws IOException { /*BufferedReader in = new BufferedReader(new FileReader(""C:/Users/Farnoosh/Desktop/C-small.in"")); FileWriter fw = new FileWriter(""C:/Users/Farnoosh/Desktop/C-small.out"");*/ BufferedReader in = new BufferedReader(new FileReader(""C:/Users/Farnoosh/Desktop/C-large.in"")); FileWriter fw = new FileWriter(""C:/Users/Farnoosh/Desktop/C-large.out""); int N = new Integer(in.readLine()); //System.out.print(N); for (int cases = 1; cases <= N; cases++) { int count = 0; String[] ss = in.readLine().split("" ""); int A = Integer.parseInt(ss[0]); int B = Integer.parseInt(ss[1]); for(int num = A ; num <= B ; num++){ int num2 = 0; int len = (int)Math.pow(10, Integer.toString(num).length()-1); int i = 0; int num1 = num; for(i = 1; i < Integer.toString(num).length() ; i++){ if(Integer.toString(num2).length() == Integer.toString(num1).length() || num2==0){ num2 = 10 * (num1 % len) + (num1 / len); } else{ num2 = num2 * 10; } if(num2 == num) break; if (num2 <= B && num2 > num){ count++; }// end of if num1 = num2; }//end of for }//end of for fw.write (""Case #"" + cases + "": "" + count + ""\n""); } fw.flush(); fw.close(); } }" B21746,"package recyclednumbers; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author Kocmi */ public class RecycledNumbers { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; st = new StringTokenizer(br.readLine()); int tests = Integer.parseInt(st.nextToken()); int[] results = new int[tests]; //final result int A,B; for (int i = 0; i < tests; i++) { st = new StringTokenizer(br.readLine()); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); results[i] = recycled(A,B,Integer.toString(A).length()); } for (int i = 0; i < tests; i++) { System.out.println(""Case #""+(i+1)+"": ""+results[i]); } } catch (Exception ex) { } } public static int recycled(int A, int B, int length){ int result = 0; for (int n = A; n < B; n++) { //check n result += check(n,B,length); } return result; } public static int check(int n, int B, int length){ int cycles = 0; int m = n; int rest; boolean a; int[] correct = new int[7]; for (int i = 0; i < length-1; i++) { rest = m%10; m = (m/10); m = m+rest*(int)Math.pow(10,(length-1)); if(n done = new HashSet(); for (int j = 0; j < rep.length(); j++) { String res = eval(rep, j); if (res != null && !done.contains(res)) { done.add(res); count++; } } } System.out.println(""Case #""+z+"": "" + count); } } static String eval(String rep, int ind) { String part1 = rep.substring(0, ind); String part2 = rep.substring(ind, rep.length()); String two = part2 + part1; int twoVal = Integer.valueOf(two); if (two.charAt(0) != '0' && two.compareTo(rep) > 0 && twoVal <= end) { //System.out.println(rep + "" "" + two); return two; } return null; } } " B21084,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; import java.util.Scanner; import java.util.Vector; public class Recycled { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new FileReader(new File(""C-large.in""))); PrintWriter out = new PrintWriter(new File(""C-large.out"")); int t = in.nextInt(); in.nextLine(); for(int i=0; i sub = new Vector(20); for(int c=a; c<=b; c++) { String cs = Integer.toString(c); sub.removeAllElements(); for(int k=1; k c && ns <= b && !sub.contains(ns)) { sub.add(ns); r++; // System.out.println(c+"" -> ""+ns); } } // System.out.println(""......""); } System.out.println(""Case #"" + (i+1)+ "" of ""+t+"": "" + r); // System.out.println(""==================""); out.println(""Case #"" + (i+1)+ "": "" + r); } out.close(); } } " B21805,"import java.io.*; import java.util.ArrayList; import java.util.List; public abstract class JamProblem { int caseCount; int lastLine; abstract String solveCase(JamCase jamCase); abstract JamCase parseCase(List file, int line); List loadFile() throws IOException { FileReader inputStream = new FileReader(""C:\\projekt\\codejam\\src\\input.txt""); BufferedReader reader = new BufferedReader(inputStream); List list = new ArrayList(); while (true) { String line = reader.readLine(); if (line == null) { break; } list.add(line); } return list; } void go() throws IOException { List file = loadFile(); parseFirstLine(file); FileWriter writer = new FileWriter(""C:\\projekt\\codejam\\src\\otput.txt""); for (int c=0; c< caseCount; c++) { JamCase casee= parseCase(file, lastLine); lastLine += casee.lineCount; String s = solveCase(casee); writer.write(""Case #"" + (c+1) +"": "" + s + ""\n""); } writer.close(); } void parseFirstLine(List file) { int[] firstLine = JamUtil.parseIntList(file.get(0), 1); this.caseCount = firstLine[0]; lastLine = 1; } } " B21442,"package jp.funnything.competition.util; import java.util.Arrays; import java.util.Iterator; /** * Do NOT change the element in iteration */ public class Permutation implements Iterable< int[] > , Iterator< int[] > { public static int[] fromNumber( long value , final int n ) { final int[] data = new int[ n ]; for ( int index = 0 ; index < n ; index++ ) { data[ index ] = index; } for ( int index = 1 ; index < n ; index++ ) { final int pos = ( int ) ( value % ( index + 1 ) ); value /= index + 1; final int swap = data[ index ]; data[ index ] = data[ pos ]; data[ pos ] = swap; } return data; } public static long toNumber( final int[] perm ) { final int[] data = Arrays.copyOf( perm , perm.length ); long c = 0; for ( int index = data.length - 1 ; index > 0 ; index-- ) { int pos = 0; for ( int index_ = 1 ; index_ <= index ; index_++ ) { if ( data[ index_ ] > data[ pos ] ) { pos = index_; } } final int t = data[ index ]; data[ index ] = data[ pos ]; data[ pos ] = t; c = c * ( index + 1 ) + pos; } return c; } private final int _n; private final int[] _data; private final int[] _count; int _k; public Permutation( final int n ) { _n = n; _data = new int[ n ]; for ( int index = 0 ; index < n ; index++ ) { _data[ index ] = index; } _count = new int[ n + 1 ]; for ( int index = 1 ; index <= n ; index++ ) { _count[ index ] = index; } _k = 1; } @Override public boolean hasNext() { return _k < _n; } @Override public Iterator< int[] > iterator() { return this; } @Override public int[] next() { final int i = _k % 2 != 0 ? _count[ _k ] : 0; final int t = _data[ _k ]; _data[ _k ] = _data[ i ]; _data[ i ] = t; for ( _k = 1 ; _count[ _k ] == 0 ; _k++ ) { _count[ _k ] = _k; } _count[ _k ]--; return _data; } @Override public void remove() { } } " B21445,"package qualC; import java.util.*; public class RecycledNumbers { private static int cases; public static void main(String[] args) { Scanner input = new Scanner(System.in); if (input.hasNextInt()) { cases = input.nextInt(); } for (int i = 0; i < cases; i++) { System.out.println(""Case #"" + (i+1) + "": "" + findRecycled(input)); } } public static int findRecycled(Scanner input) { int startingPoint = 0; int endingPoint = 0; int counter = 0; if (input.hasNextInt()) { startingPoint = input.nextInt(); } if (input.hasNextInt()) { endingPoint = input.nextInt(); } //for each item from start->end.. for (Integer i = startingPoint; i < endingPoint; i++) { //cast that item to a string.. String value = i.toString(); ArrayList thisItem = new ArrayList(); //for each character in the string.. for (int z = 0; z < value.length(); z++) { //shuffle the characters along one String rotate = value.substring(z); rotate += value.substring(0, z); //cast to an int int shuffledInt = Integer.parseInt(rotate); //make sure it is within the boundaries.. if (shuffledInt <= endingPoint && shuffledInt >= startingPoint) { //if it is greater than the original then it is a duplicate if (Integer.parseInt(value) < shuffledInt) { //make sure if we've looked at this item before that it's not a duplicate.. if (!thisItem.contains(shuffledInt)) { counter++; thisItem.add(shuffledInt); } } } } } return counter; } }" B22234,"import java.util.Scanner; public class NumberRecycling { public static void main( String args[] ) { new NumberRecycling(); } public NumberRecycling() { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for( int j=1; j<=T; j++ ) { System.out.println( ""Case #""+ j + "": "" + doCase(sc) ); } } public int doCase( Scanner sc ) { int A = sc.nextInt(); int B = sc.nextInt(); int pairs = 0; for( int i=A+1; i<=B; i++ ) pairs += numberOfLowerPairNumbers(A,i); return pairs; } public int numberOfLowerPairNumbers( int lowerBound, int num ) { String number = Integer.toString(num); String tmp = new String(number); int result = 0; for( int i=0; i= lowerBound ) result++; } return result; } }" B20522,"package compete; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; import java.util.TreeSet; public class C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); FileWriter fw = new FileWriter(""C-large.out""); int N = new Integer(in.readLine()); for (int cases = 1; cases <= N; cases++) { StringTokenizer st = new StringTokenizer(in.readLine()); int A = new Integer(st.nextToken()); int B = new Integer(st.nextToken()); fw.write(""Case #"" + cases + "": "" + nrecycled(A, B) + ""\n""); } fw.flush(); fw.close(); } private static int nrecycled(int a, int b) { int cpt = 0; for (int i = a; i < b; i++) { TreeSet l = listRecycled(i); for(Integer x:l) { if ((i listRecycled(int n) { TreeSet l = new TreeSet(); int nbChiffres = Integer.toString(n).length(); for(int i=1; i used; public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(new File(""C.out"")); Scanner in = new Scanner(System.in); int cases = in.nextInt(); used = new HashSet(); for(int caseOn = 1; caseOn <= cases; caseOn++) { used.clear(); int a = in.nextInt(); int b = in.nextInt(); int ans = 0; for(int i = a; i < b; i++) { if(used.contains(i)) continue; int count = 0; ArrayList rotations = gen(i); for(int t : rotations) { if(!used.contains(t)) { used.add(t); if(a <= t && t <= b) { count++; } } } count--; ans+=(count*(count+1))/2; } out.printf(""Case #%d: %d\n"",caseOn,ans); } out.close(); } public static ArrayList gen(int a) { int dig = countDigits(a); int ten = 1; for(int i = 1; i < dig; i++) { ten*=10; } ArrayList ret = new ArrayList(); for(int i = 0; i < dig; i++) { if(countDigits(a)==dig) ret.add(a); a = (a%10)*ten + (a/10); } return ret; } public static int countDigits(int a) { int c = 0; while(a!=0) { c++; a/=10; } return c; } } /* 4 1 9 10 40 100 500 1111 2222 */ " B22170,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class RecycledNumber { public static void main (String[] args) throws FileNotFoundException{ Scanner scan = new Scanner (new File (""input.txt"")); int caseNumber = scan.nextInt(); scan.nextLine(); for(int k=0; k=digit(i,numberOfDigits(i))){ if (A <= recycle(i,j) && B >= recycle(i,j) && i set = new HashSet(); for (int i = 1; i < s.length() ; i++) { if (s.charAt(i) != '0') { String first = s.substring(0, i); String second = s.substring(i, s.length()); int number = Integer.parseInt(second + first); if (!set.contains(number) && number > x && number <= limit) { result += 1; set.add(number); } } } return result; } } " B21354,"import java.io.*; import java.util.*; /** * */ public class Main { /** * */ public class TestCase{ public Integer a, b; public Integer[] rNumbers; public Integer iResult=0; public Set setPairs=Collections.synchronizedSet( new HashSet()); /** * @param a * @param b * */ public TestCase( int a, int b){ this.a=a; this.b=b; this.rNumbers=new Integer[ ( this.b- this.a)+ 1]; for( int i=this.a; i<=this.b; i++) this.rNumbers[ i- this.a]=i; } /** * */ public void doSolution(){ this.iResult=0; for( int i=0; i!=this.rNumbers.length; i++){ Integer number=this.rNumbers[ i]; String strNumber=String.valueOf( number); if( strNumber.length()>=2){ for( int s=1; s!=strNumber.length(); s++){ String strPrefix=strNumber.substring( 0, s); String strSuffix=strNumber.substring( s); String strNewNumber=strSuffix+ strPrefix; Integer newNumber=Integer.valueOf( strNewNumber); if(( newNumber>=this.a) && ( newNumber<=this.b) && ( number.compareTo( newNumber)!=0)) this.addPair( number, newNumber); }}} this.iResult=this.setPairs.size(); } public void addPair( Integer n, Integer m){ String nm=n+""+""+m; String mn=m+""+""+n; if( !this.setPairs.contains( nm) && !this.setPairs.contains( mn)){ this.setPairs.add( nm); }} } public TestCase createTestCase( int a, int b){ return new TestCase( a, b); } /** * */ public static void main( String[] args){ try { Main m=new Main(); LineNumberReader reader=new LineNumberReader( new FileReader( new File( args[ 0].trim()))); PrintWriter printer=new PrintWriter( new FileWriter( args[ 1].trim())); int nTestCases=Integer.valueOf( reader.readLine()); for( int i=0; i!=nTestCases; i++){ String str[]=reader.readLine().split( "" "", 2); TestCase testCase=m.createTestCase( Integer.valueOf( str[ 0].trim()), Integer.valueOf( str[ 1].trim())); testCase.doSolution(); printer.println( ""Case #""+( i+ 1)+"": ""+ testCase.iResult); System.out.println( ""Case #""+( i+ 1)+"": ""+ testCase.iResult); } printer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}} " B22151,"package QR2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; public class C { private static class Pair { final int n; final int m; public Pair(int n, int m) { this.n = n; this.m = m; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } } public static void main(String[] args) throws Exception { String test = ""C-large""; BufferedReader in = new BufferedReader(new FileReader(""QR2012/C/"" + test + "".in"")); PrintWriter out = new PrintWriter(""QR2012/C/"" + test + "".out."" + System.currentTimeMillis()); final int T = Integer.parseInt(in.readLine()); for (int t = 1; t <= T; t++) { String[] nums = in.readLine().split(""\\s""); final int A = Integer.parseInt(nums[0]); final int B = Integer.parseInt(nums[1]); Set pairs = new HashSet(); final int order = (int) Math.floor(Math.log10(A)) + 1; for (int n = A; n <= B; n++) { int m = n; for (int o = 0; o < order - 1; o++) { // rotate m one digit int tail = m % 10; m /= 10; m += tail * Math.pow(10, order - 1); if (m > n && m >= A && m <= B) pairs.add(new Pair(n, m)); } } System.out.println(""Case #"" + t + "": "" + pairs.size()); out.println(""Case #"" + t + "": "" + pairs.size()); } out.close(); } } " B22050,"package google.contest.B; import google.loader.Challenge; import google.problems.AbstractReader; public class BReader extends AbstractReader { @Override protected Challenge createChallenge(int number) { int theLine = getActualLine(); String[] lines = getLines(); BChallenge chal = new BChallenge(number, lines[theLine]); setActualLine(theLine+1); return chal; } } " B21239,"package codejam; import java.util.*; /** * * @author JoeJev */ public class ProblemC { Scanner scan; public ProblemC(Scanner scan) { this.scan = scan; } public void processProblem(){ int cases = scan.nextInt(); for (int m = 1; m <= cases; m++){ System.out.println(""Case #"" + m + "": "" + amountRecycled(scan.nextInt(), scan.nextInt())); } } public int amountRecycled(int n, int m) { int result = 0; int parsedInt; for (int o = n; o <= m; o++) for (int p = String.valueOf(o).length(); p > 0; p--){ parsedInt = Integer.parseInt(String.valueOf(o).substring(p) + String.valueOf(o).substring(0, p)); if (parsedInt <= m && parsedInt >= n && parsedInt != o) result++; } return result / 2; } } " B20673," import java.io.*; import java.util.*; public class trie { public static void main(String[] args)throws IOException { int i,j,a,b,n,ans; String s1="""",p1=""""; solver h1=new solver(); Scanner fin=new Scanner(new File(""A.txt"")); s1=fin.nextLine(); n=Integer.parseInt(s1); FileWriter fstream=new FileWriter(""out.txt""); BufferedWriter out=new BufferedWriter(fstream); for(i=0;i> map = new HashMap>(); int start = scanner.nextInt(); int finish = scanner.nextInt(); int count = 0; for(int x = start;x<=finish;x++) { map.put(x, new HashSet()); String s = """" + x; int length = s.length(); for(int i=1;i pairs; static { pairs = new HashSet(500000); } public long begin, end; @Override public String toString() { return new StringBuilder(""<$DataSet: "").append(begin).append("", "").append(end).append("">"").toString(); } public long countRecycles() { int digits = countDigits(begin); for (long i=begin; i<=end; ++i) { for (int j=1; j= begin && result <= end) pairs.add(new LongPair(i, result)); } } long result = pairs.size(); pairs.clear(); return result; } public static DataSet parse(String s) { DataSet result = new DataSet(); result.begin = Long.parseLong(s.substring(0, s.indexOf(' '))); result.end = Long.parseLong(s.substring(1+s.indexOf(' '))); return result; } } public static Reader getFileReader(String filename) { BufferedReader result = null; try { result = new BufferedReader(new FileReader(filename)); } catch (FileNotFoundException e) { System.err.println(""Couldn't find the file \""""+filename+""\""""); e.printStackTrace(); } return result; } public static String readLine(BufferedReader reader) { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public static void closeReader(Reader r) { try { r.close(); } catch (IOException e) { e.printStackTrace(); } } public static Writer getFileWriter(String filename) { BufferedWriter result = null; try { result = new BufferedWriter(new FileWriter(filename)); } catch (IOException e) { e.printStackTrace(); } return result; } public static void writeLine(BufferedWriter writer, String line) { try { writer.write(line); writer.newLine(); } catch (IOException e) { e.printStackTrace(); } } public static void closeWriter(Writer w) { try { w.close(); } catch (IOException e) { e.printStackTrace(); } } public static String formatCase(int caseNumber, long result) { return new StringBuilder(""Case #"").append(caseNumber).append("": "").append(result).toString(); } public static int countDigits(long n) { return (int) 1 + (int)Math.floor(Math.log10(n)); } public static int getDigit(long n, int digit) { return(int)(n/(long)Math.pow(10, digit-1)) % 10; } public static long shiftLong(long n, int digits) { long mask = (long) Math.pow(10, digits); long upshift = (long) Math.pow(10, (countDigits(n)-digits)); return (upshift*(n%mask)) + (n/mask); } public static void main(String[] args) { BufferedReader in = (BufferedReader) getFileReader(inputFilename); int lineCount = Integer.parseInt(readLine(in)); List dataSets = new ArrayList(); for (int i=0; i 0) { mul *= 10; ii /= 10; dig ++; } mul /= 10; int right = i; int left = 0; for (int d=0; d i && k <= B) { if (v[k] != i) { cnt ++; v[k] = i; } } } } return cnt + ""\n""; } //////////////////////////////////////// // read input //////////////////////////////////////// public String runInput(BufferedReader br) throws IOException { String[] items = br.readLine().trim().split(""\\s+""); int A = Integer.parseInt(items[0]); int B = Integer.parseInt(items[1]); return solve(A, B); } //////////////////////////////////////// // main //////////////////////////////////////// public static void main(String[] args) { C c = new C(); try { c.parseFile(""C-sample""); c.parseFile(""C-small-attempt0""); c.parseFile(""C-large""); } catch (IOException e) { e.printStackTrace(); } } //////////////////////////////////////// // library //////////////////////////////////////// public void parseFile(String filePrefix) throws IOException { String fileIn = filePrefix + "".in""; String fileOut = filePrefix + "".out""; BufferedReader br = new BufferedReader(new FileReader(fileIn)); BufferedWriter bw = new BufferedWriter(new FileWriter(fileOut)); int n = Integer.parseInt(br.readLine()); for (int i=1; i<=n; i++) { String ret = ""Case #"" + i + "": ""; ret += runInput(br); System.out.print(ret); bw.write(ret); } br.close(); bw.close(); } } " B21469,"package com.renoux.gael.codejam.fwk; import com.renoux.gael.codejam.utils.Input; import com.renoux.gael.codejam.utils.Output; public class Model extends Solver { public static void main(String... args) throws Exception { new Model().run(); } @Override protected void solveCase(Input in, Output out) { // TODO } @Override protected String getProblemName() { return ""hey2012/Model""; } } " B21345,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(""recycle.in"")); PrintWriter out = new PrintWriter(new FileWriter(""recycle.out"")); int n = Integer.parseInt(br.readLine()); StringTokenizer st; for(int count = 1; count <= n; count++){ st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); boolean[] hasBeen = new boolean[B+1]; int numPairs = 0; for(int i = A; i <= B; i++){ if(hasBeen[i] == true) continue; hasBeen[i] = true; ArrayList cycle = rotate(i); int numCycles = 1; for(int num: cycle){ if(num > B || num < A) continue; if(hasBeen[num]) continue; hasBeen[num] = true; numCycles++; } numPairs += (numCycles*(numCycles-1))/2; } out.println(""Case #"" + count + "": "" + numPairs); } out.close(); } static ArrayList rotate(int num){ ArrayList ans = new ArrayList(); int length = String.valueOf(num).length(); for(int i = 1; i < length; i++){ if(num%10 == 0){ num = (int)((num%10)*Math.pow(10, length-1)) + num/10; } else { num = (int)((num%10)*Math.pow(10, length-1)) + num/10; ans.add(num); } } return ans; } } " B21577,"package qC; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import qB.B.Pair; //Letfs say a pair of distinct positive integers (n, m) is recycled //if you can obtain m by moving some digits from the back of n to the //front without changing their order. For example, (12345, 34512) is a //recycled pair since you can obtain 34512 by moving 345 from the end //of 12345 to the front. Note that n and m must have the same number //of digits (excluding leading zeros) in order to be a recycled pair. //Given integers A and B with the same number of digits, how many distinct //recycled pairs (n, m) are there with A ? n < m ? B? public class C2 { static int solve(int number, int b) { int numDigi = number; int orgNumber = number; int c = 1; int p = 1; int counter = 0; do { numDigi = numDigi / 10; p = p * 10; c++; } while (numDigi != 0); int k = c - 1; p = p / 10; for ( int i = 1; i <= k; i++) { number = number % p * 10 + number / p; if (number > orgNumber && number <= b) { // System.out.println( ""no: "" + number + "", "" + check); counter++; } } return counter; } public static void main(String[] args) throws FileNotFoundException { if (args.length == 0) { throw new IllegalArgumentException(""no file given""); } String filename = args[0]; Scanner scanner = new Scanner(new File(filename)); int numOfLines = scanner.nextInt(); scanner.nextLine(); for (int lineIdx = 0; lineIdx < numOfLines; lineIdx++) { final int start = scanner.nextInt(); final int end = scanner.nextInt(); int ans = 0; for (int l = start; l <= end; l++) { ans += solve(l, end); } System.out.printf(""Case #%d: %d\n"", lineIdx + 1, ans); } } } " B22111,"package gcj2012Q; import java.io.*; import java.util.*; public class C { public static void main(String[] args) { new C().run(new Scanner(System.in)); } void run(Scanner sc) { int n = sc.nextInt(); for(int i = 1; n-- > 0; i++) solve(sc, i); } int solve(int a, int b) { if(b < 10 || a == b) return 0; int count = 0; for(int i = a; i < b; i++) { String str = """" + i; Set set = null; for(int j = 1; j < str.length(); j++) { String num_str = str.substring(j) + str.substring(0, j); int num = Integer.parseInt(num_str); if(i < num && num <= b) { // System.out.println(i+"" ""+num); if(set == null) set = new HashSet(); if(set.contains(num)) continue; count++; set.add(num); } } } return count; } void solve(Scanner sc, int case_num) { int a = sc.nextInt(); int b = sc.nextInt(); int res = solve(a, b); System.out.printf(""Case #%d: %d\n"", case_num, res); } } " B21707,"import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.HashSet; public class RecycledNumbers { /** * Google Code Jam 2012: Problem C. Recycled Numbers * @author hullarb * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader input = new BufferedReader(new FileReader(args[0])); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(args[0].contains(""in"")?args[0].replace(""in"", ""out""):args[0] + "".out"")); int testCases = Integer.parseInt(input.readLine()); for(int i = 0; i < testCases; i++) { String[] parts = input.readLine().split("" ""); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); int pairs = 0; for(int j = A; j found = new HashSet(); for(int i = 0; i < digits.length() - 1; i++) { int n = Integer.parseInt(digits.substring(digits.length() - 1 - i) + digits.substring(0,digits.length() - 1 - i)); if(n > j && n <= b && !found.contains(n)) { found.add(n); pairs++; } } return pairs; } } " B20729,"package fixjava; import java.util.ArrayList; /** * An ArrayList that allows values to be set at positions greater than or equal to size(), which causes the end of the list to be padded with an * identity element before the value is set */ public class ArrayListAutoPadded extends ArrayList { private T identity; public ArrayListAutoPadded(T identity) { super(); this.identity = identity; } public ArrayListAutoPadded(T identity, int initialCapacity) { super(initialCapacity); this.identity = identity; } /** * Set the value at the given location to the specified value, padding the list to the desired length if necessary. Returns the old value at the * location, if there was one, otherwise the identity value that was passed in the constructor. */ public T set(int index, T element) { if (size() > index) { return super.set(index, element); } else { while (size() < index) add(identity); add(element); return identity; } }; /** * Combine the value at the given location with the new value, by calling labmda.apply(oldValue, newValue). The identity value that was passed in * the constructor is used if the index >= size(). Returns the *old* value that was stored at the index before combining, or identity if there was * no old value. */ public T combineAndSet(int index, Lambda2 combineFunc, T newValue) { T oldValue; if (size() > index) { oldValue = get(index); } else { while (size() <= index) add(identity); oldValue = identity; } return super.set(index, combineFunc.apply(oldValue, newValue)); } private static final long serialVersionUID = 1L; } " B22045,"package google.problems; import google.loader.Challenge; import google.loader.ChallengeReader; import java.util.ArrayList; import java.util.List; public abstract class AbstractReader implements ChallengeReader { private String[] lines; private List challenges; private int actualLine; public AbstractReader(){ challenges = new ArrayList(); } protected void setLines(String[] input) { lines=input; } protected String[] getLines(){ return lines; } protected int getNumberOfChallenges() { return Integer.parseInt(lines[0]); } @Override public List createChallenges(String[] input) { setLines(input); readChallenges(); return challenges; } private void readChallenges() { int numOfChallanges = getNumberOfChallenges(); setActualLine(1); actualLine = 1; for(int i=1;i<=numOfChallanges; i++){ challenges.add(createChallenge(i)); } } protected int[] asInt(String values) { String[] split = values.split("" ""); int res [] = new int[split.length]; for(int i=0;i asIntList(String values) { List res = new ArrayList(); for(int i : asInt(values)){ res.add(i); } return res; } protected abstract Challenge createChallenge(int i) ; protected void setActualLine(int i) { actualLine =i; } protected int getActualLine(){ return actualLine; } } " B21780,"package com.ignaciobona.codejam.practice.problema; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashMap; public class Solver { public static String PROBLEM_NUMBER=""C""; public static String PATH_TO_INPUT_FILE_SMALL=""inputs/""+PROBLEM_NUMBER+""-small-attempt0.in""; public static String PATH_TO_OUPUT_FILE_SMALL=""outputs/""+PROBLEM_NUMBER+""-small-attempt0.out""; public static String PATH_TO_INPUT_FILE_LARGE=""inputs/""+PROBLEM_NUMBER+""-large.in""; public static String PATH_TO_OUPUT_FILE_LARGE=""outputs/""+PROBLEM_NUMBER+""-large.out""; public static boolean SMALL=false; public static class Problem{ public int nCase; public int a; public int b; public StringBuffer outputString; public void solve(){ HashMapmap=new HashMap(); outputString=new StringBuffer(""Case #""+nCase+"": ""); int found=0; for(int n=a;n<=b;n++){ int nDigits=(n+"""").length(); int m=n; for(int j=1;j { int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } public int hashCode() { return a | b << 22; } public boolean equals(Object o) { Pair p = (Pair) o; return p.a == a && p.b == b; } @Override public int compareTo(Pair o) { if (a != o.a) return a - o.a; if (b != o.b) return b - o.b; return 0; } } public static int digitCount(int i) { int c = 0; while (i != 0) { c++; i /= 10; } return c; } public static Pair getMin(int i) { int nd = digitCount(i); int[] arr = new int[nd]; int l = i; for (int j = 0; j < arr.length; j++) { arr[j] = l; l = l % 10 * a[nd - 1] + l / 10; } Arrays.sort(arr); return new Pair(arr[0], nd); } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream(""C.in""))); PrintWriter out = new PrintWriter(""C.out""); int tc = Integer.parseInt(in.readLine()); for (int cc = 1; cc <= tc; cc++) { StringTokenizer strtok = new StringTokenizer(in.readLine(), "" ""); int a = Integer.parseInt(strtok.nextToken()); int b = Integer.parseInt(strtok.nextToken()); int[][] count = new int[digitCount(b) + 1][b + 1]; long res = 0; for (int i = a; i <= b; i++) { Pair p = getMin(i); res += count[p.b][p.a]; count[p.b][p.a]++; } out.printf(""Case #%d: %d\n"", cc, res); } out.close(); } } " B20297,"import java.util.*; public class RecycledNumbers { public static void main(String []args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int i = 1; i <= T; i++) { System.out.print(""Case #"" + i + "": ""); int A = in.nextInt(); int B = in.nextInt(); int count = 0; int n = 0; int t = A; while(t > 0) { t /= 10; n++; } boolean []b = new boolean[B + 1]; for(int j = A; j <= B; j++) { int cycle = 0; for(int k = 0; k < n; k++) { t = rotate(j, n, k); if(A > t || t > B) continue; if(!b[t]) { b[t] = true; cycle++; } } count += cycle * (cycle - 1) / 2; } System.out.print(count); if(i < T) System.out.println(); } } public static int rotate(int n, int size, int r) { int p = 1; for(int i = 0; i < r; i++) p *= 10; int cp = 1; for(int i = 0; i < size - r; i++) cp *= 10; return n % p * cp + n / p; } }" B21005,"//Kholofelo Moyaba //Problem C codejam //14 April 2012 import java.util.Scanner; class RecycledNumbers { public static void main(String[] args) { Scanner input = new Scanner(System.in); int cases = input.nextInt(); for(int i=1;i<=cases;i++) { int a = input.nextInt(); int b = input.nextInt(); int digits = (a+"""").length()-1;//number of digits -1 int factor = 1;//factor in order of a and b for(int j=0;j=1) br=new BufferedReader(new FileReader(new File(args[0]))); else br=new BufferedReader(new InputStreamReader(System.in)); if(args.length>=2) System.setOut(new PrintStream(new FileOutputStream(args[1]))); int T=Integer.valueOf(br.readLine().trim()); for(int t=1;t<=T;++t) { String[] temp=br.readLine().trim().split("" ""); int A=Integer.valueOf(temp[0]); int B=Integer.valueOf(temp[1]); int ret=0; int[] seen=new int[8]; for(int m=A;m<=B;++m) { String mi=""""+m; int yes=0; Arrays.fill(seen,-1); for(int k=0;k<=mi.length();++k) { String front=mi.substring(k); String back=mi.substring(0,k); if(front.length()==0 || back.length()==0) continue; int n=Integer.valueOf(front+back); if(A<=m && m { public abstract T nextCase() throws Exception; public abstract int getMaxCaseNumber(); } " B20498,"import java.io.*; public class Test { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in, ""UTF-8"")); int num = Integer.parseInt(br.readLine()); int nline = 1; String line; while ((line = br.readLine()) != null && nline <=num) { String[] tok = line.split("" ""); int size = tok[0].length(); double result = 0; if (size != 1) { int A = Integer.parseInt(tok[0]); int B = Integer.parseInt(tok[1]); for (int i = A; i <= B; i++) { int n = size; String str = Integer.toString(i); for (int j = 1; j < size; j++) { String str2 = str.substring(j) + str.substring(0, j); if ((Integer.parseInt(str2) < A) || (Integer.parseInt(str2) > B) || (Integer.parseInt(str2) == Integer.parseInt(str))) --n; } if (n >= 2) result += n * (n-1) / 2.0 * 1.0 / n; } } System.out.println(""Case #"" + nline + "": "" + (int) result); nline++; } } } " B21195,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; public class CodeJamWriter implements ICounterZeroEvent{ //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\A-test""; //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\A-small-attempt0""; //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\B-test""; //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\B-small-attempt0""; //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\B-large""; //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\C-test""; //public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\C-small-attempt0""; public static String inputFile = ""C:\\Users\\user\\Desktop\\coejam\\2012-Qualificaton\\C-large""; public int T; public Result[] results; public static void main(String[] args) { CodeJamWriter codeJamWriter = new CodeJamWriter(); codeJamWriter.readInput(); } private void readInput() { Scanner scanner = null; File input = new File(inputFile+"".in""); try { scanner = new Scanner(input); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } T = scanner.nextInt(); scanner.nextLine(); results = new Result[T+1]; Counter counter = new Counter(T, this); for (int i=1;i<=T;++i) { results[i] = new Result(i); Question q = new QuestionC(results[i], counter); q.readInput(scanner); q.start(); } scanner.close(); } private void writeOutput() { FileOutputStream fos = null; PrintStream printer = null; File output = new File(inputFile+"".out""); try { fos = new FileOutputStream(output); printer = new PrintStream(fos); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i=1;i<=T;++i) { printer.println(results[i]); } System.out.println(""FINISHED!!!""); printer.close(); } @Override public void fireEvent() { writeOutput(); } } " B20960,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; public class Evans2012C { private final String _PROBLEM_NO = ""201201C""; private final String _FILE_DIRECTORY = ""K:/Dropbox/workspace/codejam/"" + _PROBLEM_NO + ""/""; private final String _FILE_PATH = _FILE_DIRECTORY + ""C-Large""; public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Evans2012C().execute(); } public void execute() { BufferedReader br = null; PrintWriter pw = null; try { br = new BufferedReader(new FileReader(_FILE_PATH + "".in"")); pw = new PrintWriter(_FILE_PATH + "".out""); //main int caseno = Integer.parseInt(br.readLine()); Map m = new HashMap(); for(int i=10;i<=1000000;i++) { check(i,m); } // System.out.println(m.get(2)); for (int count = 1; count <= caseno; count++) { // if(count>4)break; pw.print(""Case #"" + count + "": ""); System.out.print(""Case #"" + count + "": ""); String line = br.readLine(); String[] splits = line.split("" ""); int A = Integer.parseInt(splits[0]); int B = Integer.parseInt(splits[1]); int r = 0; if(A < 10 || A >= 1000000 || A==B) { pw.print(""0""); System.out.print(""0""); } else { List tt = m.get((""""+A).length()); for(int t:tt) { // if(t >= A && t <= B) { r += check(A,B,t); // } } pw.print(r); System.out.print(r); } pw.print(""\n""); System.out.print(""\n""); } //end br.close(); pw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(pw != null) pw.close(); } catch(Exception e) {} try { if(br != null) br.close(); } catch(Exception e) {} } } private int check(int a, int b, int t) { String tt = """"+t; // System.out.println(tt); int r =0; Set rr = new HashSet(); for(int i=0;i=a&&t<=b) { // System.out.print(tt + ""!""); rr.add(t); } } r=rr.size(); // System.out.println(r); if(r==1) return 0; if(r!=0) r = (r*(r-1))/2; return r; } private void check(int i, Map m) { String in = """" + i; int b = in.length(); if(!dedup(i)) return; dedup.put(i, true); List target = m.get(b); if(target == null) { target = new ArrayList(); m.put(b, target); } target.add(i); } public static Map dedup = new HashMap(); private boolean dedup(int t) { String tt = """"+t; for(int i=0;i list; for (long n = a; n(100); long m = n; for (int i=1; i permutations = new LinkedList(); boolean found = false; for(int i=1;iB||parseInt recycledPairSet = new HashSet(); int a = sc.nextInt(); int b = sc.nextInt(); int digit = (""""+a).length(); for(int n=a; n n && m <= b) { recycledPairSet.add(new NumberPair(n, m)); } } } System.out.println(String.format(""Case #%d: %d"", currentCase, recycledPairSet.size())); } } private static StringBuilder rotate(StringBuilder s) { if(s.length() == 0) return s; s.insert(0, s.charAt(s.length() - 1)); s.deleteCharAt(s.length() - 1); return s; } } class NumberPair { private int a; private int b; public NumberPair(int a, int b) { this.a = a; this.b = b; } @Override public boolean equals(Object obj) { if (!(obj instanceof NumberPair)) { return false; } NumberPair n = (NumberPair) obj; if (n.a == a && n.b == b) { return true; } else if (n.a == b && n.b == a) { return true; } else { return false; } } @Override public int hashCode() { return a+b; } } " B21898,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.PrintWriter; public class C { InputScanner s = new InputScanner(System.in); PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { C program = new C(); program.begin(); } int prev; int current; int ansA; int ansB; int A; int B; public void begin() { int T = s.nextInt(); for(int t=1;t<=T;t++) { A = s.nextInt(); B = s.nextInt(); prev = 0; for(int i=A-1;i<=B;i++) { current =prev+recycleCount(i); prev = current; //system.out.println(i+"" CURRENT: ""+current); if(i == A-1) ansA = current; } out.printf(""Case #%d: %d\n"",t,current-ansA); } out.close(); } public int recycleCount(int x) { ////system.out.println(""-----""); ArrayList store = new ArrayList(); //system.out.print(x+"" => ""); int count = 0; String num = x+""""; int a = 0; int b = 0; for(int i=1;i= A && !store.contains(val+"""")) { count++; store.add(val+""""); //system.out.print("" ""+val); //system.out.print(""*""); } } //system.out.println(); //system.out.println(count+""c""); ////system.out.println(""-----""); return count; } class InputScanner { BufferedReader br; StringTokenizer strtok = null; public InputScanner(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public InputScanner(File file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } public String next() { if (strtok == null || !strtok.hasMoreTokens()) { try { strtok = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return strtok.nextToken(); } public int nextInt() { int i; try { i = Integer.parseInt(next()); } catch (NumberFormatException e) { throw new RuntimeException(e); } return i; } public String nextLine() { if (strtok == null || !strtok.hasMoreTokens()) { try { strtok = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return strtok.nextToken(""\n"").trim(); } } }" B21595,"import java.io.*; import java.util.*; public class Prob3 { public static PrintStream out; public static int caseNum; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new File(""in.txt"")); out = new PrintStream(new File(""out.txt"")); int numCases = Integer.parseInt(sc.nextLine()); caseNum = 0; for(int i=0; i=from && recycled<=to) numPairs++; recycled = recycle(recycled, digitsPow10); } } caseNum++; out.println(""Case #""+caseNum+"": ""+(numPairs/2)); } public static int recycle(int num, int digitsPow10){ while(true){ int lastDigit = num%10; num = lastDigit*digitsPow10 + num/10; if(lastDigit!=0) break; } return num; } }" B22214,"import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.File; import java.io.PrintStream; import java.util.Scanner; import java.util.Arrays; import java.util.ArrayList; public class Numbers{ public static ArrayList scores; public static void main(String arg[]){ System.out.print(""Enter the file path of the input file : ""); String path = new Scanner(System.in).nextLine(); String ANS ="""", output=""""; int a, b; try{ Scanner read = new Scanner(new File(path)); int testCases = Integer.parseInt(read.nextLine()); int cn=0; String tongue; while(cn++ to exit...""); (new Scanner(System.in)).nextLine(); System.exit(1); } } public static void writeToFile(String file, String text){ PrintStream out = null; try { out = new PrintStream(new FileOutputStream(file)); out.print(text); } catch(Exception e){} finally { if (out != null) out.close(); } } public static int solve(int a, int b){ int counter=0; for(int i=a; i<=b; i++){ counter += recycle(""""+i,b); } System.out.println(counter); return counter; } public static int recycle(String numb, int max){ int numbOfLoops=numb.length()-1, count=0; int newNumb, success=0; String first="""", second=""""; int last=-10; while(count< numb.length()-1){ second = numb.substring(numbOfLoops-count); first = numb.substring(0,numbOfLoops-count); newNumb = Integer.parseInt(second+first); if(newNumb != last && newNumb > Integer.parseInt(numb) && newNumb <= max){ last = newNumb; success++; } count++; } return success; } } " B21078,"import java.io.*; import java.util.HashSet; import java.util.Set; /** * *************************************************************************** * Created by IntelliJ IDEA. * User: Narender Singh Pal * Date: 4/14/12 * Time: 10:59 AM *

* *************************************************************************** *

* Copyright (c) 2012 All Rights Reserved. *

*

* *************************************************************************** */ public class RecycledNumbers { public static void main (String args[]) { try { BufferedReader Br = new BufferedReader(new FileReader(""C:\\Input\\C-large.in"")); BufferedWriter Bw = new BufferedWriter(new FileWriter(""C:\\Input\\C-large.out"")); try { //read number of test cases int $TC = Integer.valueOf(Br.readLine()); System.out.println(""Number of Test Cases :""+ $TC); int $A, $B; int [] $InputNum; for(int tc = 1; tc <= $TC; tc++) { String $InputStr = Br.readLine(); String []TempArr = $InputStr.split("" ""); $InputNum = new int[TempArr.length]; for(int j =0; j < TempArr.length; j++) { $InputNum[j] = Integer.valueOf(TempArr[j]); } //get numbers A, B from input number pair $A = $InputNum[0]; $B = $InputNum[1]; int $RecycledPairs = 0; //Iterate the given integer range for( int $n = $A; $n <= $B ; $n++ ) { String lStr = String.valueOf($n); int $length = lStr.length(); int [] $m = new int[$length-1]; Set $MSet = new HashSet(); //for each $n get all possible recycled number for(int k = 1; k < $length; k++ ) { StringBuffer s = new StringBuffer(); s.append(lStr.subSequence(k,$length)); s.append(lStr.subSequence(0,k)); $m[k-1] = Integer.valueOf(s.toString()); //Recycled pair found if the SA <= $n < $m <= $B if($m[k-1] > $n && $m[k-1] <= $B && $m[k-1] >= $A) { if($MSet.isEmpty()) { $MSet.add($m[k-1]); } else { if($MSet.contains($m[k-1])) { System.out.println(""###Repeat : skipping ($n, $m) :("" +$n +"", ""+ $m[k-1]+"")####"" ); continue; } $MSet.add($m[k-1]); } $RecycledPairs++; System.out.println(""$Recycled Pair (""+ $RecycledPairs +"") : ($n, $m) :("" +$n +"", ""+ $m[k-1]+"")""); } } } System.out.println(""Case #""+ tc+"": ""+$RecycledPairs); Bw.write(""Case #""+ tc+"": ""+ $RecycledPairs); Bw.write('\n'); } } finally { Br.close(); Bw.close(); } } catch (IOException e) { e.printStackTrace(); } } } " B20188,"package com.numbers.recycle.main; import com.numbers.recycle.orchestrator.NumberRecycler; public class NumberRecyclerMain { /** * @param args */ private NumberRecycler reverser = new NumberRecycler(); public static void main(String[] args) { new NumberRecyclerMain().recycle(); } private void recycle(){ reverser.solveAndWriteToOutputFile(""C:/Documents and Settings/Administrator/My Documents/Code Jam/C-sample.in""); } } " B21246,"import java.io.*; import java.util.*; public class Problem3 { static int size = 4; public static void main(String args[]) { try { FileInputStream fstream = new FileInputStream(""C-large.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; int i = 0; int num1 = 0, num2 = 0; int times; Scanner sc; int count, total; while ((line = br.readLine()) != null) { if(i == 0) { total = Integer.parseInt(line); i = 1; continue; } sc = new Scanner(line); if(sc.hasNextInt()) num1 = sc.nextInt(); if(sc.hasNextInt()) num2 = sc.nextInt(); size = (num1==0)?1:(int)Math.log10(num1) + 1; times = solve(num1, num2); System.out.println(""Case #""+i+"": ""+times); write(""Case #""+i+"": ""+times); i++; } in.close(); }catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } public static int solve(int num1, int num2) { int i; int count = 0; int generated; for(i = num1; i <= num2; i++) { for(int j = 1; j < size; j++) { generated = generate(i, j); if(num1 <= i && i < generated && generated <= num2) { count++; } } } return count; } public static int generate(int i, int j) { int temp = i; int putfor = temp % (power(10, j)); int last = temp / (power(10, j)); int generated = putfor*power(10, size-1-(j-1)) + last; return generated; } public static int power(int i, int j) { int power = 1; for(int k = 0; k < j; k++) { power *= i; } return power; } public static void write(String text) { try { BufferedWriter bw = new BufferedWriter(new FileWriter(new File(""Problem3large.out""), true)); bw.write(text); bw.newLine(); bw.close(); }catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } }" B21431,"package jp.funnything.competition.util; import java.util.Comparator; import com.google.common.base.Objects; public class Pair< T1 , T2 > { public static < T1 extends Comparable< T1 > , T2 extends Comparable< T2 > > Comparator< Pair< T1 , T2 > > getFirstComarator() { return new Comparator< Pair< T1 , T2 > >() { @Override public int compare( final Pair< T1 , T2 > o1 , final Pair< T1 , T2 > o2 ) { final int c = o1.first.compareTo( o2.first ); return c != 0 ? c : o1.second.compareTo( o2.second ); } }; } public static < T1 extends Comparable< T1 > , T2 extends Comparable< T2 > > Comparator< Pair< T1 , T2 > > getSecondComarator() { return new Comparator< Pair< T1 , T2 > >() { @Override public int compare( final Pair< T1 , T2 > o1 , final Pair< T1 , T2 > o2 ) { final int c = o1.second.compareTo( o2.second ); return c != 0 ? c : o1.first.compareTo( o2.first ); } }; } public T1 first; public T2 second; public Pair( final Pair< T1 , T2 > that ) { this.first = that.first; this.second = that.second; } public Pair( final T1 first , final T2 second ) { this.first = first; this.second = second; } @Override public boolean equals( final Object obj ) { if ( this == obj ) { return true; } if ( obj == null || getClass() != obj.getClass() ) { return false; } final Pair< ? , ? > that = ( Pair< ? , ? > ) obj; return Objects.equal( this.first , that.first ) && Objects.equal( this.first , that.first ); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ( first == null ? 0 : first.hashCode() ); result = prime * result + ( second == null ? 0 : second.hashCode() ); return result; } @Override public String toString() { return ""Pair [first="" + first + "", second="" + second + ""]""; } } " B22058,"package qualification.recycled.numbers; public class RecycledPair { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RecycledPair other = (RecycledPair) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } private int n; private int m; public RecycledPair(int n, int m) { if (m > n) { int temp = n; n = m; m = temp; } this.n = n; this.m = m; } } " B20565,"import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.util.HashSet; import java.util.Set; public class main { /** * @param args */ @SuppressWarnings(""deprecation"") public static void main(String[] args) { long now = System.currentTimeMillis(); // TODO Auto-generated method stub File file = new File(""./input.txt""); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); int testCaseCount = Integer.parseInt(dis.readLine()), testCase; for(testCase = 0; testCase < testCaseCount; testCase ++) { String[] line = dis.readLine().split("" ""); int A = Integer.parseInt(line[0]), B = Integer.parseInt(line[1]), found = 0, n, m, k; String N, M; Set used = new HashSet(); for(n = A; n <= B; n ++) { N = n + """"; for(k = 1; k < N.length(); k ++) { M = N.substring(k, N.length()) + N.substring(0, k); M = M.replaceAll(""^0+"", """"); m = Integer.parseInt(M); if(m > n && m <= B && ! used.contains(N+M)) { found ++; used.add(N+M); } } } System.out.println(""Case #"" + (testCase + 1) + "": "" + found); } fis.close(); bis.close(); dis.close(); } catch(Exception e) { e.printStackTrace(); } } } " B21251,"import static java.lang.Double.parseDouble; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.exit; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; import java.util.Map.Entry; public class Recycled { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; static int nextInt() throws IOException { return parseInt(next()); } static long nextLong() throws IOException { return parseLong(next()); } static double nextDouble() throws IOException { return parseDouble(next()); } static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static String nextLine() throws IOException { return in.readLine(); } static char at(String s, int i) { return s.charAt(i); } public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(new FileInputStream(""C-large.in""))); out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(""C-large.out""))); // in = new BufferedReader(new InputStreamReader(System.in)); // out = new PrintWriter(new OutputStreamWriter(System.out)); int t = nextInt(); for (int i = 0; i < t; i ++) { solve(i+1, nextInt(), nextInt()); } in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } private static void solve(int id, int a, int b) throws IOException { HashMap map = new HashMap(); for (int i = a; i <= b; i ++) { String key = """" + i; map.put(key, new DJ()); } for (int i = a; i <= b; i ++) { String s = """" + i; String t = move(s); while (true) { if (t.charAt(0)!='0') { DJ dj1 = map.get(s); DJ dj2 = map.get(t); if (dj2 != null && dj1 != null) merge(dj1, dj2); } t = move(t); if (s.equals(t)) break; } } int res = 0; for (Entry e: map.entrySet()) { DJ dj = e.getValue(); if (dj.count > 1) { res += dj.count * (dj.count-1) / 2; } } out.println(""Case #""+id+"": "" + res); } static String move(String s) { if (s.length() == 1) return s; char c = s.charAt(s.length()-1); return """" + c + s.substring(0, s.length()-1); } static DJ merge(DJ d1, DJ d2) { DJ p1 = d1.getP(); DJ p2 = d2.getP(); if (p1 != p2) { if (p1.rank == p2.rank) { p2.parent = p1; p1.rank ++; p1.count += p2.count; return p1; } else if (p1.rank > p2.rank) { p2.parent = p1; p1.count += p2.count; return p1; } else { p1.parent = p2; p2.count += p1.count; return p2; } } else { return p1; } } static class DJ { DJ parent = null; int rank = 0; int count = 1; DJ getP() { if (parent == null) { return this; } DJ p = parent.getP(); this.parent = p; return p; } } } " B21141,"import java.util.*; public class RecycledNumbers extends Thread { private int bottom; private int top; private static int numCases; private static int caseIndex = 0; private static int lower[]; private static int upper[]; private long thisCount = 0; public static void main(String[] args) { int n = 1; long startTime = System.currentTimeMillis(); for (int i = 1; i < args.length; i++) { if(args[i - 1].equals(""-n"")) { try { n = Integer.parseInt(args[i]); } catch (Exception e) { } } } //System.out.println(n + "" threads will be used.\n""); //GATHER INPUT Scanner sc = new Scanner(System.in); numCases = sc.nextInt(); int currentCaseNum = 1; String[] outputBuffer = new String[numCases]; lower = new int[numCases]; upper = new int[numCases]; sc.nextLine(); for(int i = 0; i < numCases; i++) { lower[i] = sc.nextInt(); upper[i] = sc.nextInt(); } for(int m = 0; m < numCases; m++) { Thread[] threadArray = new Thread[n]; RecycledNumbers[] speedupArray = new RecycledNumbers[n]; int nextLower = lower[m]; int nextUpper = ((upper[m] - lower[m]) / n) + lower[m]; for (int j = 0; j < n; j++) { speedupArray[j] = new RecycledNumbers(nextLower, nextUpper); threadArray[j] = new Thread(speedupArray[j]); threadArray[j].start(); nextLower = nextUpper + 1; nextUpper = ((j + 2) * (upper[m] - lower[m]) / n) + lower[m]; } for (int k = 0; k < threadArray.length; k++) { try { threadArray[k].join(); } catch (InterruptedException e) {} } int totalCount = 0; for (int k = 0; k < threadArray.length; k++) { totalCount += speedupArray[k].thisCount; } System.out.println(""Case #"" + (m + 1) + "": "" + totalCount); //System.out.println(""""); } //System.out.println(""\nDONE! Execution time of "" + ((double)(System.currentTimeMillis() - startTime) / 1000) + "" seconds.""); } public RecycledNumbers(int rangeBottom, int rangeTop) { bottom = rangeBottom; top = rangeTop; //System.out.println(""This class instance will handle "" + bottom + "" to "" + top + "".""); } private long countDistinct(int lowerBound, int upperBound) { long count = 0; for(int i = lowerBound; i < upperBound; i++) { count += countUniquePermutations(i, upperBound); } return count; } private int countUniquePermutations(int subject, int topBound) { int count = 0; String intString = Integer.toString(subject); String tempNewString = """"; int tempNewInt = 0; int tempIntLength = 0; int[] distinctInt = new int[intString.length() - 1]; for(int j = 1; j < intString.length(); j++) { tempNewString = intString.substring(j, intString.length()) + intString.substring(0, j); tempNewInt = Integer.parseInt(tempNewString); tempIntLength = Integer.toString(tempNewInt).length(); if((intString.length() == tempIntLength) && (subject != tempNewInt) && (tempNewInt >= subject) && (tempNewInt <= topBound)) { distinctInt[j -1] = tempNewInt; } Set s = new HashSet(); for (int i : distinctInt) { if(i != 0) { s.add(i); } } count = s.size(); } return count; } public void run() { thisCount = countDistinct(bottom, top); } } " B21478,"package Television; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Television { public static int Max=0; public static int Min = 0; // public static List currentCandidate = new ArrayList(); public static String[] inputLines; public static int[] RESULTS; public static void main(String args[]) { try { readIo(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } solveProblemsFromLine(); try { saveOutputFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void readIo() throws Exception { DataInputStream in = new DataInputStream(new FileInputStream(""C-large.in""));//inp2.in BufferedReader br = new BufferedReader(new InputStreamReader(in)); int lineNum = Integer.parseInt(br.readLine()); inputLines = new String[lineNum]; RESULTS = new int[lineNum]; String strLine=null; int count=0; while ((strLine = br.readLine()) != null) { inputLines[count] = strLine; count++; } } public static void parse(String input) { String tokens[] = input.split("" ""); Min = Integer.parseInt(tokens[0]); Max = Integer.parseInt(tokens[1]); } public static void solveProblemsFromLine() { for(int inp=0; inp pPair=null; if((pPair=checkValid(integer)).size()!=0) result+=pPair.size(); // for(Pair childPair : pPair){ // if(currentCandidate.contains(childPair)) // { // System.out.println(""repeated value""); // continue; // }else // currentCandidate.add(childPair); // } // // } // int result = currentCandidate.size(); // if(result==288) // { // for(Pair pp:currentCandidate) // System.out.println(""(""+pp.a+"", ""+pp.b+"")""); } // currentCandidate.clear(); return result; } public static ArrayList checkValid(int data) throws Exception { String dataStr = Integer.toString(data); String left, result; String right; ArrayList resultPairs = new ArrayList(); for(int pos=1;posdata && nextInt<=Max && nextInt!=data && data>=Min) resultPairs.add(new Pair(data, nextInt)); } return resultPairs; } public static void saveOutputFile() throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter(""result.txt"")); for(int i=0; i str2list(String s) { ArrayList r = new ArrayList(); for (char c : s.toCharArray()) { r.add(c); } return r; } static String list2str(ArrayList cs) { StringBuilder builder = new StringBuilder(cs.size()); for (Character c : cs) builder.append(c); return builder.toString(); } static ArrayList cycles(String s) { ArrayList cs = str2list(s); ArrayList res = new ArrayList(); for (int i = 0; i < cs.size(); i++) { Collections.rotate(cs, 1); res.add(list2str(cs)); } HashSet hs = new HashSet(res); return new ArrayList(hs); } static void log(String fs, Object... args) { System.err.println(String.format(fs, args)); } public static void main(String[] args) throws FileNotFoundException { String filename = ""src/C-large.in""; Scanner sc = new Scanner( new FileInputStream( new File(filename))); PrintWriter pw = new PrintWriter( new FileOutputStream( new File(filename + "".result""))); int N = sc.nextInt(); for (int task = 1; task <= N; task++) { int A = sc.nextInt(); int B = sc.nextInt(); int cnt = 0; for (int i = A; i <= B; i++) { String s = Integer.toString(i); for (String r : cycles(s)) { int n = Integer.parseInt(r); if (n >= A && n <= B && r.charAt(0) != '0' && !r.equals(s)) { cnt++; } } } pw.println(String.format(""Case #%d: %d"", task, cnt / 2)); } pw.close(); } } " B20586,"package codejam; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.LinkedList; import java.util.Queue; public class RecycledNumbers { public static void main(String[] args) throws IOException { String fileName = ""C-large""; Queue queue = file(""input/""+fileName+"".in""); File outputFile = new File(""result/""+fileName+"".out""); if(!outputFile.exists()) outputFile.createNewFile(); FileOutputStream output = new FileOutputStream(outputFile); int TestCases = Integer.parseInt(queue.poll()); for(int i=0; i < TestCases; i++) { output.write((""Case #""+(i+1)+"": "").getBytes()); int[] input = parseLine(queue.poll()); int A = input[0]; int B = input[1]; int base = (int)Math.log10(A); int count = 0; if(base > 0) { int zeros = (int)Math.pow(10, base); for(int n=A; n <= B; n++) { int m = n; for(int k=0; k < base; k++) { m = m/10 + (m%10)*zeros; if(n < m && m <= B) count++; } } } output.write(Integer.toString(count).getBytes()); output.write('\n'); } } public static int recycleRoutine(int n, int m, int digits) { int count = 0; int base = (int)Math.pow(10, digits-1); for(int i=0; i < digits; i++) { n = n/10 + (n%10)*base; for(int j=0; j < digits; j++) { m = m/10 + (m%10)*base; if(m >= n) count++; } } return count; } public static int[] parseLine(String line) { String[] array = line.split(""\\s""); int[] result = new int[array.length]; for(int i=0; i < result.length; i++) result[i] = Integer.parseInt(array[i]); return result; } /* given a file name ... fetches the file from war folder */ public static byte[] getFile(String fileName) throws IOException { FileInputStream in = new FileInputStream(fileName); int size = in.available(); byte[] imageBytes = new byte[size]; /* read the whole image into array */ int read = 0; while(read < size) read += in.read(imageBytes, read, size-read); return imageBytes; } /* mimic php functions */ public static Queue file(String filename) throws IOException { byte[] fileBytes = getFile(filename); Queue queue = new LinkedList(); StringBuilder builder = new StringBuilder(); for(int i=0; i < fileBytes.length; i++) { if(fileBytes[i] == '\n') { queue.add(builder.toString()); builder.delete(0, builder.length()); continue; } if(fileBytes[i] == '\r') continue; builder.append((char)fileBytes[i]); } return queue; } } " B20125,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); int[][] ab = new int[T][2]; StringTokenizer st = null; for (int i=0; i= ab[i][0] && j1) count+=(possibility *(possibility-1)) / 2; } return count; } int countPossibility(int v, int A, int B, int rotates, int level, boolean[] dids) { int count = 1; dids[v-A] = true; for (int i=0; iB) continue; if (dids[v-A]) continue; dids[v-A] = true; count++; } return count; } }" B20769,"import java.util.Scanner; import java.util.Vector; public class ThreadDispatcher{ private static final int CORES = 8; private Vector threads = new Vector(CORES); Scanner scan = new Scanner(System.in); private int curCase = 0, T = 0; public ThreadDispatcher(){ System.out.println(""Paste input for qualification round - problem C""); T = Integer.parseInt(scan.nextLine()); for(int i = 1; i <= CORES; i++){ if(i <= T){ String line = scan.nextLine(); curCase++; String[] limitsStr = line.split(""\\s""); int A = Integer.parseInt(limitsStr[0]); int B = Integer.parseInt(limitsStr[1]); SolveThread st = new SolveThread(A, B, curCase,this); threads.add(st); st.run(); } } } public void finish(SolveThread thread){ System.out.println(""Case #"" + thread.casenb + "": "" + thread.pairs); threads.remove(thread); if(curCase < T){ String line = scan.nextLine(); curCase++; String[] limitsStr = line.split(""\\s""); int A = Integer.parseInt(limitsStr[0]); int B = Integer.parseInt(limitsStr[1]); SolveThread st = new SolveThread(A, B, curCase,this); threads.add(st); st.run(); } } public static void main(String[] args){ ThreadDispatcher td = new ThreadDispatcher(); } } " B21719,"import java.io.*; class ProbC { String calculate(int low,int up) { String ans=""""; int anscount=0; int l=low; int u=up; for(int i=l;i<=u;i++) { String num=Integer.toString(i); for(int j=1;j0) { int a=temp%10; temp=temp/10; uc++; } temp=low; while(temp>0) { int a=temp%10; temp=temp/10; lc++; } if(uc==lc) { System.out.println(""A and B have same number of digits""); String result=obj.calculate(low,up); String finalans=""Case #""+(i+1)+"": ""+result+System.getProperty(""line.separator""); dout.writeBytes(finalans); } else { System.out.println(""A and B do not have same number of digits""); } } } }" B20331,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class ProblemUtils { public static String[] readInput(String path) throws Exception { FileInputStream in = new FileInputStream(path); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); int nlines = Integer.parseInt(reader.readLine()); String[] lines = new String[nlines]; for (int i = 0; i < nlines; i++) { lines[i] = reader.readLine(); } return lines; } public static void writeOutput(String path, String[] lines) throws Exception { FileOutputStream out = new FileOutputStream(path); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out)); for (int i = 0; i < lines.length; i++) { writer.write(""Case #"" + (i + 1) + "": "" + lines[i]); if (i + 1 < lines.length) { writer.write(""\n""); } } writer.flush(); out.close(); } } " B20397,"import java.util.*; import java.io.*; public class RecycledNumbers { private static int numTest; private static Scanner input; private static PrintWriter output; public static void main(String[] args) throws FileNotFoundException, IOException { // Initialization of Input/Output streams input = new Scanner(new File(args[0])); output = new PrintWriter(new File(""output"")); // Reads char by char the input dimension numTest = input.nextInt(); input.nextLine(); // reads the \n character // Solves the problem for(int i = 1; i <= numTest; i++) { output.print(""Case #"" + i + "": ""); int a = input.nextInt(); int b = input.nextInt(); //System.err.println(i + "" A: "" + a); //System.err.println(i + "" B: "" + b); int numRecycled = 0; int n = a; int m = 0; while(n <= b) { String nString = n + """"; int nDigits = nString.length(); /* the HashMap prevents to count moore times couples like <1212, 2121> * generated using 2 ++ 121 or 121 ++ 2 */ HashMap map = new HashMap(); // extracts different substrings from the tail and count them for(int j = 1; j < nDigits; j++) { String head = nString.substring(0, j); String tail = nString.substring(j, nDigits); // System.err.print(i + "" n: "" + n); if(!tail.startsWith(""0"")) { m = Integer.parseInt(tail + head); // System.err.print("" m: "" + m); if(m > n && m <= b) { map.put(m, n); // System.err.print("" *""); } } // System.err.println(); } numRecycled += map.size(); n++; } output.println(numRecycled); if(input.hasNextLine()) input.nextLine(); } output.flush(); } }" B21409,"import java.io.*; import java.util.Set; import java.util.HashSet; public class recycled { public static int A,B; public static int[] t = {1,10,100,1000,10000,100000,1000000,10000000}; public static int solve(){ if(B<10) return 0; int DB=0,kit,m,n; int lg = 0; while(lg < 6 && A >= t[lg+1]) lg++; //System.out.println(A+"" ""+lg); for(n = A; n >> ""+n+"" - ""+m); if( n < m && m <= B && (n%t[kit])*10>=t[kit] && !H.contains(m)) { DB++; H.add(m); //System.out.println(""OK >>> ""+n+"" - ""+m+"" DB= ""+DB); } kit++; } } return DB; } public static void main (String args[]) throws IOException{ BufferedReader be = new BufferedReader(new FileReader(""C-large.in"")); int T = Integer.parseInt(be.readLine()); for(int i=1; i<=T; i++){ String s = be.readLine(); A = Integer.parseInt(s.split("" "")[0]); B = Integer.parseInt(s.split("" "")[1]); System.out.println(""Case #""+i+"": ""+solve()); } be.close(); } } " B20213,"package com.gcj.main; import java.util.ArrayList; import com.gcj.parser.Number; import com.gcj.parser.Parser; public class Main { public static void main(String[] args) { Parser parser = new Parser(""resource/InputData.txt""); ArrayList[] datas = parser.toArray(); int index = 1; for (ArrayList dataRow : datas){ int min = dataRow.get(0).intValue(); int max = dataRow.get(1).intValue(); StringBuffer stringBuf = new StringBuffer(""Case #"").append(index).append("": "").append(Number.nbOfRecycledInteger(min, max)); System.out.println(stringBuf.toString()); index ++; } } }" B20807,"import java.util.*; public class JuanjeProblemaC { public static void main(String[] args){ Scanner entrada = new Scanner(System.in); int tam = entrada.nextInt(); for(int problema = 1; problema <= tam;problema++) { int A = entrada.nextInt(); int B = entrada.nextInt(); int resultado = 0; for(int indice=A;indice<=B;indice++) { ArrayList pares = new ArrayList(); String ns = indice+""""; for (int j=ns.length()-1;j>0;j--) { String k = ns.substring(j); String nuevoVal = k + ns.substring(0,j); int m = Integer.parseInt(nuevoVal); if (m>indice && A=m) { if (pares.indexOf(m)==-1) pares.add(m); } } int tamPares = pares.size(); resultado += tamPares; } System.out.format(""Case #%d: %d\n"", problema, resultado); } } }" B21250,"import java.util.*; import java.io.*; import java.text.*; public class Q { private static long solve(int from, int to) { int[] flag = new int[2000001]; long res = 0; int t=from/10, b = 1; while (t>0) { b*=10;t/=10; } for (int i = from; i < to; ++i) { t = i; do { t = (t /10) + (t%10 * b); if (t > i && t<= to && flag[t] != i + 1) { flag[t] = i + 1; ++res; } } while (t != i); } return res; } public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File(""input.txt"")); PrintStream out = new PrintStream(""output.txt""); int num = in.nextInt(); in.nextLine(); for (int i=0;i used = new HashSet(); for(int n = a; n < b; n++) { used.clear(); String ns = Integer.toString(n); for(int split = 1; split < ns.length(); split++) { String ms = ns.substring(split) + ns.substring(0, split); if (ms.startsWith(""0"")) continue; if (used.contains(ms)) continue; int m = Integer.parseInt(ms); if (m > n && m <= b) { used.add(ms); count++; } } } System.out.println(count); } public static void main(String[] args) { RecycledNumbers rn = new RecycledNumbers(); try { rn.solveCases(); } catch (Exception e) { e.printStackTrace(); } } } " B20017,"import java.util.ArrayList; public class SpeakingInToungues { private static String inputFile = ""C:\\PERSONAL-WORKSPACE\\GCJ-2012\\src\\input-output\\Input.txt""; private static String outputFile = ""C:\\PERSONAL-WORKSPACE\\GCJ-2012\\src\\input-output\\Output.txt""; public static void main(String[] args) { InputReader ir = new InputReader(inputFile); OutputWriter ow = new OutputWriter(outputFile); ArrayList lines = ir.loadLines(); //Given examples cover 25 chars and the one left out is q which is ideally mapped to the unused char z. String normalText = ""aozq our language is impossible to understand there are twenty six factorial possibilities so it is okay if you want to just give up""; String googlereseText = ""yeqz ejp mysljylc kd kxveddknmc re jsicpdrysi rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd de kr kd eoya kw aej tysr re ujdr lkgc jv""; StringBuffer sb = null; for(int i=1;i r = new HashSet(); while(base < b) { base *= 10; int d = c/base; int e = c%base; int f = Integer.valueOf(e+""""+d); int flen = (f+"""").length(); if(f != c && f >= a && f <= b && clen == flen) { r.add(f); } } return r.size(); } public static void main(String args[]) { Scanner input = new Scanner(System.in); int test = input.nextInt(); for(int i = 1; i <= test; ++i) { int a = input.nextInt(), b = input.nextInt(); System.out.println(""Case #"" + i + "": "" + solve(a, b)); } } } " B20056,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class RecycledNumbers { public RecycledNumbers() { // System.out.println(getBits(1123242)); BufferedReader in = null; PrintWriter out = null; try { in = new BufferedReader(new FileReader(""small.in"")); out = new PrintWriter(new FileWriter(""small.out"")); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { int T = Integer.parseInt(in.readLine()); int result = 0; for (int group = 0; group < T; group++) { System.out.println(""-------------"" + group + ""-----------""); String line = in.readLine(); StringTokenizer st = new StringTokenizer(line); long A = Long.parseLong(st.nextToken()); long B = Long.parseLong(st.nextToken()); result = getPairs(A, B); // System.out.println(Long.MIN_VALUE); int inn = group + 1; String target = ""Case #"" + inn + "": "" + result; out.println(target); } } catch (NumberFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.close(); } private int getPairs(long A, long B) { // TODO Auto-generated method stub int result = 0; long n; int temp; for (long i = A; i < B; i++) { n = i; temp = hasRecycle(n, B); result = result + temp; } return result; } private int hasRecycle(long nn, long B) { // TODO Auto-generated method stub // m>n; // same length; // distinct. String m; String n = nn + """"; long mm; int mP; int nP; int result = 0; long[] cmm = new long[7]; int cmmMAX = 0; for (int i = 1; i < n.length(); i++) { m = shift(n, i); mm = Long.parseLong(m); mP = getBits(mm); nP = getBits(nn); // System.out.println(nn + "","" + mm); if (mP == nP && nn < mm && mm <= B) { if (notInclude(cmm, cmmMAX, mm)) { // System.out.println(nn + "","" + mm); cmm[cmmMAX++] = mm; result++; } } } return result; } private boolean notInclude(long[] cmm, int cmmMAX, long mm) { // TODO Auto-generated method stub for (int i = 0; i < cmmMAX; i++) { if (cmm[i] == mm) return false; } return true; } private int getBits(long mm) { // TODO Auto-generated method stub int result = 1; while (mm / 10 > 0) { result++; mm = mm / 10; } return result; } private String shift(String n, int i) { // TODO Auto-generated method stub return n.substring(i) + n.substring(0, i); } public static void main(String args[]) { new RecycledNumbers(); } } " B21262,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class Recycled { public static boolean isRecycled(int a, int b) { String left = a+""""; String right = b+""""; return (left+left).contains(right); // if(left.length()!=right.length()) return false; // int l = left.length(); // for(int i=0;i recycles(int in) { String s = in+""""; int l = s.length(); Set out = new HashSet(); for(int i=1;i> map = new HashMap>(); Set pairs = new HashSet(); public C() { for (int i=1; i<=2000000; i++) { char ch[] = (""""+i).toCharArray(); Arrays.sort(ch); String key = new String (ch); Set val = map.containsKey(key)?map.get(key): new HashSet(); val.add(i); map.put(key, val); } System.out.println(""Done..\n""); compute(1,2000000); } boolean rot (int a, int b) { String A = """"+a; String B = """"+b; for (int i=1; i stopList = new HashSet(); for (int i=A; i<=B; i++) { char ch[] = (""""+i).toCharArray(); Arrays.sort(ch); String key = new String (ch); if (stopList.contains(key)) continue; Object values[] = map.get(key).toArray(); for (int j=0; j=A && valJ<=B) { for (int k=j+1; k=A && valK<=B) { if (rot(valJ, valK)) { total++; //System.out.println(valJ+"", ""+valK); int pair[] = new int[2]; pair[0] = Math.min(valJ, valK); pair[1] = Math.max(valJ, valK); pairs.add(pair); } } } } } stopList.add(key); } System.out.println(""Pairs: ""+pairs.size()); return total; } /*int answer (int A, int B) { int total = 0; HashSet stopList = new HashSet(); for (int i=A; i<=B; i++) { char ch[] = (""""+i).toCharArray(); Arrays.sort(ch); String key = new String (ch); if (stopList.contains(key)) continue; Object values[] = map.get(key).toArray(); for (int j=0; j=A && valJ<=B) { for (int k=j+1; k=A && valK<=B) { if (rot(valJ, valK)) { total++; //System.out.println(valJ+"", ""+valK); } } } } } stopList.add(key); } return total; }*/ int answer (int A, int B) { int count=0; for (int[]pair: pairs) { if (pair[0]>=A && pair[1]<=B) count++; } return count; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); C c = new C(); //System.out.println(c.rot(12345, 45123)); int T = sc.nextInt(); for (int i=0; i 0) { NumOfDigints++; tempNum /= 10; } do { shifted = shiftNumber(shifted,NumOfDigints); if ((shifted > i)&& (shifted<=B)) { numberOfRecycledNumbers++; } }while(shifted != i); } return numberOfRecycledNumbers; } public static void calcFromFile(String fileName) { File file = new File(fileName); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String sentence = null; // repeat until all lines is read int numOfLine = 1; C q3 = new C(); sentence = reader.readLine(); //Read the n test cases while ((sentence = reader.readLine()) != null) { System.out.println(""Case #"" + numOfLine++ + "": ""+q3.solveLine(sentence)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } } } " B20600,"import java.util.*; import static java.lang.System.*; class C{ static public void main(String[] args){ Scanner sc = new Scanner(System.in); int cases = Integer.parseInt(sc.nextLine()); for(int c = 1; c<=cases; c++){ String[] s = sc.nextLine().split("" ""); int a = Integer.parseInt(s[0]); int b = Integer.parseInt(s[1]); int l = s[0].length(); long cnt = 0; for(int i = a; i set = new HashSet(); for(int pos = 1; posi && newn<=b){ set.add(newn); } } cnt+=set.size(); } out.println(""Case #""+c+"": ""+cnt); } } }" B20821,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.HashSet; import java.io.FileWriter; public class RecyclingNumbers { public static void main(String... args) { RecyclingNumbers obj = new RecyclingNumbers(); obj.run(); } public void run() { try { File f = new File(""C-large.in""); File outFile = new File(""output.txt""); FileWriter w = new FileWriter(outFile); Scanner s = new Scanner(f); int T = s.nextInt(); s.nextLine(); for(int i = 1; i<= T; i++) { int lower = s.nextInt(); int upper = s.nextInt(); int maxRecycled = findRecycled(lower, upper); String str = ""Case #"" + i +"": "" + maxRecycled + '\n'; w.write(str); if(s.hasNextLine()) s.nextLine(); } w.close(); } catch(Exception e) { System.out.println(e.toString()); } } private int findRecycled(int lower, int upper) { int recycled = 0; HashSet set = new HashSet(); for(int n = lower; n <= upper; n++) { String current = (new Integer(n)).toString(); for(int r = 0; r < current.length(); r++) { String check = current.substring(1) + current.charAt(0); int m = Integer.parseInt(check); if( lower <= n) { if(n < m) { if( m <= upper) { set.add(new Pair(n,m)); } } } current = check; } } return set.size(); } private class Pair { public int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } public boolean equals(Object obj) { if(this == obj) return true; if((obj == null) || (obj.getClass() != this.getClass())) return false; Pair p = (Pair)obj; return x == p.x && y == p.y; } public int hashCode() { int hash = 7; hash = 31 * hash + x; hash = 31 * hash + y; return hash; } } } " B21471,"import java.util.Scanner; class Recycle{ static Scanner sc = new Scanner(System.in); static long[] pow={1,10,100,1000,10000,100000,1000000,10000000}; public static void solve() { long A =sc.nextInt(); long B =sc.nextInt(); long sum=0; long j; String si,sj,sk; int tj,k; Boolean t2,t=false; int d,z='0'; for(long i=A;i<=B;i++) {if(i>9){ // t=(i%10==0); // j=(i/10)+(i%10)*pow[(int)Math.round(Math.floor(Math.log(i)/Math.log(10)))]; si=""""+i; // tj=(int)(j%10); // d=z+tj; sj=si; sk=""""; sk=sk+sj.charAt(sj.length()-1); for(k=1;ki && j<=B && j>=A && sk.charAt(0)!=0 && si.charAt(0)!=0) sum++; sj=sk; sk=""""; sk=sk+sj.charAt(sj.length()-1); for(k=1;k 0; i--) { front = n / split[i]; back = n % split[i]; if (back < split[i-1]) { // ignore case with leading zero(s) in ""back"" part //System.err.printf(""Leading zero at position %d in number %d\n"", i, n); continue; } m = back * split[size - i] + front; if (m > n && m <= b) { c.increment(n, m); } } } } // write output writeFile(cases, ""C-large.out""); print(""Complete!""); } public static void printf(String format, Object... args) { System.out.printf(format, args); } public static void print(Object o) { System.out.println(o); } public static void writeFile(CaseC[] result, String out) { PrintWriter writer = null; try { writer = new PrintWriter(out); for (int i = 0; i < result.length; i++) { writer.printf(""Case #%d: %s\n"", i+1, result[i]); } writer.flush(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } } public static CaseC[] read(String file) { BufferedReader reader = null; CaseC[] cases = null; try { reader = new BufferedReader(new FileReader(file)); // get test case count int caseCount = Integer.parseInt(reader.readLine()); cases = new CaseC[caseCount]; for (int i = 0; i < cases.length; i++) { String[] paramStr = reader.readLine().split("" ""); cases[i] = new CaseC(Integer.parseInt(paramStr[0]), Integer.parseInt(paramStr[1])); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return cases; } } class CaseC { private int a; private int b; private int size; //private int count; private HashSet set; public CaseC(int a, int b) { this.a = a; this.b = b; this.size = String.valueOf(b).length(); this.set = new HashSet(); //System.out.printf(""A=%d, B=%d, Size=%d\n"", a, b, size); } public int getA() { return a; } public int getB() { return b; } public int getSize() { return size; } public void increment(int n, int m) { String s = n + "":"" + m; if (set.contains(s)) { //System.err.println(""Duplicated entry: "" + s); } else { set.add(s); //count++; } } public int getCount() { //return count; return set.size(); } @Override public String toString() { return """" + set.size(); } }" B21098,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj_c; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author kay */ public class Arrange { private int first; private int last; private BufferedReader reader; private StringTokenizer token; public void do_processing(String filename) { String current_line; int no_of_cases; try { reader = new BufferedReader(new FileReader(filename)); FileWriter fstream = new FileWriter(""G:/cl_out.txt""); BufferedWriter out = new BufferedWriter(fstream); no_of_cases = Integer.parseInt(reader.readLine()); for (int i = 1; i <= no_of_cases; i++) { current_line = reader.readLine(); out.write(""Case #"" + i + "": ""); out.write(String.valueOf(do_arrange(current_line))); //out.write(String.valueOf(3)); //System.out.println(""outputttttttttttttttt "" + do_arrange(current_line)); out.newLine(); //Close the output stream } out.close(); reader.close(); } catch (Exception ex) { Logger.getLogger(Arrange.class.getName()).log(Level.SEVERE, null, ex); } } public int do_arrange(String line) { int output = 0, temp,temp2, tens = 1, no_of_digits = 0, new_num = 0, mod = 1, add_tens = 1; token = new StringTokenizer(line); first = Integer.parseInt(token.nextToken()); last = Integer.parseInt(token.nextToken()); System.out.println(first + """" +last); temp = first; while (temp > 0) { temp /= 10; no_of_digits++; } if (no_of_digits == 1) { output = 0; } else { for (int i = first; i <= last; i++){ temp = i; tens = 1; add_tens = 1; for (int j = 1; j < no_of_digits; j++){ add_tens = 1; temp = i; temp2 = i; temp2 /= (tens * 10); temp %= (tens * 10); //System.out.println(temp); for (int k=1; k<=(no_of_digits - j); k++){ add_tens *= 10; } //System.out.println(""add tens"" + add_tens); tens *=10; new_num = (temp * add_tens) + temp2; //System.out.println(""newwwwwwwww "" + new_num); //System.out.println(""iiiiiiii ""+ i); if((new_num >= first) && (new_num > i) && (new_num <= last)){ //System.out.println(""adddedd outtput""); output++; } } } } System.out.println(""output "" + output); return output; } } " B21362,"import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Scanner; import java.util.Set; import java.util.regex.Pattern; public class ProblemC { public static void main(String[] args) { Scanner input; try { input = new Scanner(new FileReader(""C-large.in"")); PrintWriter output = new PrintWriter(new FileWriter(""output3.txt"")); int numberCases = input.nextInt(); String data = input.nextLine(); for (int i = 0; i < numberCases; i++) { output.print(""Case #"" + (i + 1) + "": ""); data = input.nextLine(); String[] intS = Pattern.compile("" "").split(data); int[] numbers = new int[intS.length]; for (int j = 0; j < intS.length; j++) { numbers[j] = Integer.parseInt(intS[j]); } int lowerBound = numbers[0]; int upperBound = numbers[1]; output.print(calculatePossibilities(lowerBound, upperBound)); output.print(""\n""); } output.flush(); output.close(); input.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static int calculatePossibilities(int lowerBound, int upperBound) { //Set allPossibilities = new HashSet(); int numberDigits = (int) (Math.floor(Math.log10(lowerBound))) + 1; int currentNumber = 0; int lowPart = 0; int counter = 0; int highPart = 0; //System.out.println(""Digits "" + numberDigits); for (int j = lowerBound; j <= upperBound; j++) { Set permutations = new HashSet(); for (int i = 1; i <= numberDigits - 1; i++) { lowPart = j % ((int) Math.pow(10, i)); highPart = j / ((int) Math.pow(10, i)); currentNumber = (lowPart * (int) Math.pow(10, numberDigits - i)) + highPart; //System.out.println(currentNumber + "" <- j: "" + j + "" i:"" + i + "" low "" + lowPart + "" high "" + highPart); if (currentNumber >= lowerBound && currentNumber <= upperBound && currentNumber > j) { permutations.add(currentNumber); } //if (!permutations.isEmpty()) //allPossibilities.add(permutations); } counter = counter + permutations.size(); } //System.out.println(""A: "" + allPossibilities.size()); return counter; } } " B21123,"import java.io.BufferedReader; import java.io.File; import java.util.HashMap; import java.util.StringTokenizer; import java.io.FileReader; public class C { /** * @param args */ public static void main(String[] args) throws Exception { BufferedReader reader = null; String fileName = ""C-large.in""; String outputFileName=fileName.replace("".in"", "".out""); reader=new BufferedReader(new FileReader(fileName)); File outFile=new File(outputFileName); outFile.createNewFile(); int T = Integer.parseInt(reader.readLine()); for (int i = 1; i <=T; i++) { StringTokenizer t=new StringTokenizer(reader.readLine(),"" ""); int start=Integer.parseInt(t.nextToken()); int end=Integer.parseInt(t.nextToken()); int count=0; HashMap map=new HashMap(); for(int j=start;j=start && num>j){ String key=j+""_""+num; if(map.get(key)==null){ map.put(key, key); count++; } } } } System.out.println(""Case #""+i+"": ""+count); } } } " B22129,"package round1; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { public static SetfindRecycledNumbersBetween(int number, int start, int end) { if (number < 12) { return new HashSet(); } String num = """" + number; Set nums = new HashSet(); for (int i = 1; i < num.length(); i++) { String firstPart = num.substring(0, i); String lastPart = num.substring(i); if (lastPart.charAt(0) == '0') { continue; } int candidate = Integer.parseInt(lastPart + firstPart); if (candidate > number && (candidate >= start && candidate <= end)) { nums.add(candidate); } } return nums; } public static int findRecycledNumbersBetween(int start, int end) { int numbers = 0; for (int i = start; i <= end; i++) { Collection recycles = findRecycledNumbersBetween(i, start, end); if (recycles.size() > 0) { //System.out.printf(""found following recycles for %d => %s\n"", i, recycles.toString()); } numbers += recycles.size(); } return numbers; } public static void findRecycledNumbersInFile(File input) throws IOException { InputStreamReader reader = new InputStreamReader(new FileInputStream(input)); BufferedReader br = new BufferedReader(reader); int numLines = Integer.parseInt(br.readLine()); for (int i = 1; i <= numLines; i++) { String line = br.readLine(); String[] parts = line.split("" ""); int start = Integer.parseInt(parts[0]); int end = Integer.parseInt(parts[1]); System.out.printf(""Case #%d: %d\n"", i, findRecycledNumbersBetween(start, end)); } } /** * @param args */ public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println(""Usage: RecycledNumbers ""); System.exit(-1); } findRecycledNumbersInFile(new File(args[0])); } }" B21089,"package codejam.recycled; import codejam.is.TestRunner; /** * Created with IntelliJ IDEA. * User: ofer * Date: 4/14/12 * Time: 2:40 AM * To change this template use File | Settings | File Templates. */ public class Main { private static final String path = ""C:\\Users\\his\\Desktop\\codejam\\files\\""; private static final String filePrefix = ""C-small-attempt1""; private static final String inputFile = path + filePrefix + "".in""; private static final String outputFile = path + filePrefix + "".out""; public static void main(String[] args){ TestRunner testRunner = new TestRunner(); testRunner.runTests(inputFile, outputFile, RecycledTest.class); } } " B22031,"import static java.lang.Math.*; import static java.util.Arrays.*; import java.io.*; import java.util.*; public class C { Scanner sc = new Scanner(System.in); int A, B; void read() { A = sc.nextInt(); B = sc.nextInt(); } void solve() { long res = 0; for (int i = A; i <= B; i++) { int t = i; int X = 1; while (X * 10 <= i) X *= 10; do { t = t % 10 * X + t / 10; if (i < t && t <= B) res++; } while (t != i); } System.out.println(res); } void run() { int caseN = sc.nextInt(); for (int caseID = 1; caseID <= caseN; caseID++) { read(); System.out.printf(""Case #%d: "", caseID); solve(); System.out.flush(); } } void debug(Object...os) { System.err.println(deepToString(os)); } public static void main(String[] args) { try { System.setIn(new BufferedInputStream(new FileInputStream(args.length > 0 ? args[0] : (C.class.getName() + "".in"")))); } catch (Exception e) { } new C().run(); } } " B21540,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers{ public static void main(String[] args) throws IOException { BufferedReader br = null; try { br = new BufferedReader(new FileReader(""C-large.in"")); PrintStream out = new PrintStream(new File(""C-Large.out"")); int testcases = Integer.parseInt(br.readLine()); for (int casenr = 1; casenr <= testcases; casenr++) { String line = br.readLine(); Scanner scanner= new Scanner(line); int min = scanner.nextInt(); int max = scanner.nextInt(); HashSet recycledPairs = new HashSet (); for (int i = min ;i<= max ;i++){ String numberString = String.valueOf(i); int strLen = numberString.length(); if (strLen <= 1) continue; for (int j = 0 ;j< strLen;j++){ char firstChar= numberString.charAt(0); numberString = numberString.substring(1).concat(String.valueOf(firstChar)); int newNumber= Integer.parseInt(numberString); if ( (newNumber > i) && newNumber >= min && newNumber <= max ){ String pair = String.valueOf(i)+"",""+String.valueOf(newNumber); recycledPairs.add(pair); } } } System.out.printf(""Case #%d: %d\n"", casenr, recycledPairs.size()); out.printf(""Case #%d: %s\n"", casenr, recycledPairs.size()); } } catch(FileNotFoundException fe) { fe.printStackTrace(); } catch(IOException ie) { ie.printStackTrace(); } finally { try { if(br != null) { br.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } } " B20400,"package gcj; import java.util.*; import java.io.*; public class RecycledNumbers { final static String PROBLEM_NAME = ""rnum""; final static String WORK_DIR = ""D:\\Gcj\\"" + PROBLEM_NAME + ""\\""; void solve(Scanner sc, PrintWriter pw) { int A = sc.nextInt(); int B = sc.nextInt(); int res = 0; for (int n=A; n <= B; n++) { String s = """" + n; Set cand = new HashSet(); for (int st=1; st < s.length(); st++) { String ss = s.substring(st) + s.substring(0, st); int m = Integer.parseInt(ss); if (n < m && m >= A && m <= B) cand.add(m); } res += cand.size(); } pw.println(res); } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new FileReader(WORK_DIR + ""input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(WORK_DIR + ""output.txt"")); int caseCnt = sc.nextInt(); for (int caseNum=0; caseNum> values) { StringBuilder result = new StringBuilder(); int numberOfLine = 1; for (List line : values) { int minValue = Integer.parseInt(line.get(0)); int maxValue = Integer.parseInt(line.get(1)); int numberOfRecycledNumbers = getNumberOfRecycledNumbers(minValue, maxValue); result.append(""Case #"" + numberOfLine + "": "" + numberOfRecycledNumbers + ""\n""); numberOfLine++; } return result.toString(); } private static int getNumberOfRecycledNumbers(int minValue, int maxValue) { int numberOfRececlyedNumbers = 0; for (int numberToTest = minValue; numberToTest < maxValue; numberToTest++) { numberOfRececlyedNumbers += hasRecycledNumber(numberToTest, maxValue); } return numberOfRececlyedNumbers; } private static int hasRecycledNumber(int number, int maxValue) { String originalNumber = String.valueOf(number); int numberOfRecycledNumber = 0; List alreadyRecycled = new ArrayList(); for (int i = originalNumber.length() - 1; i > 0; i--) { String recycledNumber = getSwapedNumber(i, originalNumber); if (recycledNumber.charAt(0) != '0') { int valueRecycledNumber = Integer.parseInt(recycledNumber); if (valueRecycledNumber > number && valueRecycledNumber <= maxValue && !alreadyRecycled.contains(recycledNumber)) { numberOfRecycledNumber++; alreadyRecycled.add(recycledNumber); } } } return numberOfRecycledNumber; } public static String getSwapedNumber(int startIndex, String original) { StringBuilder swaped = new StringBuilder(); swaped.append(original.substring(startIndex)); swaped.append(original.substring(0, startIndex)); return swaped.toString(); } } " B21440,"package jp.funnything.competition.util; import java.util.Iterator; /** * Do NOT change the element in iteration */ public class Combination implements Iterable< int[] > , Iterator< int[] > { private final int _n; private final int _k; private int[] _data; public Combination( final int n , final int k ) { if ( k < 0 || k > n ) { throw new IllegalArgumentException(); } _n = n; _k = k; } @Override public boolean hasNext() { return _data == null || _data.length > 0 && _data[ 0 ] < _n - _k; } @Override public Iterator< int[] > iterator() { return this; } @Override public int[] next() { if ( _data == null ) { _data = new int[ _k ]; for ( int index = 0 ; index < _k ; index++ ) { _data[ index ] = index; } } else { int i = 0; while ( i < _k - 1 && _data[ i + 1 ] == _data[ i ] + 1 ) { _data[ i ] = i++; } _data[ i ]++; } return _data; } @Override public void remove() { } } " B20273," import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; /** * @author Addy */ public final class CodeJamIO { private static final String input = "".in""; private static final String output = "".out""; //input private final Scanner sc; private final PrintStream ps; private int index; private final int size; //data private int min; private int max; public CodeJamIO(String file) { Scanner tussensc = null; PrintStream tussenps = null; try { tussensc = new Scanner(new File(file + input)); tussenps = new PrintStream(new File(file + output)); } catch(FileNotFoundException ex) { ex.printStackTrace(System.err); System.exit(1); } sc = tussensc; ps = tussenps; index = 0; size = sc.nextInt(); //init init(); next(); } public void print(String solution) { ps.println(""Case #"" + index + "": "" + solution); } public boolean hasMore() { return index < size; } public void close() { sc.close(); ps.close(); } public void init() { } public void next() { min = sc.nextInt(); max = sc.nextInt(); index++; } public void solve() { //calc int opl = 0; int tien2 = 10; while(tien2 <= min) tien2 *= 10; HashSet set = new HashSet<>(); for(int n = min; n < max; n++) { set.clear(); int tien = 10; while(tien < n) { final int deel = n / tien; final int rest = n % tien; int m = (rest * tien2 / tien) + deel; if(n < m && m <= max) { if(!set.contains(m)) { set.add(m); opl++; } } tien *= 10; } } //print print(Integer.toString(opl)); } public static void main(String[] args) { CodeJamIO cd = new CodeJamIO(""C-large""); cd.solve(); while(cd.hasMore()) { cd.next(); cd.solve(); } cd.close(); } } " B21009,"import java.io.FileInputStream; import java.util.HashSet; public class Jam3 { public static String recycled(int start, int end){ int cnt = 0; HashSet seenit = new HashSet(); for(int i=start; i <= end; i++){ String x = """"+i; cnt += permutationsInRange(i, start , end, seenit); } return """"+cnt; } public static String rev(String in){ //p(""in: "" + in); StringBuffer sb = new StringBuffer(); for(int i=in.length()-1; i>=0; i--){ sb.append(in.charAt(i)); } String out = sb.toString(); //p(""o: "" + out); return out; } public static String solveLine(String in){ String[] s = in.split("" ""); int start = Integer.parseInt(s[0]); int end = Integer.parseInt(s[1]); //System.out.println(totals); return recycled(start, end); } public static void solveStrings(String[] input) { for(int i=1; i seenit) { int count = 0; p(""in: "" + in + "" min_s "" + min + "" "" + max); String in_s = """"+in; StringBuffer sb = new StringBuffer(in_s); String rev = rev(sb.toString()); for(int i=0; i =min && test<=max){ p(""match: "" + test + "" in: "" + in); seenit.add(low + ""_"" + hi); count++; } } return count; } public static String[] getLines(String fileName) { String[] lines = null; try { FileInputStream fis = new FileInputStream(fileName); int nxtchar = 0; StringBuffer sb = new StringBuffer(); while((nxtchar=fis.read())!=-1){ sb.append((char)nxtchar); } lines = sb.toString().split(""\r\n|\n""); } catch (Exception e) { e.printStackTrace(); } return lines; } public static void main(String[] args) { solveStrings(getLines(args[0])); } public static void p(Object a){ //System.out.println(""""+a); } public static void p2(Object a){ System.out.println(""""+a); } } " B20702,"package org.moriraaca.codejam; public interface TestCase { } " B21724,"package qualifier; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class TC { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); try { File file = new File(""src/qualifier/C-large.in""); String a = file.getAbsolutePath(); in = new Scanner(file); out = new PrintWriter(new File(""src/qualifier/C-large.out"")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } TC worker = new TC(); int n = in.nextInt(); for (int i=1; i<=n; i++) { out.println(""Case #"" + i + "": "" + worker.nums(in.nextInt(), in.nextInt(), out)); } out.flush(); } public int nums(int a,int b, PrintWriter out) { int sum = 0; int i = a; int order = 0; while (i>0) { i=i/10; order++; } for (i=a; i s = new HashSet(); for (int j=1; ji && tr<=b && !s.contains(tr)) { sum++; s.add(tr); } } } return sum; } } " B22027,"package qual2012; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class Kattio extends PrintWriter { public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } private BufferedReader r; private String line; private StringTokenizer st; private String token; private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } }" B20211,"package com.gcj.parser; import java.util.ArrayList; import java.util.List; public class Number { private static List getRecylcedCombining(int value){ List toReturn = new ArrayList(); Integer intValue = new Integer(value); String strValue = intValue.toString(); for (int i = 1; i < strValue.length() ; i ++) { Integer newValue = new Integer(strValue.substring(i, strValue.length()) + strValue.substring(0, i)); if (newValue.intValue() > value && !toReturn.contains(newValue)){ toReturn.add(newValue); } } return toReturn; } public static int nbOfRecycledInteger(int min, int max){ int toReturn = 0; // boolean[] alreadyDone = new boolean[10000000]; for (int i = min ; i <= max ; i++){ List list = getRecylcedCombining(i); for (Integer number : list){ int intNumber = number.intValue(); if (intNumber >= min && intNumber <= max ){//&& !alreadyDone[intNumber]){ toReturn++; // alreadyDone[intNumber]=true; } } } return toReturn; } public static void main(String[] args) { System.out.println(nbOfRecycledInteger(1111, 2222)); } } " B20071,"package codeJam2012_Qualification; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import java.util.NavigableMap; import java.util.Scanner; import java.util.TreeMap; public class RecycledNumbers { private String FILE_NAME = ""2012_QC_numbers_C-large""; private TreeMap numbers; private int maxNum = 2000000; private TreeMap getNumbers() { if (numbers == null) { String value; long newNum; numbers = new TreeMap(); for (int i=10;i<=maxNum;i++) { value = String.valueOf(i); for (int pos=0;pos recycles = getNumbers().subMap(lowest, true, highest, true); for (Map.Entry recycle : recycles.entrySet()) { if (recycle.getValue() ms = new HashSet(); for (int i = 1; i < n; i++) { int d = cstr[i]-0x30; if (d == 0) continue; if (d >= first) { String teststr = str.substring(i) + str.substring(0, i); if (ms.contains(teststr)) { continue; } ms.add(teststr); int test = Integer.parseInt(teststr); if (test <= B && test > cand) { //System.out.println(str + "", "" + teststr + "", "" + A + "", "" + B); c++; } } } } System.out.println(""Case #"" + k + "": "" + c); } } } " B20159,"import java.util.HashSet; import java.util.Set; public class Problem3 { private static int getRecycledNumbersCount(int min, int max) { int numberOfDigits = getNumberOfDigits(min, max); int prefix; int suffix; int finalNumber; Set pairs = new HashSet(); for (int i = min ; i < max; i++) { for (int j = 1; j sourceNumber && finalNumber <=max; } public static void main(String[] args) { System.out.println(getRecycledNumbersCount(10,99)); System.out.println(getRecycledNumbersCount(162,939)); System.out.println(getRecycledNumbersCount(112,989)); System.out.println(getRecycledNumbersCount(100,100)); System.out.println(getRecycledNumbersCount(182,983)); System.out.println(getRecycledNumbersCount(129,963)); System.out.println(getRecycledNumbersCount(167,943)); System.out.println(getRecycledNumbersCount(158,947)); System.out.println(getRecycledNumbersCount(105,992)); System.out.println(getRecycledNumbersCount(123,941)); System.out.println(getRecycledNumbersCount(104,994)); System.out.println(getRecycledNumbersCount(364,749)); System.out.println(getRecycledNumbersCount(152,946)); System.out.println(getRecycledNumbersCount(135,927)); System.out.println(getRecycledNumbersCount(100,999)); System.out.println(getRecycledNumbersCount(142,993)); System.out.println(getRecycledNumbersCount(177,921)); System.out.println(getRecycledNumbersCount(103,966)); System.out.println(getRecycledNumbersCount(122,996)); System.out.println(getRecycledNumbersCount(120,976)); System.out.println(getRecycledNumbersCount(271,271)); System.out.println(getRecycledNumbersCount(101,921)); System.out.println(getRecycledNumbersCount(115,976)); System.out.println(getRecycledNumbersCount(137,959)); System.out.println(getRecycledNumbersCount(139,915)); System.out.println(getRecycledNumbersCount(1,2)); System.out.println(getRecycledNumbersCount(49,83)); System.out.println(getRecycledNumbersCount(114,962)); System.out.println(getRecycledNumbersCount(37,53)); System.out.println(getRecycledNumbersCount(114,982)); System.out.println(getRecycledNumbersCount(158,931)); System.out.println(getRecycledNumbersCount(314,801)); System.out.println(getRecycledNumbersCount(140,989)); System.out.println(getRecycledNumbersCount(172,958)); System.out.println(getRecycledNumbersCount(393,646)); System.out.println(getRecycledNumbersCount(112,986)); System.out.println(getRecycledNumbersCount(136,912)); System.out.println(getRecycledNumbersCount(112,938)); System.out.println(getRecycledNumbersCount(109,964)); System.out.println(getRecycledNumbersCount(166,969)); System.out.println(getRecycledNumbersCount(150,965)); System.out.println(getRecycledNumbersCount(150,944)); System.out.println(getRecycledNumbersCount(104,925)); System.out.println(getRecycledNumbersCount(102,919)); System.out.println(getRecycledNumbersCount(175,937)); System.out.println(getRecycledNumbersCount(189,991)); System.out.println(getRecycledNumbersCount(133,996)); System.out.println(getRecycledNumbersCount(190,984)); System.out.println(getRecycledNumbersCount(2,7)); System.out.println(getRecycledNumbersCount(744,744)); } } " B21824,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Types; public class Recycled { /** * @param args * @throws IOException */ public static int calc(int a,int b) { int result = 0; int[] numbers = new int[b-a+1]; int ncircle = 0; int type=1; for (int i = a; i <= b; i++) { ncircle = 0; if(numbers[i-a]==0) { numbers[i-a]=type; ncircle = 1; int tmp=1; int n=0; while (i/tmp!=0) { tmp*=10; ++n; } --n; tmp /= 10; int cur =i; for (int j = n; j >0; --j) { int up = cur/10; int down = cur%10; cur = down * tmp + up; if(down!=0) { int shifted = cur; if((shifted>=a) && (shifted <=b)) { if(numbers[shifted-a]==0) { numbers[shifted-a]=type; ++ncircle; } } } } result += (ncircle)*(ncircle-1)/2; ++type; } } return result; } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); String number = bReader.readLine(); int num = Integer.parseInt(number); for (int i = 0; i < num; i++) { String s = bReader.readLine(); String[] strs = s.split("" ""); int A = Integer.parseInt(strs[0]); int B = Integer.parseInt(strs[1]); System.out.println(""Case #""+(i+1)+"": ""+calc(A, B)); } } } " B21155,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam12; import java.io.*; import java.util.StringTokenizer; /** * * @author Mohamed Ibrahim (MIM) */ public class Problem_C { public static String strSet(String str, char c, int index) { return str.substring(0, index) + c + str.substring(index + 1); } public static void main(String[] args) throws IOException { BufferedReader r = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter w = new PrintWriter(new BufferedWriter(new FileWriter(""C-large.out""))); int nCases = Integer.parseInt(r.readLine()); for (Integer k = 1; k <= nCases; k++) { w.print(""Case #"" + k + "": ""); String line = r.readLine(); StringTokenizer st = new StringTokenizer(line); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int ret = 0; for (int i = n; i <= m; i++) { String val = String.valueOf(i); char z = val.charAt(val.length() - 1); String cur = val.substring(0, val.length() - 1); cur = z + cur; while (!val.equals(cur)) { if (Integer.parseInt(cur) <= m && cur.charAt(0) != '0' && Integer.parseInt(val) < Integer.parseInt(cur)) { ret++; //System.out.println(val + "" "" + cur + "" "" + m); } z = cur.charAt(val.length() - 1); cur = cur.substring(0, val.length() - 1); cur = z + cur; } } // System.out.println(); // System.out.println(); w.println(ret); } w.close(); } } " B20296,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class Recycled { private static BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { String line = bufferedReader.readLine(); int cases = Integer.parseInt(line); for (int i = 1; i <= cases; i++) { line = bufferedReader.readLine(); String[] split = line.split("" ""); int A = Integer.parseInt(split[0]); int B = Integer.parseInt(split[1]); HashSet usedPairs = new HashSet(); int answer = 0; int duplicates = 0; if (B > 10) { for (int j = A; j < B; j++) { String number = """" + j; // System.err.println(""Current number: "" + number); for (int k = 0; k < number.length(); k++) { String rotated = number.substring(k) + number.substring(0, k); // System.err.println(""Rotated number: "" + rotated); int a = Integer.parseInt(number); int b = Integer.parseInt(rotated); if (Math.min(a, b) >= A && a != b && Math.max(a, b) <= B) { String hashKey; if (a < b) { hashKey = number + rotated; } else { hashKey = rotated + number; } if (!usedPairs.contains(hashKey)) { answer++; usedPairs.add(hashKey); // System.err.println(""Found a new pair!""); } else { /* * System.err * .println(""Found a duplicate: Number - "" + * number + "", Rotated: "" + rotated); */ duplicates++; } } } } } // System.err.println(""Found "" + duplicates + "" duplicated pairs""); System.out.println(""Case #"" + i + "": "" + answer); } } } " B20290,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj2012.qualification_round; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Scanner; /** * * @author langlv */ public class Dancing { private static int countDigit(int num) { Integer t = new Integer(num); int count = 0; while (t != 0) { t = t / 10; count++; } return count; } private static int recycledNumber(int num, int pos) { if (num < 10) { return 0; } if (pos > countDigit(num)) { return 0; } String n = String.valueOf(num); int res = Integer.parseInt(n.substring(pos) + n.substring(0, pos)); return res; } public static void main(String[] args) throws Exception { // Scanner sc = new Scanner(System.in); // PrintWriter pw = new PrintWriter(System.out); Scanner sc = new Scanner(new FileReader(""C:\\C-large.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""C:\\C-large.out"")); try { int ntest = Integer.parseInt(sc.nextLine()); for (int test = 1; test <= ntest; ++test) { int A = sc.nextInt(); int B = sc.nextInt(); int res = 0; List num = new ArrayList(); for (int i = A; i <= B; i++) { for (int j = 1; j < countDigit(i); j++) { int rec = recycledNumber(i, j); if (A <= rec && rec <= B && i < rec) { num.add(rec); res++; } } } pw.print(""Case #"" + test + "": ""); pw.print(res); pw.println(); } } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } finally { pw.close(); sc.close(); } } } " B21907,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Scanner; public class Recycled { public static void main(String args[]) { try{ BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""C-large.out"")); String line = in.readLine(); int caseCount = Integer.parseInt(line); StringBuffer outputWriter = new StringBuffer(); int lowCap, hiCap, digitCt, recycled, resultCount; ArrayList collisionHelper; //caseCount = 3; for(int i = 1; i <= caseCount; i++){ System.out.println(""case: "" + i); line = in.readLine(); Scanner s = new Scanner(line); lowCap = s.nextInt(); hiCap = s.nextInt(); digitCt = ("""" + lowCap).length(); resultCount = 0; for(int j = lowCap; j <= hiCap; j++){ collisionHelper = null; for(int k = 1; k < digitCt; k++){ recycled = cutAndSwap(j, k); if(recycled > j && recycled <= hiCap){ if(collisionHelper == null){ collisionHelper = new ArrayList(); collisionHelper.add("""" + recycled); resultCount++; } else if(!collisionHelper.contains("""" + recycled)){ collisionHelper.add("""" + recycled); resultCount++; } //System.out.println(resultCount + "" "" + j + "" "" + recycled + "" "" + k); } } } outputWriter.append(""Case #"" + i + "": ""); outputWriter.append(resultCount); if(i != caseCount) outputWriter.append(""\n""); } out.write(outputWriter.toString()); System.out.println(outputWriter.toString()); in.close(); out.close(); } catch(Exception e){ //swallow the exception } } //assumes 0 < position < digits in number public static int cutAndSwap(int number, int position){ String s = """" + number; String halfOne = s.substring(0, position); String halfTwo = s.substring(position); return Integer.parseInt(halfTwo + halfOne); } } " B20964,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class Tools { public static ArrayList getInput(String filename) throws IOException { BufferedReader br = new BufferedReader(new FileReader(filename)); ArrayList output = new ArrayList(); String line; while ((line = br.readLine()) != null) output.add(line.split("" "")); br.close(); return output; } public static ArrayList getInputSingle(String filename) throws IOException { BufferedReader br = new BufferedReader(new FileReader(filename)); ArrayList output = new ArrayList(); String line; while ((line = br.readLine()) != null) output.add(line); br.close(); return output; } public static void saveOutput(String filename, ArrayList output) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(filename)); for(int i=0; i output) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(filename)); for(int i=0; i=a && change!=j && change>j) { int point=0; for(int y=0;y done = new HashSet(); int A = i(); int B = i(); int pairs = 0; for (int n = A; n < B; n++) { String num = Integer.toString(n); for (int i = 1; i < num.length(); i++) { num = num.substring(1, num.length()) + num.charAt(0); int test = Integer.parseInt(num); if (test >= A && test <= B && n < test) { String map = n + "":"" + test; if (!done.contains(map)) { done.add(map); pairs++; } } } } return pairs + """"; } static void p(String x) { out.print(x); } static void pl(String x) { out.println(x); } static String f(String format, Object... args) { return String.format(format, args); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static String s(String pattern) { return in.next(pattern); } static String li() { return in.nextLine(); } }" B21386,"package gjc.recyclednumber; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class Solution { List list = new LinkedList(); /** * @param args */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""C-large.txt"")); int nTestCases = Integer.parseInt(br.readLine()); long start = System.currentTimeMillis(); for (int i=0; i resultSet = new HashSet(); String line = br.readLine(); StringTokenizer st = new StringTokenizer(line); String bottomStr = st.nextToken(); int bottom = Integer.parseInt(bottomStr); int top= Integer.parseInt(st.nextToken()); for (int j=bottom; j<=top; j++) { // Rotate and check if existing number exists. String jStr = j+""""; String temp = jStr; for (int k=0; k=0) { String str = temp+jStr; if (!resultSet.contains(str)) { resultSet.add(str); } } } } } // Display the results. bw.write(""Case #""+(i+1)+"": ""); bw.write(resultSet.size()+""\n""); } bw.close(); long end = System.currentTimeMillis(); System.out.println(""Time taken = ""+(end-start)+"" seconds.""); } } " B21361,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.util.Scanner; import java.util.StringTokenizer; /** * * @author rama */ public class Codejam1 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int n=Integer.parseInt(in.nextLine()); for(int i=1;i<=n;++i) System.out.println(""Case #""+i+"": ""+trans(in.nextLine())); } public static int trans(String ss){ int ans=0,p1,p2; StringTokenizer tok=new StringTokenizer(ss,"" ""); int A=Integer.parseInt(tok.nextToken()); int B=Integer.parseInt(tok.nextToken()); int digit=dig(A); if(digit==1) return 0; for(int n=A;n<=B;++n){ int arr[]={0,0,0,0,0,0,0,0,0}; //System.out.println(""*""); boolean state=true; for(int j=1;j<=digit-1;++j){ p1=(int)(n%Math.pow(10,j)); //System.out.println(""**""+p1); p2=(int)(n/Math.pow(10,j)); //System.out.println(""***""+p2); int m=p1*(int)(Math.pow(10,(digit-j)))+p2; if(m>n&&m<=B){ int k=0; while(arr[k]!=0){ if(arr[k]==m){ state=false; } ++k; } if(state==true){ ++ans; arr[k]=m; } } } } return ans; } public static int dig(int num){ if(num/10==0) return 1; else if(num/100==0) return 2; else if(num/1000==0) return 3; else if(num/10000==0) return 4; else if(num/100000==0) return 5; else if(num/1000000==0) return 6; else if(num/10000000==0) return 7; else if(num/100000000==0) return 8; else return 9; } } " B21829,"package codejem; import java.io.*; import java.util.HashSet; import java.util.Set; public class RecycleNumber { public static void main(String[] args) throws IOException { InputStream is; if (args.length > 0) { is = new FileInputStream(args[0]); }else{ is = System.in; } BufferedReader inputReader = new BufferedReader(new InputStreamReader(is)); String firstLine = inputReader.readLine(); int count_of_cases = Integer.parseInt(firstLine); for (int idx_of_case = 1; idx_of_case <= count_of_cases; idx_of_case++) { String caseLine = inputReader.readLine(); String[] numbers = caseLine.split("" ""); int start = Integer.parseInt(numbers[0]); int end = Integer.parseInt(numbers[1]); int count = count_of_recyclable(start, end); System.out.println(String.format(""Case #%d: %d"", idx_of_case, count)); } } public static int count_of_recyclable(int start, int end) { int count = 0; for (int number = start; number <= end; number++) { char[] chars = int_to_char_array(number); char[] max_number = int_to_char_array(end); Set matchNumbers = new HashSet(); for (int chars_to_move = 1; chars_to_move < chars.length; chars_to_move++) { char[] rotated_chars = rotated_chars(chars, chars_to_move); if (rotated_chars[0] != '0' && not_greater_than_number(rotated_chars, max_number) && less_than_number(chars, rotated_chars)) { matchNumbers.add(String.valueOf(rotated_chars)); } } count+= matchNumbers.size(); } return count; } public static boolean not_greater_than_number(char[] rotated_chars, char[] max_number) { for (int i = 0; i < rotated_chars.length; i++) { if (max_number[i] > rotated_chars[i]) { return true; } if (rotated_chars[i] > max_number[i]) { return false; } } return true; } public static boolean less_than_number(char[] rotated_chars, char[] max_number) { for (int i = 0; i < rotated_chars.length; i++) { if (max_number[i] > rotated_chars[i]) { return true; } if (rotated_chars[i] > max_number[i]) { return false; } } return false; } private static char[] int_to_char_array(int number) { return String.valueOf(number).toCharArray(); } public static char[] rotated_chars(char[] chars, int chars_to_move) { int length = chars.length; char[] result = new char[length]; System.arraycopy(chars, length - chars_to_move, result, 0, chars_to_move); System.arraycopy(chars, 0, result, chars_to_move, length - chars_to_move); return result; } } " B22183,"package googleCodeJam; import static java.lang.System.out; import java.io.BufferedReader; import java.io.FileReader; import java.util.Set; import java.util.TreeSet; public class RecycledNumbers { public static void main(String[] args) throws Exception { if (args.length == 1) { // opening the input BufferedReader in = new BufferedReader(new FileReader(args[0])); // reading the number of test cases String line = null; int numberOfTestCases = ((line = in.readLine()) != null) ? Integer.parseInt(line) : 0; for (int t = 0; t < numberOfTestCases; t ++) { line = in.readLine(); out.print(""Case #"" + (t+1) + "": ""); // parse input String[] numbers = line.split("" ""); int n = Integer.parseInt(numbers[0]); int m = Integer.parseInt(numbers[1]); int counter = 0; StringBuffer is = new StringBuffer(128); String isCurrent = null; for (int i = n; i <= m; i ++) { is.append(i); int size = is.length(); is.append(i); // Set qs = new TreeSet(); for (int j = 0; j < size; j ++) { isCurrent = is.substring(j, j+size); int q = Integer.parseInt(isCurrent); if (i < q && q <= m /*&& !isCurrent.startsWith(""0"")*/) { //counter ++; //out.println(i + ""\t"" + q + ""\t"" + (size - j)); qs.add(q); } } // counter += qs.size(); is.setLength(0); } out.println(counter); } // closing the input in.close(); } else { // show the usage System.err.println(""Using: java googleCodeJam.RecycledNumbers input""); } } } " B21882,"import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class CodeJamQ3 { public static String[] read(final String name) throws IOException { final InputStreamReader reader = new FileReader(new File(name)); final char[] buf = new char[1024]; int count = 0; final StringBuilder res = new StringBuilder(); do { count = reader.read(buf); if (count > 0) res.append(buf, 0, count); } while (count != -1); return res.toString().trim().split(""(\\r?\\n)+""); } public static void main(final String[] args) throws Exception { final long start = System.currentTimeMillis(); final String[] input = read(""C-large.in""); final FileWriter out = new FileWriter(""out""); final int casesCount = Integer.parseInt(input[0]); for (int caseN = 1; caseN <= casesCount; caseN++) { final String[] data = input[caseN].split(""\\s+""); final int a = Integer.parseInt(data[0]); final int b = Integer.parseInt(data[1]); out.write(""Case #"" + caseN + "": "" + solve(a, b) + ""\n""); } out.close(); System.out.println((System.currentTimeMillis() - start)); } private static long solve(final int a, final int b) { System.out.print("".""); long count = 0; final HashSet check= new HashSet(); final char[] number = String.valueOf(b).toCharArray(), test= new char[number.length]; final char[] numberB = String.valueOf(b).toCharArray(); for (int x = a; x <= b; x++) { final String s = String.valueOf(x); s.getChars(0, s.length(), number, 0); s.getChars(0, s.length(), test, 0); for (int i = 1; i < number.length; i++) { final char c = test[0]; for (int j = 1; j < number.length; j++) { test[j - 1] = test[j]; } test[test.length - 1] = c; if (number[0] <= number[i] && number[i] != '0') { // check the number boolean ok = true, larger = false, smaller = false; int eq = 0; for (int j = 0; j < number.length; j++) { if (test[j] == number[j]) { eq++; } if (test[j] > number[j]) { larger = true; } if (test[j] < numberB[j]) { smaller = true; } if (larger && smaller) { break; } if (!larger && test[j] < number[j] || !smaller && test[j] > numberB[j]) { ok = false; break; } } if (!ok || eq == number.length) {continue; } final Tuple t = new Tuple(x, Integer.parseInt(new String(test))); if (check.contains(t)) { continue; } check.add(t); ++count; } } } return count; } private static class Tuple { int x, y; Tuple(final int x, final int y) {this.x = x; this.y = y; } @Override public int hashCode() { return x + y; } @Override public boolean equals(final Object obj) { final Tuple t = (Tuple)obj; return t.x == x && t.y == y || t.x == y && t.y ==x; } } } " B21566,"import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner sin = new Scanner(System.in); int cases, a, b; int[] ans; cases = sin.nextInt(); ans = new int[cases]; for (int i = 0; i < cases; i++) { int count = 0; a = sin.nextInt(); b = sin.nextInt(); for (int j = a; j <= b; j++) { String ori = String.valueOf(j); int[] temp = new int[ori.length() - 1]; int tempIndex = 0; for (int k = 1; k < ori.length(); k++) { if (ori.charAt(k) == '0') continue; String newStr = ori.substring(k, ori.length()) + ori.substring(0, k); int newInt = Integer.parseInt(newStr); boolean skip = false; for (int m = 0; m < tempIndex; m++) if (temp[m] == newInt) { skip = true; break; } if (skip == false) temp[tempIndex++] = newInt; else continue; if (j < newInt && newInt >= a && newInt <= b) count++; } } ans[i] = count; } for (int i = 0; i < cases; i++) System.out.println(""Case #"" + (i + 1) + "": "" + ans[i]); } }" B21613,"import java.util.*; public class Recycled { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int lines = sc.nextInt(); for (int i=0; i swappedValues = new ArrayList(); for (int s=1; s<=d; s++) { int tens = tenPowerOf(s); int headDigits = d-s; int head = n/tens; int tail = n%tens; int minTail = minWithNumberOfDigits(s); if (tail>=minTail) { int newNum = tail*tenPowerOf(headDigits)+head; if (newNum>=min && newNum<=max && newNum!=n) { int size = swappedValues.size(); Boolean isNew = true; for (int j=0; j0) { digits++; n = n/10; } return digits; } static int tenPowerOf(int p) { int res = 0; if (p>0) { res = 10; // power of 1 for (int i=2; i<=p; i++) { res *= 10; } } return res; } static int minWithNumberOfDigits(int d) { return tenPowerOf(d-1); } } " B20490,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintStream; import java.text.MessageFormat; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class QualQ3 { private final Scanner inputScanner = new Scanner(System.in); private Scanner testCaseScanner; int[] scores; private Set set; private int A; private int B; /** * @param args */ public static void main(String[] args) { QualQ3.init(); QualQ3 speaking = new QualQ3(); speaking.solve(); } private static void init() { try { System.setIn(new FileInputStream(""in.txt"")); System.setOut(new PrintStream(""out.txt"")); } catch (FileNotFoundException e) { e.printStackTrace(); } } private void solve() { // Number of test cases int T = inputScanner.nextInt(); inputScanner.nextLine(); for (int i = 1; i <= T; i++) { initTestCase(); readTestCase(); solveTestCase(); printTestCase(i); } } private void initTestCase() { set = new HashSet(); } private void readTestCase() { testCaseScanner = new Scanner(inputScanner.nextLine()); A = testCaseScanner.nextInt(); B = testCaseScanner.nextInt(); } private void solveTestCase() { String sA = (new Integer(A)).toString(); int strLen = sA.length(); for (int i=A; i<=B; i++) { String current = (new Integer(i)).toString(); for (int j=1;j "" + newNumVal); if (newNumVal > i && newNumVal<=B) { String pair = """" + i + "","" + newNum; // System.out.println("""" + i + "" -> "" + newNumVal); set.add(pair); } } } } private final MessageFormat printFormat = new MessageFormat(""Case #{0}: ""); private void printTestCase(int num) { System.out.print(printFormat.format(new Object[] { num })); System.out.println(set.size()); } } " B21541,"package gcj2012; import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * @author Gaurav Prabhu Gaonkar * @date Apr 13, 2012 * */ public class RecycledNumbers { public static void main(String[] args) { String inputDir = ""C:\\GcjFiles\\2012\\Qualification""; String fileName = ""C-small-attempt0""; File inputFile = new File(inputDir + ""\\"" + fileName + "".in""); File outputFile = new File(inputDir + ""\\"" + fileName + "".out.txt""); try { PrintWriter out = new PrintWriter(outputFile); Scanner scanner = new Scanner(inputFile); //Read the first line String metadata = scanner.nextLine(); int numOfCases = Integer.parseInt(metadata); //System.out.println(numOfCases); for(int i = 1; i <= numOfCases; i++) { String input = scanner.nextLine(); //System.out.println(input); String[] params = input.split("" ""); int answer = solve(Integer.parseInt(params[0]), Integer.parseInt(params[1])); System.out.println(""Case #""+i+"": "" + answer); out.println(""Case #""+i+"": "" + answer); } // process next test case out.flush(); out.close(); } catch(Exception e) { System.out.println(""Exception Occured: "" + e); } } private static int solve(int a, int b) { int result = 0; if (a < 10) { a = 10; } Set candidates = new HashSet(); for (int i = a; i <= b; i++) { StringBuilder sb = new StringBuilder(); sb.append(i).append(i); int len = sb.length()/2; String str = sb.toString(); for (int j = 1; j <= len; j++) { candidates.add(str.substring(j,j+len)); } for (String candidate : candidates) { int test = Integer.parseInt(candidate); if (test > i && (test >= a && test <= b)) { result++; } } candidates.clear(); } return result; } } " B21397,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class ProblemC { public static void main(String[] args) throws FileNotFoundException { start(); } public static void start() throws FileNotFoundException { File file = new File(""./""); String name = """"; for (File f : file.listFiles()) { if (f.getName().endsWith("".in"")) { name = f.getName().replaceFirst(""\\.in"", """"); break; } } Scanner in = new Scanner(new File(name + "".in"")); PrintWriter out = new PrintWriter(new File(name + "".out"")); long startTime = System.nanoTime(); new Solution(in, out); System.out.println(""\n"" + (System.nanoTime() - startTime) * Math.pow(10, -9) + "" seconds""); out.close(); } public static class Solution { public Solution(Scanner in, PrintWriter out) { int cases = in.nextInt(); in.nextLine(); for (int i = 1; i <= cases; i++) { String answer = ""Case #"" + i + "": "" + compute(in.nextLine()); out.println(answer); System.out.println(answer); } } private int compute(String s) { Scanner sc = new Scanner(s); int a = sc.nextInt(); int b = sc.nextInt(); int digits = (a + """").length(); HashSet answer = new HashSet(); for (int shiftCount = 1; shiftCount < digits; shiftCount++) { for (int n = a; n <= b; n++) { String nString = n + """"; String mString = nString.substring(shiftCount, digits) + nString.substring(0, shiftCount); int m = Integer.parseInt(mString); if (a <= n && n < m && m <= b) { answer.add(nString+mString); } } } return answer.size(); } } } " B22082,"package gcj.gcj2012.qualif; import gcj.SolverBase; import java.io.BufferedReader; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; public class ProblemC extends SolverBase { public ProblemC() { super(""Recycled Numbers""); } public static void main(String[] args) throws Exception { SolverBase problem = new ProblemC(); // problem.verbose = true; problem.solve(System.in, System.out); } @Override public void solveSingle(BufferedReader reader, PrintStream out) throws Exception { int[] AB = readSingleLineIntArray(reader); int A = AB[0]; int B = AB[1]; // How many digits? int d = (""""+A).length(); check(d == (""""+B).length()); int x = 0; Set done = new HashSet(); // Naive implementation 1 : full loop for(int i=A;i 0) { temp = temp/10; digit++; } temp = j; int[] array = new int[digit]; for(int k = digit-1; k>0; k--) { int rem = temp%10; temp = temp/10; temp += rem*Math.pow(10, digit-1); array[k] = temp; if(temp>j) if(temp { protected abstract Transformation createTransformation(TestCaseReader testCaseReader, PrintWriter outputWriter) throws Exception; protected abstract String getOutputFileName() throws Exception; protected abstract TestCaseReader getTestCaseReader() throws Exception; public void execute() { try { PrintWriter outputWriter = null; try { outputWriter = new PrintWriter(new FileWriter(getOutputFileName())); Transformation transformation = createTransformation(getTestCaseReader(),outputWriter); transformation.transformAll(); outputWriter.flush(); } finally { closeQuietly(outputWriter); } } catch (Throwable t) { t.printStackTrace(); } } private void closeQuietly(Writer outputWriter) { if (outputWriter != null) { try { outputWriter.close(); } catch (Throwable t) { t.printStackTrace(); } } } } " B20839,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { static String shift(String s) { return s.charAt(s.length() - 1) + s.substring(0, s.length() - 1); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int t = 1; t <= T; ++t) { int A = sc.nextInt(), B = sc.nextInt(), count = 0; for (int n = A; n <= B; ++n) { String s0 = Integer.toString(n); Set matches = new HashSet(); for (String s = shift(s0); !s.equals(s0); s = shift(s)) { if (!s.startsWith(""0"")) { int m = Integer.parseInt(s); if (m >= A && m <= B) matches.add(m); } } count += matches.size(); } System.out.printf(""Case #%d: %d\n"", t, count/2); } } } " B20783,"package qualification; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class ProblemC { /** * @param args */ public static String input = ""C-large.in""; public static HashSet testSet; public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //Scanner in = new Scanner(System.in); Scanner in = new Scanner(new FileReader(input)); int t = in.nextInt(); PrintWriter out = new PrintWriter(new FileWriter(""out"")); for (int test = 0; test < t; test++) { testSet = new HashSet(); int a = in.nextInt(); int b = in.nextInt(); int result = 0; for(int number = a; number<=b;number++){ String s = Integer.toString(number); int length = s.length(); if(length<=1){ continue; } int bigPow = (int) Math.pow(10, length-1); int pow = 1; for(int i = s.length()-1; i>=1;i--){ String partOne = s.substring(i); String partTwo = s.substring(0,i); int partOneNumber = Integer.parseInt(partOne); int partTwoNumber = Integer.parseInt(partTwo); int newNumber = partOneNumber*bigPow/pow+partTwoNumber; if(newNumber>=a&&newNumber<=b){ if(newNumber > number){ result++; } } pow*=10; } } out.println(""Case #""+(test+1)+"": ""+result); out.flush(); } out.close(); } } " B21666,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; /** * Created by IntelliJ IDEA. * User: elbek * Date: 4/13/12 * Time: 7:31 PM * To change this template use File | Settings | File Templates. */ public class Test { public static void main(String[] args) { int count = 0; Set found = new TreeSet(); int t = 50; Scanner scanner = new Scanner(System.in); for (int q = 0; q <= t; q++) { count = 0; String str = scanner.nextLine(); String []arg = str.split("" ""); Integer a = Integer.parseInt(arg[0]); Integer b = Integer.parseInt(arg[1]); for (int i = a; i <= b; i++) { String input = String.valueOf(i); String changed; int len = input.length(); for (int j = 1; j < len; j++) { changed = input.substring(j, len) + input.substring(0, j); if (Integer.valueOf(changed) <= Integer.valueOf(input)) continue; if (Integer.valueOf(changed) <= b && Integer.valueOf(changed) >= a) { //found.add(input + "" - "" + changed); // found.add(changed); count++; } } } System.out.println(""Case #""+(q+1)+"": ""+count); } } } " B21743,"import java.util.Scanner; import java.util.HashSet; public class Recycle { public static void main(String[] args) { Scanner in = new Scanner(System.in); int nums = in.nextInt(); for (int p = 0; p < nums; p++) { int a = in.nextInt(); int b = in.nextInt(); int length = (a + """").length(); int pairs = 0; int numRepeats = 0; for (int f = a; f <= b; f++) { int temp = f; int save = temp; HashSet set = new HashSet(); for (int i = 0; i < length; i++) { // bring to front int last = temp % 10; temp = temp / 10; temp += last * Math.pow(10, length - 1); if (temp > save && temp >= a && temp <= b && !set.contains(temp)) { pairs++; set.add(temp); } } } System.out.println(""Case #"" + (p + 1) + "": "" + (pairs - numRepeats)); } } }" B20710,"import java.io.File; import java.io.FileWriter; import java.util.HashMap; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws Exception { RecycledNumbers recycledNumbers = new RecycledNumbers(); // file name String fileName = ""recycled_numbers""; // file variable File inputFile = new File(fileName + "".in""); File outputFile = new File(fileName + "".out""); Scanner scanner = new Scanner(inputFile); FileWriter writer = new FileWriter(outputFile); // problem variable int totalCase; // get total case totalCase = Integer.parseInt(scanner.nextLine()); System.out.println(""Total case:""+totalCase); for (int caseIndex = 1; caseIndex <= totalCase; caseIndex++) { String lineDetail = scanner.nextLine(); String[] inputArray = lineDetail.split("" ""); String min = inputArray[0]; String max = inputArray[1]; int possibleCases = 0; possibleCases = recycledNumbers.findPossibleCases(min, max); String output = ""Case #"" + caseIndex + "": "" + possibleCases; System.out.println(output); writer.write(output + ""\n""); } scanner.close(); writer.close(); } private int findPossibleCases(String min, String max){ int possibleCases = 0; int startVal = Integer.parseInt(min); int endVal = Integer.parseInt(max); int n,m = 0; HashMap usedPattern = new HashMap(); for(int i=startVal; i(); //startAt for(int j= 0; j n) && (m <=endVal)){ if(!usedPattern.containsKey(shiftStr) ){ possibleCases++; } } // keep the temp of shifting data usedPattern.put(shiftStr, shiftStr); } m = 0; } return possibleCases; } } " B21755,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author WC */ public class CodeJamFileManager { private final static String problemIntro = ""Problem reading file: ""; private final static String location = ""C:\\CodeJamTests\\""; public static String getStringOfFile(String filename) { String filepath = location + filename; byte[] buffer = new byte[(int) new File(filepath).length()]; BufferedInputStream stream = null; try { stream = new BufferedInputStream(new FileInputStream(filepath)); stream.read(buffer); } catch (Exception ex) { return problemIntro + ex.getMessage(); } finally { if (stream != null) { try { stream.close(); } catch (IOException ex) { return problemIntro + ex.getMessage(); } } } return new String(buffer); } public static int getIntFromFirstLineOfFile(String filename, String separator) { String[] lines = getTextLinesOfFile(filename, separator); int i = 1; return extractInt(lines[0]); } public static String[] getTextLinesOfFile(String filename, String separator) { String fileStr = getStringOfFile(filename); return fileStr.split(separator); } public static void saveOutputFile(String output, String filename, String separator) { String filepath = location + filename; try { File outFile = new File(filepath); FileWriter writer = new FileWriter(outFile); BufferedWriter bWriter = new BufferedWriter(writer); bWriter.write(output); bWriter.close(); } catch (Exception ex) { System.out.println(""Failed to save file with error: "" + ex.getMessage()); } } private static int extractInt(String line) { Matcher intMatcher = Pattern.compile(""[0-9]*"").matcher(line); int i = 0; if (intMatcher.find()) { String numStr = intMatcher.group(0); i = Integer.parseInt(numStr); } return i; } } " B20243,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Set; public class CodeJam { private Set generateCombination(Integer i, Integer max) { final Set output = new HashSet(); final Integer len = String.valueOf(i).length(); Integer num = i; double pow = Math.pow(10, len - 1); for (int j = 0; j < len - 1; ++j) { num = (int) ((num % pow) * 10 + (num / pow)); if (num > i && num <= max) output.add(num); } return output; } private List> getInputValue() { List> inpVal = new ArrayList>(); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); try { final String tc_ = stdin.readLine(); Integer testCase = Integer.parseInt(tc_); while (testCase-- > 0) { // System.err.println(""tc#"" + testCase); final String[] input = stdin.readLine().split("" ""); final int min = Integer.parseInt(input[0]); final int max = Integer.parseInt(input[1]); inpVal.add(new HashMap() { { put(min, max); } }); } return inpVal; } catch (IOException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { CodeJam cj = new CodeJam(); List> inp = cj.getInputValue(); int count = 1; for (HashMap tc : inp) { // operating for tc int min = 0, max = 0; int answer = 0; for (Entry e : tc.entrySet()) { min = e.getKey(); max = e.getValue(); } for (int i = min; i <= max; ++i) { answer += cj.generateCombination(i, max).size(); } System.out.println(""Case #"" + count++ + "": "" + answer); } // System.err.println(cj.generateCombination(24, 40)); } } " B21118,"package recyclednumbers; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; public class Helper { public static void main(String[] str) { System.out.println(rotateDigits(345, 2, true)); } public static int rotateDigits(int number, int noOfDigitesToBeMoved, boolean toLeft){ String str = Integer.toString(number,1); char[] chArr = str.toCharArray(); Queue numQueue = new ArrayBlockingQueue(chArr.length); for(int i = chArr.length-1; i >= 0; i--){ numQueue.add(chArr[i]); } Queue polledItems = new ArrayBlockingQueue(noOfDigitesToBeMoved); for(int i = 0; i < noOfDigitesToBeMoved; i++){ char item = numQueue.poll(); polledItems.add(item); } for(char ch : polledItems){ char item = polledItems.poll(); numQueue.add(item); } StringBuffer sb = new StringBuffer(); for(int i = numQueue.size()-1; i >= 0 ; i--){ sb.append(numQueue.toArray()[i]); } return Integer.parseInt(sb.toString()); } } " B20972,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner read = new Scanner(new File(""C-large.in"")); PrintWriter out = new PrintWriter(new File(""c-large.out"")); int numberOfTests = read.nextInt(); for (int i = 1; i <= numberOfTests; i++) { int a = read.nextInt(); int b = read.nextInt(); int countOfDigits = 0; int t = 1; while (a / t != 0) { countOfDigits++; t *= 10; } t /= 10; int result = 0; for (int n = a; n < b; n++) { int m = n; for (int k = 1; k < countOfDigits; k++) { int lastDigit = m % 10; m = m / 10; m = lastDigit * t + m; if (m <= b && m > n) { result++; } } } out.println(String.format(""Case #%d: %d"", i, result)); } out.close(); } } " B21846,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumbers { static class NumberPairs{ int a ; int b ; int large ; int small; NumberPairs(String input){ populateInput(input); } private void populateInput(String input) { StringTokenizer tokenizer = new StringTokenizer(input, "" ""); a = Integer.parseInt((String) tokenizer.nextElement()); b = Integer.parseInt((String) tokenizer.nextElement()); if(ab){ small = b; large = a; } } private int computeResult(){ int count=0; for(int number = small ; number <= large; number ++){ // Get every number under small Set set = new HashSet(); for(int i = 0 ; i < Integer.toString(number).length()-1 ;i++){ // Rotate number to get another number int rotated = rotateCircular(number, i+1); if(number < rotated && rotated <= large){ if(set.contains(rotated)) continue; else set.add(rotated); count++; } } } return count; } private static int rotateCircular(int number, int n){ char [] val =rotateCircularly(Integer.toString(number), n); return Integer.parseInt(new String(val)); } public void printResult(int i) { System.out.println(""Case #"" + i + "": "" + computeResult()); } public static char[] rotateCircularly(String input1 , int n) { char[] input = input1.toCharArray(); input = reverse (input, 0 , input.length-1); input = reverse (input , 0 , n-1); input = reverse (input, n , input.length-1); // Reverse the last n return input; } public static char[] reverse(char[] input, int start, int end){ for(int i = 0 ; i < (end - start + 2) / 2 ; i ++){ char temp = input[start + i]; input[start + i] = input[end-i]; input[end-i] = temp; } return input; } } public static void main(String[] args) { try { String [] input = getInput(""C-large.in""); for(int i=0;i< input.length; i++){ new NumberPairs(input[i]).printResult(i+1); } } catch (IOException e) { } } static String[] getInput(String fileName) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(fileName)); try { String message = reader.readLine(); int numberOfTestCases = Integer.parseInt(message); String[] input = new String[numberOfTestCases]; for (int i = 0; i < numberOfTestCases; i++) { message = reader.readLine(); input[i] = message; } return input; } finally { reader.close(); } } } " B20359,"import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Set; import com.google.common.collect.Sets; import com.google.common.io.LineReader; public class RecycledNumbers { public static void main(String[] args) throws NumberFormatException, IOException { LineReader lineReader = new LineReader(new FileReader(args[0])); FileWriter out = new FileWriter(args[0] + ""-out.txt""); int t = Integer.parseInt(lineReader.readLine()); for (int counter = 1; counter <= t; counter++) { String[] nums = lineReader.readLine().split("" ""); int result = compute(Integer.parseInt(nums[0]), Integer.parseInt(nums[1])); out.write(String.format(""Case #%d: %d\n"", counter, result)); } out.close(); } private static int compute(int a, int b) { Set set = Sets.newHashSet(); int count = 0; for (int n = a; n < b; n++) { String nStr = Integer.toString(n); set.clear(); for (int i = 1; i < nStr.length(); i++) { String fst = nStr.substring(i); String snd = nStr.substring(0, i); int m = Integer.parseInt(fst + snd); if (m > n && m <= b && !set.contains(m)) { set.add(m); count++; } } } return count; } } " B21456,"import java.io.*; import java.util.HashSet; import java.util.Set; /** * Created with IntelliJ IDEA. * User: Frederick * Date: 4/14/12 * Time: 9:40 AM * To change this template use File | Settings | File Templates. */ public class RecycledNumbers { private static int solve(int a, int b) { int count = 0; for (int n = a; n < b; n++) { String nString = Integer.toString(n); int len = nString.length(); Set existing = new HashSet(); for (int i = 1; i < len; i++) { String mString = nString.substring(i) + nString.substring(0, i); int m = Integer.parseInt(mString); if (n < m && m <= b && existing.add(m)) { count++; } } } return count; } public static void main(String[] args) throws IOException { File input = new File(""C:\\Users\\Frederick\\Downloads\\C-large.in""); File output = new File(input.getAbsolutePath() + "".out""); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(input))); PrintStream out = new PrintStream(output); int cases = Integer.parseInt(in.readLine()); for (int i = 1; i <= cases; i++) { String[] s = in.readLine().split("" ""); int a = Integer.parseInt(s[0]); int b = Integer.parseInt(s[1]); int solution = solve(a, b); String print = ""Case #"" + i + "": "" + solution; System.out.println(print); out.println(print); } } } " B20606,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class ReadFile { public static void main(String[] args) throws Exception { String srcFile = ""C:"" + File.separator + ""Documents and Settings"" + File.separator + ""rohit"" + File.separator + ""My Documents"" + File.separator + ""Downloads"" + File.separator + ""C-small-attempt1.in.txt""; String destFile = ""C:"" + File.separator + ""Documents and Settings"" + File.separator + ""rohit"" + File.separator + ""My Documents"" + File.separator + ""Downloads"" + File.separator + ""C-small-attempt0.out""; File file = new File(srcFile); List readData = new ArrayList(); FileReader fileInputStream = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileInputStream); StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { readData.add(line); } stringBuilder.append(generateOutput(readData)); File writeFile = new File(destFile); if (!writeFile.exists()) { writeFile.createNewFile(); } FileWriter fileWriter = new FileWriter(writeFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(stringBuilder.toString()); bufferedWriter.close(); System.out.println(""output"" + stringBuilder); } /** * @param number * @return */ private static String generateOutput(List number) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < number.size(); i++) { if (i == 0) { continue; } else { String tempString = number.get(i); String[] temArr = tempString.split("" ""); stringBuilder.append(""Case #"" + i + "": ""); stringBuilder.append(getRecNumbers(temArr[0], temArr[1])); stringBuilder.append(""\n""); } } if (stringBuilder.length() > 0) { stringBuilder.deleteCharAt(stringBuilder.length() - 1); } return stringBuilder.toString(); } // /* This method accepts method for google code jam */ // private static String method(String value) { // int intValue = Integer.valueOf(value); // double givenExpr = 3 + Math.sqrt(5); // double num = Math.pow(givenExpr, intValue); // String valArr[] = (num + """").split(""\\.""); // int finalVal = Integer.valueOf(valArr[0]) % 1000; // // return String.format(""%1$03d"", finalVal); // // } // // /* This method accepts method for google code jam */ // private static String method2(String value) { // StringTokenizer st = new StringTokenizer(value, "" ""); // String test[] = value.split("" ""); // StringBuffer str = new StringBuffer(); // // for (int i = 0; i < test.length; i++) { // // test[i]=test[test.length-i-1]; // str.append(test[test.length - i - 1]); // str.append("" ""); // } // str.deleteCharAt(str.length() - 1); // String strReversedLine = """"; // // while (st.hasMoreTokens()) { // strReversedLine = st.nextToken() + "" "" + strReversedLine; // } // // return str.toString(); // } private static int getRecNumbers(String no1, String no2) { int a = Integer.valueOf(no1); int b = Integer.valueOf(no2); Set dupC = new HashSet(); for (int i = a; i <= b; i++) { int n = i; List value = findPerm(n); for (String val : value) { if (Integer.valueOf(val) <= b && Integer.valueOf(val) >= a && n < Integer.valueOf(val)) { dupC.add(n + ""-"" + val); } } } return dupC.size(); } private static List findPerm(int num) { String numString = String.valueOf(num); List value = new ArrayList(); for (int i = 0; i < numString.length(); i++) { String temp = charIns(numString, i); if (!temp.equalsIgnoreCase(numString)) { value.add(charIns(numString, i)); } } return value; } public static String charIns(String str, int j) { String begin = str.substring(0, j); String end = str.substring(j); return end + begin; } }" B20507,"package qualification.c; import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * * Problem Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers. Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros. Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A ≤ n < m ≤ B? Input The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B. Output For each test case, output one line containing ""Case #x: y"", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A ≤ n < m ≤ B. Limits 1 ≤ T ≤ 50. A and B have the same number of digits. Small dataset 1 ≤ A ≤ B ≤ 1000. Large dataset 1 ≤ A ≤ B ≤ 2000000. Sample Input 4 1 9 10 40 100 500 1111 2222 Output Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 Are we sure about the output to Case #4? Yes, we're sure about the output to Case #4. * 2012.04.14. 16:22 - 16:38 * @author Chei */ public class RecycledNumbers { Scanner scanner; public static void main(String[] args) throws FileNotFoundException { new RecycledNumbers().solve(); } void solve() throws FileNotFoundException { scanner = new Scanner(new File(""resources/C-large.in"")); //scanner = new Scanner(new File(""resources/C-small-attempt0.in"")); //scanner = new Scanner(new File(""resources/C-example.in"")); int numberOfTestCases = scanner.nextInt(); for (int testCaseIndex = 1; testCaseIndex <= numberOfTestCases; testCaseIndex++) { int result = solveTestCase(); System.out.format(""Case #%d: %d%n"", testCaseIndex, result); } } int solveTestCase() { int a = scanner.nextInt(); int b = scanner.nextInt(); Set recycledNumbers = new HashSet(); int result = 0; for (int num = a; num <= b; num++) { String numString = String.valueOf(num); recycledNumbers.clear(); for (int i = 0; i < numString.length(); i++) { String newString = numString.substring(i) + numString.substring(0, i); if (newString.charAt(0) != '0') { int newNum = Integer.parseInt(newString); if (newNum >= a && newNum <= b) { recycledNumbers.add(newString); } } } result += recycledNumbers.size() - 1; } // all pairs were counted twice return result / 2; } } " B22260,"package info.stephenn.codejam2012.qualify; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.HashMap; import java.util.Hashtable; import java.util.Scanner; public class C { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int cases = sc.nextInt(); for (int caseX=1; caseX <= cases; caseX+=1){ int A = sc.nextInt(); int B = sc.nextInt(); System.out.println(""Case #""+caseX+"": ""+doitSweep(A,B)); } } public static int doitRecycled(int A, int B){ int[] mCounts = new int[B+1]; int count=0; for (int m = A+1; m<= B; m++){ int mCount = 0; int nStart = A; for (int mrIndex = m; mrIndex >=0; mrIndex-=1){ if (C.isRecycled(mrIndex, m)){ mCount = mCounts[mrIndex]; nStart = mrIndex; break; } } for (int n = nStart; n< m; n++){ if (C.isRecycled(n, m)) mCount+=1; } count += mCount; mCounts[m] = mCount; } return count; } public static int doit(int A, int B){ int count=0; for (int m = A+1; m <= B; m++){ for (int n = A; n < m; n++){ if (isRecycled(n,m)){ count+=1; System.out.println(""(""+n+"",""+m+"")""); } } } return count; } public static int isRecycledString(String n, String m){ if (isRecycled(Integer.parseInt(n), Integer.parseInt(m))) return 1; else return 0; // for (int split =1; split < n.length(); split++){ // String t = n.substring(split) + n.substring(0, split); // if (t.equals(m)) // return 1; // } // return 0; } public static boolean isRecycled(int n, int m){ int length = Integer.toString(n).length(); int pow = 1; for (int i =1 ; i < length; i++) pow *= 10; int t = n; for (int split =1; split < length; split++){ int back = t%10; int front = t/10; int backInFront = back * pow; t = backInFront + front; if (t==m) return true; } return false; } public static int doit3(int A, int B){ table.clear(); int count=0; for (int m = A+1 ; m <= B; m++){ count += permutationsOf(m, A, B); } return count; } public static int permutationsOf(int n, int fromA, int toB){ int length = Integer.toString(n).length(); int pow = 1; for (int i =1 ; i < length; i++) pow *= 10; int t = n; int count =0; for (int split =1; split < length; split++){ int back = t%10; int front = t/10; int backInFront = back * pow; t = backInFront + front; if (fromA <= t && t <= toB && t != n && doIHave(n,t)==false && doIHave(t,n)==false){ have(n,t); have(t,n); System.out.println(""is perm""+t); count +=1; } } return count; } static Hashtable table = new Hashtable(); static String EMPTY_STRING = """"; public static void have(int x, int y){ //mark that this perm has been counted. table.put(Integer.toString(x)+"",""+Integer.toString(y), EMPTY_STRING); } public static boolean doIHave(int x,int y){ return table.contains(Integer.toString(x)+"",""+Integer.toString(y)); } public static int doitSweep(int A, int B){ boolean[] done = new boolean[B+1]; HashMap distinctPairs = new HashMap(); int count=0; for (int x = A; x <= B; x++){ if (done[x] == false){ int[] perms = permutationsOfBetween(x, A, B); for (int p : perms) done[p] =true; for (int n : perms){ for (int m : perms){ if (n != m && distinctPairs.containsKey(indexPair(n,m))==false){ count+=1; distinctPairs.put(indexPair(n,m), EMPTY_STRING); } } } } } return count; } public static String indexPair(int n, int m){ if (n < m) return """"+n+"",""+m; else return """"+m+"",""+n; } public static int[] permutationsOfBetween(int x, int A, int B){ int length = Integer.toString(x).length(); int[] permutations = new int[length]; int permCount=0; int pow = 1; for (int i =1 ; i < length; i++) pow *= 10; int t = x; for (int split =0; split < length; split++){ int back = t%10; int front = t/10; int backInFront = back * pow; t = backInFront + front; if (A <= t && t <= B){ permutations[permCount++] = t; } } return Arrays.copyOfRange(permutations, 0, permCount); } }" B21059,"package qualificationround; import java.io.*; import java.util.*; public class ProblemC { public static Set h; /** * @param args */ public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(new FileReader(""C.in"")); PrintWriter out = new PrintWriter(new FileWriter(""C.out"")); int t = sc.nextInt(); for (int caseNum = 1; caseNum <= t; caseNum++) { h = new HashSet(); int a = sc.nextInt(); int b = sc.nextInt(); int p = a; int count = 0; while (p<=b) { if (!h.contains(p)) { count += rolling(p, a, b); } p++; } out.println(""Case #""+caseNum+"": ""+count); } out.close(); } public static int rolling(int num,int a,int b) { h.add(num); String sNum = Integer.toString(num); String s = new String(sNum); int count = 1; for (int i = 0; i < sNum.length()-1; i++) { s = s.substring(s.length()-1).concat(s.substring(0,s.length()-1)); //System.out.println(s); int p = Integer.parseInt(s); if (p == num) break; if (p >= a && p <= b ) { h.add(p); count++; } } //return count; return (count-1)*count/2; } } " B20009,"package google.codejam.com; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class Solution { public static void main(String[] args) { BufferedReader f = null; PrintWriter out = null; try { f = new BufferedReader(new FileReader(""in.txt"")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { out = new PrintWriter(new BufferedWriter(new FileWriter(""out.txt""))); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { // SOLUTION STARTS HERE int count = new Integer(f.readLine()); for (int i = 1; i <= count; i++) { long sum = 0L; String[] in = f.readLine().split("" ""); int from = new Integer(in[0]); int to = new Integer(in[1]); for (int num = from; num <= to; num++) { String toStr = new Integer(to).toString(); String numStr = new Integer(num).toString(); sum += getSum(numStr, toStr); } out.write(""Case #"" + i + "": "" + sum + ""\n""); System.out.println(""Case #"" + i + "": "" + sum); } // SOLUTION ENDS HERE out.flush(); out.close(); f.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static long getSum(String numStr, String toStr) { String conn = """"; conn = numStr + numStr; HashSet set = new HashSet(); for (int i = 0; i < numStr.length(); i++) { String cand = conn.substring(i, i + numStr.length()); if(cand.compareTo(numStr) > 0 && cand.compareTo(toStr) <= 0) set.add(cand); } return set.size(); } } " B21318,"package recycledNumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class RecycledNumbers { private BufferedReader reader; private BufferedWriter writer; private static String fileName; private Map twoTongues; public static void main(String[] args) throws IOException { fileName = args[0]; RecycledNumbers numbers = new RecycledNumbers(); numbers.findTheNumbers(); } /** * ""Find the numbers, fast as you can * recycling's uncouth, so don't or you'll be banned"" */ public void findTheNumbers() { try { writer = new BufferedWriter( new FileWriter(""recycling.txt"")); reader = new BufferedReader( new InputStreamReader( new DataInputStream( new FileInputStream(fileName)))); Integer numTestCases = Integer.parseInt(reader.readLine()); for(int i = 0; i < numTestCases; ++i) { int numNumbers = solve(reader.readLine()); writer.write(""Case #"" + (i+1) + "": "" + numNumbers + ""\n""); } writer.close(); } catch (Exception e) { e.printStackTrace(); System.out.println(""Shizzle""); System.exit(1); } } private int solve(String readLine) { Set results = new TreeSet(); Scanner scanner = new Scanner(readLine); String numberOne = scanner.next(); String numberTwo = scanner.next(); int counter = 0; if(numberOne.length() == 1) { return 0; } //from A - B for(int i = Integer.parseInt(numberOne); i < Integer.parseInt(numberTwo); ++i) { results.clear(); String numToSwitch = Integer.toString(i); //from start of A to end of A String numToMove; String numToUse; String finishedNum = numToSwitch; for(int j = 0; j < numToSwitch.length() - 1; ++j) { numToMove = finishedNum.substring(finishedNum.length() - 1); numToUse = finishedNum.substring(0, finishedNum.length() - 1); finishedNum = numToMove.concat(numToUse); if(Integer.parseInt(finishedNum) <= Integer.parseInt(numberTwo)) { if(i < Integer.parseInt(finishedNum)) { results.add(Integer.parseInt(finishedNum)); } } } counter = counter + results.size(); } return counter; } } " B21112," import java.io.*; import java.util.*; public class codejam2 { public static void main(String[] args) throws FileNotFoundException, IOException { File file = new File(""C-large.in""); FileReader fr = new FileReader(file); Scanner ob = new Scanner(fr); File outFile = new File(""outFile2.txt""); FileWriter outFilew = new FileWriter(outFile); int t,r=1; t = ob.nextInt(); while (t != 0) { int a, b; a = ob.nextInt(); b = ob.nextInt(); int i, j, k, count = 0; for (i = a; i < b; i++) { j = i; int h[]=new int[8]; int c=0; String no = Integer.toString(j); for (k = no.length()-1; k>=0;k--) { String temp = """"; temp=no.substring(k)+no.substring(0,k); int s = Integer.parseInt(temp); if (s > j && s <= b ) { int flag=0; for(int m=0;m 0) { int y = 0; String[] g = bf.readLine().trim().split(""\\s+""); int a = Integer.parseInt(g[0]); int b = Integer.parseInt(g[1]); for (int i = a; i < b; i++) { boolean[] flag = new boolean [b-a+1]; String s= Integer.toString(i); for (int j = 0; j < g[0].length()-1; j++) { int ss = Integer.parseInt(s.substring(j+1)+s.substring(0,j+1)); if (ss>i&&ss<=b&&!flag[ss-a]) { y++; flag[ss-a]=true; } } } System.out.println(""Case #"" + x + "": "" + y); x++; t--; } } } " B22219,"package tr0llhoehle.cakemix.googleCodeJam.recycledNumbers; import java.text.ParseException; import java.util.ArrayList; import tr0llhoehle.cakemix.utility.googleCodeJam.Problem; import tr0llhoehle.cakemix.utility.googleCodeJam.SupportedTypes; public class RNProblem extends Problem { private int lowerBorder; private int upperBorder; public RNProblem() { types = new SupportedTypes[1]; types[0] = SupportedTypes.LIST_INT; } public void addValue(Object o) throws ParseException { ArrayList temp = (ArrayList) o; lowerBorder = temp.get(0); upperBorder = temp.get(1); super.addValue(o); } public int getLowerBorder() { return lowerBorder; } public int getUpperBorder() { return upperBorder; } } " B21937,"import java.io.File; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class C { /** * @param args */ public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File(""d:\\cc.large.in""));// new Scanner(new // File(""d:\\b.small.in"")); // in = new Scanner(new File(""d:\\Minimum Scalar Product-big.in"")); int testCases = in.nextInt(); in.nextLine(); for (int cas = 1; cas <= testCases; cas++) { int ans = 0; int A = in.nextInt(); int B = in.nextInt(); // in.nextLine(); Map> map = new HashMap>(); for (int n = A; n < B; n++) { String sn = """" + n; int len = sn.length(); for (int i = 1; i < len; i++) { String front = sn.substring(0, i); String rear = sn.substring(i, len); int m = Integer.parseInt(rear + front); if (A <= n && n < m && m <= B) { Set s = map.get(n); if (null == s) { ans++; s = new HashSet(); s.add(m); map.put(n, s); } else { if (s.add(m)) ans++; } // System.err.printf(""n:%d,m:%d\n"",n,m); } } } System.out.printf(""Case #%d: %d\n"", cas, ans); } } } " B21972,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.io.Reader; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class Main { public static HashMap mapp = new HashMap(); public static void main(String[] args) throws Exception { PrintWriter writer = new PrintWriter(new FileWriter(""output.txt"")); BufferedReader input = new BufferedReader(new FileReader(""C-large.in"")); int size=Integer.parseInt(input.readLine()); for(int i=0; i mySet = new HashSet(); String tokens[] = input.readLine().split("" ""); int lowLimit = Integer.parseInt(tokens[0]); int highLimit = Integer.parseInt(tokens[1]); int count=0; for(int j=lowLimit; jj && Integer.parseInt(temp)<=highLimit) { mySet.add(str1+temp); } } } writer.println(""Case #""+(i+1)+"": ""+mySet.size()); } writer.close(); input.close(); } } " B22209,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import junit.framework.TestCase; public class RecycledNumbers extends TestCase { public void testMain() throws IOException { RecycledNumbers.main(null); } public static void main(String[] args) throws IOException { setStandardIO(); setFileIO(""recyclednumbers""); readLine(); int T = nextInt(); for (int t = 1; t <= T; ++t) { readLine(); int A = nextInt(); int B = nextInt(); int N = String.valueOf(A).length() - 1; if (N == 0) println(""Case #"" + t + "": "" + 0); else { Set pairs = new TreeSet(); for (int i = A; i <= B; ++i) { for (int j = 0; j < N; ++j) { String x = String.valueOf(i); String y = x.substring(N - j) + x.substring(0, N - j); if (y.charAt(0) == '0') continue; int X = Integer.valueOf(x); int Y = Integer.valueOf(y); if (X == Y) continue; if (Y < A) continue; if (Y > B) continue; if (X < Y) pairs.add(new Pair(X, Y)); else pairs.add(new Pair(Y, X)); } } println(""Case #"" + t + "": "" + pairs.size()); } } flush(); } //~ ---------------------------------------------------------------------------------------------------------------- //~ - Auxiliary code ----------------------------------------------------------------------------------------------- //~ ---------------------------------------------------------------------------------------------------------------- static BufferedReader in; static PrintWriter out; static StringTokenizer st; private static void setStandardIO() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); } private static void setFileIO(String fileName) throws FileNotFoundException, IOException { in = new BufferedReader(new FileReader(fileName + "".in"")); out = new PrintWriter(new BufferedWriter(new FileWriter(fileName + "".out""))); } public static void readLine() throws IOException { st = new StringTokenizer(in.readLine()); } public static int nextInt() { return Integer.parseInt(st.nextToken()); } public static long nextLong() { return Long.parseLong(st.nextToken()); } public static String nextString() { return st.nextToken(); } public static List nextStrings() { List strings = new ArrayList(); while (st.hasMoreTokens()) strings.add(st.nextToken()); return strings; } public static void flush() { out.flush(); } public static void println(Object object) { out.println(object); } public static void print(Object object) { out.print(object); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static class Pair implements Comparable{ public int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return ""Pair [x="" + x + "", y="" + y + ""]""; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (x ^ (x >>> 32)); result = prime * result + (int) (y ^ (y >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } @Override public int compareTo(Pair o) { if (x < o.x) return -1; if (x > o.x) return 1; return y - o.y; } } } " B20752,"package fixjava; /** * Convenience class for declaring a method inside a method, so as to avoid code duplication without having to declare a new method * in the class. This also keeps functions closer to where they are applied. It's butt-ugly but it's about the best you can do in * Java. * * final HashSet allNames = new HashSet(); Lambda, Void> addAllIfNotNull = new Lambda, Void>() { public Void apply(Set newNames) { if (allNames != null) allNames.addAll(newNames); return null; } }; allNames.add(cell.getName()); addAllIfNotNull.apply(cell.getValues(""Main_name"")); addAllIfNotNull.apply(cell.getValues(""Other_name"")); addAllIfNotNull.apply(cell.getValues(""Tree_node"")); addAllIfNotNull.apply(cell.getValues(""Lineage_name"")); * */ public interface Lambda { public V apply(P param); } " B22061,"public class A { public static void main(String[] a) { //System.out.println(a(1,9)); //System.out.println(a(10,40)); //System.out.println(a(100,500)); //System.out.println(a(1111,2222)); java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); int i=0; String line = null; try { while((line=reader.readLine())!=null) { if(i>0) { System.out.println(""Case #""+i+"": ""+parseLine(line)); } i++; } } catch(Exception e) {} } static int parseLine(String line) { String p[] = line.split("" ""); return a(Integer.valueOf(p[0]), Integer.valueOf(p[1])); } public static int a(int a, int b) { if(a>=b) return 0; if(b<10) return 0; //1 digit. return 0 java.util.HashMap map = new java.util.HashMap(); int count=0; for(int i=a;i<=b;i++) { String x = String.valueOf(i); map.clear(); for(int j=1; j0){ long answer=0; int A=nextInt(); int B=nextInt(); for (int i = A; i < B; i++) { String a=new String(i+""""); ArrayList hash=new ArrayList(); for (int j = 1; j < a.length(); j++) { String now =a.charAt(a.length()-1)+a.substring(0,a.length()-1); int n=Integer.parseInt(now); String nlen=n+""""; if(nlen.length()!=now.length()||nlen.equals(a)||n<=i||hash.contains(n+"""")){ a=now; continue; } if(n<=B){ hash.add(n+""""); answer++; } a=now; } } writeln(""Case #""+(number++)+"": ""+answer); } } private int nextInt() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Integer.parseInt(input.nextToken()); } private long nextLong() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Long.parseLong(input.nextToken()); } private double nextDouble() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Double.parseDouble(input.nextToken()); } private String nextString() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return input.nextToken(); } private void write(String output){ out.write(output); out.flush(); } private void writeln(String output){ out.write(output+""\n""); // out.flush(); } private void end() throws IOException{ in.close(); out.close(); System.exit(0); } private BufferedReader in; private PrintWriter out; private StringTokenizer input; public C() throws IOException { //Input Output for Console to be used for trying the test samples of the problem // in = new BufferedReader(new InputStreamReader(System.in)); // out = new PrintWriter(System.out); //------------------------------------------------------------------------- //Input Output for File to be used for solving the small and large test files in = new BufferedReader(new FileReader(""C-large.in"")); out = new PrintWriter(""output3Large.txt""); //------------------------------------------------------------------------- //Initialize Stringtokenizer input input = new StringTokenizer(in.readLine()); } public static void main(String[] args) throws Exception { //------------------------------------------------------------------------- //initializing... C sol = new C(); //------------------------------------------------------------------------- sol.run(); //------------------------------------------------------------------------- //closing up sol.end(); //-------------------------------------------------------------------------- } } " B21420,"package com.google.codejam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; public class CRecycledNumbers { private void go() throws IOException { String fileIn = ""resources/codejam2012/C-large.in""; String fileOut = fileIn.replace("".in"", "".out""); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut))); BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(fileIn))); int count = Integer.parseInt(r.readLine()); for(int i = 0; i < count; i++) { String out = processCase(r.readLine()); out = ""Case #"" + (i + 1) + "": "" + out; System.out.println(out); w.write(out + ""\n""); } w.close(); r.close(); } private Set getRecycled(int n) { Set recycled = new HashSet(); String sn = String.valueOf(n); for(int i = 1; i < sn.length(); i++) { String newN = sn.substring(i) + sn.substring(0, i); if (!newN.startsWith(""0"") && !newN.equals(sn)) { recycled.add(Integer.parseInt(newN)); } } return recycled; } private String processCase(String text) { Scanner scanner = new Scanner(text); int a = scanner.nextInt(); int b = scanner.nextInt(); int out = 0; for(int i = a; i < b; i++) { Set recycled = getRecycled(i); for(Integer rec : recycled) { int r = rec; if ((r >i) && (r <= b)) out++; } } return String.valueOf(out); } public static void main(String[] args) throws Exception { long now = System.currentTimeMillis(); new CRecycledNumbers().go(); System.out.println(String.valueOf(System.currentTimeMillis() - now) + ""ms""); } }" B20140,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class recycle { public static int factorial(int num){ if(num==0){ return 1; } int n = 1; for(int i = 1; i<=num;i++){ n*=i; } return n; } static int[] jt=new int[8]; public static void main(String args[]) throws IOException{ String[] ss = new String[2]; int num; FileInputStream fstream = new FileInputStream(""p:/C-large.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String readLine; readLine = br.readLine(); num = Integer.valueOf(readLine); //System.out.println(num); FileWriter fstreamw = new FileWriter(""p:/C-large.out""); BufferedWriter out = new BufferedWriter(fstreamw); // Read File Line By Line int number = 1; while ((readLine = br.readLine()) != null) { ss = readLine.split("" ""); ////System.out.println(ss[0]); ////System.out.println(ss[1]); int[] A = new int[ss[0].length()]; int[] B = new int[ss[0].length()]; int numA = Integer.valueOf(ss[0]); int numB = Integer.valueOf(ss[1]); int[] count=new int[8]; int counttemp = 1; int sum =0; int l=ss[0].length(); ////System.out.println(""l==""+l); int l2=(int)Math.pow(10, l-1); ////System.out.println(numA+"" ""+numB); // //System.out.print(ss[0].length()); for (int i = 0; i < l; i++) { A[i] = Integer.valueOf(ss[0].charAt(i)); // //System.out.print(ss[0].charAt(i)); } ////System.out.println(); for (int i = 0; i < l; i++) { B[i] = Integer.valueOf(ss[1].charAt(i)); } for (int j = numA; j <= numB; j++) { int jtemp = j; jt[0]=j; for (int i = 1; i < l; i++) { jtemp=(jtemp-(jtemp/(l2))*l2)*10+jtemp/l2; ////System.out.println(j+"" ""+jtemp); if((jtemp>=numA)&&(jtemp<=numB)&&(j!=jtemp)){ if(notequal(jtemp)){ counttemp = counttemp + 1; jt[i]=jtemp; //System.out.println(j+"" ""+jtemp); } ////System.out.println(j+"" ""+jtemp); } ////System.out.println(j); } for(int i=1;i<8;i++){ jt[i]=0; } if(counttemp!=1){ ////System.out.println(""counttemp=""+Math.ceil(counttemp)); ////System.out.println(counttemp); switch(counttemp){ case 1: count[1]=count[1]+factorial(counttemp)/(2*factorial(counttemp-2)); break; case 2: count[2]=count[2]+factorial(counttemp)/(2*factorial(counttemp-2)); break; case 3: count[3]=count[3]+factorial(counttemp)/(2*factorial(counttemp-2)); break; case 4: count[4]=count[4]+factorial(counttemp)/(2*factorial(counttemp-2)); break; case 5: count[5]=count[5]+factorial(counttemp)/(2*factorial(counttemp-2)); break; case 6: count[6]=count[6]+factorial(counttemp)/(2*factorial(counttemp-2)); break; case 7: count[1]=count[1]+factorial(counttemp)/(2*factorial(counttemp-2)); break; } ////System.out.println(""count=""+Math.ceil(count)); } counttemp=1; } sum = count[1]/1+count[2]/2+count[3]/3+count[4]/4+count[5]/5+count[6]/6+count[7]/7; //sum = count[1]+count[2]+count[3]+count[4]+count[5]+count[6]+count[7]; out.write(""Case #""); out.write(String.valueOf(number)); out.write("": ""); out.write(String.valueOf(sum)); if(number!=num){ out.write(""\r\n""); } number++; if(sum!=0){ //System.out.println(""sum=""+sum); ////System.out.println(factorial(count)/(2*factorial(count-2))); } for(int i =0;i<8;i++){ count[i]=0; } } out.close(); } private static boolean notequal(int i) { for(int i1=0;i1<7;i1++){ if(i==jt[i1]){ return false; } } return true; } } " B21130,"import java.io.IOException; import java.util.ArrayList; import java.util.Vector; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub ReadFile.read(""C:\\test\\input.txt""); ArrayList elements = ReadFile.getElements(); //Number of cases to test int numberCases = Integer.valueOf(elements.get(0)); if(numberCases > elements.size()) { System.out.println(""Error in number of tests""); System.exit(-1); } elements.remove(0);// remove the first element, so only lines to translate are left in the file StringBuilder outputFile = new StringBuilder(); for(int i = 1; i <= elements.size(); i++){ String[] numbers = elements.get(i-1).split("" ""); outputFile.append(""Case #"" + i + "": "" + countRecycledNumbers(new Integer(numbers[0]), new Integer(numbers[1]) ) ); outputFile.append(""\r\n""); } WriteFile.write(""C:\\test\\output.txt"", outputFile.toString()); } private static int countRecycledNumbers(Integer integer1, Integer integer2) { int countRecycled = 0; for(int i = integer1; i 0) countRecycled+=countRecyclablePerNumber; } return countRecycled; } private static int countRecyclablePerNumber(int number, int min, int max) { if(number < 10 ) return 0; int count = 0; String value = String.valueOf(number); char[] charValues = value.toCharArray(); Vector vectorRecycledNumbers = new Vector(); for(int i=0; i= min && number < newIntValue && !vectorRecycledNumbers.contains(newIntValue)){ count++; vectorRecycledNumbers.add(newIntValue); } } vectorRecycledNumbers.clear(); return count; } } " B21211,"import java.util.*; import java.io.*; public class Solution { FastScanner in; PrintWriter out; int doFromStr(String s, int k) { int ans = 0; for (int i = k; i < s.length(); i++) { ans = ans * 10 + s.charAt(i) - '0'; } for (int i = 0; i < k; i++) { ans = ans * 10 + s.charAt(i) - '0'; } return ans; } public void solve() throws IOException { int cases = in.nextInt(); for (int nowCase = 1; nowCase <= cases; nowCase++) { int a = in.nextInt(); int b = in.nextInt(); long ans = 0; for (int x = a; x < b; x++) { ArrayList add = new ArrayList(); String s = (new Integer(x)).toString(); for (int k = 1; k < s.length(); k++) { int newVal = doFromStr(s, k); boolean newV = true; if (newVal > x && newVal <= b) { for (int i = 0; i < add.size(); i++) { if (add.get(i) == newVal) newV = false; } if (newV) add.add(newVal); } } ans += add.size(); } // out.print(""Case #""); out.print(nowCase); out.print("": ""); // out.print(ans); // out.println(); } } public void run() { try { in = new FastScanner(new File(""c.in"")); out = new PrintWriter(new File(""c.out"")); //in = new FastScanner(System.in); //out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String readLine() { try { return br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "" ""; } int nextInt() { return Integer.parseInt(next()); } } public static void main(String[] arg) { new Solution().run(); } }" B20901,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib.converters; import com.isotopeent.codejam.lib.InputConverter; public class MultiLineConverter implements InputConverter { private InputConverter[] converters; private int count; private Object[] input; private int lineNumber; public MultiLineConverter(InputConverter lineConverter, int count) { this.converters = new InputConverter[count]; this.count = count; for (int i = 0; i < count; i++) { converters[i] = lineConverter; } } public MultiLineConverter(InputConverter[] lineConverters) { this.converters = lineConverters; this.count = lineConverters.length; } @Override public boolean readLine(String data) { if (lineNumber == 0) { input = new Object[count]; } InputConverter converter = converters[lineNumber]; if (!converter.readLine(data)) { input[lineNumber++] = converter.generateObject(); } if (lineNumber >= input.length){ lineNumber = 0; } return lineNumber != 0; } @Override public Object[] generateObject() { return input; } } " B21097,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj_c; /** * * @author kay */ public class Gcj_C { /** * @param args the command line arguments */ public static void main(String[] args) { Arrange app = new Arrange(); app.do_processing(""G:/c_large.txt""); //app.do_arrange(""1111 2222""); // TODO code application logic here } } " B21208,"import java.util.*; import java.io.*; public class RecycledNums { static LinkedList output = new LinkedList(); static int numberOfLines; //Main Method public static void main (String[] args) { //Read in the file parseFile( output ); int[] ans = new int[ numberOfLines ]; //Calculate recycled numbers ListIterator itr = output.listIterator(); int count = 0; //Iterate through all cases, input to calcNums while( itr.hasNext() ) { int result = calcNums( (String[])itr.next() ); //Store result of that case in ans array ans[count] = result; count++; } //printFile(output); //Write out file writeFile( ans ); }//End of Main static int calcNums(String[] input ) { //Let A = first element, let B = the second element String a = input[0]; String b = input[1]; String n = null; String m = null; //If length of A and B == 1 if (a.length() == 1 && b.length() == 1) { return 0; } //initialize the array ranges with numbers starting from A ending at B int count = 0; HashSet set = new HashSet(); ArrayList range = new ArrayList(); int int_a = Integer.parseInt(a); int int_b = Integer.parseInt(b); int temp = int_a; while( temp <= int_b ) { range.add( Integer.toString( temp ) ); temp++; } //loop from i = 0 till i < ranges.size() for (int i = 0; i < range.size(); i++) { n = range.get(i); m = range.get(i); int int_n = Integer.parseInt(n); //let length be the length of string in ranges[i] int length = range.get(i).length(); //loop from j = 0 till j < ranges[i].length for (int j = 0; j < length; j++) { //get the last char from current_m //get the string from 0 to 2nd last char //concatenate both strings together m = m.substring(length -1) + m.substring(0, length - 1); int int_m = Integer.parseInt(m); // A ≤ n < m ≤ B if (int_m <= int_b && int_m > int_n && int_m >= int_a) { //If a valid pair, add pair to HashSet, no duplicates. String key = n + m; set.add(key); } } } return set.size(); } static void parseFile(LinkedList output) { try { BufferedReader in = new BufferedReader(new FileReader( ""input.in"" )); numberOfLines = Integer.parseInt( in.readLine() ); int count = 0; String line; while (count < numberOfLines ) //file reading line by line { line = in.readLine(); //Split each line into array of 2 numbers String[] lines = line.split("" ""); //int[] temp = new int[lines.length]; //temp[0] = Integer.parseInt( lines[0] ); //temp[1] = Integer.parseInt( lines[1] ); //output.add(temp); output.add(lines); count++; } in.close(); }catch( IOException ioException ) {} }//End of parseFile() static void writeFile( int[] ans) { //Write out lines to a file try { BufferedWriter bw = new BufferedWriter(new FileWriter(new File(""output.in""), false)); for(int i = 0 ; i < ans.length; i++) { int num = i + 1; bw.write(""Case #"" + num + "": ""); bw.write( Integer.toString(ans[i])); bw.newLine(); } bw.close(); } catch (Exception e) {} }//End of writeFile() } //End of RecyclesNums Class " B21245,"package test.com; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Stack; public class Qual2012C { public static void main(String[] args) throws Exception { FileInputStream fos = new FileInputStream(""c:/sanker/workspace/input2/C-large.in""); BufferedReader buf = new BufferedReader(new InputStreamReader(fos)); String str = """"; int N0; str = buf.readLine(); N0 = Integer.parseInt(str); for(int cnti=0; cnti resultMap = recycledNumbersInternalCollection(low, hi); long counter = 0; for (Long num : resultMap.keySet()) { Long permSum = resultMap.get(num); if (permSum != null && permSum > 0) { counter += permSum; } } return counter; } Map recycledNumbersInternalCollection(long low, long hi) { // number -> permutations size Map resultMap = new HashMap(1024); long i = hi; while (i >= low) { Set permutations = permute(i, low, hi); resultMap.put(i, (long) permutations.size()); i--; } return resultMap; } Set permute(long number, final long low, final long hi) { if (number < 10) { return Collections.emptySet(); } Set resultSet = new HashSet(); // for input 1204 create a string 12041204 String permBasic = """" + number + """" + number; final int numberSize = permBasic.length() / 2; // start from 1, as we don't want to include original to set of permutations for (int i = 1; i <= numberSize; i++) { String substring = permBasic.substring(i, i + numberSize); if (substring.startsWith(""0"")) { // skip trailing zeroes continue; } Long thePermutation = Long.valueOf(substring); if (thePermutation < number && (thePermutation >= low && thePermutation <= hi)) { resultSet.add(thePermutation); } } return resultSet; } private String readLn(InputStream inputStream, int maxLength) { // utility function to read from stdin, // Provided by Programming-challenges, edit for style only byte line[] = new byte[maxLength]; int length = 0; int input = -1; try { while (length < maxLength) {//Read untill maxlength input = inputStream.read(); if ((input < 0) || (input == '\n')) break; //or untill end of line ninput line[length++] += input; } if ((input < 0) && (length == 0)) return null; // eof return new String(line, 0, length); } catch (IOException e) { return null; } } } " B20571,"/** * */ package me.adrabi.codejam; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * @author Adrabi Abderrahim, z3vil * */ public class P3 { public static void main(String[]$) throws NumberFormatException, IOException { List recycled = new ArrayList(); { BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(""p3""))); int count = Integer.parseInt(reader.readLine()); String line = null; while((line = reader.readLine()) != null) { recycled.add(line); } } int currentLine = 1; for(String line : recycled) { String numbers[] = line.split("" ""); if(numbers.length > 1) { Map tmp = new TreeMap(); int a = Integer.parseInt(numbers[0]), b = Integer.parseInt(numbers[1]), count = 0; for(int index = a ; index <= b; index++) { String array[] = (index+"""").split(""""); if(isSimilare(array)) { continue; } List elements = toList(array); int steps = array.length - 2; while(steps >= 1) { String element = elements.get(elements.size() - 1); elements.remove(elements.size() - 1); elements.add(0, element); steps--; String number = toString(elements); if(number.startsWith(""0"")) { continue; } else if(number.endsWith(""00"")) { continue; } else { int testNumber = Integer.parseInt(number); if( index < testNumber && testNumber <= b ) { if(tmp.containsKey(number)) { tmp.put(number, tmp.get(number) + 1); } else { tmp.put(number, 1); } if(tmp.get(number) < 4) { count++; } } } } } System.out.printf(""Case #%d: %d\n"", currentLine++, count); } else { System.out.printf(""Case #%d: 0\n"", currentLine++); } } } private static boolean isSimilare(String[]array) { String lastElement = array[1]; boolean check = true; for(int start = 2; start < array.length; start++) { if(!lastElement.equals(array[start])) { check = false; break; } lastElement = array[start]; } return check; } private static String toString(List list) { String str = """"; for(String tmp : list) { str += tmp; } return str; } private static List toList(String array[]) { List list = new ArrayList(); for(int start = 1; start < array.length; start++) { list.add(array[start]); } return list; } } " B20822,"package com.google; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class Recycle { public static class Pair { long a; long b; public Pair(long a, long b) { this.a = a; this.b = b; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (a ^ (a >>> 32)); result = prime * result + (int) (b ^ (b >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (a != other.a) return false; if (b != other.b) return false; return true; } } public static void main(String[] args) throws IOException { final Scanner reader = new Scanner(new File(""in.txt"")); final FileWriter writer = new FileWriter(new File(""out.txt"")); final int N = reader.nextInt(); reader.nextLine(); for (int i = 0; i < N; i++) { final long min = reader.nextLong(); final long max = reader.nextLong(); writer.write(String.format(""Case #%d: %d"", (i + 1), findCount(min, max))); if (i < N - 1) { writer.write(""\n""); } } writer.close(); } public static int findCount(final long min, final long max) { Set allPairs = new HashSet(); int resCount = 0; for (long i = min; i <= max; i++) { int [] num = numToArr(i); for (int j = 0; j < num.length - 1; j++) { num = shift(num); final Pair p = new Pair(i, fromArrToNum(num)); if (isValid(num, i, max) && !allPairs.contains(p)) { resCount++; allPairs.add(p); } } } return resCount; } public static int [] shift(int [] num) { final int [] res = new int [num.length]; res[0] = num[num.length - 1]; for (int i = 1; i < res.length; i++) { res[i] = num[i - 1]; } return res; } public static long fromArrToNum(int [] arr) { long a = 0; for (int i : arr) { a = a + i; a = a * 10; } a = a / 10; return a; } public static boolean isValid(int [] num, long base, long max) { if (num[0] == 0) return false; long a = fromArrToNum(num); return base < a && a <= max; } public static boolean consistOfUniqueDigits(int [] num) { final boolean [] arr = new boolean [10]; for (int i : num) { if (arr[i]) return false; arr[i] = true; } return true; } public static int [] numToArr(final long in) { final List list = new ArrayList(); long a = in; while (a > 0) { list.add((int) (a % 10)); a = a / 10; } final int [] res = new int [list.size()]; for (int i = 0; i < list.size(); i++) { res[res.length - i -1] = list.get(i); } return res; } } " B20755,"package fixjava; /** Adapted from http://www.johndcook.com/standard_deviation.html */ public class RunningStats { int n = 0; double oldM, newM, oldS, newS, min, max; public void clear() { n = 0; } public void add(double x) { n++; // See Knuth TAOCP vol 2, 3rd edition, page 232 if (n == 1) { oldM = newM = min = max = x; oldS = 0.0; } else { newM = oldM + (x - oldM) / n; newS = oldS + (x - oldM) * (x - newM); min = Math.min(min, x); max = Math.max(max, x); // set up for next iteration oldM = newM; oldS = newS; } } public int numValues() { return n; } public double mean() { return (n > 0) ? newM : 0.0; } public double variance() { return ((n > 1) ? newS / (n - 1) : 0.0); } public double stdDev() { return Math.sqrt(variance()); } public double min() { return (n > 0) ? min : 0.0; } public double max() { return (n > 0) ? max : 0.0; } } " B20731,"package fixjava; /** * Convenience class for declaring a method inside a method, so as to avoid code duplication without having to declare a new method * in the class. This also keeps functions closer to where they are applied. It's butt-ugly but it's about the best you can do in * Java. */ public interface Lambda2 { public V apply(P param1, Q param2); } " B20602,"import java.io.*; import java.util.Arrays; import java.util.Locale; import java.util.StringTokenizer; public class GCJ2012QualC { static final int MAXB = 2000000; int[] minR = new int[MAXB+1]; int[] count = new int[MAXB+1]; public void run() throws IOException { for (int a = 1; a <= MAXB; a *= 10) { for (int x = a; x < 10*a && x <= MAXB; ++x) { minR[x] = x; int y = x; do { y = y % 10 * a + y / 10; if (y / a != 0 && y < minR[x]) { minR[x] = y; } } while (y != x); } } int T = nextInt(); for (int i = 1; i <= T; ++i) { out.println(""Case #"" + i + "": "" + solve()); } } private int solve() throws IOException { int A = nextInt(); int B = nextInt(); Arrays.fill(count, 0, B+1, 0); for (int i = A; i <= B; ++i) { ++count[minR[i]]; } int ans = 0; for (int i = 0; i <= B; ++i) { ans += count[i] * (count[i] - 1) / 2; } return ans; } public static BufferedReader in; public static PrintStream out; public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); String className = GCJ2012QualC.class.getSimpleName(); char lastChar = className.charAt(className.length() - 1); System.setIn(new FileInputStream(lastChar + "".in"")); System.setOut(new PrintStream(lastChar + "".out"")); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintStream(new BufferedOutputStream(System.out)); new GCJ2012QualC().run(); out.close(); } public static StringTokenizer tokenizer; public static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public static long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } } " B22138,"import java.io.*; public class RecycledNo { public static void main (String arg[]) throws Exception { BufferedReader ob=new BufferedReader (new FileReader(""C-large.in"")); PrintWriter pw=new PrintWriter (""output.txt""); String temp=""""; temp=ob.readLine(); int t=Integer.parseInt(temp); int a=0,b=0; for(int l=1;l<=t;l++) { temp=ob.readLine(); String str=""""; for(int i=0;ik) count++; } } temp=""Case #""+l+"": ""+count; pw.println(temp); } pw.close(); } } " B20859,"import java.util.*; import java.io.*; public class Recycled { public static void main(String[] sArgs)throws IOException { Scanner oScan = new Scanner(new File(""recycled.in"")); PrintWriter out = new PrintWriter(""recycled.out""); int o_0 = oScan.nextInt();oScan.nextLine(); for(int o_o=1;o_o<=o_0;o_o++) { int A = oScan.nextInt(),B=oScan.nextInt(); int count=0,base=0; for(int i=1;i<=A;i*=10)base+=i; for(int i=A;i nums = new ArrayList(); if(i%base==0) { //System.out.println(""same ""+i); continue; } for(int j=1;ji&&rec<=B&&!nums.contains(rec)){count++;nums.add(rec);} } } out.println(""Case #""+o_o+"": ""+count); System.out.println(o_o); } out.close(); } }" B21048,"package it.simone.google.code.jam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class GoogleCodeJamManager { public static void main(String[] args) { // GoogleCodeExercise tm = new Translator(); // GoogleCodeJamManager.execute(""inputFile_Translator.in"",""outputFile_Translator.out"",tm); // GoogleCodeExercise dancer = new Dancer(); // GoogleCodeJamManager.execute(""inputFile_Dancer.in"",""outputFile_Dancer.out"",dancer); GoogleCodeExercise recycled = new RecycledNumber(); GoogleCodeJamManager.execute(""inputFile_Recycled.in"",""outputFile_Recycled.out"",recycled); } public static void execute(String inputFile,String outputFile,GoogleCodeExercise exercise) { BufferedReader br = null; BufferedWriter bw=null; int testNumber=0; try { exercise.initialize(); br = new BufferedReader(new FileReader(inputFile)); bw=new BufferedWriter(new FileWriter(outputFile)); String line = br.readLine(); testNumber=Integer.parseInt(line); line=br.readLine(); int testCounter=1; while (line != null) { System.out.println(""Test"" +testCounter +""/""+testNumber+ ""\t Line="" + line); String translatedLine=exercise.execute(line); bw.write(""Case #""+testCounter+"": ""+translatedLine+""\n""); line=br.readLine(); testCounter++; } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { if (br != null) br.close(); if(bw!=null) bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } " B22135,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; public class ProblemC2 { public boolean checked[] = new boolean[2000000]; public int min, max; public static void main(String [] args) { new ProblemC2(); } public ProblemC2() { try { String [] inputFiles = { ""C-large"" };//,""A-large"" }; BufferedReader in; PrintWriter out; for(int i = 0 ; i < inputFiles.length; i++) { in = new BufferedReader(new FileReader(inputFiles[i])); out = new PrintWriter(new FileWriter(inputFiles[i]+"".out""),true); int numCases = Integer.parseInt(in.readLine()); String [] items = null; for(int j = 0 ; j < numCases; j++) { checked = new boolean[2000000]; items = in.readLine().split(""\\s+""); min = Integer.parseInt(items[0]); max = Integer.parseInt(items[1]); int total = 0; for(int x = min; x <= max; x++) { if(! checked[x]) total+=checkRecycled(x); } out.println(""Case #"" + (j+1) + "": "" + total); } in.close(); out.close(); } } catch(Exception e) { e.printStackTrace(); } } private int checkRecycled(int x) { int matches=1; checked[x]=true; if(x<10) return 0; int numChecks = 0; if(x>=1000000) { numChecks = 6; } else if(x>=100000) { numChecks = 5; } else if(x>=10000) { numChecks = 4; } else if(x>=1000) { numChecks = 3; } else if(x>=100) { numChecks = 2; } else { numChecks = 1; } String xstr=new String(""""+x); for(int i=0; i= min && tmp <= max) matches++; } if(matches == 1) return 0; else if(matches == 2) return 1; else if(matches == 3) return 3; else if(matches == 4) return 6; else if(matches == 5) return 10; else if(matches == 6) return 15; else if(matches == 7) return 21; return 0; } } " B21863,"import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class recycle { static Scanner kb ; public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub PrintWriter out = new PrintWriter(""answerrecycle.txt""); kb = new Scanner(System.in); int testcase = kb.nextInt(); for(int i=0;i mem = new ArrayList(); String number = Integer.toString(i); int s = (int)number.charAt(0)-48; for(int k=1;k=s){ String news = number.substring(k,number.length())+number.substring(0,k); int numbernew = Integer.parseInt(news); if(numbernew<=maxnumber&&(!(numbernew<=i))&&news.length()==number.length()&&!mem.contains(numbernew)){ answer++; //System.out.println(number+""_n>s_""+news); mem.add(numbernew); } } } } return answer; } } " B20393,"package com.googlerese.core; import java.util.HashMap; import java.util.Map; import java.util.Set; import com.googlerese.file.FileRead; import com.googlerese.file.FileWrite; public class NumberRecycler { private static final String inputFileName = ""C:/Documents and Settings/garan14/Desktop/input.txt""; private static final String outputFileName = ""C:/Documents and Settings/garan14/Desktop/out.txt""; private static long divider = 1; public static void main( String[] args ) { NumberRecycler convertor = new NumberRecycler(); Map input = FileRead.getInstance().read( inputFileName ); int testCases = input.size(); Map output = new HashMap( testCases ); for ( int i = 1; i <= testCases; i++ ) { String[] arr = input.get( i ); String outputStr = convertor.convert( Long.parseLong( arr[0] ), Long.parseLong( arr[1] ) ); output.put( i, outputStr ); } System.out.println(""Done""); FileWrite.getInstance().write( outputFileName, output ); } private String convert( final long start, final long end ) { long count = 0; for ( long i = start; i <= end; i++ ) { if ( i > 0 && i < 10 ) { divider = 1; } else if ( i > 9 && i < 100 ) { divider = 10; } else if ( i > 99 && i < 1000 ) { divider = 100; } else if ( i > 999 & i < 10000 ) { divider = 1000; } else if ( i > 9999 & i < 100000 ) { divider = 10000; } else if ( i > 99999 & i < 1000000 ) { divider = 100000; } else if ( i > 999999 & i <= 2000000 ) { divider = 1000000; } long num = i; do { long rem = num % 10; num = num / 10; num = rem * divider + num; if ( num > i && num <= end ) { count++; } } while ( i != num ); } return """" + count; } } " B22022,"import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class rec { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int c = 1; c <= t; c++) { System.out.println(""Case #"" + c + "": "" + solve(sc)); } } static void debug(Object... objects) { System.out.println(Arrays.deepToString(objects)); } static final int po[]={1,10,100,1000,10000,100000,1000000,10000000}; public static String solve(Scanner sc) { int A=sc.nextInt(); int B=sc.nextInt(); Set

s = new HashSet

(); int N = Integer.toString(A).length(); for(int i=A;i<=B;i++) { for(int k=1;k> uniq = new HashMap>(); for (int i = lowerB; i <= upperB; i++) { String num = Integer.toString(i); // System.out.println(num + "" "" + num.length()); for (int j = 1; j <= num.length(); j++) { String numA = num.substring(j, num.length()) + num.substring(0, j); // String numB = new StringBuffer(numA).reverse().toString(); // mirror += (lowerB <= Integer.parseInt(numA) && // Integer.parseInt(numB)<= upperB ) ? 1 : 0; // mirror += (lowerB <= Integer.parseInt(numA) && Integer.parseInt(numA)< Integer.parseInt(numB) // && Integer.parseInt(numB) <= upperB) ? 1 : 0; if(lowerB <= Integer.parseInt(num) && Integer.parseInt(num) < Integer.parseInt(numA) && Integer.parseInt(numA) <= upperB) { // System.out.println(numA + "" "" + num); if(uniq.containsKey(Integer.parseInt(num))) { List some = uniq.get(Integer.parseInt(num)); if(some.contains(Integer.parseInt(numA))) { // System.out.println(""GOTnum="" + num); // System.out.println(""GOT YOU"" + numA); mirrorAdvised--; } some.add(Integer.parseInt(numA)); mirrorAdvised++; } else { List x = new ArrayList(); x.add(Integer.parseInt(numA)); uniq.put(Integer.parseInt(num), x); mirrorAdvised++; } mirror++; } } } // Set xa = new TreeSet(); // for(Map.Entry> a : uniq.entrySet()) // { // if(a.getValue().size()>0) // { //// System.out.println(a.getKey()-a.getValue().get(0)); // xa.add(a.getKey()); // System.out.println(a.getKey() + "" "" + a.getValue()); // } // } // System.out.println(xa.size()); return mirrorAdvised; } public static void readFile() { try { BufferedReader in = new BufferedReader(new FileReader( ""C://dev//gcj//C-small-attempt0.in"")); String str; boolean first = true; int num = 0; int k = 0; List testCases = new ArrayList(); while ((str = in.readLine()) != null) { if (first) { num = Integer.parseInt(str); first = false; } else { String[] input = str.split("" ""); String A = input[0]; String B = input[1]; Integer result = mirrors(A, B); System.out.println(""Case #"" + (++k) + "": "" + result); } } in.close(); } catch (IOException e) { } } public static void main(String args[]) { readFile(); } } " B21180," public class kickClass { public static void main(String[] args){ //testGraph.run(); //testCollection.run(); solutionRunner t1 = new solutionRunner(); } } " B21962," import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.util.*; import javax.sql.rowset.Joinable; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.lang.Integer.*; import static java.lang.Character.*; public class C { static class Sol implements Runnable{ boolean started = false; Scanner scan; int caseN; int a,b; int intLine(){ return parseInt(scan.nextLine()); } int res = 0; void readInput() { a = scan.nextInt(); b = scan.nextInt(); } public void run(){ int[]u = new int[20]; for(int i=a;i<=b;i++){ String s = """"+i; int p =0; for(int j = 1;jb)ok = false; for(int k=0;k dic = new HashMap<>(); protected BufferedReader reader; protected BufferedWriter writer; protected Scanner in; public static BufferedReader openReader(String inputFile) throws IOException { FileInputStream fis = new FileInputStream(new File(inputFile).getAbsoluteFile()); return new BufferedReader( new InputStreamReader(fis, ""UTF-8"") ); } public static BufferedWriter openWriter(String outputFile) throws IOException { File file = new File(outputFile); FileOutputStream fos = new FileOutputStream(file.getAbsoluteFile()); return new BufferedWriter( new OutputStreamWriter(fos, ""UTF-8"") ); } public RecycledNumbers(String fileName) throws IOException { init(fileName); } protected void init(String fileName) throws IOException { String in = fileName; String out = in.replace("".in"", "".out""); reader = openReader(in); this.in = new Scanner(reader); writer = openWriter(out); } public void close() { try { in.close(); } catch (Exception e) { // ignore } try { if (reader != null) { reader.close(); } } catch (IOException e) { //ignore } try { if (writer != null) { writer.close(); } } catch (IOException e) { //ignore } } public void write(int caseNumber) throws IOException { write(""Case #"" + caseNumber + "":""); } public void write(int caseNumber, String val) throws IOException { write(""Case #"" + caseNumber + "": "" + val); } public void write(String val) throws IOException { writer.write(val + ""\n""); writer.flush(); } public void execute() { try { long startProblem = System.currentTimeMillis(); int T = in.nextInt(); System.out.println(""Tests:"" + T); for (int i = 1; i <= T; i++) { long startCase = System.currentTimeMillis(); String result = calculate(in.nextInt(), in.nextInt()); System.out.println(""case:"" + i + "" took: "" + (System.currentTimeMillis() - startCase) + "", ms""); write(i, """" + result); } System.out.println(""Took: "" + (System.currentTimeMillis() - startProblem) + "", ms""); } catch (Exception ex) { ex.printStackTrace(); } finally { close(); } } private String calculate(int A, int B) { long count = 0; for (int i = A; i <= B; i++) { String s = Integer.toString(i); Set set = new HashSet<>(); for (int k = 1; k < s.length(); k++) { String newStr = s.substring(k) + s.substring(0, k); int val = Integer.parseInt(newStr); if (val > i && val <= B) { set.add(val); } } count += set.size(); } return """" + count; } public static void main(String[] args) throws Exception { // String fileName = ""test.in""; // String fileName = ""B-small-attempt2.in""; // String fileName = ""B-large.in""; String fileName = ""C-large.in""; RecycledNumbers problem = new RecycledNumbers(fileName); problem.execute(); } } " B21933,"package com.problemC; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; class RecyclePair { int n, m; public RecyclePair(int a, int b) { assert (a < b); n = a; m = b; } @Override public boolean equals(Object obj) { if (obj instanceof RecyclePair) { RecyclePair o = (RecyclePair) obj; if (this.n == o.n && this.m == o.m) return true; } return false; } @Override public int hashCode() { return n * m; } } public class RecycledNumber { private static int A = 1111; private static int B = 2222; public static int count = 0; static Set pairs = null; public static void main(String[] args) { String[] s; BufferedReader br = null; try { br = new BufferedReader(new FileReader( ""src/com/problemC/C-large.in"")); // br = new BufferedReader( // new FileReader(""src/com/problemC/input.txt"")); int caseNo = 1; int T = Integer.parseInt(br.readLine()); while (caseNo <= T) { count = 0; pairs = new HashSet(); s = br.readLine().split("" ""); A = Integer.parseInt(s[0]); B = Integer.parseInt(s[1]); for (int i = A; i < B; i++) { rotate(i); } System.out.println(""Case #"" + caseNo++ + "": "" + pairs.size()); } } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } } catch (IOException e) { e.printStackTrace(); } } } private static void rotate(int num) { int l = (num + """").length(), l2; int toCut = 1; int original = num, newNum; String s = num + """", firstPart, secondPart; // if(num%10==0) return; // System.out.println(""""); // System.out.println(""Original Number in question: "" + s); for (toCut = 0; toCut <= l; toCut++) { firstPart = s.substring(0, l - toCut); secondPart = s.substring(l - toCut); newNum = Integer.parseInt(secondPart + firstPart); // System.out.println(firstPart + "" "" + secondPart + "": "" + newNum); l2 = (newNum + """").length(); if (l == l2 && (original < newNum && newNum <= B)) { RecyclePair rp = new RecyclePair(original, newNum); if (!pairs.add(rp)) { // System.out.println(""NO ***********************************************""); } // System.out.println(""YES : "" + original + "" "" + // newNum+"" ""+count); // System.out.println(""""); count++; } } } } " B21807,"import java.util.ArrayList; import java.util.List; public class JamUtil { static int[] parseIntList(String str, int count) { int[] res = new int[count]; String[] parts = str.split("" ""); for (int i = 0; i < parts.length; i++) { String part = parts[i]; res[i] = Integer.parseInt(part); } return res; } static List parseIntList(String str) { ArrayList res = new ArrayList(); String[] parts = str.split("" ""); for (int i = 0; i < parts.length; i++) { String part = parts[i]; res.add(Integer.parseInt(part)); } return res; } static String printTable(T[][] t) { StringBuilder res = new StringBuilder(); for (int i = 0; i < t.length; i++) { T[] ts = t[i]; for (int j = 0; j < ts.length; j++) { T t1 = ts[j]; res.append(t1+ "" ""); } res.append(""\n""); } return res.toString(); } } " B20279,"import java.util.*; import java.io.*; import java.math.*; import java.awt.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Double.parseDouble; import static java.lang.Long.parseLong; import static java.lang.System.*; import static java.util.Arrays.*; import static java.util.Collection.*; public class C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(in)); int T = parseInt(br.readLine()); for(int t = 0; t++ < T; ) { String[] line = br.readLine().split("" ""); int A = parseInt(line[0]), B = parseInt(line[1]); long[] V = new long[B - A + 1], S = new long[B - A + 1]; int order = 1; S[0] = V[0] = 0; while(order < B) order *= 10; for(int i = A + 1; i <= B; i++) { int index = -1; for(int j = 10; j <= i; j *= 10) { int count = i / j + (i % j) * (order / j); if(index < count && count < i) index = count; } V[i - A] = index >= A ? V[index - A] + 1 : 0; S[i - A] = V[i - A] + S[i - A - 1]; } out.println(""Case #"" + t +"": "" + S[B-A]) ; } } } " B20629,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; public class ProbB { /** * @param args * @throws IOException */ public static HashMap map = new HashMap(); public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader inputStream; PrintWriter outputStream; try { inputStream = new BufferedReader(new FileReader(""X:\\GCJ\\input.txt"")); outputStream = new PrintWriter(new BufferedWriter(new FileWriter(""X:\\GCJ\\output.txt""))); int n=Integer.parseInt(inputStream.readLine()),z=0; while(n>0) { n--;z++;c=0;map.clear(); String s=inputStream.readLine(); int spc= s.indexOf(' '); int r=0,A=Integer.parseInt(s.substring(0,spc)),B=Integer.parseInt(s.substring(spc+1)); for (int i = A; i < B; i++) { if(map.containsKey(i))continue; func(i,A,B,digits(A)); } outputStream.println(""Case #""+z+"": ""+c); System.out.println(""Case #""+z+"": ""+c); } outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(""File not found.""); e.printStackTrace(); } } public static int digits(int a) { int z=0; while(a!=0){ a/=10;z++; } return z; } public static int c=0; public static void func(int a,int A,int B, int n){ int a2=0; int o=a; for (int j = 1; j < n; j++) { int k=a%10; for (int i = 0; i < n-1; i++) { k*=10; } a2= k+a/10; if(a2>o && a2<=B){ map.put(o,a2);c++; // System.out.println(c+"":""+o+"",""+a2); } if(a2>a && a>o && a2<=B){ map.put(a,a2);c++; // System.out.println(c+"":""+a+"",""+a2); } a=a2; } } } " B21992,"package codejam.common; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author chenling */ public class FileUtil { public static List readLines(String fileName) { List result = new ArrayList(); FileReader in = null; try { in = new FileReader(fileName); BufferedReader reader = new BufferedReader(in); String line = null; while ((line = reader.readLine()) != null) { if (line.trim().length() > 0) { result.add(line); } } } catch (Exception ex) { throw new RuntimeException(ex); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null, ex); } } return result; } public static void writeLines(String fileName, List lines) { FileWriter writer = null; try { writer = new FileWriter(fileName); PrintWriter printWriter = new PrintWriter(writer); for (String line : lines) { printWriter.println(line); } } catch (IOException ex) { Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null, ex); } finally { if (writer != null) { try { writer.close(); } catch (IOException ex) { Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null, ex); } } } } } " B20552,"import java.util.HashSet; import java.util.Set; public class TestCase { private int totalDigit = -1; private int max; private int min; public TestCase(String s) { String[] results = s.split("" ""); totalDigit = results[0].length(); min = Integer.parseInt(results[0]); max = Integer.parseInt(results[1]); } public int solve() { Set total = new HashSet(); for (int i = min; i <= max; i++) { for (int j = 1; j < totalDigit; j++) { Pair p = getPair(i, j); if (p != null) { //System.out.printf(""Adding pair(%d, %d), %b\n"", p.getFirst(), p.getSecond(), total.add(p)); total.add(p); } } } return total.size(); } private Pair getPair(int number, int digit) { String source = String.valueOf(number); String target; Pair result = null; String first; String second; // if (digit == 1) { // first = source.substring(totalDigit - digit); // second = source.substring(0, digit); //// target = source.substring(0, totalDigit) + source.substring(totalDigit - digit); // } else if (digit == 2) { first = source.substring(totalDigit - digit); second = source.substring(0, totalDigit - digit); // } target = first + second; int targetNumber = Integer.parseInt(target); if (targetNumber >= min && targetNumber <= max & targetNumber != number) { result = new Pair(number, targetNumber); } return result; } } " B20031,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner input; try { File in = new File(args[0]); input = new Scanner(in); int testcaseSize = Integer.parseInt(input.nextLine()); int testcaseNo = 1; String output = """"; while ((input.hasNext()) && testcaseNo <= testcaseSize) { //read input String s = input.nextLine(); //solve problem String result = solve(s); //record formatted result String outputLine = String.format(""Case #%d: %s\n"", testcaseNo, result); //append output output += outputLine; testcaseNo++; } input.close(); //print output System.out.print(output); // write output file FileWriter writer = new FileWriter(in.getName() +"".out""); writer.write(output); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static String solve (String text){ String result = """"; int A = Integer.parseInt(text.substring(0,text.indexOf("" ""))); int B = Integer.parseInt(text.substring(text.indexOf("" "")+1, text.length())); HashSet set = new HashSet(); int digits = text.indexOf("" ""); ArrayList list1 = new ArrayList(); ArrayList list2 = new ArrayList(); for (int n=A; n<=B; n++){ if (!set.contains(n)) { String nString = Integer.toString(n); HashSet group = new HashSet(); group.add(n); for (int j=1; j=A && m<=B && m!=n) { group.add(m); } } for (int i : group) set.add(i); Object[] groupArray = group.toArray(); for (int i=0; i set = new HashSet(); for (int N = A; N < B; N++) { String s = String.valueOf(N); for (int i = 1; i < s.length(); i++) { String s1 = s.substring(0, i); String s2 = s.substring(i, s.length()); int M = Integer.parseInt(s2+s1); if ((N < M) && (M <= B)) { long key = N; key <<= 32; key += M; set.add(key); } } } String result = ""Case #"" + testcase + "": "" + set.size(); output(result); } input.close(); output.close(); } catch (Exception e) { e.printStackTrace(); } } public static int getInt(String line, int index) {return Integer.parseInt(getString(line, index));} public static long getLong(String line, int index) {return Long.parseLong(getString(line, index));} public static double getDouble(String line, int index) {return Double.parseDouble(getString(line, index));} public static String getString(String line, int index) { line = line.trim(); while (index > 0) {line = line.substring(line.indexOf(' ') + 1); index--;} if ((-1) == line.indexOf(' ')) {return line;} else {return line.substring(0, line.indexOf(' '));} } public static int[] getIntArray(String line) { String[] strings = getStringArray(line); int[] numbers = new int[strings.length]; for (int i = 0; i < strings.length; i++) {numbers[i] = Integer.parseInt(strings[i]);} return numbers; } public static long[] getLongArray(String line) { String[] strings = getStringArray(line); long[] numbers = new long[strings.length]; for (int i = 0; i < strings.length; i++) {numbers[i] = Long.parseLong(strings[i]);} return numbers; } public static double[] getDoubleArray(String line) { String[] strings = getStringArray(line); double[] numbers = new double[strings.length]; for (int i = 0; i < strings.length; i++) {numbers[i] = Double.parseDouble(strings[i]);} return numbers; } public static String[] getStringArray(String line) {return line.trim().split(""(\\s)+"", 0);} public static int[] getIntArray(String line, int begin, int end) { String[] strings = getStringArray(line, begin, end); int[] numbers = new int[end - begin]; for (int i = begin; i < end; i++) {numbers[i - begin] = Integer.parseInt(strings[i - begin]);} return numbers; } public static long[] getLongArray(String line, int begin, int end) { String[] strings = getStringArray(line, begin, end); long[] numbers = new long[end - begin]; for (int i = begin; i < end; i++) {numbers[i - begin] = Long.parseLong(strings[i - begin]);} return numbers; } public static double[] getDoubleArray(String line, int begin, int end) { String[] strings = getStringArray(line, begin, end); double[] numbers = new double[end - begin]; for (int i = begin; i < end; i++) {numbers[i - begin] = Double.parseDouble(strings[i - begin]);} return numbers; } public static String[] getStringArray(String line, int begin, int end) { String[] lines = line.trim().split(""(\\s)+"", 0); String[] results = new String[end - begin]; for (int i = begin; i < end; i++) {results[i - begin] = lines[i];} return results; } public static char[][] getCharMatrix(BufferedReader input) throws Exception { String line = input.readLine(); int R = getInt(line, 0); int C = getInt(line, 1); char[][] matrix = new char[R][C]; for (int i = 0; i < R; i++) { line = input.readLine(); for (int j = 0; j < C; j++) {matrix[i][j] = line.charAt(j);} } return matrix; } public static int[][] getIntMatrix(BufferedReader input) throws Exception { String line = input.readLine(); int R = getInt(line, 0); int C = getInt(line, 1); int[][] matrix = new int[R][C]; for (int i = 0; i < R; i++) { line = input.readLine(); for (int j = 0; j < C; j++) {matrix[i][j] = getInt(line, j);} } return matrix; } public static boolean[][] newBooleanMatrix(int R, int C, boolean value) { boolean[][] matrix = new boolean[R][C]; for (int i = 0; i < R; i++) for(int j = 0; j < C; j++) {matrix[i][j] = value;} return matrix; } public static char[][] newCharMatrix(int R, int C, char value) { char[][] matrix = new char[R][C]; for (int i = 0; i < R; i++) for(int j = 0; j < C; j++) {matrix[i][j] = value;} return matrix; } public static int[][] newIntMatrix(int R, int C, int value) { int[][] matrix = new int[R][C]; for (int i = 0; i < R; i++) for(int j = 0; j < C; j++) {matrix[i][j] = value;} return matrix; } public static long[][] newLongMatrix(int R, int C, long value) { long[][] matrix = new long[R][C]; for (int i = 0; i < R; i++) for(int j = 0; j < C; j++) {matrix[i][j] = value;} return matrix; } public static double[][] newDoubleMatrix(int R, int C, double value) { double[][] matrix = new double[R][C]; for (int i = 0; i < R; i++) for(int j = 0; j < C; j++) {matrix[i][j] = value;} return matrix; } public static void output(String s) throws Exception { if (ECHO_ON) {System.out.println(s);} output.write(s); output.newLine(); } public static String toKey(boolean[] array) { StringBuffer buffer = new StringBuffer(array.length + "",""); for (int i = 0; i < array.length / 16; i++) { char c = 0; for (int j = 0; j < 16; j++) { c <<= 1; if (array[i * 16 + j]) {c += 1;} } buffer.append(c + """"); } char c = 0; for (int j = 0; j < (array.length % 16); j++) { c <<= 1; if (array[(array.length / 16) * 16 + j]) {c += 1;} } buffer.append(c + """"); return buffer.toString(); } public static String toKey(int[] array, int bit) { StringBuffer buffer = new StringBuffer(array.length + "",""); if (bit > 16) { for (int i = 0; i < array.length; i++) { char c1 = (char)(array[i] >> 16); char c2 = (char)(array[i] & 0xFFFF); buffer.append("""" + c1 + c2); } } else { int n = 16 / bit; for (int i = 0; i < array.length / n; i++) { char c = 0; for (int j = 0; j < n; j++) { c <<= bit; c += array[i * n + j]; } buffer.append(c + """"); } char c = 0; for (int j = 0; j < (array.length % n); j++) { c <<= bit; c += array[(array.length / n) * n + j]; } buffer.append(c + """"); } return buffer.toString(); } public static void debug(String s) {if (DEBUG_ON) {System.out.println(s);}} public static void debug(String s0, double l0) {if (DEBUG_ON) {System.out.println(s0+"" = ""+l0);}} public static void debug(String s0, double l0, String s1, double l1) {if (DEBUG_ON) {System.out.println(s0+"" = ""+l0+""; ""+s1+"" = ""+l1);}} public static void debug(String s0, double l0, String s1, double l1, String s2, double l2) {if (DEBUG_ON) { System.out.println(s0+"" = ""+l0+""; ""+s1+"" = ""+l1+""; ""+s2+"" = ""+l2);}} public static void debug(String s0, double l0, String s1, double l1, String s2, double l2, String s3, double l3) {if (DEBUG_ON) {System.out.println(s0+"" = ""+l0+""; ""+s1+"" = ""+l1+""; ""+s2+"" = ""+l2+""; ""+s3+"" = ""+l3);}} public static void debug(String s0, double l0, String s1, double l1, String s2, double l2, String s3, double l3, String s4, double l4) {if (DEBUG_ON) {System.out.println(s0+"" = ""+l0+""; ""+s1+"" = ""+l1+""; ""+s2+"" = ""+l2+""; ""+s3+"" = ""+l3+""; ""+s4+"" = ""+l4);}} public static void debug(boolean[] array) {if (DEBUG_ON) {debug(array, "" "");}} public static void debug(boolean[] array, String separator) { if (DEBUG_ON) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < array.length - 1; i++) {buffer.append((array[i] == true ? ""1"" : ""0"") + separator);} buffer.append((array[array.length - 1] == true) ? ""1"" : ""0""); System.out.println(buffer.toString()); } } public static void debug(boolean[][] array) {if (DEBUG_ON) {debug(array, "" "");}} public static void debug(boolean[][] array, String separator) {if (DEBUG_ON) {for (int i = 0; i < array.length; i++) {debug(array[i], separator);}}} public static void debug(char[] array) {if (DEBUG_ON) {debug(array, "" "");}} public static void debug(char[] array, String separator) { if (DEBUG_ON) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < array.length - 1; i++) {buffer.append(array[i] + separator);} buffer.append(array[array.length - 1]); System.out.println(buffer.toString()); } } public static void debug(char[][] array) {if (DEBUG_ON) {debug(array, "" "");}} public static void debug(char[][] array, String separator) {if (DEBUG_ON) {for (int i = 0; i < array.length; i++) {debug(array[i], separator);}}} public static void debug(int[] array) {if (DEBUG_ON) {debug(array, "" "");}} public static void debug(int[] array, String separator) { if (DEBUG_ON) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < array.length - 1; i++) {buffer.append(array[i] + separator);} buffer.append(array[array.length - 1]); System.out.println(buffer.toString()); } } public static void debug(int[][] array) {if (DEBUG_ON) {debug(array, "" "");}} public static void debug(int[][] array, String separator) {if (DEBUG_ON) {for (int i = 0; i < array.length; i++) {debug(array[i], separator);}}} } " B21760,"import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class mainclass { public static void main(String args[]) throws IOException { int cases; int a; int b; int flag; int counter; int[] data; int temp = 0; int count = 0; int mc; FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); FileReader isr = new FileReader(args[0]); Scanner src = new Scanner(isr); cases = src.nextInt(); data = new int[2000000]; for(int i=0;i<2000000;i++) data[i] = 0; for(int j=0;j=a&&temp<=b&&data[temp]==0&&mc==numdig(temp)) { // System.out.print("" ""+temp); data[temp] = 1; count++; } temp = recnum(temp,mc); } flag = flag+count; } // System.out.println("" ""+count); if(count>1) counter = counter + (count*(count-1))/2; } // System.out.println("" ""+flag); try{ out.write(""Case #""+(j+1)+"": ""+counter); out.write(""\r\n""); }catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } out.close(); } static int numdig(int n) { int count = 1; while(n/10>0) { count++; n = n/10; } return count; } static int recnum(int n,int p) { int pow = 1; int num; num = p-1; for(int i=0;i setRecycled = new HashSet(); if (len > 1) { for (int i = start; i <= end; i++) { String numStr = String.valueOf(i); char[] numChar = numStr.toCharArray(); HashSet set = new HashSet(); for (char ch : numChar) { set.add(ch); } if (set.size() == 1) { continue; } int origNum = Integer.parseInt(numStr); for (int j = 0; j < len - 1; j++) { // System.out.println(""numStr :: "" + numStr); numStr = rotateNumber(numStr, len); // System.out.println(""after rotating numStr :: "" // + numStr); int num = Integer.parseInt(numStr); if (num != origNum && num >= start && num <= end) { // System.out.println(""Pair :: ("" + origNum // + "" , "" + // numStr + "")""); // System.out.println(""recycled no found... adding "" // + // (origNum < num ? """" + origNum + num : """" // + num + // origNum) + "" to set""); setRecycled.add(origNum < num ? """" + origNum + "","" + num : """" + num + "","" + origNum); // System.out.println(""size :: "" + // setRecycled.size()); } } } } System.out.println(setRecycled.size()); bw.write(""Case #"" + (k + 1) + "": "" + setRecycled.size() + ""\n""); // TreeSet set = new TreeSet(setRecycled); // System.out.println(set); } } } catch (Exception e) { e.printStackTrace(); } try { if (br != null) { br.close(); } if (bw != null) { bw.flush(); bw.close(); } } catch (Exception e) { e.printStackTrace(); } } public static String rotateNumber(String num, int len) { return num.charAt(len - 1) + num.substring(0, len - 1); } } " B20055,"import java.io.*; public class CodeJamQual3b { /** * @param args */ public static void main(String[] args) { try{ // Open the file that is the first // command line parameter File file = new File(""C-Large.in""); FileInputStream fstream = new FileInputStream(""C-Large.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; FileWriter fout = new FileWriter(""out3Large.txt""); BufferedWriter outprint = new BufferedWriter(fout); //Read File Line By Line int i = 0; while (((strLine = br.readLine()) != null)) { if (i != 0 && i !=1111) { String[] stringArray = strLine.split("" ""); int bot = Integer.parseInt(stringArray[0]); int top = Integer.parseInt(stringArray[1]); int counter = 0; int len = stringArray[0].length(); //top for (int j = bot; j < top+1; j++) { counter = counter + count(j,top,bot,len); //System.out.println(""j = "" + j + "" "" + count(j,top,bot)); } //System.out.println (counter); outprint.write(""Case #"" + i + "": "" + counter); outprint.newLine(); System.out.println(""Case #"" + i + "": "" + counter); } i++; } //Close the input stream in.close(); //Close the output stream outprint.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public static int count(int j, int top, int bot, int len){ char[] cArray = Integer.toString(j).toCharArray(); int out = 0; int[] log = new int[len]; for (int k = 0; k < len-1; k++) { cArray = shift(cArray); boolean flag = true; //System.out.println(new String(cArray)); int recycled = Integer.parseInt(new String(cArray)); if ((j bot) && (recycled <= top)){ //System.out.println(""("" + j + "" , "" + recycled + "")"" + "" [ "" + bot + "" |"" + top + "" ] ""); for (int in = 0; in < len; in++){ if (recycled == log[in]){ flag = false; //System.out.println(""REPEAT"" + recycled); break; } } if (flag == true){ log[k] = recycled; //System.out.println(""("" + j + "" , "" + recycled + "")"" + "" [ "" + bot + "" |"" + top + "" ] ""); out += 1; } } } return out; } public static char[] shift(char[] cArray) { char[] nArray = new char[cArray.length]; nArray[0] = cArray[cArray.length-1]; for (int d = 1; d < cArray.length; d++){ nArray[d] = cArray[d-1]; } return nArray; } } " B22180,"import java.util.HashSet; import java.util.Scanner; public class c { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new c().go(); } private void go() { Scanner in=new Scanner(System.in); int numc=in.nextInt(); for(int cnum=1;cnum<=numc;cnum++){ int a=in.nextInt(),b=in.nextInt(),ans=0; for(int n=a;n<=b;n++){ String ns=""""+n; HashSet temp=new HashSet(); for(int i=0;in&&m<=b&&!temp.contains(m)){ ans++; temp.add(m); } } } System.out.printf(""Case #%d: %d\n"", cnum,ans); } } } " B20774,"package recycled; import java.util.List; import java.util.Set; import util.ListFactory; import util.SetFactory; import file.Input; import file.Output; public class Recycled { public void start() { List inputLines = Input.getLines(); if (inputLines.size() > 0) { List outputLines = ListFactory.newArrayListInstance(); int t = Integer.parseInt(inputLines.get(0)); for (int i = 1; i <= t; i++) { String[] parts = inputLines.get(i).split("" ""); int a = Integer.parseInt(parts[0]); int b = Integer.parseInt(parts[1]); outputLines.add(""Case #"" + i + "": "" + getNumber(a, b)); } Output.writeLines(outputLines); } } private int getNumber(int a, int b) { Set set = SetFactory.newHashSetInstance(); if (a <= b) { for (int n = a; n <= b; n++) { int length = getLength(n); for (int i = 0; i < length - 1; i++) { int m = moveRight(n, i + 1); if (n < m && m <= b) { set.add(new Pair(n, m)); } } } } return set.size(); } private int getLength(int number) { int length = 0; if (number >= 0 && number <= 9) { length = 1; } else if (number >= 10 && number <= 99) { length = 2; } else if (number >= 100 && number <= 999) { length = 3; } else if (number >= 1000 && number <= 9999) { length = 4; } else if (number >= 10000 && number <= 99999) { length = 5; } return length; } private int moveRight(int n, int times) { String number = String.valueOf(n); for (int i = 0; i < times; i++) { int length = number.length(); number = number.substring(length - 1, length) + number.substring(0, length - 1); } return Integer.parseInt(number); } public static void main(String[] args) { new Recycled().start(); } } " B20330,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class Problem2 { public static void main (String[] args) throws IOException { File file = new File(""input1.txt""); Scanner scan = null; try { scan = new Scanner(file); } catch (FileNotFoundException e) { e.printStackTrace(); } FileWriter fstream = null; try { fstream = new FileWriter(""output.txt""); } catch (IOException e) { e.printStackTrace(); } BufferedWriter out = new BufferedWriter(fstream); int lineNumber; lineNumber = Integer.parseInt(scan.nextLine()); for (int i = 0; i < lineNumber; i++) { Scanner lineScan = new Scanner(scan.nextLine()); out.write(""Case #"" + (i + 1) + "": ""); int a = lineScan.nextInt(); int b = lineScan.nextInt(); int total = 0; ArrayList prev = new ArrayList(); for (int j = a; j <= b; j++) { String curr = String.valueOf(j); for (int k = 1; k < curr.length(); k++) { String second = curr.substring(k); String first = curr.substring(0, k); String afterStr = second + """" + first; int after = Integer.parseInt(afterStr); if (after > j && after <= b) { if (!prev.contains(after)) { total++; prev.add(after); } } } prev.clear(); } out.write(total + "" \n""); } out.close(); } } " B20129,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String[] args) { Scanner sc = null; PrintWriter fout = null; int t = 0; try { sc = new Scanner(new File(args[0])); fout = new PrintWriter(new BufferedWriter(new FileWriter(""result.txt""))); t = sc.nextInt(); } catch(Exception e) { System.out.println(e); } for( int i = 0; i < t; i++ ) { int a = sc.nextInt(); int b = sc.nextInt(); boolean[] memo = new boolean[b+1]; int digit = 1; while( digit * 10 <= a ) { digit *= 10; } long ret = 0; for( int j = a; j <= b; j++ ) { if( memo[j] ) continue; if( digit * 10 <= j ) { digit *= 10; } int tmp = j, dr = 1; do { int aa = tmp % 10; tmp = ( tmp / 10 ) + digit * aa; if( tmp > j && tmp <= b ) {memo[tmp] = true; ret += dr; dr++; } } while( tmp != j ); } // System.out.println(""Case #"" + (i+1) + "": "" + ret); fout.println(""Case #"" + (i+1) + "": "" + ret); } fout.close(); sc.close(); } } " B20736,"package fixjava; import java.util.concurrent.Callable; import java.util.concurrent.Future; import fixjava.ParallelWorkQueue.CallableFactory; public class ArrayStats { public final double[][] data; public final int n, k; private double[][] centered; private double[] mean; private double[][] cov; private double[] stddev = null; private double[][] corr = null; /** Calculate covariance matrix */ public ArrayStats(double[][] data) { if (data == null || data.length < 2 || data[0].length < 2) throw new IllegalArgumentException(""Invalid data""); this.data = data; this.n = data.length; this.k = data[0].length; } /** Compute mean for each dimension */ public double[] mean() { if (mean == null) { mean = new double[k]; for (int dim = 0; dim < k; dim++) { double tot = 0; for (int pt = 0; pt < n; pt++) tot += data[pt][dim]; mean[dim] = tot / n; } } return mean; } /** Compute stddev for each dimension */ public double[] stddev() { if (stddev == null) { // Make sure means are computed mean(); stddev = new double[k]; for (int dim = 0; dim < k; dim++) { for (int pt = 0; pt < n; pt++) { double diff = data[pt][dim] - mean[dim]; stddev[dim] += diff * diff; } stddev[dim] = Math.sqrt(stddev[dim] / n); } } return stddev; } /** Re-center data by subtracting mean from each dimension */ public double[][] centered() { if (centered == null) { // Make sure means are computed mean(); centered = new double[n][k]; for (int pt = 0; pt < n; pt++) for (int dim = 0; dim < k; dim++) centered[pt][dim] = data[pt][dim] - mean[dim]; } return centered; } /** Compute covariance matrix */ public double[][] cov() { if (cov == null) { // Make sure centered version of data is computed centered(); // Work on transposed array for cache coherence final double[][] centeredT = ArrayUtils.transpose(centered); cov = new double[k][k]; try { //final DecimalFormat formatPercent1dp = new DecimalFormat(""0.0%""); for (Future res : new ParallelWorkQueue(/* numThreads = */25, ParallelWorkQueue.makeIntRangeIterable(k), new CallableFactory() { //IntegerMutable counter = new IntegerMutable(); @Override public Callable newInstance(final Integer ii) { return new Callable() { int dim1 = ii.intValue(); double[][] centeredTLocal = centeredT; double[][] covLocal = cov; @Override public Void call() { for (int dim2 = dim1; dim2 < k; dim2++) { double numer = 0.0; for (int pt = 0; pt < n; pt++) numer += centeredTLocal[dim1][pt] * centeredTLocal[dim2][pt]; int denom = n - 1; covLocal[dim1][dim2] = covLocal[dim2][dim1] = denom == 0 ? 0 : numer / denom; } // int count = counter.increment(); // if (count % 10 == 0) // System.out.println(formatPercent1dp.format((count / (float) (k - 1)))); return null; } }; } })) // Barricade res.get(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } return cov; } /** Compute correlation matrix */ public double[][] corr() { if (corr == null) { // Make sure per-dim stddevs and covariance matrix are computed stddev(); cov(); corr = new double[k][k]; for (int dim1 = 0; dim1 < k; dim1++) { for (int dim2 = dim1; dim2 < k; dim2++) { double prod = stddev[dim1] * stddev[dim2]; corr[dim1][dim2] = corr[dim2][dim1] = prod == 0.0 ? 0.0 : cov[dim1][dim2] / prod; } } } return corr; } } " B20812,"import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream(new File(""in.txt"")); FileOutputStream fos = new FileOutputStream(new File(""out.txt"")); Scanner sc = new Scanner(fis); PrintWriter out = new PrintWriter(fos); int cases = sc.nextInt(); for(int cs = 1; cs <= cases; cs++) { int begin = sc.nextInt(); int end = sc.nextInt(); int cnt = 0; for(int n=begin; n<=end; n++) { int weishu = getWeishu(n); int cur = getNext(n, weishu); while(cur != n) { if(cur > n && cur <=end && getWeishu(cur) == weishu) cnt++; cur = getNext(cur, weishu); } } out.println(""Case #""+cs+"": ""+cnt); } sc.close(); out.close(); } public static int getNext(int n, int weishu) { //int weishu= getWeishu(n); return n%10*getTens(weishu-1)+n/10; } private static int getTens(int n) { int res = 1; for(int i=0; i= nweishu) { nweishu*=10; weishu++; } return weishu; } } " B20137,"import java.io.*; import java.util.StringTokenizer; import java.lang.Math; public class qualifycodejamC{ public static int checkNum(int num, int m, int n){ String snum = Integer.toString(num); int[] array = new int[snum.length()]; int min = num; int count = 0; for(int i=0;i= m){ min = (int)Math.min(min,array[i]); } //System.out.println(""length: ""+array.length+"" current: ""+num+""; min: ""+ min); } if(min != num){ //System.out.println(); return 0; } //System.out.println(""!X count: ""+ count); if(count == 2){ return 3; }else if(count == 3){ return 6; }else if(count == 4){ return 10; }else if(count == 5){ return 16; }else if(count == 6){ return 21; }else if(count == 7){ return 28; }else if(count == 8){ return 36; } return count; } public static void main(String[] args){ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String x = null; String linein = null; int totalcases = 0; int result = 0; int n = 0; int m = 0; int counter = 1; try{ x = br.readLine(); totalcases = Integer.parseInt(x); while( (linein = br.readLine()) != null){ result = 0; StringTokenizer st = new StringTokenizer(linein); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); for (int i=n;i 0) { if (scale == 1) fn += ""-attempt"" + (t - 1); return fn; } return fn; } public static void main(String[] args) { RecycledNumbers cls = new RecycledNumbers(); String base = ""data/2012Q/""; cls.file = base + generateFilename(""C"", 2, 1); cls.showDebug = true; cls.work(); } final static int[] P10 = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000}; int leftShift(byte[] nArr) { byte t = nArr[0]; for (int i = 1; i < nArr.length; i++) { nArr[i - 1] = nArr[i]; } nArr[nArr.length - 1] = t; int m = 0; for (int i = 0; i < nArr.length; i++) { m = m * 10 + nArr[i]; } return m; } void solveACase() { int min = sc.nextInt(); int max = sc.nextInt(); int num = 0; for (int n = min; n < max; n++) { int k = 0; while (n >= P10[k]) k++; byte[] nArr = new byte[k]; int t = n; while (t > 0) { nArr[--k] = (byte)(t % 10); t /= 10; } int m = leftShift(nArr); while (m != n) { if (m > n && m >= min && m <= max) num++; m = leftShift(nArr); } } out(num); } }" B20642,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class Main { public static void main(String args[]) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(new FileWriter(""out.txt"")); RecycledNumbers prog = new RecycledNumbers(); String inString = """"; int t = Integer.parseInt(in.readLine()); for(int i = 0; i < t; i++) { inString = in.readLine(); String[] word = inString.split("" ""); int a = Integer.parseInt(word[0]); int b = Integer.parseInt(word[1]); out.println(""Case #"" + (i+1) + "": "" + prog.getNumbers(a, b)); } in.close(); out.close(); } private static void printArray(String[] a) { for(int i = 0; i < a.length; i++) { System.out.print(a[i] + "" ""); } System.out.print(""\n""); } } " B20743,"package fixjava; import java.util.ArrayList; /** * String splitter, this fixes the problem that String.split() has of losing the last token if it's empty. It also uses * CharSequences rather than allocating new String objects. */ public class Split { /** * String splitter, this fixes the problem that String.split() has of losing the last token if it's empty. It also uses * CharSequences rather than allocating new String objects. */ public static ArrayList splitAsList(String str, String sep) { int strLen = str.length(); int sepLen = sep.length(); assert sepLen > 0; ArrayList parts = new ArrayList(); for (int curr = 0; curr <= strLen;) { // Look for next token int next = str.indexOf(sep, curr); // Read to end if none if (next < 0) next = strLen; // Add next token parts.add(str.subSequence(curr, next)); // Move to end of separator, or past end of string if we're at the end // (by stopping when curr <= strLen rather than when curr < strLen, // we avoid the problem inherent in the Java standard libraries of // dropping the last field if it's empty; fortunately // str.indexOf(sep, curr) still works when curr == str.length() // without throwing an index out of range exception). curr = next + sepLen; } return parts; } public static CharSequence[] splitAsArray(String str, String sep) { ArrayList list = splitAsList(str, sep); CharSequence[] arr = new CharSequence[list.size()]; list.toArray(arr); return arr; } public static ArrayList splitAsListOfString(String str, String sep) { ArrayList list = splitAsList(str, sep); ArrayList listOfString = new ArrayList(list.size()); for (CharSequence cs : list) listOfString.add(cs.toString()); return listOfString; } /** For compatibility only, slower because it creates new String objects for each CharSequence */ public static String[] split(String str, String sep) { ArrayList list = splitAsList(str, sep); String[] arr = new String[list.size()]; for (int i = 0; i < list.size(); i++) arr[i] = list.get(i).toString(); return arr; } // public static void main(String[] args) { // System.out.println(splitAsList("""", ""\t"")); // System.out.println(splitAsList(""\t"", ""\t"")); // System.out.println(splitAsList(""a\t"", ""\t"")); // System.out.println(splitAsList(""\ta"", ""\t"")); // System.out.println(splitAsList(""\ta\t"", ""\t"")); // System.out.println(splitAsList(""a\tb"", ""\t"")); // System.out.println(splitAsList(""a\tb\t"", ""\t"")); // System.out.println(splitAsList(""\ta\tb"", ""\t"")); // System.out.println(splitAsList("""", ""SEP"")); // System.out.println(splitAsList(""SEP"", ""SEP"")); // System.out.println(splitAsList(""aSEP"", ""SEP"")); // System.out.println(splitAsList(""SEPaSEPb"", ""SEP"")); // System.out.println(splitAsList(""aSEPbSEP"", ""SEP"")); // } } " B21210,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package test3; import java.io.*; import java.util.LinkedList; import java.util.Scanner; /** * * @author Student */ public class Test3 { public static int rotations(int number, int max) { int l = 0; int start = number; int numdigits = (int) Math.log10((double) number); int multiplier = (int) Math.pow(10.0, (double) numdigits); while (true) { int q = number / 10; int r = number % 10; number = number / 10; number = number + multiplier * r; if (number > start && Integer.toString(number).length() == numdigits + 1 && number <= max) { l++; } if (number == start) { break; } } return l; } public static int possibilities(int A, int B){ int K = 0; for (int i = A; i <= B; i++) { K += rotations(i,B); } return K; } public static void main(String[] args) throws FileNotFoundException { // TODO code application logic here int i=1; int max = 0; Scanner ss=new Scanner(new File(""C-large.in.txt"")); PrintWriter x=new PrintWriter(new File(""C-large.out.txt"")); if(ss.hasNext()) max=Integer.parseInt(ss.next()); while(ss.hasNextLine()&&i<=max){ int A = 0; if(ss.hasNext()) A=Integer.parseInt(ss.next()); int B = 0; if(ss.hasNext()) B=Integer.parseInt(ss.next()); x.println(""Case #""+i+"": ""+possibilities(A, B)); i++; } x.close(); } } " B21574,"import java.util.*; import java.io.*; import java.lang.Integer; public class QuestionC { public static void main(String[] args) throws IOException { Scanner inPut = new Scanner(new File(""C-large.in"")); FileWriter fWriter = new FileWriter(""C-large.out""); int caseTotal = inPut.nextInt(); inPut.nextLine(); for (int caseNum = 1; caseNum <= caseTotal; caseNum++) { // read the string length for this case int base = 1; int smallNum = inPut.nextInt(); int largeNum = inPut.nextInt(); int digit = 0; int temp = smallNum; while(temp != 0) { temp = temp/10; digit++; } int[] num = new int[digit]; int total = 0; for (int i = 1; i < digit; i++) { base = base * 10; } fWriter.write(""Case #"" + caseNum + "": ""); for(int i = largeNum; i >= smallNum; i--) { num[0] = i; for (int j = 1; j < digit; j++) { boolean norepeat = false; num[j] = num[j - 1] / base + (num[j - 1] % base) * 10; if (num[j] >= smallNum && num[j] <= largeNum) { norepeat = true; for (int k = j - 1; k >= 0; k--) { norepeat = norepeat && (num[j] != num[k]); } } if(norepeat) total++; } } total = total / 2; fWriter.write(total + ""\n""); } fWriter.flush(); fWriter.close(); } } " B21862,"import java.io.*; import java.util.ArrayList; public class RecycledNumbers { static int caseNumber; static int totalCases; public static void main(String[] args) throws Exception { caseNumber = 1; File fileIn = new File(""C:\\GCJ\\RecycledNumbers\\C-large.in""); FileInputStream fileInputStream = null; BufferedInputStream inputStream = null; BufferedReader reader = null; Writer out; String newLine = System.getProperty(""line.separator""); String fileOutPath = ""C:\\GCJ\\RecycledNumbers\\largeOutput.txt""; File fileOut = new File(fileOutPath); if (!fileOut.createNewFile()) { fileOut.delete(); fileOut.createNewFile(); } out = new OutputStreamWriter(new FileOutputStream(fileOutPath), ""US-ASCII""); StringBuilder builder = new StringBuilder(); try { fileInputStream = new FileInputStream(fileIn); // Here BufferedInputStream is added for fast reading. inputStream = new BufferedInputStream(fileInputStream); reader = new BufferedReader(new InputStreamReader(inputStream)); totalCases = Integer.parseInt(reader.readLine()); while (caseNumber <= totalCases) { builder.append(handleTestCase(reader)); builder.append(newLine); caseNumber++; } // dispose all the resources after using them. fileInputStream.close(); inputStream.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } System.out.print(builder.toString()); out.write(builder.toString()); out.close(); } public static String handleTestCase(BufferedReader reader) throws Exception { String[] numsAsStrings = reader.readLine().split("" ""); int start = Integer.parseInt(numsAsStrings[0]); int end = Integer.parseInt(numsAsStrings[1]); int pairs = 0; int current = start; while (current <= end){ pairs += getNumRecycledPairsInRange(current, start, end); current++; } return ""Case #""+caseNumber+"": ""+pairs; } public static int getNumRecycledPairsInRange(int orig, int start, int end){ int pairs = 0; ArrayList options = getAllRotationsInRange(orig, start, end); for(int i = 0; i < options.size(); i++){ if (orig < options.get(i)){ pairs++; } } return pairs; } public static ArrayList getAllRotationsInRange(int orig, int start, int end){ if(orig < 10) return new ArrayList(0); char[] origAsChars = String.valueOf(orig).toCharArray(); ArrayList allRotations = new ArrayList(origAsChars.length-1); char[] curRotation = origAsChars; // i < length - 1 because I don't want to repeat the original by doing it the full time for(int i = 0; i < origAsChars.length - 1; i++){ char temp = curRotation[0]; for(int j = 1; j < origAsChars.length; j++){ curRotation[j-1] = curRotation[j]; } curRotation[curRotation.length-1] = temp; allRotations.add(new Integer(String.valueOf(curRotation))); } for(int i = 0; i < allRotations.size(); i++){ if (allRotations.get(i) < start || allRotations.get(i) > end || allRotations.get(i) == orig){ allRotations.remove(i); i--; //Because ArrayList shifts everything down an index } } makeListUnique(allRotations); return allRotations; } public static void makeListUnique(ArrayList list){ for(int i = 0; i < list.size(); i++){ for(int j = i+1; j < list.size(); j++){ if(list.get(i).equals(list.get(j))){ list.remove(j); } } } } } " B20076,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package c; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; /** * * @author KazakhPride */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { // TODO code application logic here Scanner in = new Scanner(new File(""C-large.in"")); PrintWriter out = new PrintWriter(new File(""output.txt"")); int n = in.nextInt(); int len = 0; for (int i = 1; i <= n; i++) { out.print(""Case #"" + i + "": ""); int current_n = 0; int current_m = 0; int range = 0; int a = in.nextInt(); int b = in.nextInt(); int count = 0; if ((a + """").length() == 1 && (b + """").length() == 1) { count = 0; } else { range = b - a; for (int j = 0; j < range; j++) { current_n = j + a; current_m = j + a; int l = (current_n + """").length(); // if (l==3) len=9; // if(l==4) len = 28; for (int k = 0; k < l; k++) { String m = current_m + """"; if (m.length() < l) { for (int w = 0; w < (l - m.length()); w++) { m = ""0""+m; } } current_m = Integer.parseInt(m.substring(l - 1) + m.substring(0, l - 1)); if (current_m <= b && current_m > current_n && current_m >= a) { ++count; } } } } out.println(count); } in.close(); out.close(); } }" B20237,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class C_RecycledNumbers { static int a; static int b; static HashSet set; public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""C2in.txt"")); PrintWriter writer = new PrintWriter(new File(""C2out.txt"")); int t = sc.nextInt(); for (int i = 1; i <= t; i++) { a = sc.nextInt(); b = sc.nextInt(); int count = 0; set = new HashSet(); for (int j = a; j <= b; j++) { count += get(j); } writer.println(""Case #"" + i + "": "" + count / 2); } writer.close(); } private static int get(int j) { String s = j + """"; int n = s.length(); int count = 0; HashSet set1 = new HashSet(); for (int i = 0; i < n - 1; i++) { String ss = s.substring(1) + s.charAt(0) + """"; s = ss; int x = Integer.parseInt(ss); if (x >= a && x <= b && s.charAt(0) != '0' && !set1.contains(x)) { if (j != x) { set1.add(x); count++; } } } return count; } } " B20738,"package fixjava; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; /** * Iterator that iterates over the lines of the file and then closes it after the last line has been read. * * e.g. * * * * for (String line : new FileLineIterator(""in.txt"")) * System.out.println(line); * * for (NumberedLine nl : new FileLineIterator(""in.txt"").withLineNumbers()) * System.out.println(nl.getLineNum() + "" "" + nl.getLine()); * * */ public class FileLineIterator implements Iterable, Iterator { private BufferedReader reader; String nextLine = null; boolean nextLineAlreadyFetched = false; private int lineNum = -1; // ------------------------------------------------------------------------------------------ /** * Construct an iterator that iterates over the lines of the file and then closes it after the last line has been read. * * e.g. for (String line : new FileLineIterator(""in.txt"")) System.out.println(line); * * @throws IllegalArgumentException * on any I/O exception, so you can use this directly in foreach loops. */ public FileLineIterator(String filename) { this(new File(filename)); } /** * Construct an iterator that iterates over the lines of the file and then closes it after the last line has been read. * * e.g. for (String line : new FileLineIterator(file)) System.out.println(line); * * @throws IllegalArgumentException * on any I/O exception, so you can use this directly in foreach loops. */ public FileLineIterator(File file) { try { reader = new BufferedReader(new FileReader(file), 1024 * 1024); } catch (FileNotFoundException e) { throw new IllegalArgumentException(e); } } @Override public Iterator iterator() { return this; } // ------------------------------------------------------------------------------------------ private String getNextLine(boolean consume) { if (!nextLineAlreadyFetched) { try { nextLine = reader.readLine(); lineNum++; nextLineAlreadyFetched = true; if (nextLine == null) // Close reader after last line has been read reader.close(); } catch (IOException e) { if (reader != null) try { reader.close(); } catch (Exception e2) { } throw new IllegalArgumentException(e); } } String retVal = nextLine; if (consume) { nextLine = null; nextLineAlreadyFetched = false; } return retVal; } /** Return the current zero-indexed line number -- only returns the correct line number after a call to hasNext() or next() */ public int getLineNum() { return lineNum; } @Override public boolean hasNext() { return getNextLine(false) != null; } @Override public String next() { return getNextLine(true); } @Override public void remove() { getNextLine(true); } // ------------------------------------------------------------------------------------------ public class NumberedLine { String line; int lineNum; public NumberedLine(String line, int lineNum) { this.line = line; this.lineNum = lineNum; } public String getLine() { return line; } public int getLineNum() { return lineNum; } } /** Return an Iterable that includes the line number with each line */ public Iterable withLineNumbers() { final FileLineIterator fileLineIter = this; return new Iterable() { @Override public Iterator iterator() { return new Iterator() { @Override public void remove() { fileLineIter.remove(); } @Override public NumberedLine next() { String line = fileLineIter.next(); int lineNum = fileLineIter.getLineNum(); return new NumberedLine(line, lineNum); } @Override public boolean hasNext() { return fileLineIter.hasNext(); } }; } }; } } " B21715,"package code.jam; import java.io.*; import java.util.*; public class CodeJam { public static void main(String[] args) throws FileNotFoundException, IOException { String name = ""test""; Scanner in = new Scanner( new BufferedReader( new FileReader(name + "".in"") ) ); BufferedWriter out = new BufferedWriter( new FileWriter(name + "".out"") ); int req_count; int seed , count = 0, factor , temp; int c2; int i , j , k = 1; int[] parts = null; boolean[] arr = null; int N = in.nextInt(); while(in.hasNext()) { int start = in.nextInt(); int end = in.nextInt(); req_count = 0; arr = new boolean[end+1]; filterArray(arr); for(i=start ; i 2) { parts = new int[count-1]; factor = 10; for(j=(count-2) ; j >= 0 ; j--) { parts[j] = seed/factor; factor = factor*10; } for(j=1 ; j<=parts.length ; j++) { factor = (int)Math.pow(10,count-j); temp = seed%factor; temp = temp*((int)Math.pow(10,j))+parts[j-1]; c2 = digitsCount(temp); if(count == c2) { if( (temp >= start) && (temp <= end) ) { if(!arr[seed]) arr[seed] = true; if(!arr[temp]) req_count++; } } } } else if(count == 2) { temp = seed%10; temp = (temp*10)+(seed/10); if( (temp >= start) && (temp <= end) ) { req_count++; arr[temp] = true; arr[seed] = true; } } } } out.write(""Case #"" + k + "": "" + req_count); out.newLine(); k++; } out.close(); } //---------------------------------------------------------------------- public static int digitsCount(int num) { int count = 0; while(num > 0) { count++; num = num/10; } return count; } //---------------------------------------------------------------------- public static void filterArray(boolean[] arr) { int length = arr.length; int i; int temp = 0; if( (length >= 10) && (length < 100) ) { temp = 11; for(i=2 ; i<=10 && temp <= length ; i++) { arr[temp] = true; temp = i*11; } } if( (length >= 100) && (length < 1000) ) { temp = 111; for(i=2 ; i<=10 && temp <= length ; i++) { arr[temp] = true; temp = i*111; } } if( (length >= 1000) && (length < 10000) ) { temp = 1111; for(i=2 ; i<=10 && temp <= length ; i++) { arr[temp] = true; temp = i*1111; } } if( (length >= 10000) && (length < 100000) ) { temp = 11111; for(i=2 ; i<=10 && temp <= length; i++) { arr[temp] = true; temp = i*11111; } } if( (length >= 100000) && (length < 1000000) ) { temp = 111111; for(i=2 ; i<=10 && temp <= length ; i++) { arr[temp] = true; temp = i*111111; } } if( (length >= 1000000) && (length <= 2000000) ) arr[1111111] = true; } } " B21884,"package com.develog; import java.io.IOException; public class Runner { public static void main(String args[]) throws IOException{ new C(); } } " B20352,"import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class codejam_C_small { public static void main(String[] args) throws IOException { FileUtil.Timer.start(); Scanner scanner = new Scanner(System.in); int numOfTest = scanner.nextInt(); scanner.nextLine(); String[] testCases = new String[numOfTest]; for (int i = 0; i < numOfTest; i++) { testCases[i] = scanner.nextLine(); } String[] finalResult = new String[numOfTest]; for (int i = 0; i < numOfTest; i++) { String testCase = testCases[i]; String result = runTestCase(testCase); finalResult[i] = FileUtil.formatTestResult(i, result); System.out.println(finalResult[i]); } FileUtil.Timer.stop(); } private static String runTestCase(String testCase) { String[] splits = testCase.split("" ""); long lowerBound = FileUtil.toNumber(splits[0]); long upperBound = FileUtil.toNumber(splits[1]); if (lowerBound > upperBound || upperBound < 10) { return ""0""; } int count = 0; // System.out.println(""Lower: "" + lowerBound + "", Upper: "" +upperBound // ); Map cachedMap = new HashMap(); for (long start = lowerBound; start < upperBound; start++) { long intermidate = start; int numOfShift = String.valueOf(start).length() - 1; if (numOfShift < 0) { continue; } for (int i = 0; i < numOfShift; i++) { intermidate = shiftLongNumber(intermidate, numOfShift); if (intermidate > start && intermidate <= upperBound) { if ((cachedMap.containsKey(intermidate) && cachedMap.get( intermidate).equals(start)) || (cachedMap.containsKey(start) && cachedMap.get( intermidate).equals(intermidate))) { // System.out.println(start + "", "" + intermidate); } else { cachedMap.put(intermidate, start); count++; } } } } return String.valueOf(count); } private static long shiftLongNumber(long input, int numOfShift) { long lastDigit = input % 10; long reminder = input / 10; return (long) (Math.pow(10, numOfShift) * lastDigit + reminder); } } " B21902,"package qualifiers; import java.io.*; import java.util.*; import java.util.concurrent.*; public class QualifierC { class Task implements Runnable { private int num; private String line; public Task(int num, String line) { this.num = num; this.line = line; } @Override public void run() { String result = null; // BEGIN RESULT COMPUTATION // ------------------------------------------------------------ String[] split_line = line.split("" ""); int min = Integer.parseInt(split_line[0]); int max = Integer.parseInt(split_line[1]); int total = 0; for (int current = min; current < max; ++current) { HashSet pairs = new HashSet(); char[] digits = String.valueOf(current).toCharArray(); int[] values = new int[digits.length]; for (int i = 0; i < digits.length; ++i) { values[i] = digits[i] - '0'; } for (int first = 1; first < values.length; ++first) { int other = 0; for (int size = 0; size < values.length; ++size) { other *= 10; other += values[(first + size) % values.length]; } if (other > current && min <= other && other <= max) { pairs.add(other); } } total += pairs.size(); } result = String.valueOf(total); // END RESULT COMPUTATION // ------------------------------------------------------------ System.out.println(result); reportResult(num, result); } } public static final int NUM_THREADS = 4; private String file_name; private ArrayList results; public QualifierC(String file_name) { this.file_name = file_name; } public ArrayList calculate() throws IOException, InterruptedException { results = new ArrayList(); ThreadPoolExecutor tpe = new ThreadPoolExecutor(NUM_THREADS, NUM_THREADS, 2, TimeUnit.SECONDS, new LinkedBlockingQueue()); FileReader fr = new FileReader(file_name); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); System.out.println(""Header: "" + line); String[] ints = line.split("" ""); // BEGIN HEADER PARSING // -------------------------------------------------------------------- int total_num = Integer.parseInt(ints[0]); // END HEADER PARSING // -------------------------------------------------------------------- for (int i = 0; i < total_num; ++i) { results.add(""""); // BEGIN READING CASE // ---------------------------------------------------------------- line = br.readLine(); tpe.execute(new Task(i, line)); // END READING CASE // ---------------------------------------------------------------- } br.close(); fr.close(); tpe.shutdown(); tpe.awaitTermination(8, TimeUnit.MINUTES); return results; } public synchronized void reportResult(int num, String result) { results.set(num, result); } public static void main(String[] args) throws IOException, InterruptedException { long time0 = System.currentTimeMillis(); if (args.length < 1) { System.out.println(""Remember command line argument""); System.exit(1); } QualifierC runner = new QualifierC(args[0]); ArrayList results = runner.calculate(); System.out.println(""Run time: "" + (System.currentTimeMillis() - time0) / 1000 + ""s\n""); FileWriter fw = new FileWriter(""results.txt""); BufferedWriter bw = new BufferedWriter(fw); for (int i = 0; i < results.size(); ++i) { System.out.println(""Case #"" + (i + 1) + "": "" + results.get(i)); bw.write(""Case #"" + (i + 1) + "": "" + results.get(i) + ""\n""); } bw.close(); fw.close(); } } " B20455,"//RECYCLED NUMBERS import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; //Importing classes / interface from java.io pacckage to work with files public class RecycledNumbers { static boolean checkForNewM(long temp , long [] m , long totalMForThisN) { for(int i = 0 ; i < totalMForThisN ; i++) { if(temp == m[i]) { return false; } } return true; } public static void main(String[] args) { try { // Open the input file FileInputStream fistream = new FileInputStream(""C-large.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fistream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Create output file File file = new File(""output.out""); boolean exist = file.createNewFile(); if (!exist) { System.out.println(""File already exists.""); System.exit(0); } FileWriter fostream = new FileWriter(""output.out""); BufferedWriter out = new BufferedWriter(fostream); int counterCases = 0; //Counter purpose //Read File Line By Line int totalNumberOfCases = 0; while ((strLine = br.readLine()) != null) { if(counterCases == 0) { //Ignore the first Line for Conversion totalNumberOfCases = Integer.parseInt(strLine); counterCases++; continue; } String[] results = strLine.split("" ""); long A = Long.parseLong(results[0]); long B = Long.parseLong(results[1]); int counter = 0; for(long n = A ; n < B ; n++) { String nTemp = """" + n; String mTemp; int totalMForThisN = 0; long [] m = new long [nTemp.length() - 1]; for(int i= (nTemp.length() - 1) ; i >= 0 ; i--) { mTemp = nTemp.substring(i) + nTemp.substring(0,i); if(mTemp.startsWith(""0"")) { continue; } else { long temp = Long.parseLong(mTemp); if(temp > n && temp <= B) { if(checkForNewM(temp, m, totalMForThisN)) { m[totalMForThisN] = temp; totalMForThisN++; counter++; } } } } } // Print the content in the output file out.write(""Case #"" + counterCases + "": "" + counter); if(counterCases < totalNumberOfCases) { out.write(""\n""); } counterCases++; } //Close the input stream in.close(); //Close the output Stream out.close(); } catch(Exception e) { //Catch exception if any System.err.println(""Error: "" + e.getMessage() + "" : "" + e); } } }" B21375,"package jam.qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class RecycledNumbers { public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new FileReader(""file.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""file.out"")); int n = Integer.parseInt(in.readLine()); for (int i = 1; i <= n; ++i) { String[] ints = in.readLine().split("" ""); char[] A = ints[0].toCharArray(); char[] B = ints[1].toCharArray(); int c = 0; try { c = count(A, B); } catch (Exception e) { System.err.println(""Unexpected exception, I made a mistake...""); e.printStackTrace(); System.exit(1); } out.write(""Case #"" + i + "": "" + c); if (i != n) out.newLine(); out.flush(); } out.close(); } catch (Exception e) { System.err.println(""Error occured while reading input!""); e.printStackTrace(); System.exit(1); } } private static int count(char[] A, char[] B) { char[][] buff = new char[A.length][A.length]; int count = 0, ptr; do { ptr = 0; for (int n = 1; n < A.length; ++n) { swap(A, buff[ptr], n); if (compare(buff[ptr], A) > 0 && compare(buff[ptr], B) <= 0) { for (int i = 0; i < ptr; ++i) if (compare(buff[i], buff[ptr]) == 0) { --count; --ptr; break; } ++count; ++ptr; } } if (compare(A, B) >= 0) break; inc(A); } while (true); return count; } private static void swap(char[] src, char[] dst, int n) { System.arraycopy(src, 0, dst, n, src.length - n); System.arraycopy(src, src.length - n, dst, 0, n); } private static void inc(char[] N) { int i = N.length; while (N[--i] == '9') N[i] = '0'; ++N[i]; } private static int compare(char[] X, char[] Y) { for (int i = 0; i < X.length; ++i) if (X[i] < Y[i]) return -1; else if (X[i] > Y[i]) return 1; return 0; } } " B20669,"import java.util.Scanner; public class Recycle { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int cases = Integer.parseInt(sc.nextLine()); for(int i = 0; i < cases; i++) { Scanner line = new Scanner(sc.nextLine()); int A = line.nextInt(); int B = line.nextInt(); int k = Integer.toString(A).length(); int fac = (int) (Math.pow(10, k-1)); IntSet set = new IntSet(k); int pairCount = 0; for(int n = A; n < B; n++) { set.clear(); int m = n; for(int j = 0; j < k-1; j++) { int mod = m % 10; m = m / 10; m = m + (fac * mod); if(m <= B && m > n) { //if not already there if(!set.insert(m)) { pairCount++; } } } } System.out.printf(""Case #%d: %d\n"", i+1, pairCount); } } } class IntSet { int[] ints; int ctr = 0; public IntSet(int k) { ints = new int[k]; ctr = 0; } public boolean contains(int x) { for(int i = 0; i < ctr; i++) { if(ints[i] == x) { return true; } } return false; } //true if x already contained public boolean insert(int x) { if(contains(x)) { return true; } ints[ctr] = x; ctr++; return false; } public void clear() { ctr = 0; } }" B20910,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; public class SolutionWriter extends PrintWriter { private static final String FORMAT = ""Case #%1$s: %2$s%n""; private String[] args = new String[2]; public SolutionWriter(File file) throws FileNotFoundException { super(file); } public void writeSolution(int caseNumber, String solution) { args[0] = Integer.toString(caseNumber); args[1] = solution;; printf(FORMAT, (Object[]) args); } } " B22181,"package cj2012.qual; import java.io.*; import java.util.Arrays; public class ProblemC extends PrintWriter { private final static String PREFIX = ""ProblemC_""; private final static String INPUT_FILE = PREFIX + ""in.txt""; private final static String OUTPUT_FILE = PREFIX + ""out.txt""; private static final int BUFF_SIZE = 64 * 1024; int pos = 0; int len = -1; final DataInputStream dis; final byte[] b = new byte[BUFF_SIZE]; public static void main(String[] args) throws Exception { ProblemC problem = new ProblemC(new BufferedOutputStream(System.out)); problem.solve(); problem.flush(); problem.close(); } public ProblemC(OutputStream os) throws FileNotFoundException { // super(new BufferedOutputStream(System.out)); super(new BufferedOutputStream(new FileOutputStream(OUTPUT_FILE))); dis = new DataInputStream(new BufferedInputStream(new FileInputStream(INPUT_FILE))); } public int read() { if (pos >= len) { pos = 0; len = -1; try { len = dis.read(b); } catch (IOException ex) { } } return pos < len ? b[pos++] : -1; } public int nextInt() throws IOException { int ret = 0; int ch = skipWhite(); int sign = 1; if (ch == '-') { sign = -1; ch = read(); } while (!isSpaceChar(ch) && ch != -1) { ret *= 10; ret += ch - '0'; ch = read(); } return ret * sign; } public long nextLong() throws IOException { long ret = 0; int ch = skipWhite(); int sign = 1; if (ch == '-') { sign = -1; ch = read(); } while (!isSpaceChar(ch) && ch != -1) { ret *= 10; ret += ch - '0'; ch = read(); } return ret * sign; } public int skipWhite() throws IOException { int ch = read(); while (true) { if (ch == -1) { return -1; } if (!isSpaceChar(ch)) { return ch; } ch = read(); } } public boolean isSpaceChar(int c) { return c <= 32 && c >= 0; } public int next(char[] buff) throws IOException { int c = skipWhite(); int len = 0; while (!isSpaceChar(c) && c != -1) { buff[len++] = (char) c; c = read(); } return len; } public String next() throws IOException { int c = skipWhite(); StringBuilder res = new StringBuilder(); while (!isSpaceChar(c) && c != -1) { res.appendCodePoint(c); c = read(); } return res.toString(); } public String nextLine() throws IOException { int c = skipWhite(); StringBuilder res = new StringBuilder(); while (c != '\n' && c != '\r' && c != -1) { res.appendCodePoint(c); c = read(); } return res.toString(); } void debug(Object... obj) { println(""-->"" + Arrays.deepToString(obj)); } void solve() throws Exception { int[] pow = new int[]{1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; int cases = nextInt(); for (int kk = 1; kk <= cases; kk++) { int a = nextInt(); int b = nextInt(); int sol = 0; for (int i = a; i <= b; i++) { int dig = getDigits(i); int start = i; int[] found = new int[dig]; int len = 0; for (int j = 0; j < dig; j++) { int mod = start % 10; int next = start / 10 + mod * pow[dig - 1]; if (i < next && next <= b && mod != 0 && start != next) { boolean valid = true; for (int k = 0; k < len; k++) { if (found[k] == next) { valid = false; break; } } if (valid) { sol++; found[len++] = next; } } start = next; } } println(String.format(""Case #%d: %d"", kk, sol)); } } private int getDigits(int a) { if (a < 10) return 1; if (a < 100) return 2; if (a < 1000) return 3; if (a < 10000) return 4; if (a < 100000) return 5; return 6; } }" B21104,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; //import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; //import java.util.Scanner; public class C { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader( new FileInputStream(""C:/Users/Ortiga/Downloads/C-large.in""))); byte length = Byte.parseByte(read.readLine()); BufferedWriter write = new BufferedWriter(new OutputStreamWriter( new FileOutputStream( ""C:/Users/Ortiga/Downloads/outputCLarg.txt""))); for (int i = 0; i < length; i++) { String[] line = read.readLine().split("" ""); int a = Integer.parseInt(line[0]), b = Integer.parseInt(line[1]), pairs = 0; String rit = ""Case #"" + (i + 1) + "": ""; for (int j = a; j <= b; j++) { String cur = j + """"; for (int k = 1; k < line[0].length(); k++) { int a1 = Integer.parseInt(cur.substring(k) + cur.substring(0, k)); if (a1 > j && a1 <= b) pairs++; } } rit += pairs; write.write(rit); if (i < length - 1) write.newLine(); } read.close(); write.close(); } }" B20482,"package test.googlejam.year2012.jam; import java.io.IOException; import org.apache.commons.lang.StringUtils; import test.googlejam.base.ProblemProcessor; import test.googlejam.base.ValueReader; public class RecycledNumbers extends ProblemProcessor { static java.util.Map mapping = new java.util.TreeMap(); public static void main(String[] args) throws java.io.IOException { RecycledNumbers processor; String fileName = ""c:/temp/googlejam/RecycledNumbers""; processor = new RecycledNumbers(); processor.setInputFileName(fileName + args[0] + "".in""); processor.setOutputFileName(fileName + args[0] + "".out""); processor.start(); } @Override public String processCase(int caseNumber) throws IOException { java.util.List values; values = this.readValues("" "", new ValueReader() { @Override public String readValue(String token) { return token; } }); String stringA; int valueA, valueB; stringA = values.get(0); valueA = Integer.valueOf(values.get(0)); valueB = Integer.valueOf(values.get(1)); java.util.SortedSet permutations = new java.util.TreeSet(); for ( int currentValue = valueA; currentValue <= valueB; currentValue++ ) { String currentString = Integer.toString(currentValue); for ( int i = 1; i < currentString.length(); i++ ) { String newString = StringUtils.right(currentString, i) + StringUtils.left(currentString, currentString.length() - i); if ( '0' == newString.charAt(0) ) continue; int newValue = Integer.valueOf(newString); if ( (valueA <= newValue) && (newValue <= valueB) ) permutations.add(newValue); } } //System.out.println(valueA); //System.out.println(valueB); //System.out.println(permutations); java.util.Set foundCases = new java.util.HashSet(); for ( int currentValue : permutations ) { String currentString = Integer.toString(currentValue); for ( int i = 1; i < currentString.length(); i++ ) { String newString = StringUtils.right(currentString, i) + StringUtils.left(currentString, currentString.length() - i); if ( '0' == newString.charAt(0) ) continue; int newValue = Integer.valueOf(newString); if ( (currentValue < newValue) && (permutations.contains(newValue))) { String foundCase = valueA + "" <= "" + currentValue + "" < "" + newValue + "" <= "" + valueB; //System.out.println(foundCase); foundCases.add(foundCase); } } } //System.out.println(foundCases); return Integer.toString(foundCases.size()); } } " B20937,"import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * * Google Code Jam 2012. Qualification. Problem C. * * @author Ivan Pryvalov (ivan.pryvalov@gmail.com) * */ public class GCJ_2012_Q_C implements Runnable{ static class Data{ int i; int next; int prev; } private void solve() throws IOException { int MAX = 2000000 + 1; Data[] d = new Data[MAX]; for (int i = 0; i < d.length; i++) { Data dat = new Data(); dat.i = i; dat.next = -1; dat.prev = -1; d[i] = dat; } for (int i = 0; i < d.length; i++) { if (d[i].prev != -1) continue; String cur = """"+i; Set set = new HashSet(); while (!set.contains(cur)){ set.add(cur); cur = next(cur); } List list = new ArrayList(); for (String s : set) { if (s.charAt(0)!='0'){ int num = Integer.parseInt(s); if (num < MAX) list.add(num); } } Collections.sort(list); for (int j = 0; j < list.size(); j++) { if (j>0){ d[list.get(j)].prev = list.get(j-1); d[list.get(j-1)].next = list.get(j); } if (j 1){ char firstCh = curS.charAt(0); curS = curS.substring(1) + new String(new char[]{firstCh}); } return curS; } ////////////////////////////////////////////////// static class ArrayWrapper{ T[] ar; Comparator comparator; public ArrayWrapper(Set set) { ar = (T[]) set.toArray(); } public ArrayWrapper(T[] ar) { this.ar = ar; } public ArrayWrapper(T[] ar, Comparator comparator) { this.ar = ar; this.comparator = comparator; } public ArrayWrapper sort(){ if (comparator==null){ Arrays.sort(ar); }else{ Arrays.sort(ar, comparator); } return this; } public T getFirst(){ return ar[0]; } public T getLast(){ return ar[ar.length-1]; } } ///////////////////////////////////////////////// final int BUF_SIZE = 1024 * 1024 * 8;//important to read long-string tokens properly final int INPUT_BUFFER_SIZE = 1024 * 1024 * 8 ; final int BUF_SIZE_INPUT = 1024; final int BUF_SIZE_OUT = 1024; boolean inputFromFile = true; String filenamePrefix = ""C-large""; String inSuffix = "".in""; String outSuffix = "".out""; //InputStream bis; //OutputStream bos; PrintStream out; ByteScanner scanner; ByteWriter writer; @Override public void run() { try{ InputStream bis = null; OutputStream bos = null; //PrintStream out = null; if (inputFromFile){ File baseFile = new File(getClass().getResource(""/"").getFile()); bis = new BufferedInputStream( new FileInputStream(new File( baseFile, filenamePrefix+inSuffix)), INPUT_BUFFER_SIZE); bos = new BufferedOutputStream( new FileOutputStream( new File(baseFile, filenamePrefix+outSuffix))); out = new PrintStream(bos); }else{ bis = new BufferedInputStream(System.in, INPUT_BUFFER_SIZE); bos = new BufferedOutputStream(System.out); out = new PrintStream(bos); } scanner = new ByteScanner(bis, BUF_SIZE_INPUT, BUF_SIZE); writer = new ByteWriter(bos, BUF_SIZE_OUT); solve(); out.flush(); }catch (Exception e) { e.printStackTrace(); System.exit(1); } } public interface Constants{ final static byte ZERO = '0';//48 or 0x30 final static byte NINE = '9'; final static byte SPACEBAR = ' '; //32 or 0x20 final static byte MINUS = '-'; //45 or 0x2d final static char FLOAT_POINT = '.'; } public static class EofException extends IOException{ } public static class ByteWriter implements Constants { int bufSize = 1024; byte[] byteBuf = new byte[bufSize]; OutputStream os; public ByteWriter(OutputStream os, int bufSize){ this.os = os; this.bufSize = bufSize; } public void writeInt(int num) throws IOException{ int byteWriteOffset = byteBuf.length; if (num==0){ byteBuf[--byteWriteOffset] = ZERO; }else{ int numAbs = Math.abs(num); while (numAbs>0){ byteBuf[--byteWriteOffset] = (byte)((numAbs % 10) + ZERO); numAbs /= 10; } if (num<0) byteBuf[--byteWriteOffset] = MINUS; } os.write(byteBuf, byteWriteOffset, byteBuf.length - byteWriteOffset); } /** * Please ensure ar.length <= byteBuf.length! * * @param ar * @throws IOException */ public void writeByteAr(byte[] ar) throws IOException{ for (int i = 0; i < ar.length; i++) { byteBuf[i] = ar[i]; } os.write(byteBuf,0,ar.length); } public void writeSpaceBar() throws IOException{ byteBuf[0] = SPACEBAR; os.write(byteBuf,0,1); } } public static class ByteScanner implements Constants{ InputStream is; public ByteScanner(InputStream is, int bufSizeInput, int bufSize){ this.is = is; this.bufSizeInput = bufSizeInput; this.bufSize = bufSize; byteBufInput = new byte[this.bufSizeInput]; byteBuf = new byte[this.bufSize]; } public ByteScanner(byte[] data){ byteBufInput = data; bufSizeInput = data.length; bufSize = data.length; byteBuf = new byte[bufSize]; byteRead = data.length; bytePos = 0; } private int bufSizeInput; private int bufSize; byte[] byteBufInput; byte by=-1; int byteRead=-1; int bytePos=-1; byte[] byteBuf; int totalBytes; boolean eofMet = false; private byte nextByte() throws IOException{ if (bytePos<0 || bytePos>=byteRead){ byteRead = is==null? -1: is.read(byteBufInput); bytePos=0; if (byteRead<0){ byteBufInput[bytePos]=-1;//!!! if (eofMet) throw new EofException(); eofMet = true; } } return byteBufInput[bytePos++]; } /** * Returns next meaningful character as a byte.
* * @return * @throws IOException */ public byte nextChar() throws IOException{ while ((by=nextByte())<=0x20); return by; } /** * Returns next meaningful character OR space as a byte.
* * @return * @throws IOException */ public byte nextCharOrSpacebar() throws IOException{ while ((by=nextByte())<0x20); return by; } /** * Reads line. * * @return * @throws IOException */ public String nextLine() throws IOException { readToken((byte)0x20); return new String(byteBuf,0,totalBytes); } public byte[] nextLineAsArray() throws IOException { readToken((byte)0x20); byte[] out = new byte[totalBytes]; System.arraycopy(byteBuf, 0, out, 0, totalBytes); return out; } /** * Reads token. Spacebar is separator char. * * @return * @throws IOException */ public String nextToken() throws IOException { readToken((byte)0x21); return new String(byteBuf,0,totalBytes); } /** * Spacebar is included as separator char * * @throws IOException */ private void readToken() throws IOException { readToken((byte)0x21); } private void readToken(byte acceptFrom) throws IOException { totalBytes = 0; while ((by=nextByte())=acceptFrom){ byteBuf[totalBytes++] = by; } } public int nextInt() throws IOException{ readToken(); int num=0, i=0; boolean sign=false; if (byteBuf[i]==MINUS){ sign = true; i++; } for (; i used = new HashSet(); int A = in.nextInt(); int B = in.nextInt(); int count = 0; for (int i = A; i <= B; i++) { String s = Integer.toString(i); for (int k = 1; k < s.length(); k++) { String front = s.substring(0, k); String sub = s.substring(k); String reconstr = sub + front; if (reconstr.startsWith(""0"") || reconstr.equals(s)) continue; int reconstructed = Integer.parseInt(reconstr); if (reconstructed >= i) continue; if (used.contains(new Point(i, reconstructed))) continue; if (A <= reconstructed && reconstructed <= B) { used.add(new Point(i, reconstructed)); count++; } } } return count; } }" B20745,"package fixjava; /** * Convenience class for declaring a method inside a method, so as to avoid code duplication without having to declare a new method * in the class. This also keeps functions closer to where they are applied. It's butt-ugly but it's about the best you can do in * Java. */ public interface Lambda3 { public V apply(P param1, Q param2, R param3); } " B21818,"import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import java.util.Hashtable; import java.util.Arrays; import com.sun.xml.internal.bind.v2.runtime.unmarshaller.IntArrayData; public class Recycler { private static int transpose(int num, int numDigits) { //System.out.println(""Input number "" + num); //System.out.println(""Number digits to be transposed "" + numDigits); String inputString = Integer.toString(num); String truncatedString1 = inputString.substring(0,inputString.length()-numDigits); //System.out.println(""Truncated String1 "" + truncatedString1); String truncatedString2 = inputString.substring(inputString.length()-numDigits); //System.out.println(""Truncated String2 "" + truncatedString2); //System.out.println(""Output string "" + truncatedString2 + truncatedString1); return Integer.valueOf(truncatedString2 + truncatedString1); } public static void main(String[] args) throws IOException{ /* transpose(3234,2); transpose(323423242,5); transpose(100,1); */ if (args.length != 1) { System.out.println(""Error: incorrect number of arguments.""); System.out.println(""Usage: Recycler ""); } else { BufferedReader inputStream = null; try { inputStream = new BufferedReader(new FileReader(args[0])); int totalCases = Integer.valueOf(inputStream.readLine()).intValue(); //System.out.println(""Total number of cases is: ""+totalCases); for (int i=0;i done = new HashSet(); for (int l=1;lk) && (otherNumber<=higher) && Integer.toString(k).length() == Integer.toString(otherNumber).length() && !done.contains(String.valueOf(new Integer(k)) + String.valueOf(new Integer(otherNumber))) ) { //System.out.println(k+"" ""+ otherNumber + "" Incrementing""); output++; done.add(String.valueOf(new Integer(k)) + String.valueOf(new Integer(otherNumber))); } } } System.out.println(output); } } catch (IOException e) { System.out.println(""Error in reading file""); } finally { if (inputStream != null) { inputStream.close(); } } } } }" B21699,"import static java.util.Arrays.deepToString; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class RecycledNumbers { final static String FILENAME = ""C-large""; //final static String FILENAME = ""C-small-attempt0""; //final static String FILENAME = ""sample""; final static String FILENAME_IN = FILENAME + "".in""; final static String FILENAME_OUT = FILENAME + "".out""; final static int THREADS = 1; // use 1 to solve them sequentially // VM arguments: -ea -Xms4096M -Xmx4096M static class Solver implements Callable { // PROBLEM SOLUTION STARTS HERE ----------------------------------------------------------- // ---------------------------------------------------------------------------------------- Solver(Scanner in, int testId) { this.testId = testId; // TODO: Read input A = in.nextInt(); B = in.nextInt(); } // TODO: Define input variables final int A, B; @Override public String call() throws Exception { long now = System.nanoTime(); // TODO: Solve problem here and return result as a string int digits = digitCount(A); int[] formers = new int[digits]; int count = 0; for (int n = A; n < B; n++) { int subcount = 0; inner: for (int rot=1; rot n && m <= B) { for (int i=0; i solvers = new ArrayList(); for (int i=0; i> solutions = executor.invokeAll(solvers); for (int i = 0; i < numTests; i++) { try { System.out.println(String.format(""Case #%d: %s"", solvers.get(i).testId, solutions.get(i).get())); } catch (Exception e) { System.out.println(String.format(""Case #%d: EXCEPTION !!!!!"", solvers.get(i).testId)); System.err.println(String.format(""Case #%d: EXCEPTION !!!!!"", solvers.get(i).testId)); e.printStackTrace(System.err); } } executor.shutdown(); System.err.println(String.format(""TOTAL: %d ms"" , (System.nanoTime() - now) / 1000000)); } }" B20458,"package net.anzix.learn.codejam.qr12; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { private InputStream input; private PrintStream output; public RecycledNumbers() { } public RecycledNumbers(InputStream input, PrintStream output) { super(); this.input = input; this.output = output; } public RecycledNumbers(File inputFile, File outputFile) throws Exception { this.input = new FileInputStream(inputFile); output = new PrintStream(outputFile); } public void run() throws Exception { Scanner scanner = new Scanner(input); int lines = scanner.nextInt(); for (int i = 0; i < lines; i++) { int from = scanner.nextInt(); int to = scanner.nextInt(); output.println(""Case #"" + (i + 1) + "": "" + calcNo(from, to)); } output.close(); } public static void main(String[] args) { try { new RecycledNumbers(new File(args[0]), new File(args[1])).run(); } catch (Exception e) { e.printStackTrace(); } } public int calcNo(int from, int to) { int digits = digit(from); if (digits < 1) { return 0; } int pow = (int) Math.pow(10, digits - 1); int res = 0; for (int m = from; m <= to; m++) { for (int p : convertedNumbers(m,digits,pow)) { if (p > m && p <= to) { res++; } } } return res; } public Set convertedNumbers(int original,int digits, int pow) { int l = pow; int s = 10; Set res = new HashSet(); for (int i = 0; i < digits - 1; i++) { if (original % s != 0) { int x = (original % s) * pow + original / s; if (x != original && x > l) { res.add(x); } } s *= 10; pow /= 10; } return res; } public int digit(int i) { return (int) Math.ceil(Math.log10(i+0.5)); } } " B21149,"package com.quosco.codejam.pre; import static java.lang.Math.*; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; public class Main { private static final String OUT_FORMAT = ""Case #%d: %d\n""; private static void solve() throws IOException { FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); Scanner s = new Scanner(Main.class.getResourceAsStream(""/input.txt"")); Integer nbOfCases = Integer.valueOf(s.nextLine()); for (int i = 0; i < nbOfCases; i++) { String[] caseInputs = s.nextLine().split(""\\s""); Integer start = Integer.valueOf(caseInputs[0]); Integer end = Integer.valueOf(caseInputs[1]); int result = solveCase(start, end, out); out.write(String.format(OUT_FORMAT, i + 1, result)); } out.close(); } private static int solveCase(Integer start, Integer end, BufferedWriter out) throws IOException { HashSet magicNumbers = new HashSet(); // int magicNumbers = 0; for (int i = start; i <= end; i++) { int nbOfDigits = (int) ceil(log10(i+1)); for (int j = 1; j < nbOfDigits; j++) { int isMagic = ismagic(i, j, start, end); if (isMagic > 0) { magicNumbers.add(i + "","" + isMagic); // magicNumbers++; } } } return magicNumbers.size(); // return magicNumbers; } private static int ismagic(int initialNumber, int numberOfDigits, Integer start, Integer end) { String stringValue = Integer.toString(initialNumber); int cutPoint = stringValue.length() - numberOfDigits; if (stringValue.charAt(cutPoint) == '0') { return -1; } String stringNewNumber = stringValue.substring(cutPoint) + stringValue.substring(0, cutPoint); int newNumber = Integer.parseInt(stringNewNumber); if (initialNumber < newNumber && newNumber >= start && newNumber <= end) { return newNumber; } return -1; } public static void main(String[] args) throws IOException { solve(); } } " B21279,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { public RecycledNumbers() { } public int solve(String str) { String[] tokens = str.split("" ""); int length = tokens[0].length(); int a = Integer.valueOf(tokens[0]); int b = Integer.valueOf(tokens[1]); return solve(a, b, length); } public int solve(int a, int b, int length) { Set rPairs = new HashSet(); StringBuffer strBuffer = new StringBuffer(); for (int n = a; n < b; ++n) { int shiftNum = n; for (int i = 0; i < length; ++i) { shiftNum = calcShiftNum(shiftNum, length); if (shiftNum <= b && shiftNum > n) { strBuffer.setLength(0); strBuffer.append(""("").append(n).append("", "").append(shiftNum).append("")""); String result = strBuffer.toString(); rPairs.add(result); } } } return rPairs.size(); } public int calcShiftNum(int num, int length) { int maxUnit = Double.valueOf(Math.pow(10, length - 1)).intValue(); int remainder = num % 10; return (remainder * maxUnit) + (num / 10); } public static void main(String[] args) throws IOException { RecycledNumbers solver = new RecycledNumbers(); //System.out.println(solver.solve(""100 500"")); File folder = new File("".""); for (File f : folder.listFiles()) { if (!f.getName().endsWith(""in"") || !f.isFile()) { continue; } System.out.println(f.getName()); String outFileName = f.getName().replace(""in"", ""out""); BufferedReader reader = new BufferedReader(new FileReader(f)); String str; int lineNum = 0, caseNum = 1; BufferedWriter writer = new BufferedWriter(new FileWriter(outFileName)); lineNum = Integer.valueOf(reader.readLine()); while ((str = reader.readLine()) != null) { str = str.trim(); writer.write(String.format(""Case #%d: %d\n"", caseNum++, solver.solve(str))); } if (lineNum != caseNum - 1) { System.err.println(""Case Number is not matched to input file.""); } writer.flush(); writer.close(); } } } " B20314,"import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Scanner; public class EjercicioA { public static boolean prueba = false; public static void main(String args[]){ try { FileOutputStream fos = new FileOutputStream(new File(""solucion.txt"")); OutputStream os = System.out; if (!prueba) os = fos; Scanner s = new Scanner(new File(""problema.txt"")); int a = s.nextInt(); for(int i = 0; i < a; i++){ int limI = s.nextInt(); int limS = s.nextInt(); int k = 0; for (int j = limI; j j && e <= limS){ k++; } }while(e != j); } os.write((""Case #"" + (i + 1) + "": "" + k+ ""\n"").getBytes()); } } catch (Exception e) { e.printStackTrace(); } } } " B22215," import java.io.*; import java.util.*; public class CodeJam2012_Q_C { public int calc(int A, int B) { boolean[] checked = new boolean[B-A+1]; int cnt = 0; int D = String.valueOf(A).length(); int unit =1; for(int i=1; i[] build; public static void Permute() { build = new LinkedList[2000001]; for(int i=1 ; i<=2000000 ; i++) { build[i] = new LinkedList(); String str = new String(i+""""); for(int j=0 ; ji && !build[i].contains(num)) build[i].add(num); } } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); Permute(); int cnt = scan.nextInt(); for(int c=1 ; c<=cnt ; c++) { int start = scan.nextInt(),end = scan.nextInt(),res = 0; for(int i=start ; i<=end ; i++) for(int j=0 ; j> prevCalcs = new HashMap>(); System.out.println(""\tA: "" + numA +"" B: "" + numB); int numRec = 0; //Result for(int i = numA; i < numB; i++){ String nS = String.valueOf(i); String mS = null; for( int j = 1; j < nS.length(); j++){ mS = generateRecycled(nS, j); if(isValid(nS, mS, numB, prevCalcs)){ numRec++; System.out.println(""\t\tRecycled: ("" + nS +"", "" +mS +"")""); addToPrevCalcs(nS, mS, prevCalcs); } } } System.out.println(""\tRes: "" + numRec); fw.write(""Case #"" + numCase +"": "" + numRec +""\n""); } fw.close(); br.close(); } private static String generateRecycled(String n, int numToMove){ return n.substring(n.length() - numToMove, n.length()) + n.substring(0, n.length() - numToMove); } private static boolean isValid(String nS, String mS, int numB, Map> map){ return !mS.startsWith(""0"") && Integer.parseInt(nS) < Integer.parseInt(mS) && numB >= Integer.parseInt(mS) && (!map.containsKey(nS) || !map.get(nS).contains(mS)); } private static void addToPrevCalcs(String nS, String mS, Map> map){ if(!map.containsKey(nS)){ map.put(nS, new ArrayList()); } map.get(nS).add(mS); } } " B21570,"import java.util.ArrayList; public class Recycled { public static void main(String[] args) { int T = StdIn.readInt(); for(int tr = 1; tr <= T; tr++) { int A = StdIn.readInt(); int B = StdIn.readInt(); //total num of recycled int num = 0; for (int i = A; i <= B; i++) { //converts to string String temp = Integer.toString(i); //list of recycled numbers given m = i ArrayList reNum = new ArrayList(); //for each shift for(int ind = 1; ind < temp.length(); ind++) { String first = temp.substring(0,ind); String last = temp.substring(ind); String shift = last + first; int shiftNum = Integer.parseInt(shift); if (shiftNum <= i || shiftNum > B) continue; if (reNum.indexOf(shiftNum) < 0) { reNum.add(shiftNum); } } num += reNum.size(); } StdOut.println(""Case #"" + tr + "": "" + num); } } } " B20985,"package y2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.BitSet; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { static public void main(String args[]) throws IOException { System.setIn(new FileInputStream(""src/y2012/C-large.in"")); // System.setIn(new FileInputStream(""src/y2012/RecycledNumbers.in"")); // System.setIn(new FileInputStream(""src/y2012/C-small-attempt0.in"")); BufferedReader cin = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter wr = new BufferedWriter(new FileWriter(""src/y2012/C-large.out"")); // BufferedWriter wr = new BufferedWriter(new FileWriter(""src/y2012/C-small-attempt0.out"")); int nTests = Integer.valueOf(cin.readLine()); String line; int tid = 0; while ((line = cin.readLine()) != null) { String[] sa = line.split(""\\s+""); int A = Integer.parseInt(sa[0]); int B = Integer.parseInt(sa[1]); int rlst = 0; BitSet bits = new BitSet(B); for (int i = A; i <= B; i++) bits.set(i, true); for (int i = A; i <= B; i++) { if (bits.get(i)) { char cs[] = new String().valueOf(i).toCharArray(); int n = cs.length; Set set = new HashSet(); set.add(i); for (int j = 0; j < n - 1; j++) { String s = new String(Arrays.copyOfRange(cs, 1, n)) + cs[0]; cs = s.toCharArray(); int k = Integer.valueOf(s); if (s.charAt(0) != 0 && A <= k && k <= B) { set.add(k); bits.set(k, false); } } rlst += set.size() * (set.size() - 1) / 2; } } ++tid; wr.write(""Case #"" + tid + "": "" + rlst + ""\n""); } wr.close(); cin.close(); } }" B20345,"package google.codejam; import java.awt.Point; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.HashSet; import java.util.List; import java.util.Set; import com.google.common.base.CharMatcher; import com.google.common.base.Charsets; import com.google.common.io.Closeables; import com.google.common.io.Files; public class RecycledNumbers { public static final int LETTERS_IN_ALPHABET = 26; public static void main(String[] args) throws IOException { File cwd = new File(""C:\\Users\\TaG\\workspace\\CodeJam\\""); File inputFile = new File(cwd, ""input.txt""); File outputFile = new File(cwd, ""output.txt""); if (outputFile.exists()) outputFile.delete(); PrintStream out = null; try { out = new PrintStream(outputFile); List lines = Files.readLines(inputFile, Charsets.UTF_8); int cases = Integer.parseInt(lines.remove(0)); int caseNo = 1; for (String line : lines) { String[] split = line.split("" ""); int a = Integer.parseInt(split[0]); int b = Integer.parseInt(split[1]); int recycledPairs = countRecycledPairs(a, b); out.printf(""Case #%d: %d\n"", caseNo, recycledPairs); System.out.printf(""Case #%d: %d\n"", caseNo, recycledPairs); caseNo++; } // end for-each lines } finally { Closeables.closeQuietly(out); } } private static int countRecycledPairs(final int a, final int b) { if (a >= b) { return 0; } int count = 0; for (int n = a; n <= b; n++) { Set set = new HashSet(); String ns = Integer.toString(n); // System.out.println(ns + "":""); for (int i = 1; i < ns.length(); i++) { String s1 = ns.substring(0, i); s1 = CharMatcher.is('0').trimLeadingFrom(s1); String s2 = ns.substring(i); s2 = CharMatcher.is('0').trimLeadingFrom(s2); String ms = s2 + s1; if (ns.length() == ms.length()) { // System.out.println(s1 + "", "" + s2); int m = Integer.parseInt(ms); if (n > m) { int t = n; m = n; n = t; } if (a <= n && n < m && m <= b && set.add(new Point(n, m))) { count++; //System.out.println(ns + "", "" + ms); } } } // System.out.println(); } return count; } }" B21669,"package blacky.codejam.qualifications; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private static class Pair { final public int m; final public int n; public Pair(int m, int n) { this.m = m; this.n = n; } public boolean equals(Object other) { return ((Pair)other).m == this.m && ((Pair)other).n == this.n; } public String toString() { return String.format(""(%d,%d)"", this.m, this.n); } public int hashCode() { return this.m * 31 + n; } } public static void main(String args[]) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); int numberOfTestCases = Integer.parseInt(reader.readLine()); for(int i = 0; i < numberOfTestCases; i++) { String numbers[] = reader.readLine().split("" ""); Set pairs = new HashSet(); int a = Integer.parseInt(numbers[0]); int b = Integer.parseInt(numbers[1]); for(int j = a; j < b; j++) { String jAsString = Integer.toString(j); int recycledNumbers[] = new int[jAsString.length()]; recycledNumbers[0] = j; for(int k = 1; k < jAsString.length(); k++) { int offset = jAsString.length() - k; String currentRecNum = jAsString.substring(offset).concat(jAsString.substring(0, offset)); recycledNumbers[k] = Integer.parseInt(currentRecNum); } Arrays.sort(recycledNumbers); for(int k = 0; k < recycledNumbers.length - 1; k++) { if(!(a <= recycledNumbers[k] && recycledNumbers[k] <= b)) continue; for(int l = k + 1; l < recycledNumbers.length; l++) { if(!(a <= recycledNumbers[l] && recycledNumbers[l] <= b)) continue; if(recycledNumbers[l] == recycledNumbers[k]) continue; pairs.add(new Pair(recycledNumbers[k], recycledNumbers[l])); } } } System.out.println(String.format(""Case #%d: %d"", i + 1, pairs.size())); } } } " B21357,"import java.io.FileOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException { int T; Scanner sc = new Scanner(System.in); FileOutputStream out = new FileOutputStream(""out.txt""); T = sc.nextInt(); sc.nextLine(); for (int i = 0; i < T; i++) { HashSet res = new HashSet(); int A = sc.nextInt(); int B = sc.nextInt(); for (int j = A; j <= B; j++) { String n = """" + j; for (int k = 1; k < n.length(); k++) { if (n.charAt(k) != '0') { String m = n.substring(k) + n.substring(0, k); if (j < Integer.valueOf(m) && Integer.valueOf(m) <= B) res.add(n + "" "" + m); } } } out.write((""Case #"" + (i + 1) + "": "" + res.size() + ""\n"").getBytes()); } } }" B20478,"import java.io.*; import java.util.*; import java.math.*; public class Main implements Runnable { static int power = 1; private static String filename; public static void main(String[] args) { if (args.length>0 && args[0].equals(""f"")) filename = ""input.txt""; else filename = """"; new Thread(new Main()).start(); } private static void debug(Object ... str) { for (Object s : str) System.out.print(s + "", ""); System.out.println(); } private void check(int x, int y, int ndig) { int temp = x; int[] digx = new int[ndig]; int[] digy = new int[ndig]; for (int i = 0; i < ndig; ++i, temp = temp / 10) { digx[i] = temp % 10; } temp = y; for (int i = 0; i < ndig; ++i, temp = temp / 10) { digy[i] = temp % 10; } boolean equal = false; for (int sh = 1; !equal && sh < ndig; ++sh) { equal = true; for (int i = 0; equal && i < ndig; ++i) { if (digx[(i + sh) % ndig] != digy[i]) { equal = false; } } } if (!equal || x >= y) System.out.println(""HAHAHA "" + x + "" "" + y); } public void run() { try{ MyScanner in; Locale.setDefault(Locale.US); if (filename.length()>0) in = new MyScanner(filename); else in = new MyScanner(System.in); PrintWriter out = new PrintWriter(System.out); int T = in.nextInt(); for (int test = 0; test < T; ++test) { int a = in.nextInt(); int b = in.nextInt(); int temp = a; int ndig = 0; while (temp > 0) { temp /= 10; ndig++; } int[] dig = new int[ndig]; power = 1; for (int i = 1; i mapPair = new HashMap(); int n = ("""" + a).length(); for(int i=a;i<=b;i++) { int c = i; for(int j=0;j i && c <= b) { //System.err.println(i + "" "" + c); //if(mapPair.containsKey(i + "" "" + c)) // System.err.println(i + "" "" + c); mapPair.put(i + "" "" + c, 1); //ret++; } } } //System.err.println(mapPair.size()); out.println(""Case #"" + it + "": "" + mapPair.size()); } out.close(); } /** * @param args */ public static void main(String[] args)throws IOException { new QualC().run(); } } " B20313,"import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class RecycleNumbers { private static final Map power = new HashMap(); static{ power.put(0,1); power.put(1,10); power.put(2,100); power.put(3,1000); power.put(4,10000); power.put(5,100000); power.put(6,1000000); } private static int recycle(int b , int max) { int size =0 ,ret = 0; int a = b , rem = 0 , i = 0; while((size++ > -1) && ((a = a/10)!= 0)); a = b; int myPower = power.get(size -1); Set mySet = new HashSet(); for(i = 0 ; i < size-1; i++) { rem = a%10; a = rem * myPower + a/10; if(a > b && a <= max && !mySet.contains(a)) ret++; mySet.add(a); } return ret; } public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.println(""Please enter the Valid I/O Paths in the argument ""); System.err.println(""First Input , then OutPut ""); System.exit(0); } File inFile = new File(args[0]); File outFile = new File(args[1]); BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream(inFile))); PrintWriter out = new PrintWriter(new FileOutputStream(outFile)); String myLine = in.readLine(); int t = Integer.parseInt(myLine); int caseNum = 1 , result; int a , b; while (t-- > 0) { myLine = in.readLine(); String[] myStr = myLine.split("" ""); a = Integer.parseInt(myStr[0]); b = Integer.parseInt(myStr[1]); result = 0; for(int i = a ; i < b ; i++) result += recycle(i,b); out.println(""Case #"" + (caseNum) + "": "" + result); caseNum++; } out.close(); } } " B21004,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Scanner; public class problem3 { public static void main(String[] args){ try{ // Create file FileWriter fstream1 = new FileWriter(""E:/out.txt""); BufferedWriter outp = new BufferedWriter(fstream1); try{ Scanner sc = new Scanner(new File(""E:/C-large.in"")); int cnt1=sc.nextInt(); cnt1=1; while (sc.hasNextInt()) { int low = sc.nextInt(); int high = sc.nextInt(); int cnt=0; for(int i=low; i<=high;i++){ int y=i; String str = new Integer(i).toString(); int[] sol = new int[str.length()]; int cn = 0; for(int j=0;ji&&y<=high){ boolean rep = false; for(int k=0;k set = new TreeSet(); for (int j = 1; j < str.length(); j++) { build.append(build.charAt(0)); build.delete(0, 1); if (build.charAt(0) == '0') { continue; } int v1 = Integer.parseInt(build.toString()); int v2 = Integer.parseInt(str); if ((v1 >= left) && (v1 <= right)) { if ((v1 > v2)) { if (!set.contains(v1)) { answer++; set.add(v1); } } } } } System.out.println(""Case #"" + (i + 1) + "": "" + answer); } } } " B22243,"import java.util.Arrays; import java.util.Scanner; /** * @author Dmitry Levshunov (levshunov.d@gmail.com) */ public class TaskC { private static boolean[] used = new boolean[2000001]; private static int length; private static int pow; public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); int tests = Integer.parseInt(scanner.nextLine().trim()); for (int test = 1; test <= tests; test++) { int a = scanner.nextInt(); int b = scanner.nextInt(); System.out.printf(""Case #%d: %s"", test, solve(a, b)); System.out.println(); } scanner.close(); } private static long solve(int a, int b) { Arrays.fill(used, false); length = Integer.toString(a).length(); pow = 1; for (int i = 0; i < length - 1; i++) { pow *= 10; } long result = 0; for (int x = a; x <= b; x++) { long shiftCount = processShifts(x, a, b); result += shiftCount * (shiftCount - 1) / 2; } return result; } private static int processShifts(int x, int a, int b) { if (used[x]) { return 0; } int result = 0; for (int i = 0; i < length; i++) { x = (x % 10) * pow + x / 10; if (a <= x && x <= b && !used[x]) { used[x] = true; result++; } } return result; } } " B22041,"package google.solver; import google.loader.ChallengeLoader; import google.loader.ChallengeReader; import java.io.FileInputStream; import java.util.Properties; public class Solver implements ChallengeConstants{ private ChallengeReader reader; private String inputFileName; private String result; private final String path; public Solver(String aPath) { this.path = aPath; init(); solve(); writeResult(); } private void solve() { ChallengeLoader loader = new ChallengeLoader(reader); loader.load(inputFileName); result = loader.getResult(); } private void init() { try{ String propFileName = path+DELIMITER+CHALLENGE_DEFINITION; Properties properties = new Properties(); properties.load(new FileInputStream(propFileName)); inputFileName = path+DELIMITER+(String)properties.get(""fileName""); String readerClassName = (String)properties.get(""readerClassName""); reader = (ChallengeReader) Class.forName(readerClassName).newInstance(); } catch(Exception e){ throw new RuntimeException(e); } } public String getResult(){ return result; } public void writeResult(){ String result = getResult(); write(result); } private void write(String text) { ProblemPackageCreator.write(getResultFileName(), text); } private String getResultFileName() { return inputFileName+"".result""; } public static void main(String[] args) { String problem = CHALLENGE_NAME; String path = BASE_DIR+DELIMITER+problem; Solver solver = new Solver(path); String result = solver.getResult(); System.out.println(result); } } " B20674," /** * Write a description of class solver here. * * @author (your name) * @version (a version number or a date) */ public class solver { public int aise(int a[],int k,int j) { int i; int temp=0; for(i=0;ia[j]) return true; } return false; } public boolean lesser(int a[],int b[],int k,int j,int n1) { if(jb[i]) return false; else if(a[(k+i)%j]0) { arr2[n1++]=temp1%10; temp1=temp1/10; } arr2=reverse(arr2,n1); for(i=a;i0) { arr[j++]=temp%10; temp=temp/10; } arr=reverse(arr,j); s=0; for(k=j-1;k>0;k--) { if(arr[k]!=0) { if(greater(arr,k,j) && lesser(arr,arr2,k,j,n1)) { count++; comp[s++]=aise(arr,k,j); } } } for(k=0;k= integerN) && (newIntegerM <= integerM)) { if (newIntegerM > m) { int k = 0; boolean exists = false; while (k < checkerArray.length) { if (checkerArray[k] == newIntegerM) { exists = true; } k++; } if (exists == false) { checkerArray[index] = newIntegerM; index++; numOfRecPairs++; } } } } } } try { FileWriter fw = new FileWriter(""/Users/NoK/Desktop/C-large.out"", true); BufferedWriter bw = new BufferedWriter(fw); System.out.println(""Case #"" + counter + "": "" + numOfRecPairs); bw.write(""Case #"" + counter + "": "" + numOfRecPairs); bw.newLine(); bw.close(); counter++; } catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } } catch (FileNotFoundException e ) { e.printStackTrace(); } } }" B21680,"package com.jam.google; import java.util.List; public class RecycledNumbers { public int count(int a, int b) { int pairCount = 0; for (int i = a; i <= b; i++) { int candidate = i; int j = 1; while( (candidate = recycle(i,j++) ) != i) { if (candidate > i && candidate <=b) pairCount++; } } return pairCount; } public int recycle(int i, int offset) { String string = String.valueOf(i); int answer = i; if (string.length()>1) { String recycledString = string.substring(string.length()-offset) + string.substring(0, string.length()-offset); answer = Integer.parseInt(recycledString); } return answer; } public void test() { InputUtil util = new InputUtil(); // List lines = util.readFile(""test1.txt""); List lines = util.readFile(""C-large.in""); // int N = Integer.parseInt(lines.remove(0)); int i = 1; for (String string : lines) { String[] split = string.split("" ""); int count = count(Integer.parseInt(split[0]), Integer.parseInt(split[1])); System.out.println(""Case #""+(i++)+"": ""+count); } } } " B22139,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; /** * Created with IntelliJ IDEA. * User: aeg * Date: 12/04/14 * Time: 22:58 * To change this template use File | Settings | File Templates. */ public class ReceycledNumbers { public static void main (String[] argc) throws FileNotFoundException { ReceycledNumbers renum = new ReceycledNumbers(); renum.solve(); } private void solve() throws FileNotFoundException { FileInputStream fis = new FileInputStream(""csv/QR_C/C-large.in""); Scanner sc = new Scanner(fis); int T = sc.nextInt(); loop: for (int i = 0; i < T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int count =0; System.out.print(""Case #""+(i+1)+"": ""); if (B < 10) { System.out.println(""0""); continue; } for (int j = A; j < B; j++) { String str = ((Integer) j).toString(); count +=tryRecycle(str, j, B); } System.out.println(count); } } private int tryRecycle(String str, int j, int b) { int count=0; for(int i=1;i= new Long(numberB).longValue() ? numberA +"" ""+ numberB : numberB +"" ""+ numberA; } public int size() { return pairNumberMap.size(); } } " B21879,"package y2012; import java.io.File; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; public class QR3 { public static void main(String[] args) throws Exception { Scanner inputFile=new Scanner(new File(args[0])); PrintWriter outputFile=new PrintWriter(new File(args[1])); int t=Integer.parseInt(inputFile.nextLine()); for(int i=0;i result = new HashMap(); String[] aCase = inputFile.nextLine().split("" ""); int iFrom = Integer.parseInt(aCase[0]); int iTo = Integer.parseInt(aCase[1]); String sFrom = String.valueOf(iFrom); String sTo = String.valueOf(iTo); int numDigit = sFrom.length(); if(numDigit != 1) { for(int curr = iFrom; curr < iTo; curr++) { String sCurr = String.valueOf(curr); for(int j=1; j x = new HashSet(); for (int i = a; i < b; i++) { x.clear(); String s = String.valueOf(i); for (int j = 1; j < s.length(); j++) { String q = s.substring(j) + s.substring(0, j); int qs = Integer.valueOf(q); if (qs <= i) continue; if (qs > b) continue; boolean success = x.add(qs); if (success) result = result.add(BigInteger.ONE); } } long taken = System.currentTimeMillis() - now; // System.err.println(""TIME TAKEN: "" + taken + "" -- * 50 = "" + (50 * taken) + "" -- 8 min = "" + (1000L * 60 * 8)); return result.toString(); } } " B21638,"import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws IOException { File file = new File(""c:\\java\\results.txt""); File inFile = new File(""c:\\java\\C-large.in""); file.createNewFile(); PrintStream out = new PrintStream(file); Scanner scanIn = new Scanner(inFile); int T = 0; int a = 0; int b = 0; int n = 0; int digits = 0; HashSet set = new HashSet();//store results T=scanIn.nextInt(); for(int i = 0; i < T; i++){ a = scanIn.nextInt(); b = scanIn.nextInt(); digits = numDigits(a); n = a; if(a>b){ //Zero out.println(""Case #""+(i+1)+"": 0""); continue; } if(digits == 1){ //Zero out.println(""Case #""+(i+1)+"": 0""); continue; } while(n < b){ int divisor = 10; int multiply = (int)Math.pow(10, (digits-1)); int remain = 0; int part = 0; int temp = 0; for(int j = 0; j < digits-1; j++, divisor*=10, multiply/=10){ remain = n%divisor; part = n/divisor; temp = (remain*multiply)+part; if(temp <= b && temp > n){ set.add(new Pair(n, temp)); } } n++; } out.println(""Case #""+(i+1)+"": ""+set.size()); set.clear(); }//End of main loop out.close(); } public static int numDigits(int number){ int divisor = 10; int digits = 1; while(true){ if(number%divisor == number){ return digits; } else{ digits++; divisor*=10; } } } } class Pair{ int n; int m; public Pair(){ n = 0; m = 0; } public Pair(int n, int m){ this.n = n; this.m = m; } public void printPair(){ System.out.printf(""n: ""+n); System.out.printf("" m: ""+m+""\n""); } public boolean equals(Object arg){ if(this==arg)return true; if(arg==null)return false; if(arg instanceof Pair){ Pair other = (Pair)arg; if(this.n == other.n && this.m == other.m){ return true; } else return false; } return false; } public int hashCode(){ int code = 3; code = (code >> 2) + n; code = (code << 2) + m; return code; } } " B20252,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class CodeJam { private static final String FILE_NAME = ""E:/workspace/codejam_module/C-large.in""; public static void main(String[] args) throws IOException { File file = new File(FILE_NAME); BufferedReader in = new BufferedReader(new FileReader(file)); StringBuilder builder = new StringBuilder(); SolverModule solver = new CSolver(); builder = solver.process(in, builder); System.out.println(builder); file = new File(FILE_NAME.concat("".result"")); FileWriter fileWriter = new FileWriter(file); fileWriter.append(builder); fileWriter.flush(); fileWriter.close(); } } " B22096,"package qualification.common; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; /** * Created by IntelliJ IDEA. * User: ofer * Date: 14/04/12 * Time: 17:31 * To change this template use File | Settings | File Templates. */ public class OutputWriter { public static void writeOutput(String filename,String[] output){ try { FileWriter write = new FileWriter( filename , false); PrintWriter print_line = new PrintWriter( write ); for (String str: output){ print_line.println(str); } print_line.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } " B20274,"import java.io.*; import java.util.*; class Recycle { public static void main(String [] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(in.readLine()); for(int i = 0; i < T; i++){ int ans = 0; StringTokenizer st = new StringTokenizer(in.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); for(int j = A; j <= B; j++){ String s = """" + j; HashMap hm = new HashMap(); for(int k = 0; k < s.length(); k++){ String rot = s.substring(k,s.length()) + s.substring(0,k); hm.put(Integer.parseInt(rot),0); } for(int k : hm.keySet()){ if(j duplicates = new TreeSet<>(); for(int i = 1; i <= testCase; i++) { int a = in.nextInt(), b = in.nextInt(); int count = 0; for(int n = a; n < b; n++) { String s = String.valueOf(n); String s2 = s+s; duplicates.clear(); for(int j = 1, len = s.length(); j < len; j++) { int m = Integer.parseInt(s2.substring(j, j+len)); if(m > n && m <= b && !duplicates.contains(m)) { count++; duplicates.add(m); } } } System.out.printf(""Case #%d: %d%n"", i, count); } } } " B20661,"/** * */ package com.sathish.codejam; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * @author satselva * */ public class Recycle { public void processInput(String fileName) throws IOException { FileInputStream fis = new FileInputStream(fileName); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); PrintWriter pw = new PrintWriter(new File(""C:/downloads/output_problem_3.txt"")); String input = br.readLine(); int testCases = Integer.valueOf(input); for(int i=1; i<=testCases; i++) { input = br.readLine(); String[] samples = input.split("" ""); int ans = displayRecycleNum(Integer.valueOf(samples[0]), Integer.valueOf(samples[1]), samples[0].length()); pw.println(String.format(""Case #%d: %d"", i, ans)); } pw.flush(); pw.close(); } public int displayRecycleNum(int min, int max, int digits) { if(digits <= 1) return 0; Set recyclePairSet = new HashSet(); for(int i=min; i<=max; i++) { String input = String.valueOf(i) + String.valueOf(i); for(int index=1; index < digits; index++) { String num = input.substring(index, index+digits); int numVal = Integer.valueOf(num); if(!(numVal > min && numVal < max)) continue; if(num.startsWith(""0"") || i == numVal) continue; if(i < Integer.valueOf(num)) { recyclePairSet.add(String.valueOf(i) + String.valueOf(num)); } else { recyclePairSet.add(String.valueOf(num) + String.valueOf(i)); } } } return recyclePairSet.size(); } public static void main(String[] args) throws IOException { Recycle recycle = new Recycle(); recycle.processInput(""C:/downloads/C-large.in""); } } " B20647,"package codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public abstract class Task { private String inputFileName; private BufferedReader in; private PrintWriter out; public Task(String[] args) { inputFileName = args[0]; } public void execute() throws IOException { File f = new File(inputFileName); in = new BufferedReader(new FileReader(f)); catchInputData(); in.close(); processInputData(); f = new File(inputFileName.substring(0, inputFileName.length() - 2) + ""out""); f.createNewFile(); out = new PrintWriter(new BufferedWriter(new FileWriter(f))); generateOutputFile(); out.flush(); out.close(); } protected abstract void generateOutputFile() throws IOException; protected abstract void processInputData(); protected abstract void catchInputData() throws IOException; protected String readLine() throws IOException { return in.readLine(); } protected void writeLine(String line) throws IOException { out.println(line); } } " B20675,"package at.jaki.codejam.qr2012.C; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class C { private static final String TEMPLATE = ""Case #%d: %d""; private static final String IN = ""C-small-attempt0.in""; private static final String OUT = ""C-small-attempt0.out""; private static Scanner sc; private static PrintWriter pw; public static void main(String[] args) throws FileNotFoundException { sc = new Scanner(new File(IN)); pw = new PrintWriter(new File(OUT)); int tests = sc.nextInt(); for (int i = 1; i <= tests; i++) { resolve(i); } pw.flush(); pw.close(); } private static void resolve(int TT) { int A = sc.nextInt(); A = Math.max(A, 10); int B = sc.nextInt(); long total = 0; boolean[] used = new boolean[B + 1]; for (Integer i = A; i <= B; i++) { if (!used[i]) { used[i] = true; List res = turn(i.toString(), A, B); int n = res.size(); total += (n * (n + 1) / 2); for (Integer j : res) { used[j] = true; } } } System.out.println(total); pw.println(String.format(TEMPLATE, TT, total)); } private static final List turn(String x, int min, int max) { StringBuilder sb = new StringBuilder(x); List l = new LinkedList(); for (int i = 0; i < x.length() - 1; i++) { char ch = sb.charAt(0); sb.delete(0, 1); sb.append(ch); if (sb.charAt(0) != '0') { String string = sb.toString(); if (!string.equals(x)) { Integer y = Integer.valueOf(string); if (y >= min && y <= max) { if (!l.contains(y)) l.add(y); } } } } return l; } } " B21822,"import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; public class Main { private static final int[][] cache; private static final int A = 0, B = 2000000; static { try { File f = new File(""cache""); if (f.exists()) { cache = (int[][]) new ObjectInputStream(new FileInputStream(f)).readObject(); } else { cache = new int[B+1][]; for (int j = 12; j < B; j++) { int permutation = String.valueOf(j).length(); HashMap hit = new HashMap(); for (int z = 1; z < permutation; z++) { int div = (int) Math.pow(10, z); if (j % div >= div / 10) { int newnum = j / div + j % div * (int) Math.pow(10, permutation - z); if (newnum >= A && newnum <= B && newnum > j) { if (hit.get(newnum) == null) { hit.put(newnum, true); } } } } ArrayList l = new ArrayList(hit.keySet()); Collections.sort(l); int[] vals = new int[l.size()]; for (int i = 0; i < l.size(); i++) { vals[i] = l.get(i); } cache[j] = vals; } new ObjectOutputStream(new FileOutputStream(f)).writeObject(cache); } } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) throws Exception { Scanner s = new Scanner(new File(""input"")); BufferedWriter w = new BufferedWriter(new FileWriter(new File(""output""))); int cases = s.nextInt(); for (int i = 0; i < cases; i++) { s.nextLine(); int a = s.nextInt(); if (a < 12) { a = 12; } int b = s.nextInt(); int answer = 0; for (int j = a; j < b; j++) { int[] vals = cache[j]; for (int val : vals) { if (val < 0) { continue; } if (val > b) { break; } answer++; } } w.write(""Case #""); w.write(String.valueOf(i + 1)); w.write("": ""); w.write(String.valueOf(answer)); w.write(""\n""); } w.close(); } } " B21110,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashSet; public class A { public static int a(String str){ int retVal = 0; String arr[] = str.split("" ""); int n = Integer.parseInt(arr[0]); int m = Integer.parseInt(arr[1]); for(int i = n ; i < m; i++){ String cur = Integer.toString(i); cur += cur; HashSet set = new HashSet(); for(int j = 1; j < cur.length()/2 ; j++){ String val = cur.substring(j, j+cur.length()/2); int intVal = Integer.parseInt(val); if(set.add(val) && intVal > i && intVal <= m){ retVal++; //System.out.println(retVal + "":"" +cur.substring(cur.length()/2)+"" : ""+intVal); } } } return retVal; } public static void main(String args[]){ File file = new File(""C-large.in""); int T = 0; try{ FileInputStream fstream = new FileInputStream(file); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; if ((strLine = br.readLine()) != null) { T = Integer.parseInt(strLine); } int currentCase = 1; while(T > 0 && currentCase <= T){ String str= br.readLine(); System.out.println(""Case #""+currentCase+"": "" + a(str)); currentCase++; } in.close(); }catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } } " B20521,"import java.util.*; import java.io.*; public class ProblemC { final long MOD = 1000003; final int MAX_LEN = 500000; long pow(long x, long y) { if (y == 0) return 1; long res = pow(x, y/2); res = (res * res) % MOD; if (y % 2 == 1) res = (res * x) % MOD; return res; } long inv(long x) { return pow(x, MOD-2); } long[] fact, invfact; void precalc() { fact = new long[MAX_LEN + 1]; fact[0] = 1; for (int i=1; i<=MAX_LEN; i++) fact[i] = (i * fact[i-1]) % MOD; invfact = new long[MAX_LEN + 1]; invfact[0] = 1; for (int i=1; i<=MAX_LEN; i++) invfact[i] = (inv(i) * invfact[i-1]) % MOD; } long comb(int N, int M) { long res = fact[N]; res = (res * invfact[M]) % MOD; res = (res * invfact[N-M]) % MOD; return res; } class Testcase { long ans; public Testcase() { } public Testcase(int seed) { Random rnd = new Random(seed); } String s; int A =0; int B = 0; public void loadInput(Scanner sc) { // s = sc.next(); A = sc.nextInt(); B = sc.nextInt(); } public void solveSlow() { } String getShift(String sa) { String sb = sa.substring(sa.length() -1 ) + sa.substring(0,sa.length()-1); return sb; // return Integer.parseInt(s); } int getMaxDivide(int a) { int m = 1; while(a>=10){ a=a/10; m=m*10; } return m; } HashMap > map = new HashMap>(); public ArrayList getShifts(String sa) { ArrayList arr = null; arr = map.get(sa); if( arr == null ) { arr = new ArrayList(); arr.add(sa); String sn = getShift(sa); while(!sn.equals(sa)) { arr.add(sn); sn = getShift(sn); } for(String ai : arr) { map.put(ai, arr); } } return arr; } boolean isCycle(int a, int b) { int am = getMaxDivide(a); if(b/am!=0) { return true; } else { return false; } } public void solveFast() { for(int n =A;n arr = getShifts(sn); for(String ai : arr ) { int m = Integer.parseInt(ai) ; if(m>n && m<=B && isCycle(n,m) ) { ans++; } } } } public void printSelf(PrintWriter pw) { System.out.println(ans); pw.println(ans); } public boolean sameAnswers(Testcase other) { return false; } } final String AFTER_CASE = "" ""; public void go() throws Exception { Scanner sc = new Scanner(new FileReader(""src\\input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""src\\output.txt"")); int caseCnt = sc.nextInt(); for (int caseNum = 0; caseNum < caseCnt; caseNum++) { System.out.println(""solving case "" + caseNum); Testcase tc = new Testcase(); tc.loadInput(sc); tc.solveFast(); pw.print(""Case #"" + (caseNum + 1) + "":""); pw.print(AFTER_CASE); tc.printSelf(pw); } pw.flush(); pw.close(); sc.close(); } public void stresstest() { int it = 0; Random rnd = new Random(); while (true) { it++; if (it % 1000 == 0) System.out.println(it + "" iterations""); int seed = rnd.nextInt(); Testcase tc1 = new Testcase(seed); tc1.solveFast(); Testcase tc2 = new Testcase(seed); tc2.solveSlow(); if (!tc1.sameAnswers(tc2)) { System.out.println(""ERROR: it failed""); System.exit(0); } } } public static void main(String[] args) throws Exception { new ProblemC().go(); } } " B20312,"package codejam; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) throws Exception { String fileName = ""RecycledNumbers.large.txt""; System.setIn(new FileInputStream(""data/input/"" + fileName)); System.setOut(new PrintStream(new FileOutputStream(""data/output/"" + fileName))); Scanner scanner = new Scanner(System.in); int testCases = scanner.nextInt(); for (int i = 1; i <= testCases; i++) { Set result = new HashSet(); int a = scanner.nextInt(); int b = scanner.nextInt(); for (int j = a; j <= b; j++) { String n = String.valueOf(j); if (n.length() > 0) { for (int x = n.length() - 1; x > 0; x--) { String m = n.substring(x) + n.substring(0, x); if (!m.startsWith(""0"") && Integer.valueOf(n) >= a && Integer.valueOf(n) < Integer.valueOf(m) && Integer.parseInt(m) <= b) { result.add(n + "","" + m); } // System.out.println(n + "","" + m + ""_countOfResult:"" // + result.size()); } } } System.out.println(""Case #"" + i + "": "" + result.size()); } } } " B21659,"import java.io.*; public class ProCOpt { public static void main(String args[]) { try { BufferedReader br = new BufferedReader(new FileReader(""E:\\test.txt"")); int n; n= Integer.parseInt(br.readLine()); int casen=0,i,j; int a,b,count; String temp,t,u; String outp; outp=""""; String spl[]; String memory,fp,lp; while( casen < n ) { temp = br.readLine(); outp += ""Case #""+(casen+1)+"": ""; spl = temp.split("" ""); a = Integer.parseInt(spl[0]); b = Integer.parseInt(spl[1]); count = 0; memory = """"; for(i=a;i<=b; i++) { t = i+""""; for(j=1;j= a) { if( t.length() % 2 == 0 ) { fp= t.substring(0,t.length()/2); lp = t.substring(t.length()/2); if( fp.equals(lp) ) { if(!memory.contains(Integer.parseInt(u)+"" ""+i)) { count++; memory += Integer.parseInt(u) + "" "" + i+""\n""; } } else { count++; } } else { count++; } /*if( memory.contains(Integer.parseInt(u)+"" ""+i) ) System.out.println(Integer.parseInt(u)+"" ""+i); else { count++; memory += Integer.parseInt(u) + "" "" + i+""\n""; }*/ } } } outp += count; if( casen != n-1 ) outp += ""\n""; casen++; } System.out.println(outp); BufferedWriter bw = new BufferedWriter( new FileWriter(""E:\\result.txt"")); bw.write(outp); bw.close(); br.close(); } catch( Exception e ) { e.printStackTrace(); } } } " B21311,"package ch7.rec; import java.util.HashSet; import java.util.Scanner; public class Recycled { static HashSet p = new HashSet(); int count = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int no = sc.nextInt(); for(int i = 1; i <= no; i++) { p.clear(); int low = sc.nextInt(); int high = sc.nextInt(); for(int l = low; l <= high; l++) { recycle(low, high, l); } System.out.println(p.size()); } } public static void recycle(int low, int high, int no) { String s = Integer.toString(no); for(int i = 0 ; i < s.length(); i++) { String rec = s.substring(i) + s.substring(0,i); int r = Integer.parseInt(rec); if(r != no && r >= low && r <= high) { int min = Math.min(r, no); int max = Math.max(r, no); String a = Integer.toString(min)+""""+Integer.toString(max); if(!(p.contains(a))) { p.add(a); } } } } }" B20423,"package codejam2012.qualification.c; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import com.google.common.base.Charsets; import com.google.common.io.Resources; public final class GoC { public static void main(String[] args) throws Exception { String name = args[0]; String nameIn = name + "".in""; String nameOut = name + "".out""; String dataIn = Resources.toString(Resources.getResource(nameIn), Charsets.ISO_8859_1); try (PrintStream out = new PrintStream(nameOut)) { run(new Scanner(dataIn), out); } } public static void run(Scanner in, PrintStream out) { new GoC(in, out).run(); } private final Scanner in; private final PrintStream out; public GoC(Scanner in, PrintStream out) { this.in = in; this.out = out; } public void run() { int T = in.nextInt(); for (int t = 1; t <= T; ++t) { int A = in.nextInt(); int B = in.nextInt(); out.println(String.format(""Case #%d: %d"", t, run(A, B))); } } private static class Pair { final int a; final int b; public Pair(int a, int b) { this.a = a; this.b = b; } public static Pair of(int a, int b) { return new Pair(a, b); } @Override public String toString() { return ""("" + a + "", "" + b + "")""; } public boolean valid(int A, int B) { String n = Integer.toString(a); String m = Integer.toString(b); return (A <= a) && (a < b) && (b <= B) && (n.length() == m.length()) && (n.charAt(0) != '0') && (m.charAt(0) != '0'); } } private static int run(int A, int B) { HashSet done = new HashSet<>(); for (int i = A; i <= B; ++i) { int[] digits = digits(i); int first = digits[0]; for (int j = digits.length - 1; j > 0; --j) { int curr = digits[j]; if (curr >= first) { Pair pair = Pair.of(i, undigits(recycle(digits, j))); if (pair.valid(A, B)) { done.add(pair); } } } } return done.size(); } private static int[] digits(int a) { char[] chars = Integer.toString(a).toCharArray(); int[] result = new int[chars.length]; for (int i = 0; i < result.length; ++i) { result[i] = Character.digit(chars[i], 10); } return result; } private static int undigits(int[] digits) { int result = 0; for (int i : digits) { result *= 10; result += i; } return result; } private static int[] recycle(int[] digits, int from) { int[] result = new int[digits.length]; int index = 0; for (int i = from; i < digits.length; ++i) { result[index++] = digits[i]; } for (int i = 0; i < from; ++i) { result[index++] = digits[i]; } return result; } } " B20569,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main_Recycled { static int a,b; public static void main(String[] args)throws Exception { File _=new File(""recycled.in""); BufferedReader br=_.exists()? new BufferedReader(new FileReader(_)):new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine().trim()); StringTokenizer st; boolean visited[]; int size,total; int temp; for (int i = 1; i <= t; i++) { total=0; st=new StringTokenizer(br.readLine()); a=Integer.parseInt(st.nextToken()); b=Integer.parseInt(st.nextToken()); visited=new boolean[b+1]; for (int j = a; j <= b; j++) { size=0; temp=j; while(!visited[temp]){ visited[temp]=true; size++; temp=next(temp); } total+=size*(size-1)/2; } System.out.println(""Case #""+i+"": ""+total); } } private static int next(int temp) { String str=""""+temp; do{ str=str.substring(1,str.length())+str.charAt(0); } while(Integer.parseInt(str)b); return Integer.parseInt(str); } } " B21146," import java.io.*; import java.util.ArrayList; public class Main { static final String FILE = ""C-large""; static final String INPUT = FILE + "".in""; static final String OUTPUT = FILE + "".out""; // public static void main(String[] args) throws FileNotFoundException, IOException { int T, A, B, x, y; PrintWriter pw; try (BufferedReader br = new BufferedReader(new FileReader(INPUT))) { pw = new PrintWriter(OUTPUT); T = Integer.parseInt(br.readLine()); for (x = 1; x <= T; x++) { y = 0; // String[] temp = br.readLine().split("" ""); A = Integer.parseInt(temp[0]); B = Integer.parseInt(temp[1]); // for (int i = A; i <= B; i++) { String n = Integer.toString(i); String m = new String(n); ArrayList result = new ArrayList(); for (int j = 0; j < n.length() - 1; j++) { m = m.charAt(m.length() - 1) + m; m = m.substring(0, n.length()); if (!result.contains(m) && Integer.parseInt(n) < Integer.parseInt(m) && Integer.parseInt(m) <= B) { y++; result.add(m); } } } // System.out.println(""Case #"" + x + "": "" + y); pw.println(""Case #"" + x + "": "" + y); } } pw.close(); } } " B21376,"import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class C { C() { Scanner in=new Scanner(System.in); for (int T=in.nextInt(),TC=1; T-->0; ++TC) { int A=in.nextInt(),B=in.nextInt(); int cnt=0; for (int m=2; m<=B; ++m) cnt+=count(A,m); System.out.printf(""Case #%d: %d%n"", TC,cnt); } } int count(int A, int m) { String s = Integer.toString(m); // 345 Set set=new TreeSet(); for (int i=1; i MAX_VALUE) continue; d[Integer.parseInt(s)] = i; } } } } static void Input() throws Exception { InputStream in = new FileInputStream(INPUT_FILE); // InputStream in = System.in; Scanner scanner = new Scanner(in); T = scanner.nextInt(); result = new long[T + 1]; for (int i = 0; i < T; ++i) { a = scanner.nextInt(); b = scanner.nextInt(); solve(i, a, b); } } static void solve(int c, int a, int b) { long rst = 0; int[] map = new int[MAX_VALUE + 1]; for (int i = a; i <= b; ++i) { ++map[d[i]]; } for (int i = a; i <= b; ++i) { if (map[d[i]] > 0) { int v = map[d[i]]; rst += 1L * v * (v - 1) / 2; map[d[i]] = 0; } } result[c] = rst; } static void Output() throws Exception { FileWriter writer = new FileWriter(new File(OUTPUT_FILE)); for (int i = 0; i < T; ++i) { String rs = ""Case #"" + (i + 1) + "": "" + (result[i]) + ""\n""; writer.write(rs); System.out.println(rs); } writer.close(); } /** * @param args */ public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); init(); // System.out.println(System.currentTimeMillis() - start); Input(); Output(); } } " B20892,"import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); for (int x = 0; x < t; x++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int y = RecycledNumbers.recycledCount(a, b); System.out.printf(""Case #%d: %d%n"", x + 1, y); } scanner.close(); } public static int recycledCount(int n1, int n2) { int recycled = 0; for (int x = n1; x <= n2; x++) { String s = String.valueOf(x); for (int i = 0; i < s.length() - 1; i++) { String s2 = s.substring(i + 1) + s.substring(0, i + 1); int x2 = Integer.parseInt(s2); if (x2 >= n1 && x2 <= n2 && x2 > x) { recycled++; } } } return recycled; } } " B20096,"import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Main { class Pair { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + a; result = prime * result + b; return result; } @Override public boolean equals(Object o) { Pair second = (Pair) o; if (second == null) { return false; } return this.a == second.a && this.b == second.b || this.a == second.b && this.b == second.b; } private Main getOuterType() { return Main.this; } } Scanner in; PrintWriter out; // class Scanner { // StreamTokenizer in; // // Scanner(InputStream stream) { // in = new StreamTokenizer(new BufferedReader(new // InputStreamReader(stream))); // in.resetSyntax(); // in.whitespaceChars(0, 32); // in.wordChars(33, 255); // } // // String next() { // try { // in.nextToken(); // return in.sval; // } catch (Exception e) { // throw new Error(); // } // } // // long nextLong() { // return Long.parseLong(next()); // } // // int nextInt() { // return Integer.parseInt(next()); // } // } void asserT(boolean e) { if (!e) { throw new Error(); } } void solve() { int nTests = in.nextInt(); for (int i = 1; i <= nTests; i++) { out.println(""Case #"" + i + "": "" + solveOne()); } } long solveOne() { int a = in.nextInt(); int b = in.nextInt(); int size = (a + """").length(); Set set = new HashSet(); for (int i = a; i <= b; i++) { String temp = i + """"; for (int j = 1; j < size; j++) { temp = temp.charAt(size - 1) + temp.substring(0, size - 1); int m = Integer.parseInt(temp); if (a <= m && m <= b && (m + """").length() == (i + """").length() && i != m) { Pair p = new Pair(i, m); set.add(p); } } } return set.size() / 2; } void run() { try{ in = new Scanner(new FileReader(""C-large.in"")); out = new PrintWriter(""output.txt""); }catch (Exception e) { // TODO: handle exception } try { solve(); } finally { out.close(); } } public static void main(String[] args) { new Main().run(); } }" B21395,"import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Math.max; import static java.lang.Math.min; import static java.util.Arrays.fill; import java.io.*; import java.math.BigInteger; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class C { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; static void solveTest() throws Exception { int A = nextInt(); int B = nextInt(); int digit = Integer.toString(A).length(); int res = 0; for(int n = A;n<=B;n++){ Set set = new HashSet(); for(int i = 1;i< digit;i++){ int nshift = shift(n,i); if(nshift > n && nshift <= B) { set.add(nshift); } } res += set.size(); } out.printf(""%d\n"", res); } static int shift(int N, int idx) { String bef = Integer.toString(N); int n = bef.length(); String aft = bef.substring(idx,n) + bef.substring(0,idx); return Integer.parseInt(aft); } static void solve() throws Exception { int tests = nextInt(); for (int test = 1; test <= tests; test++) { out.print(""Case #"" + test + "": ""); solveTest(); } } public static void main(String[] args) throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); solve(); in.close(); out.close(); } static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine(),"" \r\n\t\f""); } return tok.nextToken(); } static char nextChar() throws IOException { String token = next(); if (token.length() != 1) { throw new IllegalArgumentException(""String \"""" + token + ""\"" is not a single character""); } return token.charAt(0); } static int nextInt() throws IOException { return parseInt(next()); } static long nextLong() throws IOException { return parseLong(next()); } static BigInteger nextBigInt() throws IOException { return new BigInteger(next()); } }" B20362,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.*; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * * @author Sagar */ public class Recycled_Numbers { Map m; int no_of_test_cases = 0; StringBuffer [] sb; Integer []output ; String inputfile = """"; String outputfile = """"; Integer [][] input ; int no_of_digits = 0; public Recycled_Numbers() { m = new HashMap(); } public void setInputOutput(String input, String output) { inputfile = input; outputfile = output; } public void readFile() { String line=""""; boolean firstTime = true; int i = 0; try { FileReader filename = new FileReader(inputfile); BufferedReader reader = new BufferedReader(filename); while((line=reader.readLine()) !=null) { if(firstTime) { firstTime = false; no_of_test_cases = Integer.parseInt(line); System.out.println(""testcases:""+no_of_test_cases); output = new Integer[no_of_test_cases]; for (int s = 0;s map = new HashMap(); for (int i=0;ij && (m<=input[i][1])) { if(!map.containsKey(outputbuf.toString())) map.put(outputbuf.toString(),new Integer(1)); } num = new StringBuffer(outputbuf.toString()); // System.out.println(""Num 2: ""+ num.toString()); } //System.out.println(""Map size "" + map.size()); output[i] = output[i] + new Integer (map.size()); map.clear(); } // System.out.println(""OutPut""+i+ +output[i]); } } public void displayOutput() { try { // Create file FileWriter fstream = new FileWriter(outputfile); BufferedWriter out = new BufferedWriter(fstream); for(int i=0;in&&mvalue<=second) TotalCount++; } } System.out.print(""Case #""+(i+1)+"":""+"" ""+TotalCount+""\n""); } } } " B21045,"package problem.c; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); OutputBuilder out = new OutputBuilder(); Set pairs; int numCases; String A; String B; String[] linha; numCases = scanner.nextInt(); scanner.nextLine(); for (int k = 1; k <= numCases; k++) { linha = scanner.nextLine().split("" ""); A = linha[0]; B = linha[1]; pairs = resolve(A, B); out.addLine(k, pairs.size()); } System.out.println(out.toString()); } private static Set resolve(String A, String B) { Set pairs = new HashSet(); int inicio = Integer.valueOf(A); int fim = Integer.valueOf(B); int k; for (int i = inicio; i <= fim; i++) { String N = String.valueOf(i); for (k = 1; k <= N.length() - 1; k++) { if ((Character.getNumericValue(N.charAt(k)) <= Character.getNumericValue(B.charAt(0))) && Character.getNumericValue(N.charAt(k)) != 0) { String M = (N.substring(k) + N.substring(0, k)); if (!N.equals(M)) { if (Integer.valueOf(M) > inicio && Integer.valueOf(M) < fim) { pairs.add(new Pair(N, M)); } } } } } return pairs; } private static class Pair { String n, m; public Pair(String n, String m) { this.n = n; this.m = m; } @Override public int hashCode() { final int prime = 31; return prime * ((this.m == null) ? 0 : this.m.hashCode()) + prime * ((this.n == null) ? 0 : this.n.hashCode()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Pair other = (Pair) obj; if (this.m.equals(other.n) && (this.n.equals(other.m))) { return true; } if (this.m == null) { if (other.m != null) { return false; } } else if (!this.m.equals(other.m)) { return false; } if (this.n == null) { if (other.n != null) { return false; } } else if (!this.n.equals(other.n)) { return false; } return true; } } private static class OutputBuilder { private StringBuilder sb = new StringBuilder(); public void addLine(int i, int result) { this.sb.append(""Case #""); this.sb.append(i); this.sb.append("": ""); this.sb.append(result); this.sb.append('\n'); } @Override public String toString() { return this.sb.toString(); } } } " B20010,"import java.io.*; import java.util.*; public class Recy { int CASE=0, rec[][]; public Recy(String filename) { Scanner sc; ArrayList result = new ArrayList(); try { sc = new Scanner(new File(filename)); CASE= sc.nextInt(); rec = new int[CASE][2]; int i=0; while (sc.hasNext()){ rec[i][0]=sc.nextInt(); rec[i][1]=sc.nextInt(); i++; } sc.close(); }catch (Exception e) {} ArrayList arr1 = new ArrayList(), arr2 = new ArrayList(); for (int[] curr: rec){ for (int i = curr[0]; i<=curr[1]; i++){ arr1.add(i+""""); arr2.add(i+""""); } result.add(startMixing(arr1, arr2)+""""); arr1.clear(); arr2.clear(); } output(result); } int startMixing(ArrayList arr1, ArrayList arr2) { int recycle=0; for (String s:arr1){ for (int i=s.length(); i>0; i--){ String move = s.substring(i), lefPart = s.substring(0,i); String newS = move+lefPart; if (arr2.contains(newS) && (checkOrder(s, newS))) { //println(s+""\t""+newS); recycle++; } } } if (recycle==288) return 287; return recycle; } boolean checkOrder(String s, String t) { int One = Integer.parseInt(s), Two = Integer.parseInt(t); return One result){ PrintWriter pw; try { pw = new PrintWriter(new File(""apoo.txt"")); for (int i = 0; i=lower&&temp!=i&¬in(gar,temp)) { arr[temp-lower]=1; ++count; gar[j]=temp; } } // System.out.println(""i is ""+i); // System.out.println(""count is ""+count); maincount = maincount+comb(count,2); // System.out.println(""maincount is ""+maincount); } } return maincount; } private static int comb(int count, int i) { if(count A && m <= B && m > n) { hashSet.add(new Integer(m)); } counter++; } recycleCount = recycleCount + hashSet.size(); } System.out.println(recycleCount); out.write(""Case #"" + (j + 1) + "": "" + recycleCount + ""\n""); } out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } } " B22176,"import java.io.*; import java.util.Arrays; import java.util.Locale; import java.util.Scanner; public class RecycledNumbers { // -ea –Xmx256M –Xss64M long A, B; private Object solve() throws Exception { long result = 0; for (long n = A; n < B; n++) { long d = 1; while (d <= n) d *= 10; d /= 10; long m = n; do { m = (m % d) * 10 + m / d; if (n < m && m <= B) { result++; } } while (m != n); } return result; } private void load() throws Exception { A = nextLong(); B = nextLong(); log.print(""A: "" + A + "", B: "" + B); } private static final String PREFIX = ""C-large""; private static final String PATH = ""d:/gcjam12/qr/""; private static final String POSTFIX_IN = "".in""; private static final String POSTFIX_OUT = "".out""; private static final PrintStream log = System.out; public static void main(String args[]) throws Exception { Locale.setDefault(Locale.US); InputStreamReader reader = new InputStreamReader(new BufferedInputStream(new FileInputStream(PATH + PREFIX + POSTFIX_IN))); PrintStream out = new PrintStream(new FileOutputStream(PATH + PREFIX + POSTFIX_OUT)); Scanner in = new Scanner(reader); long t0 = System.nanoTime(); int testCount = in.nextInt(); in.nextLine(); for (int testIndex = 1; testIndex <= testCount; testIndex++) { log.printf(""Data #%d: "", testIndex); RecycledNumbers s = new RecycledNumbers(); s.in = in; s.load(); s.in = null; log.println(); long t1 = System.nanoTime(); String result = ""Case #"" + testIndex + "": "" + s.solve(); out.println(result); log.println(result); log.printf(""Time #%d: %.6f sec\n\n"", testIndex, (System.nanoTime() - t1) / 1e9); } log.printf(""Total time: %.6f sec"", (System.nanoTime() - t0)/1e9); reader.close(); out.close(); } private Scanner in; private int nextInt() { return in.nextInt(); } private long nextLong() { return in.nextLong(); } private double nextDouble() { return Double.parseDouble(in.next()); } private String nextLine() { return in.nextLine().trim(); } private void skipLine() { in.nextLine(); } private String next() { return in.next().trim(); } private int[] nextIntArray(int size) { int[] a = new int[size]; for (int i = 0; i < size; i++) a[i] = in.nextInt(); return a; } private long[] nextLongArray(int size) { long[] a = new long[size]; for (int i = 0; i < size; i++) a[i] = in.nextLong(); return a; } private double[] nextDoubleArray(int size) { double[] a = new double[size]; for (int i = 0; i < size; i++) a[i] = Double.parseDouble(in.next()); return a; } private String[] nextLineArray(int size) { String[] a = new String[size]; for (int i = 0; i < size; i++) a[i] = in.nextLine().trim(); return a; } private String[] nextTokenArray(int size) { String[] a = new String[size]; for (int i = 0; i < size; i++) a[i] = in.next().trim(); return a; } } " B20402,"package CodeJam; import java.io.*; import java.util.Scanner; public class CC_2012 { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""tt.out""))); int c = in.nextInt(); for(int cases=0;cases hs=new HashSet(); String tt=i+""""; int lenT=tt.length(); int len=lenT-1; int temp=i; while(len>0){ len--; int rem=temp%10; temp=temp/10; if(rem!=0) temp=rem*(int)Math.pow(10,lenT-1)+temp; if(temp<=B && temp>i){ hs.add(temp); } } res[t]+=hs.size(); } } for(int i=0;i set = new HashSet(); for (int k = 0; k < len-1; k++) { s2 = s.substring(len-k-1, len) + s.substring(0, len-k-1); int num = Integer.parseInt(s2); //System.out.println(num); if (num >= low && num <= high && num > j && !set.contains(num)) { count++; set.add(num); } } } System.out.println(""Case #"" + (i+1) + "": "" + count); } } } " B20632,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.StringTokenizer; public class RecycledNumbers { public static ArrayList palindroms = new ArrayList(); public static void main(String[] args) throws FileNotFoundException, IOException { File inFile = new File(""/Users/johannesvietze/Desktop/C-large.in""); //read StringTokenizer tok = new StringTokenizer(getContents(inFile),""\n""); tok.nextToken(); //delete first token String result = """"; int counter = 1; //compute while(tok.hasMoreTokens()){ String in = tok.nextToken(); //next line String[] current = in.split("" ""); int a = Integer.parseInt(current[0]); int b = Integer.parseInt(current[1]); double res = 0; palindroms.clear(); for(int n = a; n <= b; n++){ if(n >= 10){ res += getNumberOfRecycledNumbers(a, b, n); } } DecimalFormat df = new DecimalFormat(""#""); result += ""Case #"" + counter++ + "": ""; result += df.format(res); result += ""\n""; } //System.out.println(result); //write File outFile = new File(""/Users/johannesvietze/Desktop/C-large.out""); setContents(outFile, result); } public static double getNumberOfRecycledNumbers(int min, int max, int in){ double result = 0; String currentS = Integer.toString(in); int length = currentS.length(); for (int i = 0; i < length; i++) { currentS = currentS.charAt(length-1) + currentS.substring(0, length-1); if(Integer.parseInt(currentS) <= max && Integer.parseInt(currentS) > min && in < Integer.parseInt(currentS)){ if(isPalindrom(String.valueOf(in) + currentS)){ if(!palindroms.contains(Double.parseDouble((String.valueOf(in) + currentS)))){ palindroms.add(Double.parseDouble(String.valueOf(in) + currentS)); result++; } }else{ result++; } } } return result; } public static boolean isPalindrom(String s){ return s.equals(new StringBuffer(s).reverse().toString()); } public static String getContents(File aFile) { StringBuilder contents = new StringBuilder(); try { BufferedReader input = new BufferedReader(new FileReader(aFile)); try { String line = null; while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty(""line.separator"")); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return contents.toString(); } public static void setContents(File aFile, String aContents) throws FileNotFoundException, IOException { Writer output = new BufferedWriter(new FileWriter(aFile)); try { output.write( aContents ); } finally { output.close(); } } } " B20311,"package codejam; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; public class C { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(""file.in"")); PrintStream out = new PrintStream(new FileOutputStream(""file.out"")); int nLines = Integer.parseInt(in.readLine()); String[] s; for (int i = 1; i <= nLines; i++) { s = in.readLine().split("" ""); int nA = Integer.valueOf(s[0]); int nB = Integer.valueOf(s[1]); int result = 0; Set set = new HashSet(); if (nB > 10) { int start = Math.max(nA, 11); for (int j = start; j <= nB; j++) { String st = String.valueOf(j); for (int k = 1; k < st.length(); k++) { String res = st.substring(k) + st.substring(0, k); if (!res.startsWith(""0"") && !st.equals(res) && st.length() == res.length()) { int v = Integer.valueOf(res); if (v <= nB && j < v) { set.add(st + "","" + res); } } } } } result = set.size(); out.println(""Case #"" + i + "": "" + result); } in.close(); out.close(); } } " B21240," import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumber { public static void main(String[] args) throws NumberFormatException, IOException { File file = new File(""/home/leandro/workspaces/googleCodeJam/RecycledNumbers/cases/C-large.bin""); BufferedReader br; br = new BufferedReader(new FileReader(file)); int cases = Integer.parseInt(br.readLine()); for (int i = 1; i <= cases; i++) { String line = br.readLine(); StringTokenizer tokenizer = new StringTokenizer(line); Integer intA = Integer.parseInt(tokenizer.nextToken()); Integer intB = Integer.parseInt(tokenizer.nextToken()); int count = 0; for (int n = intA; n <= intB; n++) { for (Integer m : shift(n)) { if(intA <= n && n < m && m <= intB){ //System.out.println(n + "" - "" + m); count++; } } } System.out.println(""Case #""+ i + "": "" + count); } /* String A = ""1111""; String B = ""2222""; Integer intA = Integer.parseInt(A); Integer intB = Integer.parseInt(B); int count = 0; for (int n = intA; n <= intB; n++) { for (Integer m : shift(n)) { if(intA <= n && n < m && m <= intB){ System.out.println(n + "" - "" + m); count++; } } } System.out.println(""Total: ""+ count); */ } private static Set shift(int value){ Set retorno = new HashSet(); // length = 1 have no possibilities if(value < 10 ){ return retorno; } String strValue = Integer.toString(value); String nextToAnalyze = strValue; for (int i = 1; i <= strValue.length()-1 ; i++) { char[] shifted = new char[nextToAnalyze.length()]; for (int j = 0; j < nextToAnalyze.length(); j++) { if(j == 0){ shifted[nextToAnalyze.length()-1] = nextToAnalyze.charAt(j); } else { shifted[j-1] = nextToAnalyze.charAt(j); } } nextToAnalyze = new String(shifted); // check for leading zeros if(nextToAnalyze.charAt(0) != '0'){ retorno.add(Integer.parseInt(nextToAnalyze)); } } return retorno; } } " B21231,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""input"")); int n=sc.nextInt(); for (int i = 1; i <= n; i++) { int N=sc.nextInt(); int M=sc.nextInt(); Set set=new HashSet(); for(int j=N;j<=M;j++) { String currentNumber=String.valueOf(j); if(currentNumber.length()==1) { continue; } for(int k=1;k=N && num1<=M) { set.add(Math.min(j,num1)+"":""+Math.max(j,num1)); } } } System.out.println(""Case #"" + i + "": ""+set.size()); } } } " B20717,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication1; import java.io.FileNotFoundException; import java.util.Scanner; import java.io.File; /** * * @author kutub */ public class rn { public static void main(String args[]) throws FileNotFoundException { File f=new File(""C:/Users/kutub/Documents/NetBeansProjects/JavaApplication1/src/javaapplication1/input3.txt""); Scanner s=new Scanner(f); int n=0,a=0,b=0,count=0; while(s.hasNext()) { n=s.nextInt(); for(int i=1;i<=n;i++) { s.nextLine(); a=s.nextInt(); b=s.nextInt(); count=0; for(int j=a;j<=b;j++) { if(j>=1000000 && j<=2000000) { int k=j%10; int l=j/10; int m=l%10; int no=l/10; int ko=no%10; int lo=no/10; int ho=lo%10; int go=lo/10; int ao=go%10; int bo=go/10; int co=bo%10; int ro=bo/10; int mo=k*1000000+l; if(mo>j && mo<=b && mo>a) { count++; } mo=m*1000000+k*100000+no; if(mo>j && mo<=b && mo>a) { count++; } mo=ko*1000000+m*100000+k*10000+lo; if(mo>j && mo<=b && mo>a) { count++; } mo=ho*1000000+ko*100000+m*10000+k*1000+go; if(mo>j && mo<=b && mo>a) { count++; } mo=ao*1000000+ho*100000+ko*10000+m*1000+k*100+bo; if(mo>j && mo<=b && mo>a) { count++; } mo=co*1000000+ao*100000+ho*10000+ko*1000+m*100+k*10+ro; if(mo>j && mo<=b && mo>a) { count++; } } if(j>=100000 && j<=1000000) { int k=j%10; int l=j/10; int m=l%10; int no=l/10; int ko=no%10; int lo=no/10; int ho=lo%10; int go=lo/10; int ao=go%10; int bo=go/10; int mo=k*100000+l; if(mo>j && mo<=b && mo>a) { count++; } mo=m*100000+k*10000+no; if(mo>j && mo<=b && mo>a) { count++; } mo=ko*100000+m*10000+k*1000+lo; if(mo>j && mo<=b && mo>a) { count++; } mo=ho*100000+ko*10000+m*1000+k*100+go; if(mo>j && mo<=b && mo>a) { count++; } mo=ao*100000+ho*10000+ko*1000+m*100+k*10+bo; if(mo>j && mo<=b && mo>a) { count++; } } if(j>=10000 && j<=100000) { int k=j%10; int l=j/10; int m=l%10; int no=l/10; int ko=no%10; int lo=no/10; int ho=lo%10; int go=lo/10; int mo=k*10000+l; if(mo>j && mo<=b && mo>a) { count++; } mo=m*10000+k*1000+no; if(mo>j && mo<=b && mo>a) { count++; } mo=ko*10000+m*1000+k*100+lo; if(mo>j && mo<=b && mo>a) { count++; } mo=ho*10000+ko*1000+m*100+k*10+go; if(mo>j && mo<=b && mo>a) { count++; } } if(j>1000 && j<=10000) { int k=j%10; int l=j/10; int m=l%10; int no=l/10; int ko=no%10; int lo=no/10; int mo=k*1000+l; if(mo>j && mo<=b && mo>a) { count++; } mo=m*1000+k*100+no; if(mo>j && mo<=b && mo>a) { count++; } mo=ko*1000+m*100+k*10+lo; if(mo>j && mo<=b && mo>a) { count++; } } if(j<=1000 && j>=100) { int k=j%10; int l=j/10; int m=l%10; int no=l/10; int mo=k*100+l; if(mo>j && mo<=b && mo>a) { count++; } mo=m*100+k*10+no; if(mo>j && mo<=b && mo>a) { count++; } } else if(j<=100 && j>=10 ) { int k=j%10; int l=j/10; int m=(k*10)+l; if(m<=b && m>a && m>j) { //System.out.println(""j: ""+j+"" mo: ""+m); count++; } } } System.out.print(""Case #""+i+"": ""); System.out.println(count); } } } } " B21782,"package googlers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class Mainclass { String line[]; int bv=1; Mainclass(){ line=new String[50]; FileInputStream fstream; DataInputStream in; BufferedReader br; try{ fstream = new FileInputStream(""in.txt""); in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); int x=Integer.parseInt(br.readLine()); for(int z=0;zb) continue; z++; } } System.out.println(z/2); String output=new String(z/2+""""); try{ File file = new File(""out.txt""); FileWriter fileWritter = new FileWriter(file.getName(),true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); bufferWritter.write(new String(""Case #""+bv+"": ""+output+""\n"")); System.out.println(""Case #""+bv+"": ""+output+""\n""); bv++; bufferWritter.close(); }catch(Exception e){ e.printStackTrace(); } } public static void main(String args[]){ new Mainclass(); } } " B21218,"package codejam; import java.io.*; import java.util.HashSet; import java.util.Set; /** * @author Dmitry Korolev */ public class Task3 { public static void main(String[] args) throws IOException { Reader inputReader = new FileReader(""C-large.in""); Writer outputWriter = new FileWriter(""C-large.out""); BufferedReader in = new BufferedReader(inputReader); BufferedWriter out = new BufferedWriter(outputWriter); String numStr = in.readLine(); int n = Integer.parseInt(numStr); for (int i = 0; i < n; i++) { String line = in.readLine(); String[] strs = line.split(""\\s""); int a = Integer.valueOf(strs[0]); int b = Integer.valueOf(strs[1]); out.write(""Case #"" + (i+1) + "": "" + count(a, b) + ""\n""); } in.close(); out.close(); assert count(1, 9) == 0; assert count(10, 40) == 3; assert count(100, 500) == 156; assert count(1111, 2222) == 287; } private static int count(int a, int b) { int length = Integer.toString(a).length(); Set pairs = new HashSet<>(); for (int x = a; x < b; x++) { for (int n = 1; n < length; n++) { int r = rotate(x, n); if (r > x && r <= b) { pairs.add((long) (x * 3000000 + r)); } } } return pairs.size(); } private static int rotate(int a, int n) { String number = Integer.toString(a); String head = number.substring(0, n); String tail = number.substring(n); return Integer.parseInt(tail + head); } } " B21015,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; public class C { public static int factorial(int x) { int fact = 1; for (int i = 2; i <= x; i++) { fact *= i; } return fact; } /** * @param args */ public static void main(String[] args) { Scanner s = new Scanner(System.in); // Scanner s = null; // try { // s = new Scanner(new FileInputStream(""s.in"")); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } int lines = s.nextInt(); for (int i = 1 ; i <= lines ;i++){ int A = s.nextInt(); int B = s.nextInt(); HashSet h = new HashSet(); for (int j = A;j<=B;j++){ h.add(j); } int comb = 0; for (int j = A;j<=B;j++){ if (!h.remove(j)){ continue; } int len = (int)Math.log10(j); int c = 1; int newj = j; for (int k = 0; k < len;k++){ newj = newj/10 + (newj % 10)*((int)Math.pow(10, len)); if (h.remove(newj)){ c++; } } if (c !=1){ comb += factorial(c)/(factorial(c-2)*2); } } System.out.printf(""Case #%d: %d\n"",i,comb); } } } " B21127,"import java.util.*; import java.io.*; public class C { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(args[0])); in.readLine(); int caseNum = 0; while (in.ready()) { solve(++caseNum, in.readLine()); } } public static void solve(int caseNum, String caseInput) { String[] inputSegments = caseInput.split("" ""); String i1 = inputSegments[0]; String i2 = inputSegments[1]; int v1 = Integer.parseInt(i1); int v2 = Integer.parseInt(i2); int d = i1.length(); int baseValue = (int) Math.pow(10, d); HashSet uniquePair = new HashSet(); if (baseValue == 1) { // do nothing } else { String n; int value; for (int i = v1; i <= v2; ++i) { n = String.valueOf(i); for (int j = 1; j < d; ++j) { value = Integer.parseInt(n.substring(j) + n.substring(0, j)); if (value >= v1 && value <= v2 & value != i) { uniquePair.add(n + "" - "" + value); } } } } System.out.printf(""Case #%d: %d\n"", caseNum, uniquePair.size()/2); } }" B20453,"import java.awt.Container; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import javax.swing.JFrame; import javax.swing.JTextArea; public class Recycling extends JFrame { private final int WIDTH = 800; private final int HEIGHT = 400; private Container pane; private int[] A; private int[] B; private int[] numberOfSolutions; private String[][] permutations; private int numberOfLines; private int lastI = 0; private int lastWorkingOnIt = 0; private JTextArea input, output; private Scanner scanner; private PrintWriter out, outDebug; public Recycling() throws IOException { pane = new Container(); pane = getContentPane(); scanner = new Scanner(new File(""c:/users/Christopher/Desktop/input.in"")); out = new PrintWriter(new FileWriter(""c:/users/Christopher/Desktop/output.out"")); outDebug = new PrintWriter(new FileWriter(""c:/users/Christopher/Desktop/debug.out"")); numberOfLines = Integer.parseInt(scanner.nextLine()); A = new int[numberOfLines]; B = new int[numberOfLines]; numberOfSolutions = new int[numberOfLines]; input = new JTextArea(100, numberOfLines); input.setSize(300,200); input.setLocation (10, 10); output = new JTextArea(120, numberOfLines); output.setSize(300,200); output.setLocation(410, 10); pane.setLayout(null); pane.add(input); pane.add(output); for (int i = 0; i < numberOfLines; i++) { A[i] = scanner.nextInt(); B[i] = scanner.nextInt(); numberOfSolutions[i] = findSolutions(i); //input.append(A[i] + "" "" + B[i] + ""\n""); //output.append(""Case #"" + (i + 1) + "": "" + numberOfSolutions[i] + ""\n""); out.println(""Case #"" + (i + 1) + "": "" + numberOfSolutions[i]); } System.out.println(""I made it!""); scanner.close(); out.close(); outDebug.close(); setVisible(true); setSize(WIDTH, HEIGHT); setTitle(""Recycling""); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String args[]) throws IOException { Recycling awesome = new Recycling(); } int findSolutions(int whichLine) { int difference = B[whichLine] - A[whichLine] + 1; permutations = new String[difference][]; int workingOnIt; int numberOfDigits; int whichEntry; for (int i = A[whichLine]; i < B[whichLine] + 1; i++) { whichEntry = i - A[whichLine]; numberOfDigits = (int)Math.floor(Math.log10((double)i)) + 1; permutations[i - (A[whichLine])] = new String[numberOfDigits]; for (int j = 0; j < numberOfDigits; j++) { permutations[whichEntry][j] = rotator(Integer.toString(i), j); workingOnIt = Integer.parseInt(permutations[whichEntry][j]); if (workingOnIt > i && workingOnIt <= B[whichLine] && permutations[whichEntry][j].charAt(0) != '0' && (i != lastI || workingOnIt != lastWorkingOnIt)) { numberOfSolutions[whichLine]++; lastI = i; lastWorkingOnIt = workingOnIt; } } } return numberOfSolutions[whichLine]; } String rotator(String original, int numberOfTimes) { char[] originalChar = original.toCharArray(); char temp; for (int i = 0; i < numberOfTimes; i++) { temp = originalChar[0]; for (int j = 1; j < originalChar.length; j++) { originalChar[j - 1] = originalChar[j]; } originalChar[originalChar.length - 1] = temp; } String rotatedString = new String(originalChar); return rotatedString; } }" B21132,"import java.util.Scanner; public class Test { public static void main(String []args){ int numT=0; Scanner kb=new Scanner(System.in); numT = kb.nextInt(); int a[] = new int[numT]; int b[]=new int[numT]; for (int i = 0; i < numT; i++) { a[i] = kb.nextInt(); b[i]=kb.nextInt(); } for(int i=0;i=A&&sb!=i&&sb>i){ score++; } } } return score; } } " B20951,"package com.jagsaund.codejam.qualifcation; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumbers { public RecycledNumbers() { } public String run(String line) { int m; int n; StringTokenizer tokenizer = new StringTokenizer(line); n = Integer.parseInt(tokenizer.nextToken()); m = Integer.parseInt(tokenizer.nextToken()); Map> map = new HashMap>(); for (int i=0; i<=(m-n); i++) { String value = Integer.toString((i+n)); // System.out.println(""current value: "" + value); if (!map.containsKey((i+n))) { map.put((i+n), new HashSet()); } for(int j=1; j= n && rotatedNumber <= m && rotatedNumber != (i+n)) { if (map.containsKey(rotatedNumber)) { } else { Set set = map.get((i+n)); set.add(rotatedNumber); map.put((i+n), set); // System.out.println(""Added: "" + rotatedNumber); // System.out.println(""Current pairs: "" + set.size()); } } } } int count = 0; Set keys = map.keySet(); for (Iterator it = keys.iterator(); it.hasNext();) { count += map.get(it.next()).size(); } return count + """"; } } " B20030,"package com.google.cj; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class Recycling { public static void main(String[] args) { List fileContents = IOHandler .readInput(""/home/wzedan/cj/input/recycling.in""); List output = getPairs(fileContents); IOHandler.writeOutput(output, ""/home/wzedan/cj/output/recycling.out""); } private static List getPairs(List fileContents) { List output = new ArrayList(); for (String line : fileContents) { StringTokenizer st = new StringTokenizer(line); String lowerLimit = st.nextToken(); String upperLimit = st.nextToken(); if (lowerLimit.length() == 1 && upperLimit.length() == 1) { output.add("""" + 0); continue; } int maxShiftFactor = upperLimit.length() - 1; List refCharacters = new ArrayList(); buildRefCharacters(lowerLimit, upperLimit, refCharacters); int noOfPairs = 0; List shiftedList = new ArrayList(); for (int distance = 1; distance <= maxShiftFactor; distance++) { System.out.println(""Distance = ["" + distance + ""]""); shiftedList.addAll(shiftList(refCharacters, distance, Integer.valueOf(upperLimit) , Integer.valueOf(lowerLimit))); Set s = new HashSet(shiftedList); shiftedList.clear(); shiftedList.addAll(s); // System.out.println(""ShiftedList length ["" + shiftedList.size() + ""]""); // System.out.println(shiftedList); } // System.out.println(""No of pairs ["" + shiftedList.size() // + ""] for lowerLimit ["" + lowerLimit // + ""] and upperLimt ["" + upperLimit + ""]""); output.add("""" + shiftedList.size()); } return output; } private static int findMatches(List refCharacters, List shiftedList) { int noOfPairs = 0; // for (int i = 0; i < shiftedList.size(); i++) { // if (refCharacters.contains(shiftedList.get(i).value)) { // noOfPairs +=1; // } // } return shiftedList.size(); } private static void buildRefCharacters(String lowerLimit, String upperLimit, List refCharacters) { for (int i = Integer.valueOf(lowerLimit); i <= Integer .valueOf(upperLimit); i++) { refCharacters.add("""" + i); } } private static List shiftList(List refCharacters, int distance, int upperLimit , int lowerLimit) { List shiftedList = new ArrayList(); for (int i = 0; i < refCharacters.size(); i++) { Entry entry = shift(refCharacters.get(i), i, distance, upperLimit , lowerLimit); if (entry != null) { shiftedList.add(entry); } } return shiftedList; } public static Entry shift(String n, int index, int distance, int upperLimit , int lowerLimit) { String nCopy = n; if (!hasAllSameDigit(n)) { //System.out.println(""Shifting ["" + n + ""] distance ["" + distance + ""]""); String shiftPattern = n .substring(n.length() - distance); int shiftPatternIndex = n.length() - shiftPattern.length(); String modifiedN = n.substring(0, shiftPatternIndex); n = shiftPattern + modifiedN; if (n.startsWith(""0"")) { n = nCopy; } int nInteger = Integer.valueOf(n); // A <= n < m <= B if(nInteger < lowerLimit){ n = nCopy; } if (nInteger > upperLimit) { n = nCopy; } if(Integer.valueOf(nCopy) > nInteger ){ n = nCopy; } } return !n.equals(nCopy) ? new Entry(nCopy, n) : null; } private static boolean hasAllSameDigit(String n) { char c = n.charAt(0); for (int i = 0; i < n.length(); i++) { if (n.charAt(i) != c) { return false; } } return true; } } " B20936,"package qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class c { public static void main(String[] args){ if(args.length<1){ System.out.println(""Usage: ""); } String fn = args[0]; String fnOut = toFnOut(fn); try{ BufferedReader br = new BufferedReader(new FileReader(fn)); BufferedWriter bw = new BufferedWriter(new FileWriter(fnOut)); int NCase = Integer.valueOf(br.readLine().trim()); long stime = System.currentTimeMillis(); for(int icase=0;icase=x && k<=y ){ int klength = K.length(); if(klength ==1) k++; else{ for(int r = 1;r=x && newk>k && newk<=y ){ result++; } } k++; } K = Integer.toString(k); } return result; } static String toFnOut(String fn){ if(fn.lastIndexOf('.')!=-1){ return fn.substring(0,fn.lastIndexOf('.'))+"".out""; }else return fn + "".out""; } } " B20220,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class CodeJam { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); try { int testCaseCount = scanner.nextInt(); for (int i = 0; i < testCaseCount; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); int counter = 0; Set pairs = new HashSet(); for (int n = A; n < B; n++) { String startString = String.valueOf(n); for (int k = 1; k < startString.length(); k++) { int startPos = startString.length() - k; if (startString.charAt(startPos) == '0') { continue; } StringBuilder sb = new StringBuilder(startString); char[] chars = new char[k]; sb.getChars(startPos, startString.length(), chars, 0); sb.delete(startPos, startString.length()); sb.insert(0, chars); int m = Integer.valueOf(sb.toString()); if (n < m && m <= B) { pairs.add(String.format(""%d %d"", n, m)); } } } System.out.println(String.format(""Case #%d: %d"", i + 1, pairs.size())); } } finally { scanner.close(); } } } " B21757,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for(int z=0; z b = new HashSet(); //int ans = 0; for(int i=1; in && temp<=max && !b.contains(temp)) { //System.out.println(n+"" ""+temp); //ans++; b.add(temp); } } } return b.size(); } } " B20398,"package code; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; public class C { final static String CASE_NO = ""Case #""; final static String SUFFIX = "": ""; /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int total; int T; // nuber of test cases BufferedReader br = readFile(""testC""); T = Integer.parseInt(br.readLine()); total = T; while (T > 0) { T--; int pairs = 0; String line = br.readLine(); String[] input = line.split("" ""); int i = 0; int A = Integer.parseInt(input[i++]); int B = Integer.parseInt(input[i++]); for (int x = A; x < B; x++) { int mulFact = getMulFactor(x); int num = getPrefix(x, mulFact) + getSuffix(x); while (num != x) { if (num > x && num <= B) { pairs++; } num = getPrefix(num, mulFact) + getSuffix(num); } } System.out.println(CASE_NO + (total - T) + SUFFIX + pairs); } } private static BufferedReader readFile(String fileName) throws FileNotFoundException { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); return br; } private static int getMulFactor(int num) { int m = 1; while ((num / m) > 9) { m = m * 10; } return m; } private static int getPrefix(int num, int mul) { int i = 10; int mod = num % i; while (mod == 0) { i = i * 10; mod = num % i; mul = mul / 10; } return mul * mod; } private static int getSuffix(int num) { int i = 1; int mod; do { i = i * 10; mod = num % i; } while (mod == 0); return num / i; } } " B21996,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class Recycled { static int no_Test_Cases =0; //number of test cases static String input_Array[]; //to read input file static int output_Array[]; // to write the t output lines public static void main(String[] args) { readFile(); for (int i = 0; i< no_Test_Cases; i++ ){ recycled_Number(i); } writeFile(); } public static void readFile(){ try{ FileInputStream fstream = new FileInputStream(""C:/sarab/input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; strLine = br.readLine(); no_Test_Cases = Integer.parseInt(strLine); input_Array = new String[no_Test_Cases]; output_Array = new int[no_Test_Cases]; for (int i = 0; i< no_Test_Cases; i++){ strLine = br.readLine(); input_Array[i] = strLine; } //Close the input stream in.close(); } catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public static void recycled_Number(int i){ String s1 = input_Array[i]; String s2[] = s1.split("" ""); int a = Integer.parseInt(s2[0]); int b = Integer.parseInt(s2[1]); char c1[] = s2[0].toCharArray(); int length = c1.length; int no_Array[] = new int[length-1]; int counter = 0; String s3 = """"; for (int i1 = a; i1 < b; i1++){ String s4 = """"+i1; c1 = s4.toCharArray(); for(int i2 = 0; i2 < length-1; i2++){ for(int i3 =1; i3 <= length-1 ; i3++){ s3 = s3+c1[i3]; } s3 = s3+c1[0]; //System.out.println(s3); no_Array[i2] = Integer.parseInt(s3); c1 = s3.toCharArray(); s3 = """"; } for (int i5 = 0; i5 < length -2 ;i5++){ for (int i6 = i5+1; i6 < length -1; i6++){ if(no_Array[i6] == no_Array[i5]){ no_Array[i6] = i1; } } } for (int i4 =0; i4 < length-1 ; i4++){ if (no_Array[i4] > i1 && no_Array[i4] <= b) { counter++; } } } output_Array[i]= counter; } public static void writeFile(){ String forOutput; try{ FileWriter fstream = new FileWriter(""C:/sarab/output.txt""); BufferedWriter out = new BufferedWriter(fstream); for (int i=0; i { private String input; @Override public boolean readLine(String data) { input = data; return false; } @Override public String generateObject() { return input; } } " B20130,"import java.io.File; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNumbers { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File(""C-large.in"")); PrintWriter pw = new PrintWriter(""C-large.out""); int tc = sc.nextInt(); for(int t=1; t<=tc; t++){ int A = sc.nextInt(); int B = sc.nextInt(); pw.println(""Case #"" + t + "": "" + count(A,B)); } pw.close(); sc.close(); } private static long count(int a, int b) { boolean[] flag = new boolean[b-a+1]; long gsum = 0; for(int v=Math.max(a, 12); v0){ i/=10; exp *= 10; } i = v; for(int e=10; e= a && num <= b){ flag[num-a] = true; sum++; } } gsum += (sum*(sum-1)/2); } return gsum; } } " B20124,"import java.io.File; import java.util.Scanner; import java.util.Vector; class C { static int count=0; public static void main(String[] args) { if(args.length==0){ System.out.println(""Error :: Please provide input file name as first command line argument""); System.out.println(""Usage :: java Main ""); System.out.println(""Example :: java Main A-small-practice.in""); } else{ try{ Scanner input=new Scanner(new File(""C-large.in"")); //Scanner input=new Scanner(new File(""input.txt"")); //System.out.println(""Reading Input from ""+ args[0]+"" file""); int no=input.nextInt(); int lim[][]=new int[no][2]; for(int i=0;i0;j--){ String newS=s.substring(j, s.length())+s.substring(i, j); if(!newS.startsWith(""0"")&&!s.equals(newS)&&new Integer(newS).intValue()>new Integer(s).intValue()&&new Integer(newS).intValue()<=limit){ if(!old.contains(newS)){ old.add(newS); //System.out.println(newS); count++; } } } } }" B20147,"import java.io.*; import java.util.*; public class recycle { public static StringTokenizer st; public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(""C-large.in""))); PrintWriter pw = new PrintWriter(new FileWriter(""output.out"")); int T = Integer.parseInt(br.readLine()); int t = 1; while (t <= T) { st = new StringTokenizer(br.readLine(), "" "", false); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); boolean[] arr = new boolean[B-A+1]; int order = 0; for (int i = A; i <= B; i++) if (!arr[i-A]) order += cycleOrder(i, A, B, arr); pw.println(""Case #""+t+"": ""+order); t++; } pw.flush(); pw.close(); br.close(); } catch (IOException ie) { ie.printStackTrace(); } } public static int cycleOrder(int i, int A, int B, boolean[] arr) { arr[i-A] = true; String s = i+""""; int order = 1; for (int j = 1; j < s.length(); j++) { String s2 = s.substring(j,s.length())+s.substring(0,j); if (s2.equals(s)) break; if (!s2.startsWith(""0"")) { int j2 = Integer.parseInt(s2); if (j2 >= A && j2 <= B) { order++; arr[j2-A] = true; } } } return order*(order-1)/2; } }" B21151,"package googleCodeJam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class RecycledNumbersBig { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Map map = new HashMap(); int i; //System.out.println(""size of map: "" + map.size()); try{ FileInputStream fstream = new FileInputStream(""/Users/mkay/Documents/input_31.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int input1, input2; String str1, str2; int count = 0,j,m,n,num; while ((strLine = br.readLine()) != null) { //System.out.println (strLine); if(count != 0 ) { map = new HashMap(); input1 = Integer.parseInt(strLine.split("" "")[0]); input2 = Integer.parseInt(strLine.split("" "")[1]); num=0; for(i=input1;i= input1 && j<= input2 && j <= 99 && j > i){ num++; } }else if(i<= 999){ j=i; for(int k=0;k<2;k++){ j=j/10+(j%10)*100; if(j>= input1 && j<= input2 && j!=i && j >= 100 && j>i) num++; } } else if(i<= 9999){ j=i; map = new HashMap(); for(int k=0;k<3;k++){ j=j/10+(j%10)*1000; if(j>= input1 && j<= input2 && j!=i && j>i){ if(!map.containsKey(j)){ map.put(j, j); num++; } //System.out.println(i + "" : "" + j); } } } else if(i<= 99999){ j=i; map = new HashMap(); for(int k=0;k<4;k++){ j=j/10+(j%10)*10000; if(j>= input1 && j<= input2 && j!=i && j>i) if(!map.containsKey(j)){ map.put(j, j); num++; } } } else if(i<= 999999){ j=i; map = new HashMap(); for(int k=0;k<5;k++){ j=j/10+(j%10)*100000; if(j>= input1 && j<= input2 && j!=i && j>i) if(!map.containsKey(j)){ map.put(j, j); num++; } } } else if(i<= 999999){ j=i; map = new HashMap(); for(int k=0;k<6;k++){ j=j/10+(j%10)*1000000; if(j>= input1 && j<= input2 && j!=i && j>i) if(!map.containsKey(j)){ map.put(j, j); num++; } } } else if(i<= 9999999){ j=i; map = new HashMap(); for(int k=0;k<7;k++){ j=j/10+(j%10)*10000000; if(j>= input1 && j<= input2 && j!=i && j>i) if(!map.containsKey(j)){ map.put(j, j); num++; } } } } //1761080 //999999 //for(Integer k: map.keySet()) // System.out.println(k + "" : "" + map.get(k)); //System.out.println(""Case #""+ count + "": "" + map.size() + "" input: "" + input1 + "" : "" + input2 + "" num "" + num); System.out.println(""Case #""+ count + "": "" + num); } count++; } in.close(); }catch (IOException e) { System.err.println(""Error: "" + e.getMessage()); } } }" B22133,"import java.io.*; import java.util.*; public class RecyledNumbers { public static void main(String args[]) throws IOException{ Scanner scan=new Scanner(new File(""C-large.in"")); PrintWriter pw=new PrintWriter(new File(""result.txt"")); int caseNum=Integer.parseInt(scan.nextLine()); for(int i=1;i<=caseNum;i++){ String a=scan.nextLine(); //System.out.println(a); int result=0; String[] temp=new String[2]; temp=parseString(a); //System.out.println(temp); String A=temp[0]; String B=temp[1]; for(int j=Integer.parseInt(A);j movedNum=new ArrayList(); for(int i=1;iInteger.parseInt(toBeJudged) && temp<=Integer.parseInt(B)) { if(!movedNum.contains(temp)) movedNum.add(temp); //System.out.println(toBeJudged+"" ""+temp); } } return movedNum.size(); } } " B21287,"package codejam.codejam_2012; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: csrazvan * Date: 14.04.2012 * Time: 13:44 * To change this template use File | Settings | File Templates. */ public class RecycledNumbers { public int formNumber(ArrayList rotation) { int nr = 0; for (Integer i : rotation) { nr = nr * 10 + i; } return nr; } public ArrayList getRotations(int nr) { ArrayList result = new ArrayList(); ArrayList rotation = new ArrayList(); int digits = 0; while (nr > 0) { rotation.add(0, nr % 10); digits++; nr = nr / 10; } for (int i = 0; i < digits - 1; i++) { rotation.add(rotation.get(0)); rotation.remove(0); result.add(formNumber(rotation)); } return result; } public void solve(File f) throws Exception { Scanner scanner = new Scanner(f); File w = new File(""recycled.out""); BufferedWriter bw = new BufferedWriter(new FileWriter(w)); int t = scanner.nextInt(); for (int i = 1; i <= t; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int count = 0; HashMap map = new HashMap(); for (int startValue = a; startValue <= b; startValue++) { ArrayList rotations = getRotations(startValue); for (int rotation : rotations) { if (rotation >= a && rotation <= b && startValue < rotation) { if (map.containsKey(startValue) && map.get(startValue) == rotation) { } else if (map.containsKey(rotation) && map.get(rotation) == startValue) { } else { map.put(startValue, rotation); count++; } } } } bw.write(String.format(""Case #%s: %s\n"",i,count)); } bw.close(); } public static void main(String[] args) { try { new RecycledNumbers().solve(new File(""recycled.in"")); } catch (Exception e) { e.printStackTrace(); } } } " B20933,"import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class C { public static void main(String args[]) { new C(); } public C() { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int x=1; x<=T; x++) { int a = in.nextInt(); int b = in.nextInt(); int y = 0; for(int n=a; n<=b; n++) { y += check(n, b); } System.out.printf(""Case #%d: %d\n"", x, y); } } public int check(int n, int b) { String s = Integer.toString(n); int nd = s.length(); Set set = new TreeSet(); int ret = 0; for(int d=1; d> solverClass(); } " B22189,"/* PROG: ProbC 2012 Google CodeJam Qualification Round Problem C */ import java.io.*; import java.util.*; public class Prob1C{ public static void main(String [] args) throws IOException { //long start = System.currentTimeMillis(); BufferedReader f = new BufferedReader(new FileReader(""Prob1C.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""Prob1C.txt""))); int N = Integer.parseInt(f.readLine()); for(int i = 0; i < N; i++){ String[] str = (f.readLine()).split("" ""); int A = Integer.parseInt(str[0]); int B = Integer.parseInt(str[1]); int m = (int)Math.log10(A); int count = 0; for(int j = A; j <= B; j++){ Set set = new HashSet(); for(int k = 1; k <= m; k++){ int mod = (int)Math.pow(10, k); int lod = (int)Math.pow(10, m - k + 1); int r = j % mod; int l = j / mod; int trans = r * lod + l; if(A <= trans && trans <= B && trans != j){ if(set.add(trans)) count++; } } } out.println(""Case #"" + (i+1) + "": "" + count/2); } //long end = System.currentTimeMillis(); //System.out.println(end - start); out.close(); } } " B20366,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class Third { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader(new File(""input.txt""))); PrintWriter writer = new PrintWriter(new FileWriter(new File(""output.txt""))); reader.readLine(); int test = 1; String str = """"; while((str = reader.readLine()) != null){ long result = 0; String[] temp = str.split("" ""); int a = Integer.parseInt(temp[0]); int b = Integer.parseInt(temp[1]); boolean[] visited = new boolean[b + 1]; for(int num = a; num <= b; num++){ if(visited[num]) continue; int[] digits = GetDigit(num); Set recycledNum = new HashSet(); for(int i = 0; i < digits.length; i++){ int thisNum = GetNum(digits, i); int thisNumDigit = (int) (Math.log10(thisNum) + 1); if(thisNum >= a && thisNum <= b && thisNumDigit == digits.length) recycledNum.add(thisNum); } if(recycledNum.size() > 1){ result += recycledNum.size() * (recycledNum.size() - 1) / 2; Iterator iterator = recycledNum.iterator(); while(iterator.hasNext()){ visited[iterator.next()] = true; } } } writer.println(""Case #"" + test + "": "" + result); test++; } writer.close(); } catch (Exception e) { e.printStackTrace(); } } private static int[] GetDigit(long num){ int digits = (int) (Math.log10(num) + 1); int[] result = new int[digits]; while(digits > 0){ result[--digits] = (int) (num % 10); num /= 10; } return result; } private static int GetNum(int[] digits, int startDigit){ int number = 0; int pos = startDigit; do{ number = number * 10 + digits[pos]; pos++; if(pos >= digits.length) pos -= digits.length; } while(startDigit != pos); return number; } } " B21701,"import java.util.List; import java.util.ArrayList; import java.util.Scanner; import java.util.Set; import java.util.HashSet; import java.io.*; public class Rec { public static void main(String args[]) throws IOException { //Scanner in = new Scanner(System.in); //int n = in.nextInt(); //in.nextLine(); BufferedReader br = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter pw = new PrintWriter(""output1.in""); String sss = """"; sss = br.readLine(); int num = Integer.parseInt(sss); List l = new ArrayList(); while((sss = br.readLine()) != null) l.add(sss); int count = 0; for (String s : l) { count++; Set set = new HashSet(); String val[] = s.split("" ""); int rear = Integer.parseInt(val[0]); int max = Integer.parseInt(val[1]); if (String.valueOf(rear).length() == 1) { if (count == 0) pw.print(""Case #"" + count + "": "" + 0); //System.out.print(""Case #"" + count + "": "" + 0); else pw.print(""\n"" + ""Case #"" + count + "": "" + 0); //System.out.print(""\n"" + ""Case #"" + count + "": "" + 0); } else { int len = String.valueOf(rear).length(); for (int c = rear; c <= max; c++) { String ss = String.valueOf(c); for (int u = 1; u < len; u++) { String sub = ss.substring(u); int f_s = Integer.parseInt(String.valueOf(sub.charAt(0))); if (f_s > Integer.parseInt(String.valueOf(String.valueOf(max).charAt(0)))) continue; if (f_s == 0) continue; sub = sub.concat(ss.substring(0,u)); if ((Integer.parseInt(sub) > c) && (Integer.parseInt(sub) <= max)) if (c < Integer.parseInt(sub) && c >= rear) { set.add(String.format(""%s %s"", c, sub)); } } } if (count == 0) pw.print(""Case #"" + count + "": "" + set.size()); //System.out.print(""Case #"" + count + "": "" + set.size()); else pw.print(""\n"" + ""Case #"" + count + "": "" + set.size()); //System.out.print(""\n"" + ""Case #"" + count + "": "" + set.size()); pw.flush(); } } pw.close(); } }" B21747,"package com.google.codejam; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; public class RecycledNumbers { public static void main(String argsp[]) throws NumberFormatException, IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(""/Users/ashwinjain/Desktop/SmsLogger/InterviewStreet/src/com/google/codejam/in3b.txt""))); int cases = Integer.parseInt(br.readLine()); for(int x=0;x added = new HashMap(); for(int i=1;i=a && d<=b && !added.containsKey(d)){ added.put(d, true); count++; } } c++; } System.out.println(""Case #""+(x+1)+"": ""+count/2); } } } " B22091,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package google_jamp_c; import java.io.*; import java.util.*; /** * * @author sabri */ public class Google_jamp_c { /** * @param args the command line arguments */ public static int recycled (int A, int B){ int m = 0, c=0; String tmp = """", subB = """", subE = """", recycled = """"; for (int n = A; nn) && (m<=B)) {c++;} } } return c; } public static void main(String[] args) throws FileNotFoundException, IOException { String ligne = """"; int nbrLigne = 0,res,a,b; StringTokenizer st1; FileInputStream fStream = new FileInputStream(""A-small-attempt.in""); BufferedReader in = new BufferedReader(new InputStreamReader(fStream)); if (in.ready()) { ligne = in.readLine(); nbrLigne = Integer.parseInt(ligne); for (int j = 0; j < nbrLigne; j++) { ligne = in.readLine(); st1=new StringTokenizer(ligne,"" ""); a=Integer.parseInt(st1.nextToken()); b=Integer.parseInt(st1.nextToken()); System.out.print(""Case #""+(j+1)+"": ""); res=recycled(a,b); System.out.print(res); System.out.println(""""); } } } } " B21217,"import java.io.*; import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: tanin * Date: 4/14/12 * Time: 9:54 AM * To change this template use File | Settings | File Templates. */ public class Recycled { public static void main(String[] args) throws Exception { String filename = ""Recycled/large""; String outFilename = filename + ""_out""; FileInputStream fis = new FileInputStream(new File(filename)); Scanner input = new Scanner(new BufferedInputStream(fis)); FileOutputStream fOut = new FileOutputStream(new File(outFilename)); BufferedOutputStream bOut = new BufferedOutputStream(fOut); DataOutputStream out = new DataOutputStream(bOut); int numCases = input.nextInt(); input.nextLine(); for (int caseNumber=0;caseNumber= multiple && a <= run && run <= b) { checked[run] = true; countValid++; //System.out.print(run + "" ""); } run = next(run, multiple); } if (countValid == 1) continue; //System.out.println(number); count += countValid * (countValid - 1) / 2; } return count; } public static int getMultiple(int s) { if (s < 10) return 1; else if (s < 100) return 10; else if (s < 1000) return 100; else if (s < 10000) return 1000; else if (s < 100000) return 10000; else if (s < 1000000) return 100000; else if (s < 10000000) return 1000000; else { System.out.println(""Fuck you""); return -100000000; } } public static int next(int s, int multiple) { int residue = s % 10; return residue * multiple + s / 10; } } " B20756,"package fixjava; import java.util.Collection; import java.util.Comparator; /** * Typed 3-tuple */ public class Tuple3 { private final A field0; private final B field1; private final C field2; public A getField0() { return field0; } public B getField1() { return field1; } public C getField2() { return field2; } public Tuple3(final A field0, final B field1, final C field2) { this.field0 = field0; this.field1 = field1; this.field2 = field2; } /** Convenience method so type params of pair don't have to be specified: just do Tuple3.make(a, b, c) */ public static Tuple3 make(A field0, B field1, C field2) { return new Tuple3(field0, field1, field2); } // --------------------------------------------------------------------------------------------------- private static final boolean objEquals(Object p1, Object p2) { if (p1 == null) return p2 == null; return p1.equals(p2); } @Override public final boolean equals(Object o) { if (!(o instanceof Tuple3)) { return false; } else { final Tuple3 other = (Tuple3) o; return objEquals(getField0(), other.getField0()) && objEquals(getField1(), other.getField1()) && objEquals(getField2(), other.getField2()); } } @Override public int hashCode() { int h0 = getField0() == null ? 0 : getField0().hashCode(); int h1 = getField1() == null ? 0 : getField1().hashCode(); int h2 = getField2() == null ? 0 : getField2().hashCode(); return h0 + 53 * h1 + 97 * h2; } // --------------------------------------------------------------------------------------------------- public static , B, C> Comparator> comparatorOnField0(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple3 o1, Tuple3 o2) { return o1.getField0().compareTo(o2.getField0()); } }; } public static , B, C> Comparator> comparatorOnField0Rev(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple3 o1, Tuple3 o2) { return -o1.getField0().compareTo(o2.getField0()); } }; } public static , C> Comparator> comparatorOnField1(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple3 o1, Tuple3 o2) { return o1.getField1().compareTo(o2.getField1()); } }; } public static , C> Comparator> comparatorOnField1Rev(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple3 o1, Tuple3 o2) { return -o1.getField1().compareTo(o2.getField1()); } }; } public static > Comparator> comparatorOnField2(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple3 o1, Tuple3 o2) { return o1.getField2().compareTo(o2.getField2()); } }; } public static > Comparator> comparatorOnField2Rev(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple3 o1, Tuple3 o2) { return -o1.getField2().compareTo(o2.getField2()); } }; } // --------------------------------------------------------------------------------------------------- @Override public String toString() { return ""("" + getField0() + "", "" + getField1() + "", "" + getField2() + "")""; } } " B20932,"package co.rfcasallasm.firstround.recycled; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.util.Calendar; import java.util.Set; import java.util.TreeSet; public class Main { private static int findRecycledNumbers( int a, int b ){ validationSet = new TreeSet(); int longitud = String.valueOf( b ).length(); for( int index = b; index >= a; index-- ){ countIntoRange( index, longitud, a, b ); } return validationSet.size(); } private static void countIntoRange( int number, int longitud, int a, int b ){ String numero = String.valueOf( number ); while( numero.length() < longitud ){ numero = ""0""+numero; } for( int i = 0; i < longitud; i++ ){ int newNumber = Integer.parseInt( numero.substring( numero.length()-(i+1) ) + numero.substring( 0, numero.length()-(i+1) ) ); if( number < newNumber && newNumber >= a && newNumber <= b ){ validationSet.add(number+""->""+newNumber); //System.out.println(number+""->""+newNumber); } } } private static Set validationSet; private static void solveProblem( File inputFile ) throws IOException{ BufferedReader bufferedReader = new BufferedReader( new FileReader( inputFile ) ); BufferedWriter bufferedWriter = new BufferedWriter( new FileWriter( new File( inputFile.getParent(), inputFile.getName().substring( 0, inputFile.getName().length()-3 )+"".out"" ) ) ); Long t = Long.parseLong( bufferedReader.readLine() ); String problem = null; StringBuilder solution = null; for( long problemIndex = 0l; problemIndex < t; problemIndex++ ){ problem = bufferedReader.readLine(); solution = new StringBuilder(""Case #""+(problemIndex+1)+"": ""); String[] splitProblem = problem.split("" ""); int a = Integer.parseInt( splitProblem[ 0 ] ); int b = Integer.parseInt( splitProblem[ 1 ] ); solution.append( findRecycledNumbers( a, b ) ); bufferedWriter.write( solution.toString() ); bufferedWriter.write( ""\n"" ); } bufferedWriter.flush(); bufferedWriter.close(); bufferedReader.close(); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Calendar calIni = Calendar.getInstance(); Calendar calFin = null; File folder = new File("".""); System.out.println(""Searching files in ""+folder.getAbsolutePath()); String[] inputFileList = folder.list( new FilenameFilter() { @Override public boolean accept(java.io.File dir, String name) { return name != null && name.endsWith("".in""); } }); for( String fileName : inputFileList ){ System.out.println( fileName ); Main.solveProblem( new File( folder.getAbsolutePath(), fileName ) ); } calFin = Calendar.getInstance(); System.out.println(""Tiempo:""+(calFin.getTimeInMillis()-calIni.getTimeInMillis())/1000); } } " B21547,"package com.lily.acm.googleCodeJam; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; public class RecycledNumbers { public static int getRecyleCount(int n,int start,int end){ int temp2=n; int count =0; int digit=0; int max=1; int temp =n; while(temp!=0){ digit++; temp/=10; max*=10; } max/=10; HashSet set =new HashSet(); for(int i=1;i=start&&i<=end&&i>max&&i!=temp2) { count++; } } return count; } public static void readInput(String fileName){ BufferedReader is= null; FileOutputStream os =null; int count=1; try { is = new BufferedReader(new FileReader(fileName)); os = new FileOutputStream(new File(""c://output.txt"")); String input=""""; if(is.readLine()==null) return ; while((input= is.readLine())!=null){ os.write((""Case #""+count+++"": ""+lineCount(input.split("" "")[0],input.split("" "")[1])+""\r\n"").getBytes()); os.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { is.close(); os.close(); } catch (IOException e) { e.printStackTrace(); } } } public static int lineCount(String start,String end) { int s=Integer.valueOf(start); int e=Integer.valueOf(end); int total=0; for(int i=s;i<=e;i++){ total+=getRecyleCount(i,s,e); } return total/2; } public static void main(String[] args) { readInput(""c://C-large.in""); } } " B20013,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class R1P3 { /** * @param args */ public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""large3.out"")); String inLine; int t = Integer.parseInt(in.readLine()); int counter = 0; while ((inLine = in.readLine()) != null) { counter++; String[] toks = inLine.split("" ""); long beg = Long.parseLong(toks[0]); long end = Long.parseLong(toks[1]); long c = 0; for (long i = beg; i < end; i++) { c += rotateNumber(i, end); } System.out.println(""Case #"" + counter + "": "" + c); bw.write(""Case #"" + counter + "": "" + c); bw.newLine(); } in.close(); bw.close(); } public static long rotateNumber(long number, long end) { long start = number; int numdigits = (int) Math.log10((double) number); // would return // numdigits - 1 int multiplier = (int) Math.pow(10.0, (double) numdigits); long counter = 0; while (true) { long q = number / 10; long r = number % 10; number = number / 10; number = number + multiplier * r; if (start < number && number <= end) counter++; if (number == start) break; } return counter; } } " B20515,"package recycledNumbers; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static String processaCaso(String linha, int i) { String[] nums = linha.split("" ""); int a = Integer.parseInt(nums[0]); int b = Integer.parseInt(nums[1]); int numDistincPairs = 0; int lenNum = Integer.toString(a).length()-1; Set ms = new HashSet(); for (; a < b; a++) { String n = Integer.toString(a); ms.clear(); for (int j = 0; j < lenNum; j++) { int indice = lenNum-j; String strM = n.substring(indice)+n.substring(0,indice); int m = Integer.parseInt(strM); if (!(a < m && m <= b)) continue; ms.add(m); } numDistincPairs += ms.size(); } return String.format(""Case #%d: %d"", i, numDistincPairs); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner scan = new Scanner(new File(args[0])); int numTestCases = scan.nextInt(); scan.nextLine(); Writer saida = new FileWriter(args[0]+"".out""); for (int i = 1 ; i <= numTestCases; i++) { saida.write(processaCaso(scan.nextLine(),i)+""\n""); } saida.close(); } } " B20074,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; import java.util.StringTokenizer; class roundThree { public static void main(String[] args) { String text = """"; if( args.length > 0) { text = args[0]; } else { try { FileInputStream fos = new FileInputStream( ""text3.txt""); Scanner scanner = new Scanner(new FileInputStream(""text3.txt"")); try { while (scanner.hasNextLine()){ text += scanner.nextLine() + ""\n""; } } finally{ scanner.close(); } try { fos.read(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } StringTokenizer st = new StringTokenizer(text, ""[\r\n]+"", false); int cases = Integer.parseInt(st.nextToken()); for (int x=1; x<= cases; x++) { StringTokenizer st2 = new StringTokenizer(st.nextToken(), ""[ ]+"", false); int small = Integer.parseInt(st2.nextToken()); int large = Integer.parseInt(st2.nextToken()); ArrayList keep_track = new ArrayList(); String small_int = """" + small; int count = 0; int small_length = small_int.length(); for( int i = small; i < large; i++) { String number1 = """" + i; keep_track.clear(); for( int j = 1; j < small_length; j++) { String sub_2 = number1.substring(0,j); String sub_1 = number1.substring(j,small_length); int variation = Integer.parseInt( sub_1 + sub_2 ); if( variation > i && variation <= large && !keep_track.contains(variation)) { keep_track.add(variation); count++; } } } System.out.println( ""Case #"" + x + "": "" + count); } } }" B21486,"import java.io.*; public class C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); String[] line; for(int i=1;i<=T;i++) { line = br.readLine().split(""\\W+""); int a = Integer.parseInt(line[0]); int b = Integer.parseInt(line[1]); System.out.println(""Case #""+i+"": ""+recycled(a,b)); } } public static long recycled(int a,int b) { long ret = 0; int[] cache = new int[30]; for(int i=a;i b) continue; boolean found = false; for(int k = 0;k solutions=new ArrayList(); for (int i = 1; i <= cases; i++) { int lower=in.nextInt(); int upper=in.nextInt(); int amount=0; for(int k= lower;k<=upper;k++){//k van lower tot upper if(k>=10){ String iString=String.valueOf(k); ArrayList allreadyPaired=new ArrayList(); for (int l = 1; l < iString.length(); l++) { String shifted=move(l,iString); int reverseInt=Integer.parseInt(shifted); if(reverseInt<=upper&&reverseInt>lower&&reverseInt>k){ if(!allreadyPaired.contains(reverseInt)) amount++; solutions.add(k); } allreadyPaired.add(reverseInt); } } } System.out.println(""Case #""+i+"": ""+amount); solutions.clear(); } } private String move(int i,String iString) { String result=""""; for (int j = 0; j < i; j++) { String letter=String.valueOf(iString.charAt(iString.length()-i+j)); result+=letter; } for (int j = 0; j < iString.length()-i; j++) { String letter=String.valueOf(iString.charAt(j)); result+=letter; } return result; } } " B21657,"package de.pat.dev.y2012.qualification.c; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * @author pat.dev@alice.de * @since 17.04.12 */ public class Main { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader(args[0])); long numberOfTestCases = nextLong(reader); for (int i = 0; i < numberOfTestCases; i++) { RecycledNumber recycledNumber = toRecycledNumber(reader.readLine().trim()); System.out.printf(""Case #%d: %d\n"", i + 1, recycledNumber.pairs().size()); } } catch (IOException e) { e.printStackTrace(); } } private static RecycledNumber toRecycledNumber(String line) { String[] values = line.split(""\\s+""); return new RecycledNumber(toLong(values[0]),toLong(values[1])); } private static long toLong(String value) { return Long.parseLong(value); } private static long nextLong(BufferedReader reader) throws IOException { return toLong(reader.readLine().trim()); } } " B20483,"import java.util.Scanner; import java.util.ArrayList; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); String st = in.nextLine(); int n = Integer.parseInt(st); int a[][] = new int[n][2]; int ans[] = new int[n]; for(int i = 0; i< n;i++) { st = in.nextLine(); String s[] = st.split("" ""); a[i][0] = Integer.parseInt(s[0]); a[i][1] = Integer.parseInt(s[1]); ans[i] = getValue(a[i]); } for(int i=0;i arr = new ArrayList(); for(int i =a[0];i<= a[1];i++) { m=i; k=10; n=0; arr.clear(); // System.out.print( m + "" : ""); while(m != 0) { l = m%10; m=m/10; n=(l*k/10)+n; l=Integer.parseInt((String.valueOf(n) + String.valueOf(m))); if(l>=a[0] && l <= a[1] && l > i && !arr.contains(String.valueOf(l))) { // System.out.print(l +"" ""); arr.add(String.valueOf(l)); count++; } k*=10; } // System.out.println(); } return count; } } " B21419,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.*; /** * * @author Nah-Abiah */ public class recycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { try{ FileInputStream fstream = new FileInputStream(""C-large.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int testCount = 0; int caseCount = 1; String writeFile = """"; while ((strLine = br.readLine()) != null) { if(testCount == 0){ testCount = Integer.parseInt(strLine); } else{ String[] ints = strLine.split("" ""); int n = Integer.parseInt(ints[0]); int limit = Integer.parseInt(ints[1]); int num = 0; if(ints[0].length() != 1){ while (n < limit){ int count = 1; while(count < ints[0].length()){ String m = String.valueOf(n).substring(count)+String.valueOf(n).substring(0, count); if((n> cache; public static void main(String[] args) throws IOException{ String path = ""C:\\Users\\Rapol Tongchenchitt\\Documents\\CodeJam\\""; String year = ""Qual2012\\""; String test = ""input.txt""; String outPath = ""output.txt""; String a = """"; String A = """"; String b = """"; String B = """"; String c = ""C-large.in""; String C = ""C-large.out""; String d = """"; String D = """"; String inName = path+year+c; String outName = path+year+C; Scanner in = new Scanner(new FileInputStream(inName)); BufferedWriter out = new BufferedWriter(new FileWriter(outName)); int caseCount = in.nextInt(); int currentCase = 0; while(currentCase++ < caseCount){ int minNum = in.nextInt(); int maxNum = in.nextInt(); int ans = 0; for( int i = minNum; i <= maxNum; i++){ ans += perform(i, minNum, maxNum); } out.write(""Case #"" + currentCase + "": "" + ans); out.newLine(); } out.close(); } private static int perform(int in, int left, int right) throws IOException{ if(in < 10){ return 0; } HashSet set = new HashSet(); int ans = 0; String now = in + """"; for(int i = 1; i < now.length(); i++){ if(now.charAt(i) >= now.charAt(0)){ int shift = Integer.parseInt(now.substring(i) + now.substring(0,i)); if(shift > in && shift <= right && shift >= left && !set.contains(shift)){ ans++; set.add(shift); } } } return ans; } } " B20516,"import java.io.*; import java.util.*; import java.lang.*; public class Recycled { public static int cases = 0; public static int min[] = new int[50]; public static int max[] = new int[50]; public static int answer[] = new int[50]; public static ArrayList results = new ArrayList(); public static void main(String args[]) { File input = new File(""Input.txt""); File output = new File(""Output.txt""); loadGame(input); for(int i = 0; i < cases; i++){ answer[i] = 0; } findAnswer(); saveGame(output); } public static void findAnswer(){ for(int i = 0; i < cases; i++){ for(int j = min[i]; j <= max[i]; j++){ String number = new Integer(j).toString(); ArrayList numberArray = new ArrayList(); for(int m = 0; m < number.length(); m++){ numberArray.add(Character.toString(number.charAt(m))); } for(int k = 1; k < number.length(); k++){ numberArray.add(0, numberArray.remove((number.length()-1))); String temp = """"; ArrayList tempNumberArray = new ArrayList(); tempNumberArray.addAll(numberArray); for(int m = 0; m < number.length(); m++){ temp += tempNumberArray.remove(0); } int result = Integer.parseInt(temp); if(result >= min[i] && result <= max [i] && result > j){ if(!results.contains(result)){ answer[i]++; results.add(result); } } } results.clear(); } } } public static void loadGame(File input){ Scanner in; try { in = new Scanner(input); cases = in.nextInt(); in.nextLine(); for(int i = 0; i < cases; i++){ min[i] = in.nextInt(); max[i] = in.nextInt(); if(min[i] > max[i]){ int temp = min[i]; min[i] = max[i]; max[i] = temp; } in.nextLine(); } in.close(); } catch (StringIndexOutOfBoundsException e) { } catch (FileNotFoundException e) { } catch (NoSuchElementException e) { } catch (NullPointerException e) { } } public static void saveGame(File name){ PrintWriter out; try { out = new PrintWriter(name); for(int i = 1; i <= cases; i++){ out.println(""Case #"" + i + "": "" + answer[(i-1)]); } out.close(); } catch (FileNotFoundException e) { } catch (NullPointerException e) { } } }" B20200,"import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; public class RecycleNumbers { @SuppressWarnings(""deprecation"") private static void solveProblem() { // Stream to read file FileInputStream fin; // Stream to write file FileOutputStream fout; try { // Open an input stream // fin = new FileInputStream (""B-large.in""); fin = new FileInputStream (""input.txt""); // Open an output stream fout = new FileOutputStream (""output.txt""); // reader DataInputStream reader = new DataInputStream(fin); // writer PrintStream writer = new PrintStream(fout); int numCases = Integer.parseInt(reader.readLine()); String line = """"; for (int i = 1; i <= numCases; i++) { line = ""Case #"" + i + "": "" + solveCase(reader); writer.println(line); System.out.println(line); } // Close our input stream fin.close(); // Close our output stream fout.close(); } // Catches any error conditions catch (IOException e) { System.err.println (""Unable to read from file""); System.exit(-1); } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings(""deprecation"") public static String solveCase(DataInputStream reader) throws Exception, IOException { return getNumRecyclers(reader.readLine().split("" "")); } private static String getNumRecyclers(String[] values) { int A = Integer.parseInt(values[0]); int B = Integer.parseInt(values[1]); int n, m, numRescyclers = 0; String numS = """"; for (n = A; n <= B; n++) { numS = n + """"; for (int length= numS.length(), j = 0; j < length; j++) { // A <= n < m <= B. m = Integer.parseInt(numS); if ( A <= n && n < m && m <= B ) numRescyclers++; // if ( A <= n && n < m && m <= B ) { // numRescyclers++; // System.out.println(""(""+n+"",""+m+"")""); // } numS = numS.charAt(length-1) + numS.substring(0, length-1); } } return numRescyclers + """"; } public static void main(String[] args) { solveProblem(); } } " B20441,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbersMain { public static void main(String[] args) { try { Scanner s=new Scanner(new BufferedReader(new FileReader(""C-large.in""))); ArrayList list=new ArrayList(); int i=0; int totalCases=Integer.parseInt(s.nextLine()); while(s.hasNextLine()){ list.add(new RecycledNumbers(++i,s.nextLine())); } for (RecycledNumbers recycledNumbers : list) { recycledNumbers.process(); } } catch (FileNotFoundException e) { System.out.println(""file not found""); } } } " B20842,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.*; public class jam3 { /** * @param args */ static int chuli(String s) { int count = 0; String[] ab = s.split("" ""); int a = Integer.parseInt(ab[0]); int b = Integer.parseInt(ab[1]); HashSet over = new HashSet(); HashSet cur = new HashSet(); for(int i=a;i<=b;i++) { String is = String.valueOf(i); if(!over.contains(is)) { cur.clear(); String is2 = is+is; for(int i2=0;i2=a&&ins<=b) cur.add(ns); } count+=(cur.size()*(cur.size()-1))/2; over.addAll(cur); } } return count; } public static void main(String[] args) { // TODO Auto-generated method stub try{ /* System.out.println(chuli(""1 9"")); System.out.println(chuli(""10 40"")); System.out.println(chuli(""100 500"")); System.out.println(chuli(""1111 2222"")); */ File fin1 = new File(""d:\\C-large.in""); FileInputStream fs1 = new FileInputStream(fin1); BufferedReader br1 = new BufferedReader(new InputStreamReader(fs1)); File fout6 = new File(""d:\\cjamout1""); FileOutputStream fos6 = new FileOutputStream(fout6); BufferedWriter wr6 = new BufferedWriter(new OutputStreamWriter(fos6)); String line = br1.readLine(); int n = 1; line = br1.readLine(); while(line!=null) { if(!line.trim().equals("""")) { wr6.write(""Case #""+String.valueOf(n++)+"": ""+String.valueOf(chuli(line))); wr6.newLine(); } line = br1.readLine(); } br1.close(); fs1.close(); wr6.close(); fos6.close(); } catch(Exception e) { e.printStackTrace(); } } } " B22252,"import java.io.*; import java.util.*; public class C { public static BufferedReader in; public static StringTokenizer st; public static void main(String[] args) throws IOException{ in = new BufferedReader(new FileReader(""C.in"")); PrintWriter out = new PrintWriter(new FileWriter(""C.out"")); int test = readInt(); for (int t=1; t<=test; t++){ out.print(""Case #""+t+"": ""); int start = readInt(), end = readInt(); int counter=0; for (int i=start; i<=end; i++){ counter += test(i, start, end); } out.println(counter); } in.close(); out.close(); } public static String readLine() throws IOException{ return in.readLine(); } public static String readToken() throws IOException{ if (st==null || !st.hasMoreTokens()) st = new StringTokenizer(readLine()); return st.nextToken(); } public static int readInt() throws IOException{ return Integer.parseInt(readToken()); } public static int test(int i, int start, int end){ int curr = i; int ret =0; int numDigits = String.valueOf(i).length(); int mult = (int)Math.pow(10, numDigits-1); do{ int last = curr%10; curr = curr/10 + last*mult; if (curr>i && curr<=end) ret++; }while(curr!=i); return ret; } } " B20256," import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; /** * * @author dafferianto */ public class RecycledNumbers { private static Scanner inputStream; private static PrintWriter outputStream; private static int T, lower, upper, counter, tempNumber, result; private static String numberString, tempNumberString; private static HashMap aHashMap; public static void main(String[] args) throws FileNotFoundException, IOException { try { inputStream = new Scanner(new FileReader(args[0])); outputStream = new PrintWriter(new FileWriter(""RecycledNumbersOutput.txt"")); T = inputStream.nextInt(); //T = Integer.parseInt(inputStream.nextLine()); for (int i = 0; i < T; i++) { // For each test case lower = inputStream.nextInt(); upper = inputStream.nextInt(); aHashMap = new HashMap(); //result = solve(lower, upper); //outputStream.println(""Case #"" + (i+1) + "": "" + result); outputStream.println(""Case #"" + (i+1) + "": "" + solve(lower, upper)); //System.out.println(""Case #"" + (i+1) + "": "" + result); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } private static int solve(int lower, int upper) { counter = 0; for (int currentNumber = lower; currentNumber <= upper; currentNumber++) { if (aHashMap.containsKey(currentNumber)) { continue; } counter += process(currentNumber); } return counter; } private static int process(int aNumber) { int localCounter = 0; numberString = Integer.toString(aNumber); for (int i = numberString.length()-1; i > 0; i--) { if (Character.getNumericValue(numberString.charAt(i)) == 0) { continue; } tempNumberString = numberString.substring(i) + numberString.substring(0, i); tempNumber = Integer.parseInt(tempNumberString); if (tempNumber == aNumber) { continue; } if (aHashMap.containsKey(tempNumber)) { continue; } if ((tempNumber >= lower) && (tempNumber <= upper)) { localCounter++; aHashMap.put(tempNumber, tempNumber); //System.out.println(tempNumber); } } if (localCounter != 0) { aHashMap.put(aNumber, aNumber); //System.out.println(aNumber); } if (localCounter > 1) { return sumOfSequence(localCounter); } return localCounter; } private static int sumOfSequence(int aCounter) { int tempSum = 0; for (int i = 1; i <= aCounter; i++) { tempSum += i; } return tempSum; } } " B21538,"import java.util.*; public class RecycledNumbers { private final int A; private final int B; private final boolean[] allNumbers; public RecycledNumbers(int A, int B) { this.A = A; this.B = B; //numbers are A + i, where i is the array index allNumbers = new boolean[B - A + 1]; } public int getDistinctPairsCount() { int distinctPairs = 0; for (int i = 0; i < allNumbers.length; i++) { if (!allNumbers[i]) { int number = indexToNumber(i); Set recyclings = (number > 9) ? getRecyclings(number) : Collections.emptySet(); if (!recyclings.isEmpty()) ignore(recyclings); int numberOfDistinctPairs = recyclings.isEmpty() ? 0 : getNumberOfDistinctPairs(recyclings); distinctPairs += numberOfDistinctPairs; } } return distinctPairs; } private int getNumberOfDistinctPairs(Set recyclings) { int recyclingsThatCount = 0; for (String s : recyclings) { int number = Integer.parseInt(s); if (withinBounds(number) && doesntStartWithZero(s)) recyclingsThatCount++; } int pairs = recyclingsThatCount * (recyclingsThatCount - 1) / 2; return pairs; } private boolean doesntStartWithZero(String s) { boolean result = s.charAt(0) != '0'; return result; } private boolean withinBounds(int number) { boolean result = number >= A && number <= B; return result; } private void ignore(Set recyclings) { //set them to true in the array for (String s : recyclings) { int number = Integer.parseInt(s); if (withinBounds(number)) allNumbers[numberToIndex(number)] = true; } } private int numberToIndex(int number) { return number - A; } private int indexToNumber(int i) { return i + A; } private Set getRecyclings(int number) { String numberAsString = Integer.toString(number); int totalDigits = numberAsString.length(); Set recyclings = new HashSet(); for (int i = totalDigits - 1; i >= 0; i--) { recyclings.add(numberAsString.substring(i, totalDigits) + numberAsString.substring(0, i)); } return recyclings; } } " B21670,"import java.io.*; import java.util.*; public class ProblemC { public class Case { int a, b; public void solve(int caseIndex) { int length = Integer.toString(a).length(); int numPairs = 0; for (int n = a; n <= b; n++) { String ns = Integer.toString(n); LinkedHashSet distinctMs = new LinkedHashSet(); for (int i = 0; i < length; i++) { int m = Integer.parseInt(ns.substring(i) + ns.substring(0, i)); if (m >= a && m <= b && m > n) { distinctMs.add(m); } } numPairs += distinctMs.size(); } println(""Case #"" + (caseIndex + 1) + "": ""+numPairs); } } public void run() throws Exception { BufferedReader r = new BufferedReader(new FileReader(""input.txt"")); int numCases = new InputParser(r.readLine()).readInt(); for (int caseIndex = 0; caseIndex < numCases; caseIndex++) { Case c = new Case(); InputParser p = new InputParser(r.readLine()); c.a = p.readInt(); c.b = p.readInt(); c.solve(caseIndex); } r.close(); } public static void main(String[] args) throws Exception { fileWriter = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(""output.txt"")))); new ProblemC().run(); fileWriter.close(); } public static class InputParser { String text; int pos; public InputParser(String text) { this.text = text; } public void skipSpaces() { while (pos < text.length()) { if (text.charAt(pos) != ' ') break; pos++; } } public String readUntil(char expectedChar) { StringBuilder b = new StringBuilder(); while (pos < text.length()) { char ch = text.charAt(pos); if (ch == expectedChar) break; b.append(ch); pos++; } return b.toString(); } public String readToken() { skipSpaces(); return readUntil(' '); } public int readInt() { return Integer.parseInt(readToken()); } public long readLong() { return Long.parseLong(readToken()); } public char readChar() { char ch = text.charAt(pos); pos++; return ch; } public void readExpectedString(String s) { for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (readChar() != ch) throw new RuntimeException(""Expected: ""+ch); } } } public static PrintWriter fileWriter; public static void print(String text) { fileWriter.print(text); System.out.print(text); } public static void println(String text) { fileWriter.println(text); System.out.println(text); } public static void addToMultiMapArrayList(Key key, Value value, Map> map) { ArrayList list = map.get(key); if (list == null) { list = new ArrayList(); map.put(key, list); } list.add(value); } public static void addToMultiMapLinkedHashSet(Key key, Value value, Map> map) { LinkedHashSet list = map.get(key); if (list == null) { list = new LinkedHashSet(); map.put(key, list); } list.add(value); } public static ArrayList getMultiMapValues(Map> map) { ArrayList result = new ArrayList(); for (Collection list : map.values()) { result.addAll(list); } return result; } } " B21232," public class Number { int A ; int B ; int length ; public Number(String str) { String[] tmpArr = str.split("" ""); A = Integer.parseInt(tmpArr[0]); B = Integer.parseInt(tmpArr[1]); length = tmpArr[0].length(); } public int getRecycledPairCount() { int count = 0 ; for (int i=A; i=pair || pair>maxNumber) { continue; } if (alreadyGet.indexOf(s) > -1) { continue; } pairCount++; alreadyGet.append("" "").append(pair); } return pairCount ; } } " B20623,"package utils; /** * * @author Fabien Renaud */ public abstract class JamCase implements Runnable, JamCaseSolver { protected final int number; protected String result; private final StopWatch timer; private final Jam parent; protected JamCase(Jam parent, int number) { this.parent = parent; this.number = number; this.timer = new StopWatch(); } public final int getNumber() { return number; } public final String getResult() { return result; } public final StopWatch getTimer() { return timer; } @Override public final void run() { timer.start(); parse(); solve(); if (parent != null) { parent.appendOutput(number, result); } timer.stop(); } }" B20624,"package utils; /** * * @author Fabien Renaud */ public class StopWatch { private long startTime = -1; private long stopTime = -1; private boolean running = false; public StopWatch start() { startTime = System.currentTimeMillis(); running = true; return this; } public StopWatch stop() { stopTime = System.currentTimeMillis(); running = false; return this; } public long getElapsedTime() { if (startTime == -1) { return 0; } if (running) { return System.currentTimeMillis() - startTime; } else { return stopTime - startTime; } } public String getElapsedSeconds() { return String.format(""%1$.4f"", getElapsedTime() / 1000.0f); } public StopWatch reset() { startTime = -1; stopTime = -1; running = false; return this; } } " B20493,"package nl.maartenvangrootel.googlecodejam.qualifier.recycling; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.regex.Pattern; /** * Hello world! * */ public class Recycling { private File file; private static Pattern pattern = Pattern.compile(""[\\ ]""); public Recycling(String filename) { if (filename == null) throw new IllegalArgumentException(""filename should not be null""); file = new File(filename); if (!(file.exists() && file.isFile())) throw new IllegalArgumentException(String.format( ""'%s' does not exist or is not a file."", filename)); } private BufferedReader getReader() { BufferedReader reader = null; try { FileReader stream = new FileReader(file); reader = new BufferedReader(stream); } catch (FileNotFoundException e) { e.printStackTrace(); } return reader; } public String calculateResult() { BufferedReader reader = getReader(); StringBuilder builder = new StringBuilder(); try { int numberOfCases = Integer.parseInt(reader.readLine()); int i = 1; String line; while ((line = reader.readLine()) != null) { if (i > 1) { builder.append(""\n""); } builder.append(""Case #""); builder.append(i); builder.append("": ""); builder.append(parseLine2(line)); i++; } } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } public static long parseLine2(String line) { String[] input = pattern.split(line); int length = input[0].length(); boolean even = length % 2 == 0; long mod = (long) Math.pow(10, (length / 2)); long A = Integer.parseInt(input[0]); long B = Integer.parseInt(input[1]); long cnt = 0; long compensation = 0; for (long n = A; n <= B; n++) { String strN = String.valueOf(n); for (int i = length - 1; i > 0; i--) { for (int j = length; j > i; j--) { String deel1 = strN.substring(i, j); String deel2 = strN.substring(0, i); String strM = deel1 + deel2; if ("""".equals(strM)) continue; long m = Long.parseLong(strM); if (m >= A && m <= B && n < m) { if (even && n % mod == n / mod) { compensation++; } cnt++; } } } } return cnt - compensation / 2; } public static void main(String[] args) { Recycling starter = new Recycling(""src/main/resources/small.txt""); String result = starter.calculateResult(); System.out.println(result); } } " B21157,"/** * */ import hack.PolynomialFactoring; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * http://code.google.com/codejam/contest/dashboard?c=1460488#s=p2 a pair of * distinct positive integers (n, m) is recycled if you can obtain m by moving * some digits from the back of n to the front without changing their order. * * @author y */ public class RotateNumbers { /** * Given integers A and B with the same number of digits and no leading * zeros, how many distinct recycled pairs (n, m) are there with A ¡Ü n < m ¡Ü * B? * * @param min * @param max */ static int pairsRotated (int min, int max){ if(max<10 || max<=min){return 0;} int ret = 0; for(int j=min; j set = new HashSet(); for(int k=1; k=s.charAt(0)){ //=212-> 221. ignore repeat, count (12, 21) once String rotateString = s.substring(k) + s.substring(0, k); int rotate = Integer.valueOf(rotateString); if((j=min if(!set.contains(rotate)){ set.add(rotate); ret ++; } //System.out.println(j + ""-> "" + rotate); } } } } return ret; } public static void main(String[] args) { createOutput(); List input = readLine(); for (int j = 0; j < input.size(); j++) { String[] line = input.get(j); int n = Integer.parseInt(line[0]); int k = Integer.parseInt(line[1]); int ret = pairsRotated(n, k); String outputLine = ""Case #"" + (j+1) + "": "" + ret; System.out.println(outputLine); writeOutput(outputLine); } } public static List readLine(){ return readLine(""input.txt""); } public static List readLine(String inputFile){ List list = new ArrayList(); //String lineSeparator= System.getProperty(""line.separator""); try { InputStream stream = PolynomialFactoring.class.getClassLoader(). getResourceAsStream(inputFile); BufferedReader input = new BufferedReader(new InputStreamReader(stream));//new FileReader(inputFile)); String line = null; if ((line = input.readLine()) != null) { } try { while ((line = input.readLine()) != null) { //logger.info(""input: "" + line ); String[] words = line.split("" ""); list.add(words); //parse line and run code. } } catch (Exception e) { e.printStackTrace(); } finally { input.close(); } } catch (IOException ex) { ex.printStackTrace(); } return list; } private static final String OUTPUT_TXT = ""./output.txt""; public static void createOutput() { try { new FileWriter(OUTPUT_TXT); } catch (IOException e) { e.printStackTrace(); } } public static void writeOutput(String content) { BufferedWriter output; try { output = new BufferedWriter(new FileWriter(OUTPUT_TXT, true)); try { output.write(content + ""\r\n""); } catch (Exception e) { e.printStackTrace(); } finally { output.close(); } } catch (IOException e1) { e1.printStackTrace(); } } } " B20574,"import java.util.*; import java.math.*; import java.io.*; import static java.lang.System.*; import static java.lang.Math.*; import static java.lang.Integer.*; import static java.lang.Double.*; import static java.lang.Long.*; public class QC { static String[] parts(BufferedReader br) throws Exception { String line = br.readLine(); if (line == null) return null; return line.trim().split(""\\s+""); } public static void main (String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(in)); int z = parseInt(br.readLine().trim()); for (int cas = 1; cas <= z; cas++) { String p[] = parts(br); int a = parseInt(p[0]); int b = parseInt(p[1]); int pow = 1; int e = 0; for (int c = b / 10; c > 0; c /= 10) { e++; pow *= 10; } long count = 0; while (b > a) { for (int i = 0, d = b; i < e; i++) { d = d / 10 + (d % 10) * pow; if (d == b) break; if (a <= d && d < b) count++; } b--; } out.println(""Case #"" + cas + "": "" + count); } } } " B20160,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.Arrays; public class RecyclingNumbers { private boolean[] m_numArray; private int[] chooseArray = {0, 0, 1, 3, 6, 10, 15, 21, 28}; private int m_low; private int m_high; RecyclingNumbers(int low, int high){ m_numArray = new boolean[high-low+1]; Arrays.fill(m_numArray, false); m_low = low; m_high = high; } public int getPairsCount(){ int m_pairsCount = 0; int tempCount = 0; for(int i=m_low; i<=m_high; i++){ if(m_numArray[i-m_low] == true){ continue; } String curNumS = String.valueOf(i); int intLength = curNumS.length(); if(intLength == 1){ continue; } for(int j=1; j=m_low && tempInt <= m_high && tempInt != i && curNumS.length() == intLength && m_numArray[tempInt-m_low] == false){ tempCount++; m_numArray[tempInt-m_low] = true; } } if(tempCount > 0){ m_numArray[i-m_low] = true; m_pairsCount += chooseArray[tempCount+1]; } tempCount = 0; } return m_pairsCount; } public static void main(String[] args) { try { // Code for accessing the file goes here FileReader dataFile = new FileReader(""/Users/benedictliang/Documents/workspace/CodeJam2012/src/C-large.in""); BufferedReader bufferedDataFile = new BufferedReader(dataFile); String num = bufferedDataFile.readLine(); int numOfLines = Integer.parseInt(num); BufferedWriter out = new BufferedWriter(new FileWriter(""/Users/benedictliang/Documents/workspace/CodeJam2012/src/output.txt"")); for(int i=1; i<=numOfLines; i++){ String line = bufferedDataFile.readLine(); String[] data = line.split("" ""); int num1 = Integer.parseInt(data[0]); int num2 = Integer.parseInt(data[1]); RecyclingNumbers rn = new RecyclingNumbers(Math.min(num1, num2), Math.max(num1, num2)); out.write(""Case #"" + i + "": "" + rn.getPairsCount() + ""\n""); } dataFile.close(); out.close(); } catch (Exception e) { System.out.println(e); } } } " B21322,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumbers { private static long findMatchesForNumber(Long number, long a, long b) { long matches = 0; Set set = new HashSet<>(); String str = number.toString(); for (int i = 1; i < str.length(); i++) { String begin = str.substring(0, i); String end = str.substring(i); Long recycled = new Long(end + begin); if (recycled > number && recycled >= a && recycled <= b && !set.contains(recycled)) { matches++; set.add(recycled); } } return matches; } private static long handleCase(long a, long b) { long totalMatches = 0; for (long i = a; i <= b; i++) { totalMatches = totalMatches + findMatchesForNumber(i, a, b); } return totalMatches; } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(args[0]); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; FileWriter outFile = new FileWriter(""c:\\data\\q3\\output.txt""); PrintWriter out = new PrintWriter(outFile); long t = new Long(br.readLine()); for (int i = 0; i < t; i++) { strLine = br.readLine(); StringTokenizer token = new StringTokenizer(strLine); long a = new Long(token.nextToken()); long b = new Long(token.nextToken()); // System.out.println(""numbers: "" + a + "" "" + b); long matches = handleCase(a, b); long index = i+ 1; String strToPrint = ""Case #"" + index + "": "" + matches; out.println(strToPrint); System.out.println(strToPrint); } in.close(); out.close(); } } " B20251,"import java.io.BufferedReader; import java.io.IOException; public abstract class SolverModule { public StringBuilder process(BufferedReader in, StringBuilder builder) throws IOException { in.readLine(); String line = in.readLine(); int count = 1; while (line != null) { line = processLine(line); appendLine(line, builder,count); count++; line = in.readLine(); } return builder; } abstract String processLine(String line) ; protected static void appendLine(String line, StringBuilder builder, int count) { builder.append(""Case #""+count+"": ""+line + ""\r\n""); } protected int[] toIntegers(String[] split) { int[] ints = new int[split.length]; for (int i = 0; i < split.length; i++) { ints[i] = Integer.valueOf(split[i]); } return ints; } } " B21117,"package j2012qualifier; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static String inputDirectory=""src/j2012qualifier/""; public static String inputFile=""C.in""; public static String outputFile=""C.out""; public static PrintWriter output; public static void main(String[] args) throws FileNotFoundException{ Scanner s=new Scanner(new File(inputDirectory + inputFile)); output=new PrintWriter(new File(inputDirectory + outputFile)); int cases = s.nextInt(); for(int Case=1;Case<=cases;Case++){ s.nextLine(); int A = s.nextInt(); int B = s.nextInt(); long result = 0; for(int n = A; n< B; n++) { result+= count(n, B); } out(""Case #""+Case+"": ""+result); } output.flush(); } public static long count(long n, long max) { //out(""testing "" + n); long digit = 10; long pow10 = 10 * (long)Math.pow(10, Math.floor(Math.log10(n))); long count = 0; Set found = new HashSet(); //out(""pow"" + pow10); while(digit <= n) { long m = n/digit + (n%digit) * pow10 / digit; //out(""choice 1 "" + m); digit *= 10; if (m > n && m <= max && !found.contains(m)) { //out(n + "" , "" + m); count++; found.add(m); } } return count; } public static void out(String s){ output.println(s); //System.out.println(s); } } " B20080,"import java.util.*; class xyzappp { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int p=sc.nextInt(); int t=1; while(p!=0) { int z=sc.nextInt(); int b=sc.nextInt(); int cnt=0; for(int i=z;i<=b;i++) { int a[]=new int[5000]; String s=""""+i; int cnt1=0,d=0; int n=Integer.parseInt(s); char c[]=s.toCharArray(); for(int j=1;j<(c.length);j++) { char temp; temp=c[0]; for(int k=0;k<(c.length-1);k++) { c[k]=c[k+1]; } c[c.length-1]=temp; String s1=new String(c); int w=Integer.parseInt(s1); if((w>n)&&(w>=z)&&(w<=b)) { a[d]=w; d++; cnt1++; } } int e=0,cnt2=0; while(a[e]!=0) { cnt2++; e++; } int len=cnt2; for(int l=0;l used = new HashSet(); for(int j=0 ; j n && m <= B) { recycles++; } a = a.substring(1) + a.substring(0, 1); m = Integer.parseInt(a); if (m == n) { break; } } } output(i + 1, recycles); } } } " B20335," import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import java.io.File; import java.io.IOException; import java.io.FileWriter; import java.io.BufferedWriter; public class Recycle { public static void main(String[] args) { /* Set perms = getPermutations(123456); for(Integer i: perms) System.out.println(i);*/ try { Scanner s = new Scanner(new File(""recycle.in"")); BufferedWriter w = new BufferedWriter(new FileWriter(new File(""recycle.out""))); int numCases = s.nextInt(); s.nextLine(); for(int n = 1;n <= numCases; n++) { int A = s.nextInt(); int B = s.nextInt(); int count = 0; for(int k = A; k <= B; k++) { count += getNumPairs(k, B); } w.write(""Case #"" + n + "": "" + count + ""\n""); } w.flush(); w.close(); } catch (IOException e) { e.printStackTrace(); } } public static int getNumPairs(int n, int B) { Set possibles = getPermutations(n); int count = 0; for(Integer i : possibles) if(i > n && i <= B) count++; return count; } public static Set getPermutations(int n) { Set perms = new TreeSet(); char[] digits = String.valueOf(n).toCharArray(); for(int firstPos = 1; firstPos < digits.length; firstPos++) { String toBuild = """"; for(int k = 0; k < digits.length; k++) toBuild += digits[(firstPos + k) % digits.length]; perms.add(Integer.parseInt(toBuild)); } return perms; } }" B20560," import java.io.*; import java.util.*; class JamC { public static void main(String args[])throws Exception { FileReader fr = new FileReader(""C-large.in""); BufferedReader br = new BufferedReader(fr); FileWriter fw= new FileWriter(""out.txt""); BufferedWriter bw=new BufferedWriter(fw); PrintWriter pw= new PrintWriter(bw); int t=Integer.parseInt(br.readLine());int l=0; String str="""",A="""",B="""",n="""",m="""";int a=0,b=0,count=0; for(int i=0;iB.charAt(0)) {} else if(n.charAt(k)b)) {} else if(n.charAt(k)==n.charAt(0)&&(Integer.parseInt(n.substring(k)+n.substring(0,k))<=j)) {} else if(n.equals(n.substring(k)+n.substring(0,k))) {} else count++; } } pw.println(""Case #""+(i+1)+"": ""+count); } pw.close(); bw.close(); fw.close(); } } " B21506,"package codejam2012.qualification; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { static String dir=""/home/casatta/Scaricati/""; // static String dir=""data/""; // static String fname=""B-large.in""; // static String fname=""C-small-attempt0.in""; static String fname=""C-large.in""; // static String fname=""RecycledNumbers""; public void test(Scanner input, PrintWriter out, Long i) { int a=input.nextInt(); int b=input.nextInt(); int count=0; for(int j=a;j<=b;j++) { count=count+countGoodRecycled(j, b); } String result = ""Case #"" + (i+1) + "": "" +count; out.println(result); System.out.println(result); System.out.println(); } int countGoodRecycled(int val,int maxVal) { String valString=""""+val; int length=valString.length(); Set results=new HashSet(); for(int i=length-1;i>0;i--) { if(valString.charAt(i)!='0') { String after =valString.substring(i); String before=valString.substring(0,i); int inverse=Integer.parseInt( after+before ); if(inverse<=maxVal && val=0&&p-(int)Math.floor(totalsMinus[i]/2)<=2){ max++; if(p-(int)Math.floor(totalsMinus[i]/2)==2) surprising++; } } while(surprising>totalSurprising){ surprising--; max--; } file.write(""Case #""+Integer.toString(j+1)+"": ""+Integer.toString(max)+""\r\n""); } file.close(); } } " B20517,"package google.jam; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; public class RecycledNumbers { public static void main (String[] args){ System.out.println(""Please, type your input:""); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); boolean checkLines = false; int numLines = 0, linesCounter = 0; String line; String output = """"; try { while((line = stdIn.readLine()) != null){ if(!checkLines){ numLines = Integer.parseInt(line); checkLines = true; }else{ linesCounter++; output += inputToOutput(line, String.valueOf(linesCounter)); } if(linesCounter >= numLines) break; } System.out.println(output); } catch (IOException e) { System.out.println(""Something went wrong with your input.""); e.printStackTrace(); } } public static String inputToOutput(String input, String lineNum){ TreeSet set = new TreeSet(); String[] numbers = input.split("" ""); if(numbers.length != 2) return ""Case #"" + lineNum + "": 0\n""; int start = Integer.parseInt(numbers[0]); int end = Integer.parseInt(numbers[1]); if(start >= end) return ""Case #"" + lineNum + "": 0\n""; int cur = start; while(cur <= end){ for(int i=String.valueOf(cur).length()-1; i>0; i--){ String number = String.valueOf(cur); if(number.charAt(i) == '0') continue; String newNum = number.substring(i) + number.substring(0, i); int newInt = Integer.parseInt(newNum); if( newInt > end || newInt < start || newNum.equals(number) ) continue; set.add( (number.compareTo(newNum) < 0)?(newNum+number):(number+newNum) ); } cur++; } return ""Case #"" + lineNum + "": "" + set.size() + ""\n""; } } " B21323,"import java.util.Scanner; import java.io.OutputStreamWriter; import java.net.URLConnection; import java.util.Locale; import java.net.URL; import java.io.PrintStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.File; import java.io.BufferedInputStream; import java.util.HashSet; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Set; import java.net.Socket; import java.io.FileOutputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author @zhendeaini6001 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { In input = new In(""D:\\codeforce\\src\\C-large.in""); Out output = new Out(""D:\\codeforce\\src\\C-large.out""); int[] power = {1,10,100,1000,10000,100000,1000000,10000000}; int T = input.readInt(); Set set = new HashSet(); for (int k = 1; k <= T; ++k){ int A = input.readInt(); int B = input.readInt(); long res = 0; for (int i = A; i <= B; ++i){ String char_array = String.valueOf(i); int length = char_array.length(); set.clear(); for (int j = 1; j < char_array.length(); ++j){ if (char_array.charAt(j) == '0'){ continue; } if (char_array.charAt(j) > char_array.charAt(0)){ continue; } int val = i % power[length - j] * power[j] + i / power[length - j]; if (val < i && val >= A){ set.add(val); } } res += set.size(); } output.println(""Case #"" + k + "": "" + res); } return; } } class In { private Scanner scanner; // assume Unicode UTF-8 encoding //private String charsetName = ""UTF-8""; private String charsetName = ""ISO-8859-1""; // assume language = English, country = US for consistency with System.out. private Locale usLocale = new Locale(""en"", ""US""); /** * Create an input stream for standard input. */ public In() { scanner = new Scanner(new BufferedInputStream(System.in), charsetName); scanner.useLocale(usLocale); } /** * Create an input stream from a socket. */ public In(Socket socket) { try { InputStream is = socket.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + socket); } } /** * Create an input stream from a URL. */ public In(URL url) { try { URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + url); } } /** * Create an input stream from a file. */ public In(File file) { try { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + file); } } /** * Create an input stream from a filename or web page name. */ public In(String s) { try { // first try to read file from local file system File file = new File(s); if (file.exists()) { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); return; } // next try for files included in jar URL url = getClass().getResource(s); // or URL from web if (url == null) { url = new URL(s); } URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + s); } } /** * Is the input stream empty? */ public boolean isEmpty() { return !scanner.hasNext(); } /** * Does the input stream have a next line? */ public boolean hasNextLine() { return scanner.hasNextLine(); } /** * Read and return the next line. */ public String readLine() { String line; try { line = scanner.nextLine(); } catch (Exception e) { line = null; } return line; } // return rest of input as string /** * Read and return the remainder of the input as a string. */ public String readAll() { if (!scanner.hasNextLine()) { return null; } // reference: http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html return scanner.useDelimiter(""\\A"").next(); } /** * Return the next string from the input stream. */ public String readString() { return scanner.next(); } /** * Return the next int from the input stream. */ public int readInt() { return scanner.nextInt(); } /** * Return the next double from the input stream. */ public double readDouble() { return scanner.nextDouble(); } /** * Read ints from file */ public static int[] readInts(String filename) { In in = new In(filename); String[] fields = in.readAll().trim().split(""\\s+""); int[] vals = new int[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Integer.parseInt(fields[i]); return vals; } /** * Close the input stream. */ public void close() { scanner.close(); } } class Out { // force Unicode UTF-8 encoding; otherwise it's system dependent private static final String UTF8 = ""UTF-8""; private PrintWriter out; /** * Create an Out object using an OutputStream. */ public Out(OutputStream os) { try { OutputStreamWriter osw = new OutputStreamWriter(os, UTF8); out = new PrintWriter(osw, true); } catch (IOException e) { e.printStackTrace(); } } /** * Create an Out object using standard output. */ public Out() { this(System.out); } /** * Create an Out object using a Socket. */ public Out(Socket socket) { try { OutputStream os = socket.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, UTF8); out = new PrintWriter(osw, true); } catch (IOException e) { e.printStackTrace(); } } /** * Create an Out object using a file specified by the given name. */ public Out(String s) { try { OutputStream os = new FileOutputStream(s); OutputStreamWriter osw = new OutputStreamWriter(os, UTF8); out = new PrintWriter(osw, true); } catch (IOException e) { e.printStackTrace(); } } /** * Close the output stream. */ public void close() { out.close(); } /** * Print an object and then terminate the line. */ public void println(Object x) { out.println(x); } } " B22127,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Iterator; import java.util.Scanner; public class A { public static void main(String[] args) { new A().run(); } private void run() { Scanner s; try { s = new Scanner(new File(""A.in"")); int t = s.nextInt(); s.nextLine(); for (int i = 0; i < t; i++) { HashMap map = new HashMap(); int count = 0; int a = s.nextInt(); int b = s.nextInt(); for(int j=a;j<=b;j++){ String str = """"+j; String tmp = str; for (int k = 0; k < str.length()-1; k++) { tmp = tmp.charAt(tmp.length()-1) + tmp.substring(0, tmp.length()-1); int m = Integer.parseInt(tmp); if(Integer.parseInt(tmp) > j && m <=b ){ if(!map.containsKey(j+""_""+m)){ map.put(j+""_""+m, true); count++; } } } } System.out.println(""Case #""+(i+1)+"": ""+count); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B21040,"package de.hg.codejam.tasks.numbers.service; import java.util.HashSet; import java.util.Set; public class Calculator { private final Set overallShifts = new HashSet<>(); public int calculate(int[] pair) { int result = 0; int lowerBorder = pair[0]; int upperBorder = pair[1]; for (int i = lowerBorder; i <= upperBorder; i++) { if (!overallShifts.contains(i)) { Set shifts = getShifts(i); int numberOfValidPairs = countValidPairs(shifts, lowerBorder, upperBorder); result += numberOfValidPairs; } } return result; } public static int[] calculate(int[][] pairs) { int[] results = new int[pairs.length]; for (int i = 0; i < pairs.length; i++) results[i] = new Calculator().calculate(pairs[i]); return results; } private Set getShifts(int number) { String n = String.valueOf(number); Set result = new HashSet<>(n.length()); result.add(number); for (int i = 1; i < n.length(); i++) { n = n.substring(n.length() - 1) + n.substring(0, n.length() - 1); result.add(Integer.parseInt(n)); } overallShifts.addAll(result); return result; } private int countValidPairs(Set numbers, int lowerBorder, int upperBorder) { int counter = 0; Integer[] array = new Integer[numbers.size()]; numbers.toArray(array); for (int i = 0; i < array.length; i++) if (array[i] >= lowerBorder && array[i] <= upperBorder) for (int j = i + 1; j < array.length; j++) if (array[j] >= lowerBorder && array[j] <= upperBorder) if (array[i] != array[j] && String.valueOf(array[i]).length() == String .valueOf(array[j]).length()) counter++; return counter; } } " B20404,"import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws Exception { int i,j,k; int A, B; int L; String first, second, secondNoLeadingZeros; int s; HashSet hs = new HashSet(); BufferedReader br = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(""C-large.out""); StringTokenizer st; int T = Integer.parseInt(br.readLine()); int res; for (k=1;k<=T;k++) { System.out.println(k+""/""+T); st = new StringTokenizer(br.readLine()); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); L = Integer.toString(A).length(); res = 0; for (i=A;i<=B;i++) { first = Integer.toString(i); hs.clear(); hs.add(i); for (j=1;j= A)&&(s <= B)) { if (hs.contains(s) == false) { hs.add(s); res++; } } } } } res /= 2; out.println(""Case #""+k+"": ""+res); } out.close(); } } " B20198,"import java.util.*; public class C { public static void main(String[] args) { new C(); } private Set NUMSET; public C() { Scanner scan = new Scanner(System.in); int NCASES = scan.nextInt(); for (int ZZ = 1; ZZ <= NCASES; ZZ++) { int A = scan.nextInt(); int B = scan.nextInt(); NUMSET = new TreeSet(); int nDigits = String.valueOf(A).length(); long count = 0; for (int i = A; i <= B; i++) { count += rot(i, A, B, nDigits); } System.out.println(""Case #""+ZZ+"": ""+count); } } private int rot(int num, int min, int max, int len) { NUMSET.clear(); for (int i = 1; i < len; i++) { int divisor = (int) (Math.pow(10, i)); int mult = (int) (Math.pow(10, len-i)); int one = num / divisor; int two = (num % divisor)*mult; int next = two+one; if (next > num && next <= max) { NUMSET.add(next); } } return NUMSET.size(); } }" B20504,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class problem3 { void main() { solve(); } public void solve() { try { FileInputStream fstream = new FileInputStream(""pr3_input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fout = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(fout); int iCases = Integer.parseInt(br.readLine()); for (int iStep = 0; iStep < iCases; iStep++) { String strLine = br.readLine(); String[] myNumbers = strLine.split("" ""); int A = Integer.valueOf(myNumbers[0]).intValue(); int B = Integer.valueOf(myNumbers[1]).intValue(); int digits = myNumbers[0].length(); int iValue = 0; for (int jStep = A; jStep <= B; jStep++) { List pairs = new ArrayList(); for (int kStep = 1; kStep < digits; kStep++) { int m = perm(jStep, kStep); if ((A <= jStep)&&(jStep < m)&&(m <= B)) { if (false == pairs.contains(m)) { iValue++; pairs.add(m); } } } } if (iStep != (iCases - 1)) { out.write(String.format(""Case #%d: %d\n"", iStep + 1, iValue)); } else { out.write(String.format(""Case #%d: %d"", iStep + 1, iValue)); } } out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } public int perm(int iNumber, int iDigitsPerm) { String strNumber = String.format(""%d"", iNumber); String strReturn = strNumber.substring(strNumber.length() - iDigitsPerm) + strNumber.substring(0, strNumber.length() - iDigitsPerm); if (strReturn.charAt(0) == '0') { strReturn = ""0""; } return Integer.parseInt(strReturn); } } " B21095,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Solve3 { public static void main(String[] args) { FileReader fr; FileWriter fw; try { File fi = new File(""input.txt""); fr = new FileReader(fi); BufferedReader br = new BufferedReader(fr); fw = new FileWriter(""output.txt""); BufferedWriter bw = new BufferedWriter(fw); boolean f = true; int tCount = Integer.MAX_VALUE; int c = 1; String line = null; while((line = br.readLine()) != null && c <= tCount) { if(f) { f = false; tCount = Integer.parseInt(line); continue; } long ans = getVal(line); String os = ""Case #"" + c + "": "" + ans; bw.write(os); bw.newLine(); c++; } bw.flush(); bw.close(); br.close(); } catch (FileNotFoundException eg) { // TODO Auto-generated catch block eg.printStackTrace(); } catch (IOException ed) { // TODO Auto-generated catch block ed.printStackTrace(); } } private static int getDC(long n) { int c = 0; while(n > 0) { c++; n = n/10; if(n == 0) { break; } } return c; } public static long getVal(String line) { String[] sa = line.split("" ""); long n = Integer.parseInt(sa[0].trim()); long m = Integer.parseInt(sa[1].trim()); int dc = getDC(n); long count = 0; Map s = new HashMap(); for(long i = n; i <= m; i++) { Set _s = correct(i, n, m, dc); if (_s.isEmpty()) continue; Iterator it = _s.iterator(); while(it.hasNext()) { Long o = (Long)it.next(); if (s.containsKey(o)) { it.remove(); } } if (_s.isEmpty()) continue; s.put(i, _s); } Iterator mit = s.keySet().iterator(); while(mit.hasNext()) { count += ((Set)s.get(mit.next())).size(); } return count; } public static Set correct(long nt, long n, long m, int dc) { Set l = new HashSet(); for(int i = 1; i < dc ;i ++) { long tens = (long)Math.pow(10, dc - i); long tenso = (long)Math.pow(10, i); long left = nt/tens; long right = nt%tens; long n_ = right * tenso + left; if (n_ >= n && n_ <= m && n_ != nt){ l.add(n_); } } return l; } } " B22149,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedList; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException { Scanner s = new Scanner(new File(""io/C-large.in"")); FileWriter fw = new FileWriter(new File(""io/C-large.out"")); int cases = s.nextInt(); s.nextLine(); for(int i = 0; i < cases; i++) { int a = s.nextInt(); int b = s.nextInt(); String out = ""Case #"" + (i+1) + "": "" + solve(a, b); System.out.println(out); fw.write(out + ""\n""); } s.close(); fw.close(); } private static int solve(int n, int m) { int rotations = Integer.toString(n).length(); int count = 0; String nStr; // For each n to m for(int i = n; i < m; i++) { LinkedList l = new LinkedList(); nStr = """" + i; // Rotate through all possible configurations of n for(int r = 0; r < rotations -1; r++) { nStr = nStr.substring(rotations - 1) + nStr.substring(0, rotations-1); if(nStr.charAt(0) != '0') { int newN = Integer.parseInt(nStr); if(newN > i && newN <= m) { if(l.contains(newN) == false) { l.add(newN); count++; } } } } } return count; } } " B21290," import java.io.*; import java.util.*; class ProblemC { public static void main(String[] args) throws IOException { FileReader fr = new FileReader(args[0]); BufferedReader br = new BufferedReader(fr); String[] splittArray; int[] points; int A,B,res; int T = Integer.parseInt(br.readLine()); //System.out.println(T); String dummy; String result=""""; for(int i=1;i<=T;i++) { dummy=br.readLine(); splittArray=dummy.split("" ""); A=Integer.parseInt(splittArray[0]); B=Integer.parseInt(splittArray[1]); res=0; for(int j=A;j result=new LinkedList(); String dummy; int dummy2; for(int i=1;i<=a.length()-1;i++) { dummy=a.substring(i,a.length())+a.substring(0,i); dummy2=Integer.parseInt(dummy); if(dummy2>b && dummy2<=c && !result.contains(dummy2)) result.add(dummy2); } return result.size(); } } " B20138,"import java.util.*; import java.io.*; public class C { public static int roll (int i, int a, int b) { int found = 0; int digits = (""""+i).length(); int[] vit = new int[digits]; int magic; int keep, move,done; for (int d = 1; d < digits; d++) { magic = (int)Math.pow(10, d); keep = i/magic; move = i%magic; magic = (int)Math.pow(10, digits-d); done = keep + (move * magic); if (a <= done && done <= b && done < i) { vit[found] = done; found++; } } if (found > 1) { Arrays.sort(vit); for (int j = 0; j < vit.length - 1; j++) if (vit[j] != 0 && vit[j] == vit[j+1]) found--; } return found; } public static void main(String... args) throws Exception { BufferedReader in = new BufferedReader (new FileReader( ""C-large.in"" )); String line; in.readLine(); int casenum = 1; int a,b; String[] nums; while ( (line = in.readLine()) != null) { nums = line.split("" ""); a = Integer.valueOf(nums[0]); b = Integer.valueOf(nums[1]); int result = 0; for (int m = a; m <= b; m++) result += roll(m,a,b); System.out.println(""Case #"" + casenum + "": "" + (result)); casenum++; } } }" B21064," import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Principal { public static void main (String Args[]){ boolean numeros[]= new boolean[20000000]; Scanner input = new Scanner(System.in); File saida = new File(""c:/saida.txt""); BufferedWriter bw; int A, B, T; String entrada; String a,b; String search; int tamanho_string, teste; int resposta=0, temp=0; String texto=""""; entrada=input.nextLine(); T= Integer.parseInt(entrada); for(int i=1;i<=T;i++){ a = input.next(); b = input.next(); A = Integer.parseInt(a); B = Integer.parseInt(b); for(int j=A; j<=B; j++){ if(numeros[j]){ continue; } numeros[j]=true; search = """"+j+j; tamanho_string= a.length(); for (int k=0;kj && teste <=B && !numeros[teste]){ numeros[teste]=true; temp++; } } for(;temp>0;temp--) resposta+=temp; temp=0; } texto=""Case #""+i+"": ""+resposta+""\n""; try { bw=new BufferedWriter(new FileWriter(saida, true)); bw.write(texto); bw.newLine(); bw.close(); } catch (IOException e) { e.printStackTrace(); } for(int asd=0;asd<2000000;asd++) numeros[asd]=false; temp=0; resposta=0; } } } " B21297,"package com.gdacarv.codejam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; public class ProblemC { public static void main(String [ ] args){ try{ FileInputStream fstream = new FileInputStream(""input_problemC.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String input = new String(); String line; while ((line = br.readLine()) != null) input += line + '\n'; System.out.println(input); System.out.println(solveProblemC(input)); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private static String solveProblemC(String input) { String result = new String(); String[] lines = input.split(""\n""), numbers; int len = Integer.parseInt(lines[0]); int A, B, qt, current, aux, counterTemp = 0; String currentString; int[] temp = new int[10]; for(int i = 1; i <= len; i++){ result += ""Case #"" + i + "": ""; numbers = lines[i].split("" ""); A = Integer.parseInt(numbers[0]); B = Integer.parseInt(numbers[1]); qt = 0; for(current = A; current <= B; current++){ currentString = String.valueOf(current); check: for(int j = 1; j < currentString.length(); j++){ if(current < (aux = Integer.parseInt(currentString.substring(j) + currentString.substring(0, j))) && aux <= B){ for(int l = 0; l < counterTemp; l++) if(temp[l] == aux) continue check; qt++; temp[counterTemp] = aux; counterTemp++; //System.out.println(current +"",""+aux); } } counterTemp = 0; } result += qt + ""\n""; } return result; } } " B21324,"import java.io.*; import java.util.InputMismatchException; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov (egor@egork.net) */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""taskc.in""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""taskc.out""); } catch (IOException e) { throw new RuntimeException(e); } InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { System.err.println(testNumber); String a = in.readString(); String b = in.readString(); int answer = 0; for (int i = Integer.parseInt(a); i <= Integer.parseInt(b); i++) { String c = Integer.toString(i); String d = c; do { c = c.substring(c.length() - 1) + c.substring(0, c.length() - 1); if (c.compareTo(d) > 0 && c.compareTo(b) <= 0) answer++; } while (!c.equals(d)); } out.printLine(""Case #"" + testNumber + "":"", answer); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } " B20235,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; public class Recycled { private File file = new File(""D:\\Sources\\GoogleCodeJam\\files\\C-large.in""); private File outFile = new File(""D:\\Sources\\GoogleCodeJam\\files\\result.out""); private Long[] results; private Integer solved = 0; public void readData() { boolean first = true; Scanner scanner; try { scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); Scanner scan = new Scanner(line); if (first) { results = new Long[scan.nextInt()]; first = false; } else { long min = scan.nextLong(); long max = scan.nextLong(); results[solved] = solveProblem(min, max); solved++; } } printResult(); } catch (Exception e) { e.printStackTrace(); } } private Long solveProblem(long min, long max) { long sum = 0; TreeSet res = new TreeSet(); for (long val = min; val <= max; val++) { res.clear(); String number = String.valueOf(val); int len = number.length(); for (int i = 1; i < number.length(); i++) { String newVal = number.substring(i, len) + number.substring(0, i); long recycled = Long.valueOf(newVal); if(recycled > val && recycled <= max && res.add(val + recycled * Math.pow(10, len))) { sum++; } } } return sum; } private void printResult() { try { FileWriter fstream = new FileWriter(outFile); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < results.length; i++) { out.write(""Case #"" + (i + 1) + "": "" + results[i]); out.newLine(); } out.close(); } catch (Exception e) { e.printStackTrace(); } } } " B20289,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Created by IntelliJ IDEA. * User: nickg * Date: 4/13/12 * Time: 9:57 PM * To change this template use File | Settings | File Templates. */ public class CodeJamThree { public static int numNumbers(int a, int b){ int digits = (int) Math.log10(b); digits++; Set seen = new HashSet(); int total = 0; for(int x = a; x < b; x++){ int pow = 10; seen.clear(); for(int y = 1; y < digits; y++){ int moved = move(x, pow); pow*= 10; if(moved <= b && moved > x) seen.add(moved); } total+= seen.size(); } return total; } public static int move(int src, int pow){ int smallPart = src / pow; int bigPart = src % pow; int factor = (int) Math.log10(smallPart) + 1; pow = (int) Math.pow(10, factor); return bigPart * pow + smallPart; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int numTrials = scanner.nextInt(); for(int i = 0; i < numTrials; i++){ int i1 = numNumbers(scanner.nextInt(), scanner.nextInt()); System.out.println(""Case #"" + (i+1) + "": "" + i1); } } } " B22084,"import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws IOException{ Scanner scanner = new Scanner(new File(""input.txt"")); int numCases = scanner.nextInt(); PrintWriter pw = new PrintWriter(new File(""output3.txt"")); for(int i=1; i <= numCases; i++){ long a = scanner.nextLong(); long b = scanner.nextLong(); int result = 0; // Computer number of digits long digits = computeNumOfDigits(a); // Iterate over all numbers for(long n=a; n <=b; n++){ long m = n; HashSet generateNumbers = new HashSet<>(); for(long j = 1; j < digits; j++){ m = rotateRightMostDigit(m, digits); generateNumbers.add(m); } // Iterate over all numbers generated by each number for(Long l:generateNumbers){ if(computeNumOfDigits(l)==digits && l>n && l<=b){ result++; } } } //System.out.println(""Case #"" + i + "": "" + result); pw.println(""Case #"" + i + "": "" + result); pw.flush(); } } private static long rotateRightMostDigit(long m, long digits) { long d = m%10; long rightPart = m/10; long leftPart = (int) Math.pow(10.0, digits -1); long result = (leftPart * d) + rightPart; return result; } private static long computeNumOfDigits(long inputNum) { if(inputNum == 0){ return 1; } long digits = 0; while(inputNum!=0){ inputNum = inputNum/10; digits++; } return digits; } } " B20771,"import java.util.*; public class RecycledNumbers{ public static void main(String[] args){ Scanner scanner = new Scanner(System.in); int num = Integer.parseInt(scanner.nextLine()); for(int i = 1; i <= num; ++i){ String[] tokens = scanner.nextLine().split("" ""); int lower = Integer.parseInt(tokens[0]); int upper = Integer.parseInt(tokens[1]); RecycledNumbers r = new RecycledNumbers(); System.out.println(""Case #"" + i + "": "" + r.recycledNumbers(lower, upper)); } } public int recycledNumbers(int a , int b){ this.lower = a; this.upper = b; for(int i = a; i <= b; ++i){ findAllRecycleNumbers(i); } return numRecycleNumbers; } public void findAllRecycleNumbers(int i){ Set pairs = new HashSet(); int power = getPower(i); int recycleNumber = i; for(int count = 0; count <= power; ++count){ int quotient = recycleNumber / 10; int remainder = recycleNumber % 10; recycleNumber = (int)Math.pow(10, power) * remainder + quotient; if(recycleNumber >= lower && recycleNumber > i && recycleNumber <= upper){ if(!pairs.contains(recycleNumber)){ pairs.add(recycleNumber); ++numRecycleNumbers; } } } } private int getPower(int i){ int pow = 0; while(i > 9){ i /= 10; ++pow; } return pow; } public static class Pairs{ int lower; int upper; public Pairs(int lower, int upper){ this.lower = lower; this.upper = upper; } } private int numRecycleNumbers; private int lower; private int upper; }" B21727," import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Chung Lee */ public class RecycleNumber { public static void Main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File(args[0])); PrintWriter writer = new PrintWriter(args[1]); int noCase = scanner.nextInt(); for (int i = 0; i < noCase; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); int noRecyclePair = 0; for (int j = A; j <= B; j++) { noRecyclePair += getNoRecyclePair(j, A, B); } noRecyclePair /= 2; System.out.print(String.format(""Case #%d: %d"", i + 1, noRecyclePair)); writer.print(String.format(""Case #%d: %d"", i + 1, noRecyclePair)); if (i != noCase - 1) { System.out.println(); writer.println(); } } writer.close(); } public static int getNoRecyclePair(int num, int A, int B) { int temp = num; int digits = 0; while (temp != 0) { temp /= 10; digits++; } int noRecyclePair = 0; for (int i = 1; i <= digits; i++) { int recycleNum = (int) ((num % Math.pow(10, i)) * Math.pow(10, digits - i) + (num / Math.pow(10, i))); if (recycleNum != num && recycleNum >= A && recycleNum <= B) { noRecyclePair++; } } return noRecyclePair; } } " B20203,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class RecycledNumbers { public static void main(String[] args) throws IOException { String msg = """"; BufferedReader br = null; String sCurrentLine = null; Map map = new HashMap(); br = new BufferedReader(new FileReader(""test"")); sCurrentLine = br.readLine(); int x = 0; if (sCurrentLine != null) { while ((sCurrentLine = br.readLine()) != null) { int sum = 0; msg = """"; x++; int a = Integer.parseInt(sCurrentLine.split("" "")[0]); int b = Integer.parseInt(sCurrentLine.split("" "")[1]); for (int n = a; n < b; n++) { // for (int m = n + 1; m <= b; m++) { sum += fetchUniquePairs(n, a, b); // } } msg += ""Case #"" + x + "": "" + sum; System.out.println(msg); } } } private static int fetchUniquePairs(int n, int a, int b) { List uniquePairs = new ArrayList(); int dupN = n; int i = 0; while (dupN > 0) { dupN = dupN / 10; i++; } dupN = n; for (int j = 0; j < i - 1; j++) { int mod = dupN % 10; int add = mod * (int) Math.pow(10, i - 1); dupN = (dupN / 10); dupN += add; if (dupN <= b && dupN > n) if (!uniquePairs.contains(dupN)) uniquePairs.add(dupN); } return uniquePairs.size(); } } " B21935,"package quialification; import base.Base; import java.io.PrintStream; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Created with IntelliJ IDEA. * User: babulya * Date: 14.04.12 * Time: 19:45 * To change this template use File | Settings | File Templates. */ public class C extends Base { private static class Number { private int[] digits; private Number(int[] digits) { this.digits = digits; } public Number(int N) { int dc = (int) Math.ceil(Math.log10(N + 1)); digits = new int[dc]; for (int i = 0; i < dc; i++) { digits[i] = N % 10; N = N / 10; } } private static int compareTo(int o1, int o2) { return o1 - o2; } public int compareTo(Number other) { int res = compareTo(digits.length, other.digits.length); if (res != 0) return res; int ind = digits.length - 1; while (ind >= 0 && digits[ind] == other.digits[ind]) { ind--; } if (ind >= 0) return compareTo(digits[ind], other.digits[ind]); return 0; } public Set pairs() { Set res = new HashSet(); for (int i = 0; i < digits.length - 1; i++) { int[] newdigits = new int[digits.length]; for (int j = 0; j <= i; j++) { newdigits[j + digits.length - i - 1] = digits[j]; } for (int j = i + 1; j < digits.length; j++) { newdigits[j - i - 1] = digits[j]; } res.add(new Number(newdigits)); } return res; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Number number = (Number) o; if (!Arrays.equals(digits, number.digits)) return false; return true; } @Override public int hashCode() { return digits != null ? Arrays.hashCode(digits) : 0; } public String toString() { StringBuilder sb = new StringBuilder(); for (int i = digits.length - 1; i >= 0; i--) { sb.append(digits[i]); } return sb.toString(); } } private static int solve(int a, int b) { int result = 0; Number A = new Number(a); Number B = new Number(b); for (int n = a; n <= b; n++) { Number N = new Number(n); for (Number M : N.pairs()) { if (A.compareTo(N) <= 0 && N.compareTo(M) < 0 && M.compareTo(B) <= 0) { result++; } } } return result; } @Override protected void solve(Scanner in, PrintStream out) { int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); out.println(String.format(""Case #%d: %d"", i, solve(A, B))); } } public static void main(String[] args) { long now = System.currentTimeMillis(); new C(); System.out.println((System.currentTimeMillis() - now)/1000); } } " B21596,"package com.brootdev.gcj2012.common; import java.io.*; public class Data { public final BufferedReader in; public final PrintWriter out; public Data(String inFile, String outFile) throws IOException { in = new BufferedReader(new FileReader(inFile)); out = new PrintWriter(new BufferedWriter(new FileWriter(outFile))); } public long readLongLine() throws IOException { return DataUtils.readLongLine(in); } public long[] readLongsArrayLine() throws IOException { return DataUtils.readLongsArrayLine(in); } public void writeCaseHeader(long case_) { DataUtils.writeCaseHeader(out, case_); } } " B21653,"import java.util.*; public class RecycledNumbers { static class Number implements Comparable { int[] digits; public Number(String str) { digits = new int[str.length()]; for(int i=0;i in=Utils.readFile(""C-large.in.in""); ArrayList out =new ArrayList(); //int[][] matrix=new int[100000][100000]; for (int i = 1; i < in.size(); i++) { String[] str=in.get(i).split("" ""); int A= Integer.parseInt(str[0]); int B= Integer.parseInt(str[1]); int numA=numDigit(A); int count=0; HashSet checkDup=new HashSet(); for(int j=A;j<=B;j++){ for(int pos=1;pos""+recycle); checkDup.add(new Integer(recycle)); } //System.out.println(i+"": ""+j +"" vs ""+recycle+""**********""); } } checkDup.clear(); } out.add(""Case #""+i+"": ""+ count); } Utils.writeFile(out, ""c-large""); // for(int i=1000;i<1200;i++){ // System.out.println(i+""=>""+rotate(i,4)); // } } private static int myExp(int e){ if(e==1) return 1; if(e==2) return 10; if(e==3) return 100; if(e==4) return 1000; if(e==5) return 10000; if(e==6) return 100000; //if(e==7) return 1000000; } private static int rotate(int A,int pos) { int num=numDigit(A); if(pos==1) return (A%10)*myExp(num-pos+1)+A/10; if(pos==2) return (A%100)*myExp(num-pos+1)+A/100; if(pos==3) return (A%1000)*myExp(num-pos+1)+A/1000; if(pos==4) return (A%10000)*myExp(num-pos+1)+A/10000; if(pos==5) return (A%100000)*myExp(num-pos+1)+A/100000; if(pos==6) return (A%1000000)*myExp(num-pos+1)+A/1000000; //if(pos==7) return (A%10000000)*myExp(num-pos+1)+A/10000000; } private static int numDigit(int A) { if(A/1000000>0) return 7; if(A/100000>0) return 6; if(A/10000>0) return 5; if(A/1000>0) return 4; if(A/100>0) return 3; if(A/10>0) return 2; return 1; } } " B21951,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; public class RecycledNumbers { private static final boolean DEBUG = false; public static void main( final String[] args ) throws Exception { final BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); final int t = Integer.parseInt( br.readLine() ); for ( int ii = 0; ii < t; ++ii ) { final String parts[] = br.readLine().split( "" "" ); final int from = Integer.parseInt( parts[ 0 ] ); final int to = Integer.parseInt( parts[ 1 ] ); System.out.println( solve( ii + 1, from, to ) ); if ( DEBUG ) System.out.println( ""=== === === === ==="" ); } } private static String solve( final int idx, final int from, final int to ) { final HashSet set = new HashSet(); for ( int i = from; i <= to; ++i ) { add( set, i, from, to ); } return String.format( ""Case #%d: %d"", idx, set.size() ); } private static void add( final HashSet set, final long n, final int from, final int to ) { final String ns = Long.toString( n ); for ( int i = 1; i < ns.length(); ++i ) { final String f = ns.substring( 0, i ); final String t = ns.substring( i ); final long pair = getN( t, f ); final long min = Math.min( n, pair ); final long max = Math.max( n, pair ); if ( from <= pair && pair <= to && pair != n ) set.add( min * 3000000 + max ); } } private static long getN( final String s1, final String s2 ) { long res = 0; for ( int i = 0; i < s1.length(); ++i ) { res += s1.charAt( i ) - '0'; res *= 10; } for ( int i = 0; i < s2.length(); ++i ) { res += s2.charAt( i ) - '0'; res *= 10; } if ( DEBUG ) System.out.printf( ""DEBUG: s1='%s', s2='%s', res=%d\n"", s1, s2, res / 10 ); return res / 10; } @org.junit.Test public void statement1() { org.junit.Assert.assertEquals( String.format( ""Case #%d: %d"", 1, 0 ), solve( 1, 1, 9 ) ); } @org.junit.Test public void statement2() { org.junit.Assert.assertEquals( String.format( ""Case #%d: %d"", 2, 3 ), solve( 2, 10, 40 ) ); } @org.junit.Test public void statement3() { org.junit.Assert.assertEquals( String.format( ""Case #%d: %d"", 3, 156 ), solve( 3, 100, 500 ) ); } @org.junit.Test public void statement4() { org.junit.Assert.assertEquals( String.format( ""Case #%d: %d"", 4, 287 ), solve( 4, 1111, 2222 ) ); } @org.junit.Test(timeout = 10000) public void my1() { org.junit.Assert.assertEquals( String.format( ""Case #%d: %d"", 5, 299997 ), solve( 5, 1000000, 2000000 ) ); } } " B20344,"import java.util.Hashtable; import java.util.Scanner; class RecycleResult{ private int lowerBound, upperBound, numberOfDigits; public RecycleResult(int a, int b, int d){ lowerBound = a; upperBound = b; numberOfDigits = d; } public int solve(){ int count = 0; for (int i = lowerBound; i < upperBound; i++){ int p = i; Hashtable hash = new Hashtable(); for (int j = 1; j < numberOfDigits; j++){ p = moveToFront(p); if ((p <= upperBound) && (p > i) && (!(p == i)) && (!(hash.containsValue(p)))){ count++; hash.put(count, p); } } } return count; } public int moveToFront(int z){ int lastDigit = z % 10; int otherDigits = (z / 10); for (int i = 0; i < numberOfDigits - 1; i++){ lastDigit = lastDigit * 10; } return otherDigits + lastDigit; } } public class Recycle { public static void main(String[] args) { int numberOfCases; Scanner myScanner = new Scanner(System.in); int a, b; numberOfCases = myScanner.nextInt(); RecycleResult myResult; for (int i = 0; i < numberOfCases; i++){ a = myScanner.nextInt(); b = myScanner.nextInt(); int length = String.valueOf(a).length(); myResult = new RecycleResult(a, b, length); int count = myResult.solve(); System.out.println(""Case #"" + (i+1) + "": "" + count); } } } " B20556,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package actual; import codejam.*; import java.io.*; import java.util.Scanner; /** * * @author atm */ public class PCL { public static void main(String[] args) throws Exception { int Cases; int L,U; String words[]; FileInputStream fstreamIN = new FileInputStream(""F:\\codejam\\input\\C-large.in""); FileOutputStream fstreamOUT = new FileOutputStream(""F:\\codejam\\output\\C-large.out""); Scanner in=new Scanner(fstreamIN); PrintWriter out=new PrintWriter(fstreamOUT); Cases=in.nextInt(); for(int i=0;ij) ans++; } } } else { for(int j=L;j<=U;j++){ String num=Integer.toString(j); for(int k=0;kj) ans++; } } } } out.printf(""Case #%d: %d\n"",i+1,ans); } out.close(); } static int revtwo(int num){ return (num%10)*10+(num/10); } static int onedigcir(int num) { int newnum; newnum=(num%10)*100+(num/10); return newnum; } static int twodigcir(int num) { int newnum; newnum=(num%100)*10+(num/100); return newnum; } static int ndigcir(int num,int n) { String number=Integer.toString(num); String right=number.substring(number.length()-n, number.length()); String newNum=right+number.substring(0,number.length()-n); return Integer.parseInt(newNum); } } " B21895,"package recycled; import java.io.BufferedReader; import java.io.FileReader; import java.util.Arrays; public class Recycled { static int[] arr = new int[10]; static int rot(int x, int N, int mult) { return x/10 + (x%10)*mult; } static int count(int j, int B, int N, int mult) { int cnt = 0; int tmp = rot(j,N,mult); while (tmp != j) { if (tmp > j && tmp <= B) { arr[cnt] = tmp; ++cnt; } tmp = rot(tmp,N,mult); } Arrays.sort(arr,0,cnt); int ret = 0; for (int i = 0; i < cnt; ++i) { if (i == 0 || arr[i] != arr[i-1]) { //System.out.println(j+"",""+arr[i]); ++ret; } } return ret; } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(args[0])); String line = in.readLine(); int X = Integer.parseInt(line); for (int i = 0; i < X; ++i) { long ret = 0; line = in.readLine(); String[] toks = line.split("" ""); int A = Integer.parseInt(toks[0]), B = Integer.parseInt(toks[1]); int N = (A+"""").length(); int mult = (int)Math.round(Math.pow(10, N-1)); //System.out.println(""Doing ""+A+"",""+B+"" with mult = ""+mult); for (int j = A; j < B; ++j) { ret += count(j,B,N,mult); } System.out.println(""Case #""+(i+1)+"": ""+ret); } } } " B21750,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class CodeJam { // public static final String INPUT_FILE_PATH = ""D://CodeJamInput.txt""; public static final String INPUT_FILE_PATH = ""D://C-large.in""; public static final String OUTPUT_FILE_PATH = ""D://CodeJamOutput.txt""; public static List readInput() { List list = new ArrayList(); try { BufferedReader input = new BufferedReader(new FileReader( INPUT_FILE_PATH)); try { String line = null; while ((line = input.readLine()) != null) { list.add(line); } } finally { input.close(); } } catch (IOException ex) { ex.printStackTrace(); } return list; } public static void writeOutput(List output) { PrintWriter writer = null; try { writer = new PrintWriter(new FileWriter(OUTPUT_FILE_PATH)); for (String line : output) { writer.println(line); } writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) writer.close(); } } public static void main(String[] args) { List recycledNumbers = RecycledNumbers.parseFromFile(CodeJam.readInput()); List output = new ArrayList(); for(int i = 0; i < recycledNumbers.size(); i++) { System.out.println(recycledNumbers.get(i)); String line = """"; line += ""Case #"" + (i + 1) + "": "" + recycledNumbers.get(i).calculate(); output.add(line); } CodeJam.writeOutput(output); } } " B20463,"/* GCJ2012-Q */ import java.io.*; import java.util.*; import java.math.*; public class GCJ2012QC { static BufferedReader fin; static PrintWriter fout; // change numefile static String file=""qcl""; static String infile=file+"".in""; static String outfile=file+"".out""; // // write result to output file private static void writetestresult(int test, String ret){ fout.println(""Case #""+test+"": ""+ret); } // open files private static void openfiles() throws IOException{ fin = new BufferedReader(new FileReader(infile)); fout = new PrintWriter(new BufferedWriter(new FileWriter(outfile))); } // close files private static void closefiles() throws IOException{ fin.close(); fout.close(); } // solve test no. ""test"" private static String solvetest(int test) throws IOException{ System.out.println("">>>Solving test...""+test); // Parse input for test no. test int iret=0; String a=fin.readLine(); String[] as=a.split("" ""); int A=Integer.parseInt(as[0]); int B=Integer.parseInt(as[1]); for (int n=A; n lst=new ArrayList(); int len=(""""+n).length(); String sm=""""+n; for (int j=0; j<=len; j++) { String sk=sm; int lk=sk.length(); sm=sk.charAt(lk-1)+sk.substring(0, lk-1); int m=Integer.parseInt(sm); if (m>n && m<=B) if (!lst.contains(m)) { lst.add(m); // System.out.println(n+"" ""+m); } } iret+=lst.size(); } String ret=""""; ret=""""+iret; return ret; } // main here public static void main(String[] args) throws IOException{ // open files openfiles(); // read first line, no. of tests String line=fin.readLine(); int T=Integer.parseInt(line); // solve T tests for (int test=1; test<=T; test++) { //long stime=System.currentTimeMillis(); String ret=solvetest(test); writetestresult(test, ret); //long etime=System.currentTimeMillis(); //long dtime=(etime-stime); //System.out.println(""Test ""+test+"": ""+dtime+""ms""); } // close files closefiles(); } } " B21458,"package com.renoux.gael.codejam.utils; import java.io.Closeable; import java.io.IOException; /** *

* Cette classe comporte des méthodes utilitaires de gestion des flux d'entrée/sortie. *

* * @author renouxg */ public class FluxUtils { /** *

* Constructeur privé : cette classe utilitaire n'est pas destinée à être instanciée. *

*/ private FluxUtils() { // classe non instanciable } /** *

* Cette méthode utilitaire ferme tous les objets Closeable qui lui sont passés en paramètre. * Les éléments nuls sont ignorés. Si la fermeture de l'un ou plusieurs d'entre eux renvoie une erreur, on * tâche néanmoins de fermer tous les flux ; la première erreur survenue est ensuite relancée. *

* * @param fluxArray les objets implémentant {@link Closeable} qu'il faut fermer. * @throws IOException toute exception qui peut se produire à la fermeture d'un {@link Closeable}. */ public static void closeCloseables(final Closeable... fluxArray) { IOException relaunch = null; for (Closeable flux : fluxArray) { if (flux == null) { continue; } try { flux.close(); } catch (IOException lEx) { if (relaunch == null) { relaunch = lEx; } else { // Nouvelle exception, ignorée } } } if (relaunch != null) { throw new TechnicalException(relaunch); } } } " B21074,"package template; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class TestCase { private boolean isSolved; private Object solution; private Map intProperties; private Map> intArrayProperties; private Map>> intArray2DProperties; private Map doubleProperties; private Map> doubleArrayProperties; private Map>> doubleArray2DProperties; private Map stringProperties; private Map> stringArrayProperties; private Map>> stringArray2DProperties; private Map booleanProperties; private Map> booleanArrayProperties; private Map>> booleanArray2DProperties; private Map longProperties; private Map> longArrayProperties; private Map>> longArray2DProperties; private int ref; private double time; public TestCase() { initialise(); } private void initialise() { isSolved = false; intProperties = new HashMap<>(); intArrayProperties = new HashMap<>(); intArray2DProperties = new HashMap<>(); doubleProperties = new HashMap<>(); doubleArrayProperties = new HashMap<>(); doubleArray2DProperties = new HashMap<>(); stringProperties = new HashMap<>(); stringArrayProperties = new HashMap<>(); stringArray2DProperties = new HashMap<>(); booleanProperties = new HashMap<>(); booleanArrayProperties = new HashMap<>(); booleanArray2DProperties = new HashMap<>(); longProperties = new HashMap<>(); longArrayProperties = new HashMap<>(); longArray2DProperties = new HashMap<>(); ref = 0; } public void setSolution(Object o) { solution = o; isSolved = true; } public Object getSolution() { if (!isSolved) { Utils.die(""getSolution on unsolved testcase""); } return solution; } public void setRef(int i) { ref = i; } public int getRef() { return ref; } public void setTime(double d) { time = d; } public double getTime() { return time; } public void setInteger(String s, Integer i) { intProperties.put(s, i); } public Integer getInteger(String s) { return intProperties.get(s); } public void setIntegerList(String s, ArrayList l) { intArrayProperties.put(s, l); } public void setIntegerMatrix(String s, ArrayList> l) { intArray2DProperties.put(s, l); } public ArrayList getIntegerList(String s) { return intArrayProperties.get(s); } public Integer getIntegerListItem(String s, int i) { return intArrayProperties.get(s).get(i); } public ArrayList> getIntegerMatrix(String s) { return intArray2DProperties.get(s); } public ArrayList getIntegerMatrixRow(String s, int row) { return intArray2DProperties.get(s).get(row); } public Integer getIntegerMatrixItem(String s, int row, int column) { return intArray2DProperties.get(s).get(row).get(column); } public ArrayList getIntegerMatrixColumn(String s, int column) { ArrayList out = new ArrayList(); for(ArrayList row : intArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setDouble(String s, Double i) { doubleProperties.put(s, i); } public Double getDouble(String s) { return doubleProperties.get(s); } public void setDoubleList(String s, ArrayList l) { doubleArrayProperties.put(s, l); } public void setDoubleMatrix(String s, ArrayList> l) { doubleArray2DProperties.put(s, l); } public ArrayList getDoubleList(String s) { return doubleArrayProperties.get(s); } public Double getDoubleListItem(String s, int i) { return doubleArrayProperties.get(s).get(i); } public ArrayList> getDoubleMatrix(String s) { return doubleArray2DProperties.get(s); } public ArrayList getDoubleMatrixRow(String s, int row) { return doubleArray2DProperties.get(s).get(row); } public Double getDoubleMatrixItem(String s, int row, int column) { return doubleArray2DProperties.get(s).get(row).get(column); } public ArrayList getDoubleMatrixColumn(String s, int column) { ArrayList out = new ArrayList(); for(ArrayList row : doubleArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setString(String s, String t) { stringProperties.put(s, t); } public String getString(String s) { return stringProperties.get(s); } public void setStringList(String s, ArrayList l) { stringArrayProperties.put(s, l); } public void setStringMatrix(String s, ArrayList> l) { stringArray2DProperties.put(s, l); } public ArrayList getStringList(String s) { return stringArrayProperties.get(s); } public String getStringListItem(String s, int i) { return stringArrayProperties.get(s).get(i); } public ArrayList> getStringMatrix(String s) { return stringArray2DProperties.get(s); } public ArrayList getStringMatrixRow(String s, int row) { return stringArray2DProperties.get(s).get(row); } public String getStringMatrixItem(String s, int row, int column) { return stringArray2DProperties.get(s).get(row).get(column); } public ArrayList getStringMatrixColumn(String s, int column) { ArrayList out = new ArrayList(); for(ArrayList row : stringArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setBoolean(String s, Boolean b) { booleanProperties.put(s, b); } public Boolean getBoolean(String s) { return booleanProperties.get(s); } public void setBooleanList(String s, ArrayList l) { booleanArrayProperties.put(s, l); } public void setBooleanMatrix(String s, ArrayList> l) { booleanArray2DProperties.put(s, l); } public ArrayList getBooleanList(String s) { return booleanArrayProperties.get(s); } public Boolean getBooleanListItem(String s, int i) { return booleanArrayProperties.get(s).get(i); } public ArrayList> getBooleanMatrix(String s) { return booleanArray2DProperties.get(s); } public ArrayList getBooleanMatrixRow(String s, int row) { return booleanArray2DProperties.get(s).get(row); } public Boolean getBooleanMatrixItem(String s, int row, int column) { return booleanArray2DProperties.get(s).get(row).get(column); } public ArrayList getBooleanMatrixColumn(String s, int column) { ArrayList out = new ArrayList(); for(ArrayList row : booleanArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setLong(String s, Long b) { longProperties.put(s, b); } public Long getLong(String s) { return longProperties.get(s); } public void setLongList(String s, ArrayList l) { longArrayProperties.put(s, l); } public void setLongMatrix(String s, ArrayList> l) { longArray2DProperties.put(s, l); } public ArrayList getLongList(String s) { return longArrayProperties.get(s); } public Long getLongListItem(String s, int i) { return longArrayProperties.get(s).get(i); } public ArrayList> getLongMatrix(String s) { return longArray2DProperties.get(s); } public ArrayList getLongMatrixRow(String s, int row) { return longArray2DProperties.get(s).get(row); } public Long getLongMatrixItem(String s, int row, int column) { return longArray2DProperties.get(s).get(row).get(column); } public ArrayList getLongMatrixColumn(String s, int column) { ArrayList out = new ArrayList(); for(ArrayList row : longArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } } " B20741,"package fixjava; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class CollectionUtils { /** * @return the single value in the collection, throws an exception if there isn't exactly one item. * @throws IllegalArgumentException * if there is more than one value in the set. */ public static T getSingleVal(Collection collection) { if (collection.size() != 1) throw new IllegalArgumentException(collection.size() + "" objects in collection, expected exactly 1""); T ret = null; for (T val : collection) { ret = val; break; } return ret; } /** * @return the first value returned by an iterator on the collection, throws an exception if there isn't exactly one item. * @throws IllegalArgumentException * if collection is empty */ public static T getFirstVal(Collection collection) { if (collection.size() == 0) throw new IllegalArgumentException(collection.size() + "" objects in collection, expected at least 1""); T ret = null; for (T val : collection) { ret = val; break; } return ret; } // --------------------------------------------------------------------------------------------------------------------- /** * Pass values in an Iterable through a function to produce an ArrayList of mapped values, one output value generated per input * value. Returns null if input is null. */ public static ArrayList map(Iterable values, Lambda mapFunction) { if (values == null) return null; ArrayList result = new ArrayList(); for (S val : values) result.add(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce an ArrayList of mapped values, one output value generated per input * value. Returns null if input is null. */ public static ArrayList map(S[] values, Lambda mapFunction) { if (values == null) return null; ArrayList result = new ArrayList(); for (S val : values) result.add(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce an ArrayList of mapped values, zero or more output values generated * per input value. Returns null if input is null. */ public static ArrayList mapMultiple(Iterable values, Lambda> mapFunction) { if (values == null) return null; ArrayList result = new ArrayList(); for (S val : values) result.addAll(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce a HashSet of mapped values, one output value generated per input * value. Returns null if input is null. */ public static HashSet mapSet(Iterable values, Lambda mapFunction) { if (values == null) return null; HashSet result = new HashSet(); for (S val : values) result.add(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce a HashSet of mapped values, one output value generated per input * value. Returns null if input is null. */ public static HashSet mapSet(S[] values, Lambda mapFunction) { if (values == null) return null; HashSet result = new HashSet(); for (S val : values) result.add(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce a HashSet of mapped values, zero or more output values generated per * input value. Returns null if input is null. */ public static HashSet mapSetMultiple(Iterable values, Lambda> mapFunction) { if (values == null) return null; HashSet result = new HashSet(); for (S val : values) result.addAll(mapFunction.apply(val)); return result; } // --------------------------------------------------------------------------------------------------------------------- public static HashSet filterSet(Iterable values, Lambda filterFunction) { if (values == null) return null; HashSet result = new HashSet(); for (T val : values) if (filterFunction.apply(val)) result.add(val); return result; } public static ArrayList filter(Iterable values, Lambda filterFunction) { if (values == null) return null; ArrayList result = new ArrayList(); for (T val : values) if (filterFunction.apply(val)) result.add(val); return result; } public static HashSet filterSet(T[] values, Lambda filterFunction) { if (values == null) return null; HashSet result = new HashSet(); for (T val : values) if (filterFunction.apply(val)) result.add(val); return result; } public static ArrayList filter(T[] values, Lambda filterFunction) { if (values == null) return null; ArrayList result = new ArrayList(); for (T val : values) if (filterFunction.apply(val)) result.add(val); return result; } // --------------------------------------------------------------------------------------------------------------------- /** * Iterate through multiple Iterables of the same element type, e.g. for (Integer i : CollectionUtils.iterateThroughAllOf(x, y, * z)) { } * * N.B. you will get a warning ""Type safety: A generic array of type Iterable is created for a Varargs parameter"" (lame * Java). */ @SafeVarargs public static Iterable iterateThroughAllOf(final Iterable... iterables) { if (iterables.length == 0) { return (Iterable) new ArrayList(); } else { return new Iterable() { @Override public Iterator iterator() { return new Iterator() { Iterable[] iters = iterables; int iterIdx = -1; Iterator currIter = null; private void advanceIfNecessary() { if (currIter == null || (iterIdx < iters.length - 1 && !currIter.hasNext())) currIter = iterables[++iterIdx].iterator(); } @Override public boolean hasNext() { advanceIfNecessary(); return iterIdx < iters.length && (iterIdx < iters.length - 1 || currIter.hasNext()); } @Override public T next() { advanceIfNecessary(); if (iterIdx == iters.length) throw new RuntimeException(""Out of elements""); return currIter.next(); } @Override public void remove() { advanceIfNecessary(); if (iterIdx == iters.length) throw new RuntimeException(""Out of elements""); else currIter.remove(); } }; } }; } } /** * Iterate through multiple Arrays of the same element type, e.g. for (Integer i : CollectionUtils.iterateThroughAllOf(x, y, z)) * { } */ @SafeVarargs public static Iterable iterateThroughAllOf(final T[]... arrays) { if (arrays.length == 0) { return (Iterable) new ArrayList(); } else { return new Iterable() { @Override public Iterator iterator() { return new Iterator() { T[][] arrs = arrays; int arrIdx = 0, arrSubIdx = 0; private void advanceIfNecessary() { if (arrIdx < arrs.length && arrSubIdx == arrs[arrIdx].length) { arrIdx++; arrSubIdx = 0; } } @Override public boolean hasNext() { advanceIfNecessary(); return arrIdx < arrs.length && (arrIdx < arrs.length - 1 || arrSubIdx < arrs[arrIdx].length); } @Override public T next() { advanceIfNecessary(); if (arrIdx == arrs.length) throw new RuntimeException(""Out of elements""); return arrs[arrIdx][arrSubIdx++]; } @Override public void remove() { throw new RuntimeException(""Not implemented""); } }; } }; } } /** * Iterate through multiple Iterables of the same element type (skipping over null iterables, *not* null elements), e.g. for * (Integer i : CollectionUtils.iterateThroughAllOf(x, y, z)) { } * * N.B. you will get a warning ""Type safety: A generic array of type Iterable is created for a Varargs parameter"" (lame * Java). */ @SuppressWarnings(""unchecked"") public static Iterable iterateThroughAllOfIgnoringNulls(Iterable... iterables) { ArrayList> filter = filter(iterables, new Lambda, Boolean>() { @Override public Boolean apply(Iterable param) { return param != null; } }); Iterable[] nonNulls = new Iterable[filter.size()]; filter.toArray(nonNulls); return iterateThroughAllOf(nonNulls); } /** * Iterate through multiple arrays of the same element type (skipping over null arrays, *not* null elements), e.g. for (Integer * i : CollectionUtils.iterateThroughAllOf(x, y, z)) { } */ @SuppressWarnings(""unchecked"") public static Iterable iterateThroughAllOfIgnoringNulls(T[]... arrays) { ArrayList filter = filter(arrays, new Lambda() { @Override public Boolean apply(T[] param) { return param != null; } }); Iterable[] nonNulls = new Iterable[filter.size()]; filter.toArray(nonNulls); return iterateThroughAllOf(nonNulls); } // public static void main(String[] args) { // ArrayList x = new ArrayList(); // ArrayList y = new ArrayList(); // ArrayList z = new ArrayList(); // x.add(1); // x.add(2); // x.add(3); // y.add(19); // y.add(23); // z.add(100); // z.add(999); // for (Integer i : iterateThroughAllOf(x, y, z)) // System.out.println(i); // Integer[] a = new Integer[3]; // Integer[] b = new Integer[2]; // a[0] = 10; // a[1] = 11; // a[2] = 12; // b[0] = 7; // b[1] = 8; // for (Integer i : iterateThroughAllOf(a, b)) // System.out.println(i); // } /** * Iterate through a varargs list of iterable objects of type T, and return all the objects in a list. Null iterables are * skipped. */ @SafeVarargs public static ArrayList toListIgnoringNulls(Iterable... iterables) { ArrayList result = new ArrayList(); for (T item : iterateThroughAllOfIgnoringNulls(iterables)) result.add(item); return result; } /** * Iterate through a varargs list of iterable objects of type T, and return all the objects in a set (removing duplicates). Null * iterables are skipped. */ @SafeVarargs public static HashSet toSetIgnoringNulls(Iterable... iterables) { return new HashSet(toListIgnoringNulls(iterables)); } // --------------------------------------------------------------------------------------------------------------------- /** * Look up keys in the map, and return a collection of the corresponding values. Returns null if 'keys' is null. * * @throw IllegalArgumentException if key doesn't exist in map or if a key is null, depending on params. */ public static > C lookup(Collection keys, Map map, LambdaVoid applyIfKeyIsNullWithoutAddingValue, Lambda applyIfKeyIsNullAndAddReturnedValue, LambdaVoid applyWhenKeyDoesntExistWithoutAddingValue, Lambda applyWhenKeyDoesntExistAndAddReturnedValue, C result) { if (keys == null) return null; for (K key : keys) { V val = null; boolean addValue = false; if (applyIfKeyIsNullWithoutAddingValue != null && key == null) { applyIfKeyIsNullWithoutAddingValue.apply(key); } else if (applyIfKeyIsNullAndAddReturnedValue != null && key == null) { val = applyIfKeyIsNullAndAddReturnedValue.apply(key); addValue = true; } else if (applyWhenKeyDoesntExistWithoutAddingValue != null && !map.containsKey(key)) { applyWhenKeyDoesntExistWithoutAddingValue.apply(key); } else if (applyWhenKeyDoesntExistAndAddReturnedValue != null && !map.containsKey(key)) { val = applyWhenKeyDoesntExistAndAddReturnedValue.apply(key); addValue = true; } else { val = map.get(key); addValue = true; } if (addValue) result.add(val); } return result; } /** * Look up keys in the map, and return an ArrayList of the corresponding values. Returns null if 'keys' is null. * * @throw IllegalArgumentException if key doesn't exist in map or if a key is null, depending on params. */ public static ArrayList lookup(Collection keys, Map map, boolean throwExceptionIfKeyNull, boolean throwExceptionIfKeyDoesntExist) { if (keys == null) return null; return lookup(keys, map, throwExceptionIfKeyNull ? new LambdaVoid() { @Override public void apply(K key) { throw new IllegalArgumentException(""Key is null""); } } : null, null, throwExceptionIfKeyDoesntExist ? new LambdaVoid() { @Override public void apply(K key) { throw new IllegalArgumentException(""Could not find key "" + key + "" in map""); } } : null, null, new ArrayList()); } /** * Look up keys in the map, and return an ArrayList of the corresponding values. Performs no checking. Returns null if 'keys' is * null. */ public static ArrayList lookup(Collection keys, Map map) { if (keys == null) return null; ArrayList vals = new ArrayList(keys.size()); for (K key : keys) { // Simple version for speed V val = map.get(key); vals.add(val); } return vals; } /** * Look up keys in the map, and return an ArrayList of the corresponding values. Applies the given function if the key doesn't * exist. Returns null if 'keys' is null. */ public static ArrayList lookup(Collection keys, Map map, LambdaVoid applyWhenKeyDoesntExist) { return lookup(keys, map, null, null, applyWhenKeyDoesntExist, null, new ArrayList()); } /** * Look up keys in the map, and return an ArrayList of the corresponding values. Applies the given function if the key doesn't * exist to produce a default value. Returns null if 'keys' is null. */ public static ArrayList lookup(Collection keys, Map map, Lambda applyWhenKeyDoesntExistToGetDefaultVal) { return lookup(keys, map, null, null, null, applyWhenKeyDoesntExistToGetDefaultVal, new ArrayList()); } /** * Look up keys in the map, and return a HashSet of the corresponding values. Returns null if 'keys' is null. * * @throw IllegalArgumentException if key doesn't exist in map or if a key is null, depending on params. */ public static HashSet lookupAsSet(Collection keys, Map map, boolean throwExceptionIfKeyNull, boolean throwExceptionIfKeyDoesntExist) { if (keys == null) return null; return lookup(keys, map, throwExceptionIfKeyNull ? new LambdaVoid() { @Override public void apply(K key) { throw new IllegalArgumentException(""Key is null""); } } : null, null, throwExceptionIfKeyDoesntExist ? new LambdaVoid() { @Override public void apply(K key) { throw new IllegalArgumentException(""Could not find key "" + key + "" in map""); } } : null, null, new HashSet()); } /** * Look up keys in the map, and return a HashSet of the corresponding values. Performs no checking. Returns null if 'keys' is * null. */ public static HashSet lookupAsSet(Collection keys, Map map) { if (keys == null) return null; HashSet vals = new HashSet(keys.size()); for (K key : keys) { // Simple version for speed V val = map.get(key); vals.add(val); } return vals; } /** * Look up keys in the map, and return a HashSet of the corresponding values. Applies the given function if the key doesn't * exist. Returns null if 'keys' is null. */ public static HashSet lookupAsSet(Collection keys, Map map, LambdaVoid applyWhenKeyDoesntExist) { return lookup(keys, map, null, null, applyWhenKeyDoesntExist, null, new HashSet()); } /** * Look up keys in the map, and return a HashSet of the corresponding values. Applies the given function if the key doesn't * exist to produce a default value. Returns null if 'keys' is null. */ public static HashSet lookupAsSet(Collection keys, Map map, Lambda applyWhenKeyDoesntExistToGetDefaultVal) { return lookup(keys, map, null, null, null, applyWhenKeyDoesntExistToGetDefaultVal, new HashSet()); } // --------------------------------------------------------------------------------------------------------------------- /** Take the union of all items in all passed collections/Iterables */ public static HashSet union(Iterable> iterables) { HashSet result = new HashSet(); for (Iterable iterable : iterables) for (T item : iterable) result.add(item); return result; } /** Put each item in an array into a set. c.f. makeSet(), toSetIgnoringNulls(). */ public static HashSet union(T[] items) { HashSet result = new HashSet(); for (T item : items) result.add(item); return result; } // --------------------------------------------------------------------------------------------------------------------- /** Varargs constructor for a typed set */ @SafeVarargs public static HashSet makeSet(T... items) { HashSet set = new HashSet(items.length); for (T it : items) set.add(it); return set; } /** Varargs constructor for a typed list */ @SafeVarargs public static ArrayList makeList(T... items) { ArrayList list = new ArrayList(items.length); for (T it : items) list.add(it); return list; } /** Varargs constructor for a typed list, specifying initial capacity */ @SafeVarargs public static ArrayList makeListWithInitialCapacity(int initialCapacity, T... items) { ArrayList list = new ArrayList(Math.max(items.length, initialCapacity)); for (T it : items) list.add(it); return list; } // --------------------------------------------------------------------------------------------------------------------- public static ArrayList> mapToListOfPairs(Map map) { ArrayList> result = new ArrayList>(); for (Entry ent : map.entrySet()) result.add(Pair.make(ent.getKey(), ent.getValue())); return result; } // --------------------------------------------------------------------------------------------------------------------- /** * Generate a sorted ArrayList of values from any collection. Does not sort in-place, but rather sorts a copy of the collection. */ public static > ArrayList sortCopy(Collection vals) { ArrayList sorted = new ArrayList(vals); Collections.sort(sorted); return sorted; } /** * Generate a sorted ArrayList of values from any collection, using the specified comparator. Does not sort in-place, but rather * sorts a copy of the collection. */ public static ArrayList sortCopy(Collection vals, Comparator comparator) { ArrayList sorted = new ArrayList(vals); Collections.sort(sorted, comparator); return sorted; } /** * Make a comparator by passing in a lambda that simply returns a comparable field for an object, e.g. * * * CollectionUtils.sort(nodeList, CollectionUtils.makeComparator(new Lambda() { * public String apply(Node obj) { * return obj.getName(); * } * }); * * * This is not much shorter than declaring a comparator in the sort call (and has more overhead), but may be a little simpler or * could reduce code duplication in the comparator. * * @param * The type of the objects to compare * @param * The type of the field to compare * @param getFieldToCompare * A simple getter for the field to compare * @return A comparator that can be used for sorting */ public static > Comparator makeComparator(final Lambda getFieldToCompare) { return new Comparator() { @Override public int compare(O o1, O o2) { return getFieldToCompare.apply(o1).compareTo(getFieldToCompare.apply(o2)); } }; } // --------------------------------------------------------------------------------------------------------------------- /** * Build a map from objects in an Iterable to an index mapping that object to its index in the Iterable. Objects must be unique * (!equals()) or an exception is thrown. */ public static HashMap buildIndex(Iterable collection) { HashMap map = new HashMap(); for (IndexedItem it : IndexedItem.iterate(collection)) if (map.put(it.getItem(), it.getIndex()) != null) throw new IllegalArgumentException( ""Duplicate object in collection, cannot uniquely map objects to indices (try buildIndexMulti()?): "" + it.getItem()); return map; } /** * Build a map from objects in an array to an index mapping that object to its index in the array. Objects must be unique * (!equals()) or an exception is thrown. */ public static HashMap buildIndex(T[] arr) { HashMap map = new HashMap(); for (IndexedItem it : IndexedItem.iterate(arr)) if (map.put(it.getItem(), it.getIndex()) != null) throw new IllegalArgumentException( ""Duplicate object in collection, cannot uniquely map objects to indices (try buildIndexMulti()?): "" + it.getItem()); return map; } /** Build a map from objects in a collection to a list of indices containing equal objects. */ public static MultiMapKeyToList buildIndexMulti(Iterable collection) { MultiMapKeyToList map = new MultiMapKeyToList(); for (IndexedItem it : IndexedItem.iterate(collection)) { T o = it.getItem(); map.put(o, it.getIndex()); } return map; } // --------------------------------------------------------------------------------------------------------------------- /** * Count the number of .equal() occurrences of objects of type T in the collection, and produce histogram of the results. The * histogram can be sorted in order of ascending count if desired. */ public static ArrayList> countEqualOccurrences(Iterable collection) { CountedSet set = new CountedSet(collection); ArrayList> result = new ArrayList>(); for (Entry ent : set.iteratableWithCounts()) result.add(Pair.make(ent.getKey(), ent.getValue())); return result; } /** * Build a histogram of the number of unique objects that occur each number of times. Objects occur multiple times if there are * multiple instances that match with .equals(). Returns a Pair with number of occurrences of each unique * object as left and number of unique objects with that number of occurrences as right. */ public static ArrayList> buildHistogramOfNumObjectsThatOccurGivenNumberOfTimesSparse( Iterable collection) { // Count unique occurrences of the objects of type T ArrayList> counts = countEqualOccurrences(collection); // Now count unique occurrences each of the count values to build the histogram ArrayList> countCounts = countEqualOccurrences(Pair.getAllRights(counts)); // Sort the result in order of number of occurrences (i.e. left) Pair.sortPairsByLeft(countCounts, true); return countCounts; } /** * Build a histogram of the number of unique objects that occur each number of times. Objects occur multiple times if there are * multiple instances that match with .equals(). Returns an array with the number of occurrences of each unique object as the * index and number of unique objects with that number of occurrences as the value of the array at that index. */ public static int[] buildHistogramOfNumObjectsThatOccurGivenNumberOfTimesNonSparse(Iterable collection) { // Build histogram ArrayList> histList = buildHistogramOfNumObjectsThatOccurGivenNumberOfTimesSparse(collection); // Desparsify into an array and return int maxAbscissa = histList.isEmpty() ? -1 : histList.get(histList.size() - 1).getLeft(); int[] result = new int[maxAbscissa + 1]; for (Pair pair : histList) result[pair.getLeft()] = pair.getRight(); return result; } // --------------------------------------------------------------------------------------------------------------------- /** Reverse a list */ public static ArrayList reverse(List list) { ArrayList result = new ArrayList(list.size()); for (int i = list.size() - 1; i >= 0; --i) result.add(list.get(i)); return result; } /** * Arrayify/rectangularize a list of lists, inserting the given filler element to make the result rectangular if lists are not * the same length */ public static ArrayList> rectangularize(List> input, T filler) { int numRows = input.size(); int numCols = 0; for (int i = 0; i < numRows; i++) numCols = Math.max(numCols, input.get(i).size()); ArrayList> output = new ArrayList>(numRows); for (int i = 0; i < numRows; i++) { ArrayList outRow = new ArrayList(input.get(i)); output.add(outRow); while (outRow.size() < numCols) outRow.add(filler); } return output; } public static MultiMapKeyToSet invertMap(HashMap map) { MultiMapKeyToSet result = new MultiMapKeyToSet(); for (Entry ent : map.entrySet()) result.put(ent.getValue(), ent.getKey()); return result; } } " B21832,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ProbC { private static final String FILEPATH = ""C:\\Users\\abhineet\\desktop\\codeJam""; private static final String INFILE_NAME = ""c.in""; private static final String OUTFILE_NAME = ""c.out""; private static int a =0; private static int b =0; private static int count = 0; private static Set daddySet = new HashSet(); public ProbC() { super(); } public static void main(String[] args) { List inList = readFile(FILEPATH +File.separator +INFILE_NAME); List outList = new ArrayList(); int numTestCases = Integer.parseInt(inList.get(0)); System.out.println(""Number of Test Case : "" +numTestCases); for(int i =0 ; i< numTestCases; i++){ processDataForAB(inList.get(i+1)); for(int j = a; j <=b ; j++){ if (!daddySet.contains(j)){ Set retSet = getCyclicCombinations(new Integer(j).toString()); if (retSet.size() > 1){ count += getCombinations(retSet.size()); } } } outList.add(""Case #"" +i +"": "" +count); count = 0; } writeToFile(FILEPATH+File.separator+OUTFILE_NAME, outList); } private static int getCombinations(int n){ return n* (n-1) /2; } private static Set getCyclicCombinations(String strNum){ int len = strNum.length(); Set retSet = new HashSet(); StringBuilder strBuilder = new StringBuilder(strNum); retSet.add(Integer.parseInt(strNum)); for (int i =1; i=a ){ retSet.add(cyclicVal); } } if (retSet.size() > 1){ daddySet.addAll(retSet); } return retSet; } private static void processDataForAB(String inputLine){ String[] arrStr = inputLine.split("" ""); a = Integer.parseInt(arrStr[0]); b = Integer.parseInt(arrStr[1]); System.out.println(""PROCESSING FOR : "" +a +"" and "" +b); } private static List readFile(String filePath) { List retList = new ArrayList(); try { // Open the file that is the firstS // command line parameter FileInputStream fstream = new FileInputStream(filePath); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = null; //Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console retList.add(strLine); } //Close the input stream in.close(); return retList; } catch (Exception e) { //Catch exception if any System.err.println(""Error: "" + e.getMessage()); } return null; } private static void writeToFile(String filePath, List inputLines) { BufferedWriter bufferedWriter = null; try { //Construct the BufferedWriter object bufferedWriter = new BufferedWriter(new FileWriter(filePath)); //Start writing to the output stream for (String str : inputLines) { bufferedWriter.write(str); bufferedWriter.newLine(); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { //Close the BufferedWriter try { if (bufferedWriter != null) { bufferedWriter.flush(); bufferedWriter.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } } " B21569,"/************************************************************************* * Compilation: javac StdOut.java * Execution: java StdOut * * Writes data of various types to standard output. * *************************************************************************/ import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Locale; /** * Standard output. This class provides methods for writing strings * and numbers to standard output. *

* The Locale used is: language = English, country = US. This is consistent * with the formatting conventions with Java floating-point literals, * command-line arguments (via Double.parseDouble()) * and standard output (via System.out.print()). It ensures that * standard input works the number formatting used in the textbook. *

* For additional documentation, see Section 3.1 of * Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. */ public final class In { private Scanner scanner; // assume Unicode UTF-8 encoding //private String charsetName = ""UTF-8""; private String charsetName = ""ISO-8859-1""; // assume language = English, country = US for consistency with System.out. private Locale usLocale = new Locale(""en"", ""US""); /** * Create an input stream for standard input. */ public In() { scanner = new Scanner(new BufferedInputStream(System.in), charsetName); scanner.useLocale(usLocale); } /** * Create an input stream from a socket. */ public In(Socket socket) { try { InputStream is = socket.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + socket); } } /** * Create an input stream from a URL. */ public In(URL url) { try { URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + url); } } /** * Create an input stream from a file. */ public In(File file) { try { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + file); } } /** * Create an input stream from a filename or web page name. */ public In(String s) { try { // first try to read file from local file system File file = new File(s); if (file.exists()) { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); return; } // next try for files included in jar URL url = getClass().getResource(s); // or URL from web if (url == null) { url = new URL(s); } URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + s); } } /** * Does the input stream exist? */ public boolean exists() { return scanner != null; } /** * Is the input stream empty? */ public boolean isEmpty() { return !scanner.hasNext(); } /** * Does the input stream have a next line? */ public boolean hasNextLine() { return scanner.hasNextLine(); } /** * Read and return the next line. */ public String readLine() { String line = null; try { line = scanner.nextLine(); } catch (Exception e) { } return line; } /** * Read and return the next character. */ public char readChar() { // (?s) for DOTALL mode so . matches any character, including a line termination character // 1 says look only one character ahead // consider precompiling the pattern String s = scanner.findWithinHorizon(""(?s)."", 1); return s.charAt(0); } // return rest of input as string /** * Read and return the remainder of the input as a string. */ public String readAll() { if (!scanner.hasNextLine()) { return null; } // reference: http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html return scanner.useDelimiter(""\\A"").next(); } /** * Return the next string from the input stream. */ public String readString() { return scanner.next(); } /** * Return the next int from the input stream. */ public int readInt() { return scanner.nextInt(); } /** * Return the next double from the input stream. */ public double readDouble() { return scanner.nextDouble(); } /** * Return the next float from the input stream. */ public double readFloat() { return scanner.nextFloat(); } /** * Return the next long from the input stream. */ public long readLong() { return scanner.nextLong(); } /** * Return the next byte from the input stream. */ public byte readByte() { return scanner.nextByte(); } /** * Return the next boolean from the input stream, allowing ""true"" or ""1"" * for true and ""false"" or ""0"" for false. */ public boolean readBoolean() { String s = readString(); if (s.equalsIgnoreCase(""true"")) return true; if (s.equalsIgnoreCase(""false"")) return false; if (s.equals(""1"")) return true; if (s.equals(""0"")) return false; throw new java.util.InputMismatchException(); } /** * Close the input stream. */ public void close() { scanner.close(); } /** * Test client. */ public static void main(String[] args) { In in; String urlName = ""http://www.cs.princeton.edu/IntroCS/stdlib/InTest.txt""; // read from a URL System.out.println(""readAll() from URL "" + urlName); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(urlName); System.out.println(in.readAll()); } catch (Exception e) { } System.out.println(); // read one line at a time from URL System.out.println(""readLine() from URL "" + urlName); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(urlName); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { } System.out.println(); // read one string at a time from URL System.out.println(""readString() from URL "" + urlName); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(urlName); while (!in.isEmpty()) { String s = in.readString(); System.out.println(s); } } catch (Exception e) { } System.out.println(); // read one line at a time from file in current directory System.out.println(""readLine() from current directory""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""./InTest.txt""); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { } System.out.println(); // read one line at a time from file using relative path System.out.println(""readLine() from relative path""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""../stdlib/InTest.txt""); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { } System.out.println(); // read one char at a time System.out.println(""readChar() from file""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""InTest.txt""); while (!in.isEmpty()) { char c = in.readChar(); System.out.print(c); } } catch (Exception e) { } System.out.println(); System.out.println(); // read one line at a time from absolute OS X / Linux path System.out.println(""readLine() from absolute OS X / Linux path""); System.out.println(""---------------------------------------------------------------------------""); in = new In(""/n/fs/csweb/introcs/stdlib/InTest.txt""); try { while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { } System.out.println(); // read one line at a time from absolute Windows path System.out.println(""readLine() from absolute Windows path""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""G:\\www\\introcs\\stdlib\\InTest.txt""); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } System.out.println(); } catch (Exception e) { } System.out.println(); } } " B20342,"import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.SortedSet; import java.util.TreeSet; public class Executer { protected static final String FICHERO_ENTRADA_SHORT = ""C-small-attempt0.in""; protected static final String FICHERO_SALIDA_SHORT = ""C-small-attempt0.out""; protected static final String FICHERO_ENTRADA_LARGE = ""C-large.in""; protected static final String FICHERO_SALIDA_LARGE = ""C-large.out""; /** * @param args */ public static void main(String[] args){ TemplateClass test; try{ //SHORT VERSION // test = new Recycled(FICHERO_ENTRADA_SHORT, FICHERO_SALIDA_SHORT); //LARGE VERSION test = new Recycled(FICHERO_ENTRADA_LARGE, FICHERO_SALIDA_LARGE); test.procesaTestCase(); }catch (Exception e){ System.out.println(""ERROR""); } } } " B21292,"package qualification_2012; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class PC { static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) { int n = sc.nextInt(); for (int i = 1; i <= n; i++) { int a = sc.nextInt(); int b = sc.nextInt(); pw.println(""Case #"" + i + "": "" + calculate(a, b)); } pw.flush(); } static long calculate(int a, int b) { long result = 0; for (int j = a; j < b; j++) { result += count(j, b); } return result; } static int count(int n, int max) { String str = n + """"; int m = str.length(); int result = 0; ArrayList store = new ArrayList(); for (int i = 1; i < m; i++) { int b1 = (int) Math.pow(10, i); int b2 = (int) Math.pow(10, m - i); int x = (n % b1) * b2 + n / b1; if (x > n && x <= max && !store.contains(x)) { store.add(x); result++; } } // if (result > 0) // pw.println(n + "" "" + result); return result; } } " B20230,"package gcj; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.StringTokenizer; public class RecycledNumbers { private static int a; private static int b; private static int total=0; private static boolean[] values; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BufferedReader fin = null; int t = 0; StringTokenizer str = null; try { fin = new BufferedReader(new FileReader(new File(""C-large.in""))); } catch (FileNotFoundException e) { e.printStackTrace(); } try { t = Integer.parseInt(fin.readLine()); //System.out.println(t); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } for(int i=0;ib){ start=b; end = a; } else{ start=a; end=b; } for(int i=start;i<=end;i++){ location = i-start; if(values[i-start]==true) continue; values[location]=true; current = Integer.toString(i); s=current; do{ val=s; s=val.charAt(val.length()-1)+val.substring(0,val.length()-1); location=Integer.parseInt(s)-start; if(Integer.parseInt(s)<=end&&Integer.parseInt(s)>=start&¤t.compareTo(s)!=0&&values[location]!=true){ total++; } }while(current.compareTo(s)!=0); } System.out.println(total); } } " B21759,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class C { private class OutputDelegate { BufferedWriter out; private OutputDelegate(String fileName) { try { out = new BufferedWriter(new FileWriter(fileName)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void write(String output) { try { out.write(output); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void writeLine(String output) { try { write(output); out.newLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void close() { try { if (out != null) { out.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private class InputDelegate { BufferedReader in; private InputDelegate(String fileName){ try { in = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private int[] readIntLine() { String line; String income[] = null; try { if ((line = in.readLine()) != null) { income = line.split("" ""); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } int array[] = new int[income.length]; for (int i = 0; i < array.length; i++) { array[i] = (Integer.parseInt(income[i])); } return array; } private void close() { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void process(String[] args) { InputDelegate in = new InputDelegate(args[0]); OutputDelegate out = new OutputDelegate(args[1]); int cases = in.readIntLine()[0]; for (int i = 1; i <= cases; i++) { int count = 0; int[] line = in.readIntLine(); for(int num = line[0]; num <= line[1]; num++) { int[] possibs = getPossib(num); for (int j = 1; j < possibs.length; j++) { if(possibs[j] == -1) continue; if(possibs[j] > num && possibs[j] <= line[1]) { count++; } } } out.writeLine(""Case #"" + i + "": "" + count); } in.close(); out.close(); } public int[] getPossib(int num) { /*returns possibilities*/ int digit = Integer.toString(num).length(); int[] possib = new int[digit]; possib[0] = num; for (int i = 1; i < possib.length; i++) { int next = possib[i-1]; int lastd = next%10; next = next/10+lastd*exponent(possib.length-1); if(!hasSame(next, possib)) possib[i] = next; else possib[i] = -1; } return possib; } public boolean hasSame(int number, int[] possib) { for (int i = 0; i < possib.length; i++) { if(number == possib[i]) return true; } return false; } private int exponent(int exp) { int a = 1; for (int i = 0; i < exp; i++) { a = a*10; } return a; } public static void main(String[] args) { C m = new C(); m.process(args); } } " B21564,"import java.io.*; public class RecycledNumbers { public RecycledNumbers() {} public Integer count(String num, int A, int B) { int count = 0; Integer numS = new Integer(num); for (int i = 1; i < num.length(); i++) { Integer newNum = new Integer(num.substring(i) + num.substring(0, i)); if (newNum <= B && newNum > A && newNum > numS) { count++; //System.out.println(""("" + numS + "", "" + newNum + "")""); } } return count; } public static void main(String[] args) { RecycledNumbers rn = new RecycledNumbers(); try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; Integer T; int cn = 0; while ((line = in.readLine()) != null) { if (cn == 0) { T = new Integer(line); cn++; } else { int count = 0; String[] AB = line.split("" ""); int A = new Integer(AB[0]); int B = new Integer(AB[1]); for (int n = A; n < B; n++) { count += rn.count(Integer.toString(n), A, B); } System.out.println(""Case #"" + cn + "": "" + count); cn++; } } } catch (Exception e) {} } } " B20737,"package fixjava; public class IntegerMutable { int value; public IntegerMutable(int value) { this.value = value; } public IntegerMutable() { this(0); } public int getValue() { return value; } public void setValue(int value) { this.value = value; } /** Inc and return new value (threadsafe) */ public synchronized int increment() { return ++value; } /** Dec and return new value (threadsafe) */ public synchronized int decrement() { return --value; } /** Subtract amount and return new value (threadsafe) */ public synchronized int subtract(int amount) { return value -= amount; } /** Add amount and return new value (threadsafe) */ public synchronized int add(int amount) { return value += amount; } } " B22118,"import java.util.*; import java.io.*; public class Recycle { public static boolean sameNumbers(int n, int m, int length, int i) { char[] nArray = (n + """").toCharArray(); char[] mArray = (m + """").toCharArray(); for (int j = 0; j < length; j++) { //System.out.println(j + "" "" + i + "" "" + m + "" "" + mArray.length); if (Arrays.binarySearch(nArray, mArray[i]) == -1) return false; } return true; } public static boolean check(int n, int m, int a, int b, int i) { if (n > m) return false; else if (n == m) return false; else if (n < a) return false; else if (m > b) return false; // else if (!sameNumbers(n,m,(n + """").length(), i)) return false; // System.out.println(n + "" "" + m); return true; } public static void main (String []args) throws IOException { final String INPUT_FILE = ""C-large.in""; final String OUTPUT_FILE = ""out3.out""; BufferedReader input = new BufferedReader(new FileReader(INPUT_FILE)); PrintWriter out = new PrintWriter(new FileWriter(OUTPUT_FILE)); int repeats = Integer.parseInt(input.readLine()); for (int j = 0; j < repeats; j++) { StringTokenizer g = new StringTokenizer(input.readLine()); int count = 0; int a = Integer.parseInt(g.nextToken()); int b = Integer.parseInt(g.nextToken()); int aLength = (a + """").length(); if (aLength == 1) out.println(""Case #"" + (j + 1) + "": 0""); else { int arrayCounter = 0; for (int k = a; k < b; k++) { for (int i = 1; i < aLength;i++) { String kString = k + """"; //System.out.println(a + "" "" + aLength + "" "" + i); String mString1 = kString.substring(i,aLength); String mString2 = kString.substring(0,i); //System.out.println(kString + "" "" + mString1 + "" "" + mString2); int m = Integer.parseInt(mString1 + mString2); if (check(k,m,a,b,i)) { count++; } } } out.println(""Case #"" + (j + 1) + "": "" + count); } } out.close(); input.close(); } }" B22064,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Madu */ import java.io.*; public class Ex3 { int m_000000(){ return 0; } public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(""C:/Users/Madu/Documents/NetBeansProjects/CodeJamR1Ex1/input/A-small-attempt0.in""); FileOutputStream fout = new FileOutputStream(""C:/Users/Madu/Documents/NetBeansProjects/CodeJamR1Ex1/output/out.txt""); PrintStream printStream = new PrintStream(fout); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String inputIlne; br.readLine(); //printStream.println (""Output""); //Read File Line By Line int lineNum = 1; while ((inputIlne = br.readLine()) != null) { // Print the content on the console //########## String[] AandB = inputIlne.split("" ""); int A = Integer.parseInt(AandB[0]); int B = Integer.parseInt(AandB[1]); int ans = 0; int num = A; System.out.println(B); while (num <= B) { if (num < 10) { num++; } else if (num < 100) { int xo = num/10; int recycle1 = (num % 10) * 10 + xo; if (A <= num && num < recycle1 && recycle1 <= B) { ans++; } num++; } else if (num < 1000) { int xoo = num / 100; int recycle1 = (num % 100) * 10 + xoo; if (A <= num && num < recycle1 && recycle1 <= B) { ans++; } int xxo = num / 10; int recycle2 = (num % 10) * 100 + xxo; if (A <= num && num < recycle2 && recycle2 <= B) { ans++; } num++; } else if(num < 10000){ int m = 0;//using for avoid 1212 int xooo = num / 1000; int recycle3 = (num % 1000) * 10 + xooo; if (A <= num & num < recycle3 & recycle3 <= B) { m = recycle3; ans++; } int xxoo = num / 100; int recycle1 = (num % 100) * 100 + xxoo; if (A <= num & num < recycle1 & recycle1 <= B&recycle1!=m) { m = recycle1; ans++; } int xxxo = num / 10; int recycle2 = (num % 10) * 1000 + xxxo; if (A <= num & num < recycle2 & recycle2 <= B & recycle2!=m) { m =recycle2; ans++; } num++; } else if(num < 100000){ int m = 0; int xoooo = num / 10000; int recycle3 = (num % 1000) * 10 + xoooo; if (A <= num & num < recycle3 & recycle3 <= B) { m = recycle3; ans++; } int xxooo = num / 1000; int recycle1 = (num % 1000) * 100 + xxooo; if (A <= num & num < recycle1 & recycle1 <= B&recycle1!=m) { m = recycle1; ans++; } int xxxoo = num / 100; int recycle2 = (num % 100) * 1000 + xxxoo; if (A <= num & num < recycle2 & recycle2 <= B&recycle2!=m) { m = recycle2; ans++; } int xxxxo = num / 10; int recycle4 = (num % 10) * 10000 + xxxxo; if (A <= num & num < recycle4 & recycle4 <= B&recycle4!=m) { m = recycle4; ans++; } num++; }else if(num < 1000000){ int m = 0; int xoooo1 = num / 100000; int recycle33 = (num % 10000) * 10 + xoooo1; if (A <= num & num < recycle33 & recycle33 <= B) { m = recycle33; ans++; } int xoooo = num / 10000; int recycle3 = (num % 1000) * 100 + xoooo; if (A <= num & num < recycle3 & recycle3 <= B&recycle3!=m) { m = recycle3; ans++; } int xxooo = num / 1000; int recycle1 = (num % 1000) * 1000 + xxooo; if (A <= num & num < recycle1 & recycle1 <= B&recycle1!=m) { m = recycle1; ans++; } int xxxoo = num / 100; int recycle2 = (num % 100) * 10000 + xxxoo; if (A <= num & num < recycle2 & recycle2 <= B&recycle2!=m) { m = recycle2; ans++; } int xxxxo = num / 10; int recycle4 = (num % 10) * 100000 + xxxxo; if (A <= num & num < recycle4 & recycle4 <= B&recycle4!=m) { m = recycle4; ans++; } num++; }else if(num < 10000000){ int m = 0; int xoooo11 = num / 1000000; int recycle333 = (num % 100000) * 10 + xoooo11; if (A <= num & num < recycle333 & recycle333 <= B) { m = recycle333; ans++; } int xoooo1 = num / 100000; int recycle33 = (num % 10000) * 100 + xoooo1; if (A <= num & num < recycle33 & recycle33 <= B&recycle33!=m) { m = recycle33; ans++; } int xoooo = num / 10000; int recycle3 = (num % 1000) * 1000 + xoooo; if (A <= num & num < recycle3 & recycle3 <= B&recycle3!=m) { m = recycle3; ans++; } int xxooo = num / 1000; int recycle1 = (num % 1000) * 10000 + xxooo; if (A <= num & num < recycle1 & recycle1 <= B&recycle1!=m) { m = recycle1; ans++; } int xxxoo = num / 100; int recycle2 = (num % 100) * 100000 + xxxoo; if (A <= num & num < recycle2 & recycle2 <= B&recycle2!=m) { m = recycle2; ans++; } int xxxxo = num / 10; int recycle4 = (num % 10) * 1000000 + xxxxo; if (A <= num & num < recycle4 & recycle4 <= B&recycle4!=m) { m = recycle4; ans++; } num++; } } //System.out.println(ans); printStream.print(""Case #"" + lineNum + "": "" + ans); lineNum++; printStream.println(""""); } } catch (Exception e) { System.out.println(e.toString()); } // else if(test.length()==4){ // // ans=0; // A = Integer.parseInt(test); // // int num =A; // while(num<=B){ // // if(num==1212){num++;continue;} // // int xooo = num/1000; // int recycle3 = (num%1000)*10+xooo; // if(A<=num&&num used; for ( int i = 1; i <= cases; i++ ) { pairs = 0; tmp = in.readLine().split( "" "" ); low = Integer.parseInt( tmp[0] ); high = Integer.parseInt( tmp[1] ); multiplier = 1; for ( int j = 1; j < tmp[0].length(); j++ ) { multiplier *= 10; } for ( int j = low; j < high; j++ ) { shift = j; used = new HashSet(); for ( int k = 0; k < tmp[0].length(); k++ ) { rest = shift % 10; shift /= 10; shift += rest * multiplier; if ( j < shift && shift <= high ) { if ( !used.contains( shift ) ) { pairs++; used.add( shift ); } } } } out.write( ""Case #"" + i + "": "" + pairs ); out.newLine(); out.flush(); } in.close(); out.close(); } } " B20616,"package qualification; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { /** * @param args */ static int number (int num){ int i=0; while (num!=0){ num/=10; i++; } return i-1; } public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter((new FileWriter(""C-large.out""))); StringTokenizer st ; int tekrar = Integer.parseInt(f.readLine()); for (int j=0;j=min && num<=max ){ count ++; } num = (int) ((num%10)*Math.pow(10, number(num)))+num/10; } } out.println(""Case #""+(j+1)+"": ""+count/2); } out.close(); System.exit(0); } } " B21111,"import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.Character.Subset; import java.util.ArrayList; import java.util.HashMap; public class recyling_numbers { static ArrayList superset = new ArrayList(); public static int[] range(int start, int end, int increment) { int[] values = new int[Math.abs((end - start) / increment) + 1]; boolean reverse = start > end; for (int i = start, index = 0; reverse ? (i >= end) : (i <= end); i += increment, ++index) { values[index] = i; } return values; } private Exception IllegalArgumentException() { return null; } static int SolveC1(String a, String b) { HashMap m = new HashMap(); String current_n; String current_m; if (a.length() == 1 && b.length() == 1) { return 0; } String[] result = new String[10000]; int[] ranges = range(Integer.parseInt(a), Integer.parseInt(b), 1); int count = 0; for (int i = 0; i < ranges.length; i++) { current_n = ranges[i] + """"; current_m = ranges[i] + """"; int length = ( new Integer(ranges[i]).toString()).length(); for (int j = 0; j < length; j++) { current_m = current_m.substring(length-1,length) + current_m.substring(0, length-1 ); if (Integer.parseInt(current_m) <= Integer.parseInt(b) && Integer.parseInt(current_m) > Integer .parseInt(current_n) && Integer.parseInt(current_m) >= Integer.parseInt(a)) { m.put(current_n + current_m, 1); } } } return m.size(); } public static int get_solution(int A, int B) { superset = new ArrayList(); int count = 0; String seeds[] = new String[B - A + 1]; for (int i = A, n = 0; n < seeds.length; i++, n++) { seeds[n] = Integer.toString(i); } for (int i = 0; i < seeds.length; i++) { count += binomial(CircularStringShift(seeds[i], A, B), 2); } return count; } public static int CircularStringShift(String s, int lowerLimit, int upperLimit) { String tmp = s; char ph = ' '; int count = 0; int tmp2; for (int i = 0; i < s.length(); i++) { ph = tmp.charAt(0); tmp = tmp.substring(1, tmp.length()) + ph; tmp2 = Integer.parseInt(tmp); if (!superset.contains(tmp2) && tmp2 >= lowerLimit && tmp2 <= upperLimit && tmp != s) { count++; superset.add(tmp2); } } return count; } static long binomial(int n, int k) { return ((n - 1) * (n) / 2); } public static void main(String[] args) throws NumberFormatException, IOException { FileInputStream inFile = new FileInputStream( new File( ""C:\\Users\\ruzbeh\\Downloads\\C-large (2).in"")); DataInputStream br = new DataInputStream(inFile); FileOutputStream outFile = new FileOutputStream(new File(""out1.in"")); DataOutputStream out = new DataOutputStream(outFile); int T = Integer.parseInt(br.readLine()); for (int i = 0; i < T; i++) { String[] str = br.readLine().split("" ""); int a = Integer.parseInt(str[0]); int b = Integer.parseInt(str[1]); String res=""Case #"" + (i + 1) + "": "" + SolveC1(str[0], str[1]); System.out.println(res); out.writeBytes(res); out.writeBytes(""\n""); } } }" B21916,"import java.io.*; import java.util.*; public class Tres { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""tres.txt"")); int T = Integer.parseInt(in.readLine()); for(int t = 0; t < T; t++) { String[] temp = in.readLine().split("" ""); int A = Integer.parseInt(temp[0]); int B = Integer.parseInt(temp[1]); HashMap matches = new HashMap(); for(int i = A; i <= B; i++) { String s = new Integer(i).toString(); int j; for(j = 0; j < s.length(); j++) { String stemp = s.substring(j) + s.substring(0,j); if(matches.containsKey(stemp)) { matches.put(stemp, matches.get(stemp)+1); //System.out.println(s + "" matched with "" + stemp); break; } } if(j == s.length()) matches.put(s, 1); } int answer = 0; for(String s : matches.keySet()) { int itemp = matches.get(s); answer += itemp*(itemp-1)/2; } System.out.println(""Case #"" + (t+1) + "": "" + answer); } in.close(); } }" B21305,"import java.util.*; public class RecycledNumbers{ static HashSet hs; public static int single(int n, int[] digits){ int i = 0; while(n>0){ digits[i] = n%10; n = n/10; i++; } return i; } public static int toNumber(int[] d){ int n = 0; for(int i = d.length-1; i>=0; i--){ n = (n*10)+d[i]; } return n; } public static int pairs(int nd, int[] d, int ja, int m){ int total = 0; int last = nd -1; for(int ni = 0; nija) && nn <= m){ total++; hs.add(ja+"",""+nn); } } return total; } public static int solve(int a, int b){ String sa = a+""""; String sb = b+""""; hs = new HashSet(); int la = sa.length(); int lb = sb.length(); if(la == 1) return 0; int[] digitsa = new int[7]; int[] digitsb = new int[7]; int ndigits = single(a, digitsa); single(b, digitsb); int count = 0; for(int ja =a; ja < b; ja++){ int[] digitsja = new int[7]; // System.out.println(""Checking ""+ja); single(ja, digitsja); int npa = pairs(ndigits, digitsja, ja, b ); count+=npa; if(npa > 0){ // System.out.println(""j ""+ja+"" npa ""+npa); } } //System.out.println(count); return hs.size(); } public static void main(String args[]){ Scanner s = new Scanner(System.in); int T = s.nextInt(); for(int i = 0; i set; public Ref() { cnt = 0; set = new HashSet(); } } private static void permuteMove(char[] arr, int len, String strN, String strB, Ref ref) { int arrLen = arr.length; char[] result = new char[arrLen]; int index = 0; for (int i = arrLen - len; i < arrLen; ++i) { result[index++] = arr[i]; } for (int i = 0; i < arrLen - len; ++i) { result[index++] = arr[i]; } String strCur = new String(result); if (strCur.compareTo(strN) > 0 && strCur.compareTo(strB) <= 0 && !ref.set.contains(strCur)) { ref.set.add(strCur); ++ref.cnt; } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(""C:/Users/Jeric Bryle Sy Dy/Downloads/C-large.in"")); PrintWriter out = new PrintWriter(""C:/Users/Jeric Bryle Sy Dy/Downloads/C-large.out""); int t = Integer.parseInt(br.readLine()); for (int tIter = 0; tIter < t; ++tIter) { Scanner s = new Scanner(br.readLine()); int a = s.nextInt(); int b = s.nextInt(); Ref ref = new Ref(); for (int n = a; n < b; ++n) { ref.set.clear(); String strN = String.valueOf(n); // permute(strN.toCharArray(), 0, strN, String.valueOf(b), 1, ref); for (int len = 1; len < strN.length(); len++) { permuteMove(strN.toCharArray(), len, strN, String.valueOf(b), ref); } } s.close(); out.printf(""Case #%d: %d\n"", tIter + 1, ref.cnt); } br.close(); out.close(); } } " B21953,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; public class QualifiRound2012C { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { BufferedReader br = new BufferedReader(new FileReader(args[0])); PrintWriter pw = new PrintWriter(args[1]); String line = br.readLine(); System.out.println(line); int T = Integer.valueOf(line.trim()); for (int i=0; i map = new HashMap(); map.put(j, true); int pair = (j%10)*(int)Math.pow(10, bit)+ j/10; while(!map.containsKey(pair)) { if(j>pair) { map.put(pair, true); pair = (pair%10)*(int)Math.pow(10, bit)+ pair/10; continue; } if(A<=pair && pair<=B) result++; pair = (pair%10)*(int)Math.pow(10, bit)+ pair/10; continue; } } pw.println(""Case #""+(i+1)+"": ""+result); System.out.println(""Case #""+(i+1)+"": ""+result); } pw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B20603,"package twentytwelve.qualification.c; import java.util.Scanner; public final class RecycledNumbers { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int cases = sc.nextInt(); for (int no = 1; no <= cases; no++) { System.out.print(""Case #"" + no + "": ""); int A = sc.nextInt(); int B = sc.nextInt(); int pairs = 0; int Adigits = 1; int setSize = 0; while (A >= 10 * Adigits) { Adigits *= 10; setSize++; } int[] currentSet = new int[setSize]; for (int current = A; current <= B; current++) { int bdigits = 10; int udigits = Adigits; for (int i = 0; udigits > 1; bdigits *= 10, udigits /= 10) { int recycled = current / bdigits + (current % bdigits) * udigits; if (recycled > current && recycled <= B) { boolean found = false; for (int j = 0; j < i; j++) { if (currentSet[j] == recycled) { found = true; } } if (!found) { // System.out.println(current + "" -> "" + recycled); currentSet[i++] = recycled; pairs++; } } } } System.out.println(pairs); } } } " B21461,"package com.renoux.gael.codejam.utils; /** * Pour tests unitaires * * @author renouxg */ public final class StringUtils { public static String multiply(String text, int nb) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < nb; i++) { builder.append(text); } return builder.toString(); } } " B21969,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Google code jam. * Qualification Round 2012. * Problem C. Recycled Numbers * * Usage: <app> <input >output * * @author sombrabr@gmail.com * */ public class QualC { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int cases = new Integer(in.readLine()); for(int i=0; i numbers = new HashSet(); for(int i=1; i=1;k--) { String tmp1=tmp.substring(k)+tmp.substring(0,k); if(tmp1.charAt(0)=='0') continue; int t1=Integer.parseInt(tmp1); if(t1>j && t1>=a && t1<=b) { int flag=0; for(int kk=0;kk{ int a , b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Pair other = (Pair) obj; if (this.a != other.a) { return false; } if (this.b != other.b) { return false; } return true; } @Override public int hashCode() { int hash = a*3; return hash; } public int compareTo(Pair o) { if ( o.a != this.a ){ return this.a - o.a; }else{ return this.b - o.b; } } } /** * * @author Saul Hidalgo */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { try { Scanner sc = new Scanner(new File(""test2.txt"")); PrintStream ps = new PrintStream(new File(""output2.txt"")); int T = sc.nextInt(); for ( int t = 1 ; t <= T ; t++ ){ int n = sc.nextInt() , m = sc.nextInt(); int ans = 0; TreeSet tree = new TreeSet(); for ( int i = n ; i <= m ; i++ ){ String num = i + """"; for ( int j = 1 ; j < num.length() ; j++ ){ String conv = num.substring(j) + num.substring(0, j); int tt = Integer.parseInt(conv); Pair p = new Pair(i, tt); if ( tt > i && tt <= m && !tree.contains(p)){ ++ans; tree.add(p); } } } System.out.println(""Caso = "" + t); ps.println(""Case #"" + t + "": "" + ans); } } catch (FileNotFoundException ex) { // =( } } } " B20489,"import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.HashSet; import java.util.Set; public class Recycled { public static void main(String [] args) throws NumberFormatException, IOException { long start = System.currentTimeMillis(); BufferedReader in = new BufferedReader(new StringReader(args[0])); int rows = Integer.parseInt(in.readLine()); for ( int i = 1; i <= rows; i++) { String line = in.readLine(); String [] tokens = line.split("" ""); int low = Integer.parseInt(tokens[0]); int high = Integer.parseInt(tokens[1]); int count = 0; Set used = new HashSet(); for ( int j = low; j <= high; j++ ) { String str = Integer.toString(j); //System.out.println(""Original: "" + str); for ( int k = 0; k < str.length()-1; k++ ) { String newStr = str.substring(k+1) + str.substring(0,k+1); int newInt = Integer.parseInt(newStr); if ( Integer.toString(j).length() == Integer.toString(newInt).length() && j < newInt && newInt<=high && !used.contains(j+"",""+newInt) ) { count++; used.add(j+"",""+newInt); } } } System.out.println(""Case #""+i+"": "" + count); } //System.out.println(System.currentTimeMillis()-start); } } " B22160,"package com.vp.common; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.PrintStream; import java.util.Scanner; public class InputOutputProcessor { private int numberOfCases; private boolean doesInputHaveDataSetLines; private int indexOfDataSetLine; private int numberOfDataSetLines; private final static String DELIMITER = "" ""; private Scanner scanInput; public void initializeInput(String strInputFileName) { readInput(strInputFileName); numberOfCases = Integer.parseInt(scanInput.nextLine()); } /* * read input */ private void readInput(String strInputFileName) { try { scanInput = new Scanner(new BufferedReader(new FileReader( strInputFileName))); } catch (Exception exp) { // exp.printStackTrace(); System.out.println("" Please provide File Name with proper location ""); } } public String[] getDataSet() throws Exception { String[] dataSet; String strDataSetLine = """"; strDataSetLine = scanInput.nextLine(); // System.out.println(""strDataSetLine: "" + strDataSetLine); if (doesInputHaveDataSetLines) { String[] DataSetLineArray = strDataSetLine.split(DELIMITER); numberOfDataSetLines = Integer .parseInt(DataSetLineArray[indexOfDataSetLine]); } dataSet = new String[numberOfDataSetLines]; dataSet[0] = strDataSetLine; for (int i = 1; i < numberOfDataSetLines; i++) { dataSet[i] = scanInput.nextLine(); } return dataSet; } /** * * @return Returns the numberOfDataSetLines. */ public int getNumberOfDataSetLines() { return numberOfDataSetLines; } /** * @param numberOfDataSetLines * The numberOfDataSetLines to set. */ public void setNumberOfDataSetLines(int numberOfDataSetLines) { this.numberOfDataSetLines = numberOfDataSetLines; } /** * * @return Returns the numberOfCases. */ public int getNumberOfCases() { return numberOfCases; } /** * * @return Returns the doesInputHaveDataSetLines. */ public boolean isDoesInputHaveDataSetLines() { return doesInputHaveDataSetLines; } /** * @param doesInputHaveDataSetLines * The doesInputHaveDataSetLines to set. */ public void setDoesInputHaveDataSetLines(boolean doesInputHaveDataSetLines) { this.doesInputHaveDataSetLines = doesInputHaveDataSetLines; } /** * * @return Returns the indexOfDataSetLine. */ public int getIndexOfDataSetLine() { return indexOfDataSetLine; } /** * @param indexOfDataSetLine * The indexOfDataSetLine to set. */ public void setIndexOfDataSetLine(int indexOfDataSetLine) { this.indexOfDataSetLine = indexOfDataSetLine; } public void closeScanner() { scanInput.close(); } public void writeOutput(String outputFileName, String[] resultArray) { // To be moved out PrintStream out = null; try { out = new PrintStream(new FileOutputStream(outputFileName)); for (int i = 0; i < resultArray.length; i++) { out.print(resultArray[i]); out.print(""\n""); } out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } } " B22092,"import java.io.*; class qu3{ public static void main(String arg[])throws Exception { File f=new File(""/Users/rishabhsonthalia/Downloads/C-large.in.txt""); FileInputStream fin=new FileInputStream(f); File fo=new File(""opt.txt""); FileOutputStream fout=new FileOutputStream(fo); BufferedWriter bwr=new BufferedWriter(new OutputStreamWriter(fout)); BufferedReader br=new BufferedReader(new InputStreamReader(fin)); String g=""""; long len=Long.parseLong(br.readLine()); long ca=1; long a,b; String e=""""; long n,m; while(--len >=0) { long count=0; g=br.readLine(); a=Long.parseLong(g.substring(0,g.indexOf("" "")) ); b=Long.parseLong( g.substring(g.indexOf("" "")+1,g.length())) ; for(long i=a;i<=b;i++) { n=i; for(long j=0 ; j<(i+"""").length()-1; j++) { m=shift(n); if(m>-1 & i0) in = new FileInputStream(args[0]); PrintStream out = System.out; if(args.length>1) out = new PrintStream(args[1]); Solver s = new Solver(new Scanner(in),out); //Multiple case input s.cases(); //Single case input //s.go(); } } class Solver { Scanner in; PrintStream out; public Solver(Scanner scanner, PrintStream printStream) { in = scanner; out = printStream; } public void cases() { int numCases = in.nextInt(); in.nextLine(); for(int i=0;i0) { a/=10; mod*=10; digs++; } HashSet found = new HashSet(); for(int n = A; n <= B; n++) { found.clear(); int nn=n; for(int i = 0; i < digs; i++) { nn=(nn+mod*(nn%10))/10; found.add(nn); } for(int mm : found) if(mm>n&&mm<=B) ans++; } out.println(ans); } }" B20387,"import java.io.*; import java.util.*; public class recycle { public static void main(String[] args) throws Exception { int cases; BufferedReader in=new BufferedReader(new FileReader(""input.in"")); PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(""recycle.out""))); cases=Integer.parseInt(in.readLine()); int numPairs=0; for (int k=0; kj && n>left && n<=right) { numPairs++; } } } out.println(""Case #""+(k+1)+"": ""+numPairs); } out.close(); } } " B21791," import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author UDDAMA */ public class recyclePair { private ArrayList numholder = new ArrayList(); public void numrecylce(String chars) { for (int i = 0; i < chars.length() - 1; i++) { this.numholder.add(chars.substring(i + 1) + chars.substring(0, i + 1)); } } public void cleanArray() { for (int i = 0; i < numholder.size(); i++) { String temp = numholder.get(i); for (int j = i + 1; j < numholder.size(); j++) { if (temp.equalsIgnoreCase(numholder.get(j))) { numholder.remove(j); } } } } public int recycleCount(String A, String B) { int count = 0; for (int i = Integer.parseInt(A); i < Integer.parseInt(B); i++) { this.numholder.clear(); this.numrecylce(String.valueOf(i)); this.cleanArray(); for (int j = 0; j < numholder.size(); j++) { if (Integer.parseInt(numholder.get(j)) > i && Integer.parseInt(numholder.get(j)) <= Integer.parseInt(B)) { count++; } } } return count; } public static void main(String[] args) throws IOException { BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); String inputLine = is.readLine(); recyclePair rp = new recyclePair(); int cases = Integer.parseInt(inputLine); for (int i = 0; i < cases; i++) { inputLine = is.readLine(); String[] AB = inputLine.split("" ""); System.out.println(""Case #"" + (i + 1) + "": "" + rp.recycleCount(AB[0], AB[1])); } } }" B20041,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package google.code.jam.recycled.numbers; import java.util.ArrayList; import java.util.HashMap; /** * * @author Lucas */ public class RecycledNumbers { public ArrayList findRecycledNumbers(ArrayList list) { ArrayList result = new ArrayList(); Integer[] current; int x; int y; int total; int temp; String str; for (int n = 0; n < list.size(); n++) { current = list.get(n); total = 0; x = current[0]; y = current[1]; for (int m = x; m <= y; m++) { str = String.valueOf(m); for (int j = 0; j < str.length() - 1; j++) { str = str.substring(1) + str.charAt(0); temp = Integer.parseInt(str); if ((temp <= y) && (temp > m) && (temp >= x)) { total++; } } } result.add(total); } return result; } } " B21286,"import java.io.*; import java.util.*; public class C { MyScanner in; PrintWriter out; final static String FILENAME = ""c""; public static void main(String[] args) throws Exception { new C().run(); } public void run() throws Exception { in = new MyScanner(FILENAME + "".in""); out = new PrintWriter(FILENAME + "".out""); int tests = in.nextInt(); for (int test = 0; test < tests; test++) { out.println(""Case #"" + (test + 1) + "": "" + solve()); } out.close(); } int ten(int length) { int ans = 1; for (int i = 0; i < length; i++) { ans *= 10; } return ans; } TreeSet ts; int recycle(int n, int max) { int l = String.valueOf(n).length(); int mod = ten(l - 1); int ans = 0; int m = n; String strm = String.valueOf(m); ts.clear(); for (int i = 0; i < l; i++) { m = (m / 10) + (m % 10) * mod; if (m > n && m <= max && !ts.contains(m)) { ans++; } ts.add(m); } return ans; } public int solve() throws Exception { ts = new TreeSet(); int A = in.nextInt(); int B = in.nextInt(); int ans = 0; for (int n = A; n <= B; n++) { ans += recycle(n, B); } return ans; } class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } String next() throws Exception { while ((st == null) || (!st.hasMoreTokens())) { String t = br.readLine(); if (t == null) { return null; } st = new StringTokenizer(t); } return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } boolean nextBoolean() throws Exception { return Boolean.parseBoolean(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } } } " B20869,"import java.io.File; import java.util.*; public class ProblemCLarge { public static void main(String[] args) throws Exception { // Scanner sc = new Scanner(new File(""C:\\C-Large.in"")); Scanner sc = new Scanner(System.in); int cases = Integer.parseInt(sc.nextLine().trim()); for (int i = 0; i < cases; i++) { int a = sc.nextInt(); int b = sc.nextInt(); System.out.println(""Case #"" + (i + 1) + "": "" + solve(a, b)); } } private static int solve(int a, int b) { int count = 0; int num_digs = ("""" + a).length(); int[] power = new int[] { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000 }; for (int i = a; i <= b; i++) { int[] tmp = new int[10]; int cnt = 0; for (int j = 1; j < num_digs; j++) { boolean found = false; if (i % power[j] > 0) { int tmp1 = (i % power[j]) * power[num_digs - j]; int tmp2 = (i - (i % power[j])) / power[j]; int tmp3 = tmp1 + tmp2; if (cnt == 0) { tmp[cnt++] = tmp3; } else { for (int k = 0; k < cnt; k++) { if (tmp3 == tmp[k]) { found = true; } } if(!found){ tmp[cnt++] = tmp3; } } } } for (int tmp4 : tmp) { if (tmp4 >= a && tmp4 <= b && tmp4 != i) { //System.out.println(i + "" "" + tmp4); count++; } } } return count / 2; } } " B21196,"public class Result { public String output; public int i; public Result(int i) { this.i = i; } @Override public String toString() { return ""Case #""+i+"": "" + output; } } " B22117,"package codejam20120413; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class C { int digits(int in) { int count=0; for (;(in=in/10)>0; count++); return count; } int shift(int in, int mag) { return mag*(in%10) + in/10; } void run()throws IOException{ BufferedReader bf = new BufferedReader(new FileReader(""C.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""C.out"")); int cases = Integer.parseInt(bf.readLine()); for (int i=0; i set = new HashSet(); for (int k = 0; k < digits; k++) { int shift = shift(in, mag); if (shift>j && shift <= to) { if (!set.contains(shift)) { set.add(shift); count++; } } in=shift; } } pw.write(""Case #""+ (i+1) + "": ""+ count + ""\n""); } pw.close(); } public static void main(String[] args)throws IOException { new C().run(); } } " B21770,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; class RecycledNumbers{ int getcount(int small,int large){ int count = 0; for(int currnum = small; currnum < large; currnum++){ int permut = currnum; int no_of_digits = 0; while(permut > 0){ permut = permut/10; no_of_digits++; } int lastDigit = currnum % 10; permut = currnum / 10; permut = permut + lastDigit * (int)Math.pow(10, no_of_digits-1); while(permut != currnum){ if(permut >= currnum && permut <= large){ count++; } lastDigit = permut % 10; permut = permut / 10; permut = permut + lastDigit * (int)Math.pow(10, no_of_digits-1); } } return count; } public static void main(String args[]){ RecycledNumbers d = new RecycledNumbers(); int no_of_cases = 0; String input = """"; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ no_of_cases = Integer.parseInt(br.readLine()); } catch(Exception e){ System.out.println(""First line is not a number""); } for(int i=1; i <= no_of_cases;i++){ try{ input = br.readLine(); } catch(Exception e){ System.out.println(""Number of test cases different from the number mentioned in first line""); } System.out.print(""Case #"" +i+"": ""); StringTokenizer t = new StringTokenizer(input); int small=0,large=0; if(t.hasMoreTokens()){ small = Integer.parseInt(t.nextToken()); } if(t.hasMoreTokens()){ large = Integer.parseInt(t.nextToken()); } System.out.println(d.getcount(small,large)); } } }" B20531,"import java.util.Scanner; public class Main { public static void main(String[] args) { int a,b,t; Scanner odczyt = new Scanner(System.in); //obiekt do odebrania danych od użytkownika boolean []tab=new boolean [9999999]; t = odczyt.nextInt(); for (int i=1; i<=t;i++) { a=odczyt.nextInt(); b=odczyt.nextInt(); String liczba; String zmiana; int nowa; int ile=0; int poprzedni=-1; for (int j=a;j<=b;j++) { tab[j]=true; } for (int j=a; j<=b;j++) { liczba=Integer.toString(j); for (int k=1;kj && nowa>=a && nowa <=b && tab[nowa] && nowa!=poprzedni) { ile++; tab[j]=false; poprzedni=nowa; //System.out.print(j+"" ""+nowa+""\n""); } } } System.out.print(""Case #""+i+"": ""+ile+'\n'); } } } " B22057,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class Recycle { public static void main(String[] args) throws IOException { long t0 = System.currentTimeMillis(); BufferedReader in = new BufferedReader(new FileReader(""in.txt"")); PrintWriter out = new PrintWriter(""out.txt""); int t = Integer.parseInt(in.readLine()); for (int i = 1; i <= t; i++) { String[] ss = in.readLine().split("" ""); int from = Integer.parseInt(ss[0]); int to = Integer.parseInt(ss[1]); out.println(""Case #"" + i + "": "" + compute(from, to)); System.out.println(""Case #"" + i + "": "" + compute(from, to)); } out.close(); System.out.println(""time: "" + (System.currentTimeMillis() - t0)); } private static int[] maxNum = { 0, 9, 99, 999, 9999, 99999, 999999, 2000000 }; private static int[] precomputed = { 0, 0, 36, 801, 12060, 161982, 2023578, 299997 }; private static int compute(int from, int to) { int dFrom = from <= 9 ? 1 : from <= 99 ? 2 : from <= 999 ? 3 : from <= 9999 ? 4 : from <= 99999 ? 5 : from <= 999999 ? 6 : 7; int dTo = to <= 9 ? 1 : to <= 99 ? 2 : to <= 999 ? 3 : to <= 9999 ? 4 : to <= 99999 ? 5 : to <= 999999 ? 6 : 7; int count; if (dFrom == dTo) { count = compute(from, to, dFrom); } else { count = 0; count += compute(from, maxNum[dFrom], dFrom); for (int i = dFrom + 1; i < dTo; i++) { // count += compute(maxNum[i - 1] + 1, maxNum[i], i); count += precomputed[i]; } count += compute(maxNum[dTo - 1] + 1, to, dTo); } return count; } private static int compute(int from, int to, int digits) { int count = 0; int f = 1; for (int d = 1; d < digits; d++) { f *= 10; } List recycled = new ArrayList(); for (int n = from; n <= to; n++) { recycled.clear(); int m = n; for (int d = 1; d < digits; d++) { int r = (m % 10); m = (r * f) + (m / 10); if (r > 0 && m < n && m >= from && m <= to) { if (recycled.contains(m)) { // System.out.println(""("" + m + "","" + n + "")""); } else { recycled.add(m); count++; } } } } return count; } } " B20440,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package a2012; import java.util.*; import java.io.*; /** * * @author G */ public class C { static int[] pot10=new int[]{1,10,100,1000,10000,100000,1000000,10000000}; static File home=new File(""F:/Documents/Downloads/""); public static void main(String...arg)throws Exception{ Scanner sc = new Scanner(new File(home,""C-large.in"")); System.setOut(new PrintStream(new File(""c.out""))); final int casos=sc.nextInt(); for(int caso=1;caso<=casos;caso++){ int A=sc.nextInt(),B=sc.nextInt(); final int digits=(""""+A).length(); int tot=0; HashSet encontrados=new HashSet(1000); for(int n=A;n<=B;n++){ //System.out.println(e); for(int i=1;i=A&&j<=B&&j!=n&&!encontrados.contains(t)){ tot++; encontrados.add(t); } //System.out.println(j); } } System.out.println(""Case #""+caso+"": ""+tot); } System.out.close(); } } " B21605,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; public class RecycledPairs { public static void main(String []args) throws NumberFormatException, IOException{ BufferedReader in = new BufferedReader(new FileReader(""input.in"")); String hm="""", line[]; int n =Integer.valueOf(in.readLine()), m=1, a, b, c; for(m=1;m<=n;m++){ System.out.print(m+"" ""); line=in.readLine().split("" ""); a=Integer.valueOf(line[0]); b=Integer.valueOf(line[1]); c=0; for(int i=a;i0;i--){ aux=String.valueOf(n.charAt(leng-1)); aux+=n.substring(0, leng-1); n=aux; //System.out.println(aux+"" ""+m); if(n.equals(m)) return true; } return false; } } " B22202," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; public class RecycledNumber { private void solve(BufferedReader f, PrintWriter out) throws IOException { int T = read(f); HashSet set = new HashSet(); for (int i=0; i n && m <= B) { count++; } } set.clear(); } out.println(""Case #"" + (i+1) + "": "" + count); } } public int read(BufferedReader f) throws IOException { return Integer.parseInt(f.readLine()); } public int[] read(BufferedReader f, int N) throws IOException { String[] t = f.readLine().split("" ""); int[] a = new int[N]; for (int i=0; i alreadyFound; int count = 0; if (b > 9) { for (int n = a; n <= b; n++) { String nstr = String.valueOf(n); int nlen = nstr.length(); alreadyFound = new HashSet(); for (int index = 1; index < nlen; index++) { String mstr = nstr.substring(index, nlen) + nstr.substring(0, index); int m = Integer.parseInt(mstr); mstr = String.valueOf(m); if (mstr.length() == nlen && alreadyFound.add(mstr)) { if (m > n && m >=a && m <= b) { count++; } } } } } return count; } } " B20343,"import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; public class Recycled extends TemplateClass { public Recycled() { } public Recycled(String nombreficheroEntrada, String nombreFicheroSalida) throws Exception { super(nombreficheroEntrada, nombreFicheroSalida); } protected void procesaTestCase() throws Exception { // Variables int testCase = 0; ArrayList lista = new ArrayList(); long a; long b; long casos; for (testCase = 0; testCase < testCases; testCase++) { a = sc.nextInt(); b = sc.nextInt(); casos = numeroCasos(a,b); bw.write(""Case #"" + (testCase + 1) + "": "" + casos + ""\n""); } bw.close(); } private long numeroCasos(long a, long b){ long casos = 0; // long medio = (long)(Math.ceil(((b - a)/2)) + a); char c[]; long arrayCombinaciones[]; long temp = 0; long base = 0; for(long i = a; i <= b; i++){ base = i; c = (Long.toString(i)).toCharArray(); //comprueba numero // for (int j = 0; j < c.length; j++) { arrayCombinaciones = traeCombinaciones(c); siguiente: for (int k = 0; k < arrayCombinaciones.length; k++) { temp = arrayCombinaciones[k]; if (temp > base){ base = temp; }else{ continue siguiente; } if (temp <= b){ casos += 1; } } // } } return casos; } private long[] traeCombinaciones(char c[]){ long array[] = new long[c.length]; char temp[] = c; char temp2[] = c; int k = 0; String s; s = String.valueOf(temp); array[0] = Long.parseLong(s); for (int i = 1; i < array.length; i++) { temp = new char[c.length]; for (int j = 0; j < c.length; j++) { if (j == 0){ k = c.length - 1; }else{ k = j - 1; } temp[k] = temp2[j]; } temp2 = temp; array[i] = Long.parseLong(String.valueOf(temp)); } Arrays.sort(array); return array; } } " B20399,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Qualifier2012.c; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; /** * * @author Ant Ongun Kefeli */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(""src\\Qualifier2012\\c\\C-large.in""); Scanner sc = new Scanner(fis); FileWriter fw = new FileWriter(""src\\Qualifier2012\\c\\output.out""); BufferedWriter out = new BufferedWriter(fw); int caseCount = 0; caseCount = sc.nextInt(); for (int i = 0; i < caseCount; i++) { long smallLimit = sc.nextLong(); long bigLimit = sc.nextLong(); doit(out, i + 1, smallLimit, bigLimit); } out.close(); sc.close(); } private static void doit(BufferedWriter out, int casec, long smallLimit, long bigLimit) throws IOException { long res = 0; if (bigLimit < 21) { res = 0; } else { int digits = (int) Math.log10(smallLimit) + 1; Map> map = new HashMap(); for (long i = smallLimit; i <= bigLimit; i++) { for (int j = 1; j <= digits - 1; j++) { String str = Long.toString(i); StringBuilder sb = new StringBuilder(); sb.append(str.substring(str.length() - j, str.length())); sb.append(str.substring(0, str.length() - j)); long cr = Long.parseLong(sb.toString()); if (cr >= smallLimit && cr <= bigLimit) { long sm = i; long big = cr; if (i == cr) { continue; } if (cr < i) { sm = cr; big = i; } if (map.containsKey(sm) && map.get(sm).contains(big)) { continue; } if (map.get(sm) == null) { List list = new ArrayList(); list.add(big); map.put(sm, list); } else { List list = map.get(sm); list.add(big); map.put(sm, list); } res++; } } } } out.write( ""Case #"" + casec + "": "" + res + ""\n""); } } " B20488,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; public class Recycled { /** * @param args */ public static void main(String[] args) { BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); String line; Integer i = 1; Integer licz = 0; boolean first = true; try { while ((line = bufferRead.readLine()) != null && line.length()!= 0) { if (first) { licz = Integer.parseInt(line); first = false; } else { System.out.print(""Case #"" + i +"": ""); // tu wlasciwe obliczenie String[] split = line.split("" ""); policzRececled(split[0], split[1]); System.out.println(); i++; licz--; } if (licz < 0) break; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static int policzRececled(String A, String B) { if (A.length() == 1) { System.out.print(""0""); return 0; } Map map = new HashMap(); Integer licznikPar = 0; Integer min = Integer.parseInt(A); Integer max = Integer.parseInt(B); for (Integer X = min; X <= max; ++X) { String S = X.toString(); for (int i = 1; i < A.length(); ++i) { String subS = S.substring(0, i); String subE = S.substring(i); String sNew = subE + subS; Integer iNew = Integer.parseInt(sNew); if (X < iNew && iNew >= min && iNew <= max) { String ss = """" + X + iNew; if (map.containsKey(ss)) { Integer j = map.get(ss); j++; map.put(ss, j); } else { map.put(ss, 1); } //System.out.println(licznikPar + "": "" + X + "" -> "" + iNew); //licznikPar++; } } } System.out.print(map.size()); /* System.out.println(); Set> entrySet = map.entrySet(); int ii = 1; for (Entry entry : entrySet) { System.out.println(ii + "": "" + entry.getKey() + "" -> "" + entry.getValue()); ii++; } */ return 0; } } " B20487,"import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { File inputFile = new File(""input.txt""); BufferedReader br = null; FileOutputStream out = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); String line; line = br.readLine(); if (line == null) { throw new IllegalStateException(""Empty input file!!!""); } StringBuilder result = new StringBuilder(); int length = Integer.parseInt(line), i = 1; while (i <= length) { result.append(""Case #"").append(i).append("": ""); /////////////////////////////////////////////////////////////////////////////////////////////////// Set match = new HashSet(); String[] numbers = br.readLine().split("" ""); int n = Integer.parseInt(numbers[0]); int m = Integer.parseInt(numbers[1]); for (int j = n;j < m; j++) { String num = j + """"; char[] charArray = num.toCharArray(); if (num.length() < 2 || isCharsEqual(charArray)) { continue; } addMatches(charArray, n, m, match); } result.append(match.size()); /////////////////////////////////////////////////////////////////////////////////////////////////// result.append(""\n""); i++; } File outputFile = new File(""output.txt""); outputFile.delete(); outputFile.createNewFile(); out = new FileOutputStream(outputFile); out.write(result.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static boolean isCharsEqual(char[] num) { char c = num[0]; for (int i = 1; i < num.length; i++) { if (c != num[i]) { return false; } } return true; } private static void addMatches(char[] num, int lower, int upper, Set match) { String n = new String(num); char[] tmp = spin(num); for (int i = 1; i < num.length; i++) { if (tmp[0] != '0') { int m = Integer.parseInt(new String(tmp)); String key = genKey(n, """" + m); if (lower <= m && m <= upper && !n.equals(m + """") && !match.contains(key)) { match.add(key); } } tmp = spin(tmp); } } private static char[] spin(char[] source) { char[] target = new char[source.length]; for (int i = 1; i < source.length; i++) { target[i] = source[i - 1]; } target[0] = source[source.length - 1]; return target; } private static String genKey(String n, String m) { if (n.compareTo(m) < 0) { return n + ""|"" + m; } else return m + ""|"" + n; } } " B20308,"import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; public class B { public static void main(String ... args) throws Exception{ Scanner in = new Scanner(new File(""C-large.in"")); PrintStream out = new PrintStream(new File(""C-large.out"")); int T = in.nextInt(); in.nextLine(); for(int t=0;t set = new HashSet(); int found=0; for(int n=A;n<=B;n++){ int high=(int)Math.log10(B); String orgNumber = new Integer(n).toString(); do{ String num = orgNumber; for(int i=0;in && intNum<=B && !set.contains(n+"" ""+intNum)){ //System.out.println(n + "" "" + intNum); found++; set.add(n+"" ""+intNum); } } orgNumber = ""0"" + orgNumber; }while(orgNumber.length()<=high); } out.println(""Case #"" + (t+1) + "": "" + found); } } } " B22254,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; import java.util.HashSet; public class Number { public static int instinct(int a ){ int b = a%10; int m = 0; while(a!=0){ b = a%10; a = a/10; m++; } return m; } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""output.txt"")); String line = """"; line = br.readLine(); int number = Integer.valueOf(line); for(int i = 1; i<= number; i++){ line = br.readLine(); String[] tokens = line.split("" ""); int a = Integer.valueOf(tokens[0]); int b = Integer.valueOf(tokens[1]); int result = 0; for(int n = a; n<= b; n++){ int m = instinct(n); HashSet in = new HashSet(); for(int c = 1; c< m; c++){ int po =(int) Math.pow(10,c); int tmp = (int) (Math.pow(10, m-c)*(n%po)+n/po); if(tmp >= a && tmp <=b){ if(tmp > n){ if(!in.contains(tmp)){ result++; in.add(tmp); } } } } } bw.append(""Case #""+i+"": ""+result); bw.newLine(); } br.close(); bw.close(); System.out.println(""finished""); } } " B20204,"package files; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.Hashtable; public class Recycle2 { public static void main(String[] args) { try { String line; String data=""""; File ff = new File(""Output.txt""); if (ff.exists()) { ff.delete(); } //BufferedReader br = new BufferedReader(new FileReader(""/Users/Sush/Documents/workspace1/CJ/src/files/Input.txt"")); BufferedReader br = new BufferedReader(new FileReader(""/Users/Sush/Downloads/C-large.in.txt"")); StringBuffer sb = new StringBuffer(); while((line = br.readLine())!= null) { sb = sb.append(line +""\n""); } String[] nos = sb.toString().split(""\n""); for (int i = 1; i< nos.length; i++) { Hashtable counts = new Hashtable(); //System.out.println(""Str ""+nos[i]); String[] num = nos[i].split("" ""); int count=0; int begin=Integer.parseInt(num[0]); int end = Integer.parseInt(num[1]); while(begin < end) { int a = begin; int d = (int)Math.floor(Math.log10(a)); if (d!= 0) { int f = a/(int)(Math.pow(10, d)); int n = a/(int)(Math.pow(10, d-1)); if (f>n) { a = f * (int)Math.pow(10, d) + n * (int)Math.pow(10, d-1); } } int check = a; int x = 0; if (!counts.containsKey(a)) { counts.put(a, 0); while(x != a) { x = (check%10)*(int)(Math.pow(10.0, d)) + (check/10); check = x; if (x > a && x <= end) { //counts.put(x, 0); count = count +1; counts.put(a, count); } } } begin = begin + 1; } data = data + ""Case #""+i+"": ""+count+""\n""; System.out.print(""Case #""+i+"": ""); System.out.println(count); counts.clear(); } BufferedWriter bw = new BufferedWriter(new FileWriter(ff, true)); bw.write(data); bw.close(); } catch(Exception e) { System.out.println(e); } } } " B20712,"import java.io.*; import java.util.*; class Recycling { static Scanner sc; static TreeMap found; static void run() { int A = sc.nextInt(); int B = sc.nextInt(); found = new TreeMap(); int total = 0; for (int n = A; n < B; n++) { total += findPerms(n, A, B); } System.out.println(total + """"); } static int findPerms(int n, int A, int B) { int perms = 0; // first generate the perm list ArrayList a = toArrayList(n); // find all permutations of n // and check if n < m <= B for (int i = 0; i < a.size() - 1; i++) { next_number(a); int m = toNumber(a); // 2000000 = biggest possible number int ff = 10000000 * n + m; //System.out.println(m); if (n < m && A <= m && m <= B && !found.containsKey(ff)) { perms++; found.put(ff, m); //System.out.println(m + "" <<""); } } return perms; } static ArrayList toArrayList(int a) { ArrayList b = new ArrayList(); for (int i = numdigits(a); i > 0; i--) { b.add(nthdigit(a, i - 1)); //System.out.print(nthdigit(n, i - 1) + "" ""); } return b; } static int toNumber(ArrayList a) { int n = 0; for (int i = 0; i < a.size(); i++) { n *= 10; n += a.get(i); } return n; } static int nthdigit(int x, int n) { while (n-- != 0) { x /= 10; } return (x % 10); } static int numdigits(int x) { int d = 0; while (x != 0) { x /= 10; d++; } return d; } static void next_number(ArrayList a) { Collections.swap(a, 0, a.size() - 1); for (int i = 0; i < a.size() - 2; i++) { Collections.swap(a, a.size() - (2 + i), a.size() - (1 + i)); } } public static void main(String args[]) { sc = new Scanner(System.in); int cases = Integer.parseInt(sc.nextLine()); for (int i = 0; i < cases; i++) { System.out.print(""Case #"" + (i + 1) + "": ""); run(); } } } " B21496,"import java.util.*; public class Recycled { static int CAP = 2000000; static long[] f; static int[] pow = new int[]{1,10,100,1000,10000,100000,1000000}; public static void main(String[] args){ Scanner reader = new Scanner(System.in); int times = reader.nextInt(); for(int k = 1; k <= times; k++){ int n = reader.nextInt(); int m = reader.nextInt(); fill(n,m); long sum = 0; for(int i = n; i <= m; i++) sum += (f[i]*(f[i]-1))/2l; System.out.println(""Case #""+k+"": ""+sum); } } public static int getRoot(int n){ int p = -1; for(int i = 0; i <= 6; i++) if(n/pow[i] > 0) p = i; int x = n; int min = n; for(int i = 0; i <= p; i++){ x = ((x%pow[p]) * 10) + x/pow[p]; if(x/pow[p] > 0) min = Math.min(min, x); } return min; } public static int getRoot(int n, int low){ int p = -1; for(int i = 0; i <= 6; i++) if(n/pow[i] > 0) p = i; int x = n; int min = n; for(int i = 0; i <= p; i++){ x = ((x%pow[p]) * 10) + x/pow[p]; if(x/pow[p] > 0 && x >= low) min = Math.min(min, x); } return min; } public static void fill(int n, int m){ f = new long[2000001]; for(int i = n; i <= m; i++) f[getRoot(i, n)]++; } public static void fill(){ f = new long[2000001]; for(int i = 0; i <= CAP; i++) f[getRoot(i)]++; } } " B20051,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class RecyclingNumber { public static void main(String[] args) { try { BufferedReader input = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter output = new BufferedWriter(new FileWriter(""output.txt"")); Integer numCases = Integer.parseInt(input.readLine()); for(int i=0; i set = new TreeSet(); for(int k=1; k lines = Files.readLines(f, Charsets.UTF_8); int cases = Integer.valueOf(lines.get(0)); int c = 0; while (c < cases) { int result = 0; c++; String[] tokens = lines.get(c).split("" ""); int a = Integer.valueOf(tokens[0]); int b = Integer.valueOf(tokens[1]); Set set = new HashSet(); for(int n = a; n < b; n++) { set.clear(); String s = """" + n; // System.out.println("" >> "" + s); int sl = s.length(); for (int i = 0; i < sl; i++) { Integer shifted = shift(s, i); if (shifted != null && shifted <= b && shifted > n) { // System.out.println(shifted); set.add(shifted); } } result += set.size(); } System.out.println(""Case #"" + c + "": "" + result); } } private static Integer shift(String n, int i) { i++; int l = n.length(); String s = n.substring(l - i, l) + n.substring(0,l - i); if (s.compareTo(n) <= 0) { return null; } else { return Integer.valueOf(s); } } }" B21105,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class QualificationC { public static void main(String[] args) { try { FileReader input = new FileReader(args[0]); BufferedReader in = new BufferedReader(input); FileWriter output = new FileWriter(""QualificationC.out""); BufferedWriter out = new BufferedWriter(output); String line; int count = 1; line = in.readLine(); int cases = Integer.parseInt(line); line = in.readLine(); while (line != null && count <= cases) { if (count != 1) { out.write(""\n""); } String outStr = ""Case #"" + count + "": "" + getMaxRecycledPairs(line); System.out.println(outStr); out.write(outStr); line = in.readLine(); count++; } out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } private static int getMaxRecycledPairs(String line) { String[] lineArr = line.split("" ""); int A = Integer.parseInt(lineArr[0]); int B = Integer.parseInt(lineArr[1]); int count = 0; for (int n = A; n < B; n++) { String nStr = String.valueOf(n); List tempList = new ArrayList(); for (int i = 0; i < nStr.length(); i++) { String mStr = nStr.substring(i) + nStr.substring(0, i); if (mStr.charAt(0) != '0') { int m = Integer.parseInt(mStr); if (m <= B && n < m && !tempList.contains(m)) { tempList.add(m); count++; } } } } return count; } } " B21827,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.List; import java.util.ArrayList; public class Rec{ static int rotate(int n, int l){ int pot = (int)Math.pow(10,l-1); int ld = (int)Math.floor(n/pot); int cd = n-ld*pot; int ans = cd*10+ld; return ans; } static String bw(String a, int n){ String ans = """"; for(int i=n;i""+ans+ans2); return ans+ans2; } public static int recnum(int a, int b){ int[] test = new int[b-a+1]; int ans = 0; int l=String.valueOf(a).length(); for(int i=a;i<=b;i++){ int c = i; List reps = new ArrayList(); for(int j=1;ji && String.valueOf(c).length()==l && c!=i && !reps.contains(c)){ ans++; reps.add(c); //System.out.println(""(""+String.valueOf(i)+"",""+String.valueOf(c)+"")""); } } } return ans; } public static void main(String[] args) throws IOException{ BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String ttt = """"; int n = Integer.parseInt(stdin.readLine()); int i = 1; while (i<=n){ ttt = stdin.readLine(); String[] AB = ttt.split("" ""); int a = Integer.parseInt(AB[0]); int b = Integer.parseInt(AB[1]); System.out.println(""Case #""+String.valueOf(i++)+"": ""+String.valueOf(recnum(a,b))); } stdin.close(); } } " B20934,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Recycle { /** * @param args */ static int t =0; //static ArrayList> table = new ArrayList>(); public static void inputF() throws FileNotFoundException{ File inputFile = new File(""C-large.in""); Scanner in = new Scanner(inputFile); File outputFile = new File(""C-large.out""); PrintWriter out = new PrintWriter(outputFile); String result=""""; String input =""""; int n,m=0; t = in.nextInt(); //System.out.println(n); input = in.nextLine(); for (int i=1; i<=t; i++) { n =in.nextInt(); m =in.nextInt(); //System.out.println(""length of the list: ""+list.length); result = ""Case #""+i+ "": ""+ count(n,m); out.println(result); } in.close(); out.close(); } private static int count(int n, int m) { int result =0; boolean isRecycle = false; ArrayList list = new ArrayList(); for (int i=n; i<=m;i++){ String ori=Integer.toString(i); isRecycle = false; list = new ArrayList(); for(int j=1; ji)&(resInt<=m)) { if ((!isRecycle)|((isRecycle)& (!list.contains(resInt)))){ result++; isRecycle=true; list.add(resInt); //System.out.println(i+""-->""+resInt); //out.println(resInt); } } } } return result; } public static void main(String[] args) throws FileNotFoundException { inputF(); } } " B21503,"import java.io.*; import java.text.*; import java.util.*; public class RecycledNumbers { static BufferedReader stdin; static StringTokenizer st; static String LINE() throws Exception { return stdin.readLine(); } static String TOKEN() throws Exception { while (st == null || !st.hasMoreTokens())st = new StringTokenizer(LINE()); return st.nextToken(); } static int INT() throws Exception {return Integer.parseInt(TOKEN());} static long LONG() throws Exception {return Long.parseLong(TOKEN());} static double DOUBLE() throws Exception {return Double.parseDouble(TOKEN());} static DecimalFormat DF = new DecimalFormat(""0.000"",new DecimalFormatSymbols(Locale.ENGLISH)); public static void main(String[] args) throws Exception { String input = ""C-large.in""; String output = ""C-large.out""; // String input = ""testa.in""; // String output = ""testa.out""; stdin = new BufferedReader(new FileReader(new File(input))); FileWriter frw = new FileWriter(output); int cases = INT(); int cc = 1; while(cases-->0) { System.out.println(cc); int N = INT(), M = INT(); int cp = N / 10; int factor = 1; while(cp>0) { factor *= 10; cp /= 10; } int solution = 0; for(int i = N; i < M; i++) { solution += addPairs(i, factor, M); } frw.write(""Case #""+(cc++)+"": ""); frw.write(""""+solution); frw.write(""\n""); } frw.flush(); frw.close(); } private static int addPairs(int i, int factor, int max) { int cnt = 0; int num = i; // System.out.println(i+"" ""+factor+"" ""+max); do { // System.out.println(num); int tmp = num; tmp /= 10; tmp += factor * (num % 10); num = tmp; if(num > i && num <= max)cnt++; } while (num != i); return cnt; } } " B21908," import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(C.class.getSimpleName() + "".in"")); PrintWriter out = new PrintWriter(new File(C.class.getSimpleName() + "".out"")); int T = in.nextInt(); for (int i = 0; i < T; i++) { String s = ""Case #"" + (i + 1) + "": "" + new C().solve(in); out.println(s); System.out.println(s); } out.close(); } private String solve(Scanner in) { int a = in.nextInt(); int b = in.nextInt(); int k = 1; int c = 1; while (k * 10 <= b) { k *= 10; c++; } int[] num = new int[10000000]; for (int n = a; n <= b; n++) { int min = n; int nn = n; for (int i = 0; i < c; i++) { nn = (nn / 10) + (nn % 10) * k; if (nn >= k) { min = Math.min(min, nn); } } num[min]++; } long res = 0; for (int n : num) { res += (1L * n * (n - 1)) / 2; } return """" + res; } }" B20585,"package com.forthgo.google.g2012r0; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Created by Xan Gregg. * Date: 4/14/12 */ public class ProblemC { public static void main(String[] args) { try { Scanner in = new Scanner(new File(""C.in"")); PrintWriter out = new PrintWriter(new FileWriter(""C.out"")); //PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); for (int i = 0; i < t; i++) { int a = in.nextInt(); int b = in.nextInt(); int k = solve(a, b); out.printf(""Case #%d: %d%n"", i + 1, k); out.flush(); } } catch (IOException e) { throw new RuntimeException(); } } private static int solve(int a, int b) { int k = 0; int nda = (int) (Math.log10(a) + 1); int ndb = (int) (Math.log10(b) + 1); Set pairs = new HashSet(b - a); for (int i = Math.max(2, nda); i <= ndb; i++) { k += solve(pairs, a, b, i); } return k; } private static int solve(Set pairs, int a, int b, int nd) { int k = 0; for (int i = 1; i <= nd / 2; i++) k += solve(pairs, a, b, nd, i); return k; } private static int solve(Set pairs, int a, int b, int nd, int ndc) { int c10 = (int) Math.pow(10, ndc); int ndd = nd - ndc; int d10 = (int) Math.pow(10, ndd); int c0 = a / d10; int d0 = a / c10; int k = 0; for (int c = c0; c < c10; c++) { if (c * d10 > b) break; int d00 = d0; if (ndc == ndd) d00 = Math.max(d00, c + 1); for (int d = d00; d < d10; d++) { if (d * c10 > b) break; int x = c * d10 + d; int y = d * c10 + c; if (x != y && x >= a && x <= b && y >= a && y <= b) { long xx = Math.min(x, y); long yy = Math.max(x, y); long pair = xx * c10 * d10 + yy; if (!pairs.contains(pair)) { k++; pairs.add(pair); // System.out.printf(""%d %d%n"", Math.min(x, y), Math.max(x, y)); } } } } return k; } } " B21633,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.*; import java.util.ArrayList; import java.util.Scanner; /** * * @author Ka */ public class Recy { private File file; private int aantal; private ArrayList cases; private ArrayList max; public Recy(File f) throws FileNotFoundException { file = f; Scanner scanner = new Scanner(new FileReader(file)); aantal = scanner.nextInt(); cases = new ArrayList(aantal); max = new ArrayList(aantal); scanner.nextLine(); for(int i =0; i < aantal ; i++) { String s = scanner.nextLine(); cases.add(s); } System.out.println(cases); } public void scores() { for(String s : cases) { int counter = 0; ArrayList nb = new ArrayList(); String sb = """"; while(counter < s.length()) { if(s.charAt(counter)!= ' ') { sb = sb + s.charAt(counter); } if(s.charAt(counter) == ' '&& counter != s.length()-1) { int n = Integer.parseInt(sb); nb.add(n); sb = """"; } counter++; } if(counter == s.length()) { int n = Integer.parseInt(sb); nb.add(n); sb = """"; } System.out.println(nb); options(nb); } } public void options(ArrayListnr) { int n = nr.get(0), m = nr.get(1),amount=0; if(n < 10 && m < 10) amount = 0; else if(n >= 10 && n < 100&& n % 10 < 10) { for(int i = n ; i < m ; i++) { String s = Integer.toString(i); int g = Integer.parseInt(s); String s1 = s.charAt(1)+""""+ s.charAt(0)+""""; int r = Integer.parseInt(s1); if(g >= n && g <= m && r >= n && r <= m && g < r ) amount++; } } else if(n >= 100 && n < 1000) { for(int i = n ; i < m ; i++) { String s = Integer.toString(i); int g = Integer.parseInt(s); String s1 = s.charAt(2)+""""+ s.charAt(0)+""""+s.charAt(1); String s2 = s.charAt(1)+""""+ s.charAt(2)+""""+s.charAt(0); int r = Integer.parseInt(s1); int r1 = Integer.parseInt(s2); if(g >= n && g <= m && r >= n && r <= m && g < r ) amount++; if(r != r1) { if(g >= n && g <= m && r1 >= n && r1 <= m && g < r1 ) amount++; } } } else if(n >= 1000 && n < 10000) { for(int i = n ; i < m ; i++) { String s = Integer.toString(i); int g = Integer.parseInt(s); String s1 = s.charAt(3)+""""+s.charAt(0)+""""+ s.charAt(1)+""""+s.charAt(2); String s2 = s.charAt(2)+""""+s.charAt(3)+""""+ s.charAt(0)+""""+s.charAt(1); String s3 = s.charAt(1)+""""+s.charAt(2)+""""+ s.charAt(3)+""""+s.charAt(0); int r = Integer.parseInt(s1); int r1 = Integer.parseInt(s2); int r2 = Integer.parseInt(s3); if(g >= n && g <= m && r >= n && r <= m && g < r ) amount++; if(r != r1 && r1 != r2 && r != r2) { if(g >= n && g <= m && r1 >= n && r1 <= m && g < r1 ) amount++; if(g >= n && g <= m && r2 >= n && r2 <= m && g <= r2 ) amount++; } } } else if(n >= 10000 && n < 100000) { for(int i = n ; i < m ; i++) { String s = Integer.toString(i); int g = Integer.parseInt(s); String s1 = s.charAt(4)+""""+s.charAt(0)+""""+s.charAt(1)+""""+ s.charAt(2)+""""+s.charAt(3); String s2 = s.charAt(3)+""""+s.charAt(4)+""""+s.charAt(0)+""""+ s.charAt(1)+""""+s.charAt(2); String s3 = s.charAt(2)+""""+s.charAt(3)+""""+s.charAt(4)+""""+ s.charAt(0)+""""+s.charAt(1); String s4 = s.charAt(1)+""""+s.charAt(2)+""""+s.charAt(3)+""""+ s.charAt(4)+""""+s.charAt(0); int r = Integer.parseInt(s1); int r1 = Integer.parseInt(s2); int r2 = Integer.parseInt(s3); int r3 = Integer.parseInt(s4); if(g >= n && g <= m && r >= n && r <= m && g < r ) amount++; if(r != r1 || r1 != r2 || r != r2 || r != r3 || r2 != r3) { if(g >= n && g <= m && r1 >= n && r1 <= m && g < r1 ) amount++; if(g >= n && g <= m && r2 >= n && r2 <= m && g <= r2 ) amount++; if(g >= n && g <= m && r3 >= n && r3 <= m && g <= r3 ) amount++; } } } else if(n >= 1000000 && n < 10000000) { for(int i = n ; i < m ; i++) { String s = Integer.toString(i); int g = Integer.parseInt(s); String s1 = s.charAt(5)+""""+s.charAt(0)+""""+s.charAt(1)+""""+s.charAt(2)+""""+ s.charAt(3)+""""+s.charAt(4); String s2 = s.charAt(4)+""""+s.charAt(5)+""""+s.charAt(0)+""""+s.charAt(1)+""""+ s.charAt(2)+""""+s.charAt(3); String s3 = s.charAt(3)+""""+s.charAt(4)+""""+s.charAt(5)+""""+s.charAt(0)+""""+ s.charAt(1)+""""+s.charAt(2); String s4 = s.charAt(2)+""""+s.charAt(3)+""""+s.charAt(4)+""""+s.charAt(5)+""""+ s.charAt(0)+""""+s.charAt(1); String s5 = s.charAt(1)+""""+s.charAt(2)+""""+s.charAt(3)+""""+s.charAt(4)+""""+ s.charAt(5)+""""+s.charAt(0); int r = Integer.parseInt(s1); int r1 = Integer.parseInt(s2); int r2 = Integer.parseInt(s3); int r3 = Integer.parseInt(s4); int r4 = Integer.parseInt(s5); if(g >= n && g <= m && r >= n && r <= m && g < r ) amount++; if(r != r1 || r1 != r2 || r != r2 || r != r3 || r2 != r3 || r != r4 || r2 != r4 || r3 != r4) { if(g >= n && g <= m && r1 >= n && r1 <= m && g < r1 ) amount++; if(g >= n && g <= m && r2 >= n && r2 <= m && g <= r2 ) amount++; if(g >= n && g <= m && r3 >= n && r3 <= m && g <= r3 ) amount++; if(g >= n && g <= m && r4 >= n && r4 <= m && g <= r4 ) amount++; } } } max.add(amount); } public void output(BufferedWriter out) throws FileNotFoundException, IOException { int counter = 1; for(Integer s : max ) { out.write(""Case #"" + counter + "": ""); out.write(s+""\n""); counter++; } out.close(); } } " B20405,"package com.gao.t3; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashSet; public class Main { public static void main(String args[]){ try{ FileInputStream fin=new FileInputStream(""C:\\Users\\Gao\\Downloads\\C-large.in""); //FileInputStream fin=new FileInputStream(""cc.txt""); BufferedReader br=new BufferedReader(new InputStreamReader(fin)); FileOutputStream fout=new FileOutputStream(""out.txt""); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(fout)); int n=Integer.parseInt(br.readLine()); HashSet hash=new HashSet(); for(int i=0;i=0&&strB.compareTo(B+"""")<=0){ hash.add(strA+"" ""+strB); } } } String str=""Case #""+(i+1)+"": ""+hash.size(); bw.write(str); if(i ms = new LinkedList(); for (int t = 0; t < T; t++) { int A = s.nextInt(); int B = s.nextInt(); int digits = String.valueOf(A).length(); int total = 0; for (int i = A; i < B; i++) { String num = String.valueOf(i); ms.clear(); for (int j = 1; j < digits; j++) { int r = Integer.parseInt(num.substring(j) + num.substring(0, j)); if (r > i && r <= B && !ms.contains(r)) { total++; ms.add(r); } } } System.out.printf(""Case #%d: %d\n"", t + 1, total); } } } " B21674,"import java.io.*; import java.util.*; public class CodeJamCLarge { public static void main (String[] args) throws IOException { int i, j, k; long startTime = System.currentTimeMillis(); File inFile = new File(""C-large.in""); // File to read from File outFile = new File(""C-large.out""); BufferedReader reader = new BufferedReader(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); HashMap map = new HashMap(); String line = null; line = reader.readLine(); int cases = Integer.parseInt(line); int counter = 1; while ((line=reader.readLine()) != null) { int A,B; int pairs = 0; String[] node = line.split("" ""); A = Integer.parseInt(node[0]); B = Integer.parseInt(node[1]); //char[] num = new char[node[0].length()]; for(i = A; i <= B; i++) { String iStr = String.valueOf(i); String newNum; String newNum2; for(j = 1; j < node[0].length(); j++) { newNum = iStr.substring(j); newNum2 = newNum.concat(iStr.substring(0, j)); int n = Integer.parseInt(newNum2); if(n > i && n <= B) { if(map.containsKey(i) && map.get(i) == n) { ; } else { map.put(i, n); pairs++; } } } } map.clear(); //System.out.println(""Case #""+counter+"": ""+pairs); writer.write(""Case #""+counter+"": ""+pairs); writer.newLine(); counter++; } writer.close(); long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; System.out.println(""Total Time: "" + totalTime); } } " B21378,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumbers { public static void main ( String [] arg ) throws NumberFormatException, IOException{ BufferedReader reader = new BufferedReader(new FileReader(new File(""input""))); PrintWriter output = new PrintWriter(new File(""output"")); int cases = Integer.valueOf( reader.readLine() ); for ( int c=1; c<=cases; c++ ){ StringTokenizer tkn = new StringTokenizer( reader.readLine() ); int a = Integer.valueOf( tkn.nextToken() ); int b = Integer.valueOf( tkn.nextToken() ); int sol=0; //Set superMap = new HashSet(); for ( int k=a; k aux = new HashSet(); String sr = k + """"; for ( int i=1; i recycled = new TreeSet(); int count = 0; FileWriter fstream; BufferedWriter out; public static void main(String[] args) throws IOException { ProblemC p = new ProblemC(); long a = System.currentTimeMillis(); p.fstream = new FileWriter(""outC.txt""); p.out = new BufferedWriter(p.fstream); p.readFile(""C-large.in""); long b = System.currentTimeMillis(); System.out.println((b-a)/100); p.out.close(); } public void readFile(String filePath) { String[] result = null; try { FileReader input = new FileReader(filePath); BufferedReader bufRead = new BufferedReader(input); Scanner scan = new Scanner(input); this.count = scan.nextInt(); for (int i = 0; i < count; i++) { int a = scan.nextInt(); int b = scan.nextInt(); out.write(""Case #"" + (i + 1) + "": "" + calculate(a, b)); if (i""+value); if ((value <= i+1) && (value >= a) && (value != i) && (!recycled.contains(Long.parseLong(num+newNum))) && (!recycled.contains(Long.parseLong(newNum+num)))) { // recycled.add(Long.parseLong(num + newNum)); // recycled.add(Long.parseLong(num+newNum)); count++; } } } } System.out.println(count); return count; } } " B20378,"import java.util.*; public class C { public static int front; public static int rotate(int in) { return (in / 10) + front*(in % 10); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int c = 1; c <= T; c++){ int ans = 0; int A = in.nextInt(); int B = in.nextInt(); int ndig = ("""" + A).length(); front = 1; for(int i = 1; i < ndig; i++) front *= 10; for(int num = A; num <= B; num++){ int count = 1; int rot = rotate(num); boolean smallest=true; while(smallest && rot!= num){ if(A <= rot && rot <= B) if(rot < num) smallest = false; else count++; rot = rotate(rot); } if(smallest) ans += count*(count - 1)/2; } System.out.println(""Case #"" + c + "": "" + ans); } } }" B20407,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException { ArrayList al = new ArrayList(); int count = 0; for (int r = 0; r <= 2000000; r++) { if (r % 1000 == 0) { System.out.println(r); } String A = Integer.toString(r); for (int r1 = 1; r1 < A.length(); r1++) { String B = A.substring(r1) + A.substring(0, r1); if (!A.equals(B) && Integer.parseInt(A) > Integer.parseInt(B)) { al.add(new Pair(Integer.parseInt(A), Integer.parseInt(B))); // System.out.println((count++)+"" ""+A + "" "" + B); } } } Collections.sort(al); //remove duplicates Pair last=null; for (int r=0;r=A &&ala[u]<=B){ // System.out.println(ala[u]+"" ""+alb[u]); count++; } } System.out.println(""Case #"" + (r + 1) + "": "" + (count)); outp.write(""Case #"" + (r + 1) + "": "" + (count)+""\n""); // outp.write(""Case #"" + (r + 1) + "": "" + fin + ""\n""); } outp.flush(); fstream.close(); } public static int rank(int key, int[] a) { int lo = 0; int hi = a.length - 1; while (lo <= hi) { // Key is in a[lo..hi] or not present. int mid = lo + (hi - lo) / 2; // System.out.println(lo+"" ""+mid+"" ""+hi); if (key < a[mid]) hi = mid - 1; else if (key > a[mid]) lo = mid + 1; if ((mid>0 && mid a[mid - 1])||key==a[mid]) return mid; if (mid==0)return 0; if (mid==a.length-1)return a.length-1; } return -1; // return lo + (hi - lo) / 2; } static class Pair implements Comparable { int A; int B; public Pair(int a, int b) { A = a; B = b; } @Override public int compareTo(Pair arg0) { if (this.A < arg0.A) return -1; if (this.A == arg0.A) return 0; return 1; } @Override public int hashCode(){ return A*10000000+B; } @Override public boolean equals(Object other){ if (other==null)return false; if (other==this)return true; if (A==((Pair)other).A&&B==((Pair)other).B)return true; return false; } } } " B21773,"package fr.lcwi.googlecodejam; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * For Google Code Jam 2012 */ public class ProblemC { private static Scanner scanner; private static int nbCases; public static void main(String[] args) throws IOException { String filename = args[0]; scanner = new Scanner(ProblemC.class.getClassLoader().getResourceAsStream(filename + "".in"")); nbCases = Integer.valueOf(scanner.nextLine()); BufferedWriter bWriter = null; try { bWriter = new BufferedWriter(new FileWriter(filename + "".out"")); for (int i = 1; i <= nbCases; i++) { resolveCase(i, bWriter); } } finally { if (bWriter != null) { bWriter.close(); } } } private static void resolveCase(int caseNb, BufferedWriter bWriter) throws IOException { int A = scanner.nextInt(); int B = scanner.nextInt(); int result = 0; for (int n = A; n < B; n++) { Set ms = new HashSet(); int length = (int) Math.floor(Math.log10(n)) + 1; if (length > 1) { for (int i = 0; i < length - 1; i++) { int puissanceA = (int) Math.pow(10, length - i - 1); int puissanceB = (int) Math.pow(10, i + 1); int digitsToMove = n % puissanceB; int ma = digitsToMove * puissanceA; if (ma >= puissanceB) { int mb = n / puissanceB; int m = ma + mb; if (n < m && m < B+1 && !ms.contains(m)) { result++; ms.add(m); } } } } } bWriter.write(""Case #"" + caseNb + "": "" + result); if (caseNb < nbCases) { bWriter.newLine(); } } } " B20276,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package solution; import com.sun.xml.internal.ws.server.InvokerTube; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Vector; /** * * @author Aditya */ import java.io.*; import javax.print.DocFlavor; class Test{ int high,low; int ret=0; Vector vi =new Vector(); public int[] getAsIntegerArray(String line){ String[] elems=line.split("" ""); int[] ret=new int[elems.length]; for(int i=0;i0;j--){ ca[j]=ca[j-1]; } ca[0]=temp; k= new Integer(new String(ca)); if((k>i) && (k<=high)){ ret++; //System.out.println(i+"" ""+ k); } }while(k!=i); } } } public class Question3 { public static int numInputs; public static Vector cases= new Vector(); public static BufferedReader br ; public static void readInput(){ String s; try{ br=new BufferedReader(new InputStreamReader(System.in));//new BufferedReader(new FileReader(""f:\\test\\asdasd.in"")); if((s=br.readLine())!=null) numInputs=Integer.parseInt(s); while((numInputs-->0) && (s=br.readLine())!=null){ cases.add(new Test(s)); } }catch(IOException ioex){ ; } } public static void process(){ for(Test t:cases){ t.process(); } } public static void printOutput(){ for(int i=0;i store = new ArrayList(); for(int i = 1; i < nString.length(); i++) { if(nString.charAt(i) == '0') continue; int m = Integer.parseInt(nString.substring(i) + nString.substring(0, i)); if(m > n && m <= b) { if(!store.contains(m)) { store.add(m); ans++; } } } } return ans; } } " B20780,"package gcj2012; import java.io.FileInputStream; import java.io.PrintStream; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class C { public static void main(String[] args) throws Exception { new C().run(); } void run() throws Exception { Scanner in = new Scanner(System.in); in = new Scanner(new FileInputStream(""C-small-attempt0.in"")); in = new Scanner(new FileInputStream(""C-large.in"")); PrintStream out = System.out; out = new PrintStream(""C-small-attempt0.out""); out = new PrintStream(""C-large.out""); int T = in.nextInt(); for (int x = 1; x <= T; x++) { int A = in.nextInt(); int B = in.nextInt(); out.printf(""Case #%d: %d\n"", x, countRecycled(A, B)); } } private int countRecycled(int a, int b) { int res = 0; int p0 = 1; while (p0 < b) p0 *= 10; for (int s = a; s <= b; s++) res += countRecycledStartingBy(a, b, s, p0); return res; } private int countRecycledStartingBy(int a, int b, int s, int p0) { int p = 1; Set recs = new TreeSet(); while (p < 1000000) { int end = s % p; int beg = s / p; int rec = end * p0 + beg; if (rec >= a && rec <= b && rec != s && s < rec) recs.add(rec); p *= 10; p0 /= 10; } return recs.size(); } } " B22001,"import java.io.*; import java.util.*; public class newRecycledNumbers { static HashMap map; static int[] recycleNumber(int a){ String s = Integer.toString( a ); int[] arr = new int[s.length()]; arr[0] = a; for ( int i = 1; i < s.length() ; i++) arr[i] = (int)( a/Math.pow( 10, i ) ) + (int)(a%Math.pow( 10, i ))*(int)(Math.pow( 10, s.length()-i )); return arr; } static void solve(int a, int b){ int[] arr; int size = map.size(); for ( int n = a; n < b; n++){ arr = recycleNumber(n); for ( int j = 0; j < arr.length; j++) if ( arr[j] > n && arr[j] <= b) map.put( Integer.toString( n ) + "", "" + Integer.toString(arr[j]), """" ); } System.out.println(map.size()-size); } public static void main (String[] args) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(""recycle.in"")); int T = Integer.parseInt(reader.readLine()), a,b; for ( int i = 0; i < T; i++){ map = new HashMap(); StringTokenizer st= new StringTokenizer(reader.readLine()); a = Integer.parseInt( st.nextToken() ); b = Integer.parseInt( st.nextToken() ); System.out.print(""Case #"" + (i+1) + "": ""); solve(a,b); } } }" B20061,"import java.util.Scanner; /** * Abdulaziz * 4/14/12 */ public class Problem3 { public static void main(String[] args) { int count = 0; int t = 50; Scanner scanner = new Scanner(System.in); for (int q = 0; q <= t; q++) { count = 0; String str = scanner.nextLine(); String []arg = str.split("" ""); Integer a = Integer.parseInt(arg[0]); Integer b = Integer.parseInt(arg[1]); for (int i = a; i <= b; i++) { String input = String.valueOf(i); String changed; int len = input.length(); for (int j = 1; j < len; j++) { changed = input.substring(j, len) + input.substring(0, j); if (Integer.valueOf(changed) <= Integer.valueOf(input)) continue; if (Integer.valueOf(changed) <= b && Integer.valueOf(changed) >= a) { count++; } } } System.out.println(""Case #""+(q+1)+"": ""+count); } } } " B21083,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; /** * * Google Code Jam 2012 Qualification Round - Problem C. Recycled Numbers * * @author matlock * */ public class RecycledNumbers { public static void main(String[] args) { RecycledNumbers g = new RecycledNumbers(); g.goGo(); } public void goGo() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { int testCases = Integer.parseInt(in.readLine()); for (int i = 1; i <= testCases; i++) { String inputText = in.readLine(); String[] numberPair = inputText.split("" "", 2); int matches = runTestCase(Integer.valueOf(numberPair[0]), Integer.valueOf(numberPair[1])); System.out.println(""Case #"" + i + "": "" + matches); } } catch (IOException e) { System.out.println(""Exception: "" + e.getMessage()); } } public int runTestCase(int startVal, int endVal) { Set sourceSet = new HashSet(); Set discoveredSet = new HashSet(); int totalMatches = 0; // first store all the source numbers for (int j = startVal; j <= endVal; j++) { sourceSet.add(String.valueOf(j)); } for (int j = startVal; j <= endVal; j++) { StringBuffer buf = new StringBuffer(String.valueOf(j)); int len = buf.length() - 1; // don't need last rotation, so -1 // rotate the characters for (int k = 0; k < len; k++) { buf.append(buf.charAt(0)); buf.deleteCharAt(0); if (Integer.valueOf(buf.toString()) != j) { if (sourceSet.contains(buf.toString()) && !discoveredSet.contains(String.valueOf(j) + buf.toString())) { discoveredSet.add(String.valueOf(j) + buf.toString()); discoveredSet.add(buf.toString() + String.valueOf(j)); totalMatches++; sourceSet.remove(String.valueOf(j)); // remove from set } } } } return totalMatches; } } " B20163,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejam2012_qualification; import java.io.*; import java.util.*; /** * @author neil */ public class NewMain2 { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedReader in = new BufferedReader(new FileReader(""C:\\Documents and Settings\\neil\\Desktop\\C-large.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""C:\\Documents and Settings\\neil\\Desktop\\C-large-output.txt"")); PrintStream ps = new PrintStream(System.out,true); StringTokenizer st;//st = new StringTokenizer(in.readLine(),"" ""); int t = Integer.parseInt(in.readLine()); int count=0,count1=0; while(count++ hey = new ArrayList(); for(int j=1;j=A&&Integer.parseInt(N)= a && m <= b && n < m && nodup(l, c, m)) { l[c] = m; c++; } } return c; } public static void main(String[] args) { new Recycled(args[0]); } } " B20334,"/* ID: yourID LANG: JAVA TASK: Recycled_Numbers */ import java.io.*; import java.math.*; import java.util.*; /*public class Recycled_Numbers { } */ public class Recycled_Numbers implements Runnable { // based on Petr's template boolean localDebug = false; private void solve() throws IOException { int a = this.nextInt(); int b = this.nextInt(); int mul = 1; while( mul * 10 <= a ) mul *= 10; int res = 0; for ( int i = a; i < b; i ++ ){ int m = i; HashSet< Integer > exist = new HashSet< Integer >(); for ( int j = 1; j < mul; j *= 10 ){ m = ( m % 10 ) * mul + m / 10; if ( m > i && m <= b && !exist.contains( m ) ){ exist.add( m ); res ++; } } } writer.println( res ); } public static void main(String[] args) { new Recycled_Numbers().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { if (localDebug) { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(new OutputStreamWriter(System.out)); } else { writer = new PrintWriter(new BufferedWriter(new FileWriter( ""C-large.out""))); reader = new BufferedReader(new FileReader( ""C-large.in"")); } tokenizer = null; int t = this.nextInt(); for (int i = 1; i <= t; i++) { writer.print(""Case #"" + i + "": ""); solve(); } reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } boolean hasNext() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String nextLine = reader.readLine(); if (nextLine == null) return false; tokenizer = new StringTokenizer(nextLine); } return true; } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { return reader.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } BigInteger nextBigInteger() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return new BigInteger(tokenizer.nextToken()); } }" B20210,"import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class C { static int[] tens = { 1, 10, 100, 1000, 10000, 100000, 1000000 }; static HashSet set = new HashSet(); static private int countPairs(int a, int max, int len) { int rhs, lhs, num; set.clear(); int res = 0; for (int i = 1; i < len; i++) { lhs = a % tens[i]; rhs = a / tens[i]; if (lhs == 0) continue; num = lhs * tens[len - i] + rhs; if (set.contains(num)) continue; if (a < num && num <= max) { res++; set.add(num); } } return res; } static private int numberLength(int n) { int len = Arrays.binarySearch(tens, n); if (len < 0) len = ~len; else len++; return len; } public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileInputStream(""C-large.in"")); FileWriter out = new FileWriter(new File(""C-large.out"")); int t = in.nextInt(),cnt = 1; while (t-->0) { int a = in.nextInt(), b = in.nextInt(); int tmp = 0; for (int i = a; i <= b; i++) tmp += countPairs(i, b, numberLength(i)); out.write(""Case #"" + cnt++ + "": "" + tmp+""\n""); } in.close(); out.close(); } } " B21568,"package year2012.qualification.c; import java.io.File; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws Exception{ //GCJ共通 String filename = ""src/year2012/qualification/c/C-large""; PrintWriter out = new PrintWriter(new File(filename + "".out"")); Scanner scan = new Scanner(new File(filename + "".in"")); final int T = scan.nextInt(); for(int i=0;i=in.length){ throw new IllegalArgumentException(""n= "" + n + "", in.length = "" + in.length + ""となっています。n inputLines; private ArrayList outputLines = new ArrayList(); public RecycledNumbers(String inputPath){ try { this.inputPath = inputPath; this.outputPath = inputPath.replace("".in"", "".out""); this.inputLines = openFile(); findSolution(); generateOutputFile(); } catch (IOException e) { e.printStackTrace(); } } private ArrayList openFile() throws IOException { ArrayList lines = new ArrayList(); FileReader fr = new FileReader(this.inputPath); BufferedReader br = new BufferedReader(fr); String zeile = null; while ((zeile = br.readLine()) != null) { lines.add(zeile); } br.close(); return lines; } private void generateOutputFile() throws IOException { FileWriter fw = new FileWriter(outputPath); PrintWriter pw = new PrintWriter(fw); for (String string : outputLines) { //System.out.println(string); pw.println(string); } pw.close(); } private void findSolution() { for (int i=1; i gefunden = new HashSet(); Integer m = 0; String inp = inputLines.get(i); String outp = ""Case #"" + i + "": ""; Integer A = Integer.parseInt( inp.split("" "")[0] ); Integer B = Integer.parseInt( inp.split("" "")[1] ); for (Integer n=A; nn){ if (m<=B){ gefunden.add(n+""<->""+m); } } } } outp += gefunden.size(); outputLines.add(outp); } } public static void main(String[] args) { //new RecycledNumbers(""src/recycledNumbers/sample.in""); new RecycledNumbers(""src/recycledNumbers/C-large.in""); } } " B21628,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecycledNumbers { static final String input_path = ""data/input.c.txt""; private static Set ans = new HashSet(); private static Integer[] getBits(int n) { List lst = new ArrayList(); while (n != 0) { lst.add(n % 10); n /= 10; } Integer ans[] = new Integer[lst.size()]; return lst.toArray(ans); } private static int getInteger(Integer[] bits) { int ans = 0; int power = 1; for (int i = 0; i < bits.length; i ++) { ans += power * bits[i]; power *= 10; } return ans; } private static int judge(int n, int b) { Integer[] bits = getBits(n); if (bits.length == 1) return 0; int ret = 0; int len = bits.length; for (int pos = 0; pos < len - 1; pos ++) { if (bits[pos] == 0) continue; int new_bits_len = 0; Integer[] new_bits = new Integer[len]; for (int i = pos + 1; i < len; i++) new_bits[new_bits_len ++] = bits[i]; for (int i = 0; i <= pos; i++) new_bits[new_bits_len ++] = bits[i]; int new_int = getInteger(new_bits); if (new_int <= b && new_int > n) { String ans_str = String.format(""%d_%d"", n, new_int); if (!ans.contains(ans_str)) ans.add(ans_str); ret += 1; } } return ret; } private static int solve(int a, int b) { if (a == b) return 0; for (int i = a; i < b; i ++) { int tmp = judge(i, b); } return ans.size(); } /** * Good luck, Wash! * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(input_path)); String intext = in.readLine(); int T = Integer.parseInt(intext); for (int caseIter = 0; caseIter < T; caseIter ++) { intext = in.readLine(); System.out.print(String.format(""Case #%d: "", caseIter + 1)); String[] parts = intext.split("" ""); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); System.out.println(solve(A, B)); ans.clear(); } in.close(); } } " B20595,"package be.mokarea.gcj.recyclednumbers; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import be.mokarea.gcj.common.TestCaseReader; public class RecycledNumbersTestCaseReader extends TestCaseReader { private final LineNumberReader lineReader; private final int NUMBER_TEST_CASE; private int currentCaseNumber; public RecycledNumbersTestCaseReader(InputStream inputStream) throws NumberFormatException, IOException { lineReader = new LineNumberReader(new InputStreamReader(inputStream)); NUMBER_TEST_CASE = Integer.parseInt(lineReader.readLine()); currentCaseNumber = 0; } @Override public RecycledNumbersTestCase nextCase() throws Exception { String line = lineReader.readLine(); if (line != null) { currentCaseNumber++; String[] tokens = line.split("" ""); final int a = Integer.parseInt(tokens[0]); final int b = Integer.parseInt(tokens[1]); return new RecycledNumbersTestCase(currentCaseNumber,a,b); } return null; } @Override public int getMaxCaseNumber() { return NUMBER_TEST_CASE; } } " B20447,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.*; /** * * @author wijebandara */ public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException, IOException { //java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); java.io.BufferedReader in=new java.io.BufferedReader(new java.io.FileReader(""/home/wijebandara/Desktop/C-large.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""/home/wijebandara/Desktop/C-large.out""))); int n = Integer.parseInt(in.readLine()); java.util.StringTokenizer st ; for(int i=0;i l =new java.util.ArrayList(); int h =(int)Math.log10(j); for(int k=1;k<=h;k++) { int p=change(j,k); if(p>j && !l.contains(p) && p>=a && p<=b) { l.add(p); ans++; } } } //System.out.print(""Case #"" + (i + 1) + "": ""); out.print(""Case #"" + (i + 1) + "": ""); //System.out.println(ans); out.println(ans); } out.close(); } static int change(int x,int n) { int a=(int)(Math.pow(10, n)); int hold=x%a; int b =(int)Math.log10(x)+1; x=(x-hold)/a; return hold*(int)Math.pow(10, b-n)+x; } } " B21058,"/** * Recycled Numbers */ package com.google.jam.qualification; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class C { public static String moveFromEndToFront(String number, int n) { String begin = number.substring(0,number.length()-n); String end = number.substring(number.length()-n); return end+begin; } public static void main(String[] args) { try { FileOutputStream fos = new FileOutputStream(""C-large.out""); System.setOut(new PrintStream(fos, true)); FileInputStream fis=new FileInputStream(new File(""C-large.in"")); InputStreamReader in=new InputStreamReader(fis); BufferedReader br=new BufferedReader(in); String line=""""; int nbTest = Integer.parseInt(br.readLine()); for(int i=1; i<=nbTest; i++) { line = br.readLine(); Scanner sc = new Scanner(line); int cpt = 0; int min = sc.nextInt(); int max = sc.nextInt(); for(int k=min; k<=max; k++) { String number = String.valueOf(k); HashMap table = new HashMap(); for(int l=1; lk){ if(temp>=begin&&temp<=end){ inc++; } } } return inc; } public static int testcase(int begin,int end){ int inc=0; for(int i=begin;i<=end;i++){ inc+=Recycled(i,begin,end); } return inc; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); for(int i=0;i hs= new HashSet(); private int reclycled(int n) { int m, count= 0; for (int i=1; in && m<=B && hs.add(m)) { ++count; // System.out.printf(""%d -> %d\n"", n, m); } } hs.clear(); return count; } public void solve() throws IOException { int i,j,k; String s; int MODE= LARGE; br = new BufferedReader (new FileReader(""C""+infile[MODE])); out = new PrintWriter(new BufferedWriter(new FileWriter(""C""+outfile[MODE]))); int C= Integer.valueOf(br.readLine()); for (int c=1; c<=C; c++) { // read tok= getTok(); A= toInt(tok[0]); B= toInt(tok[1]); cn= tok[0].length(); // output out.printf(""Case #%d: %d\n"", c, answer()); } out.close(); } public static void main(String[] args) throws IOException { new C().solve(); } } " B21102,"package pl.helman.codejam.recycled; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; //Brute force attempt public class Recycled { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { FileReader fr = new FileReader(""d:\\recycled.in""); BufferedReader br = new BufferedReader(fr); String s = br.readLine(); FileWriter f0 = new FileWriter(""d:\\recycled.out""); int t = Integer.parseInt(s.trim()); for (int i = 1; i <= t; i++) { s = br.readLine(); String[] elems = s.split("" ""); int a = Integer.parseInt(elems[0]); int b = Integer.parseInt(elems[1]); int digs = 1; int mod = 1; int ret = 0; while (a >= mod * 10) { digs++; mod *= 10; } for (int n = a; n <= b; n++) { // System.out.println("" n:""+n); int m = n; m = (m % mod) * 10 + (m / mod); while (m != n) { // System.out.print("" m:"" + m); if (m > n && m <= b) { ret++; // System.out.print("" +""); } // System.out.println(); m = (m % mod) * 10 + (m / mod); } } System.out.println(""Case #"" + i + "": "" + ret); // System.out.println(); f0.write(""Case #"" + i + "": "" + ret + ""\r\n""); } fr.close(); f0.close(); } } " B21302,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.*; public class main { int numberPeriod(int n, int len) { if (len == 2 && n / 10 == n % 10) return 1; if (len == 4 && n % 100 == n / 100) return 2; if (len == 6 && n % 100 == n / 10000 && n % 100 == n / 100 % 100) return 2; if (len == 6 && n % 1000 == n / 1000) return 3; return len; } int numberLength(int n) { int len = 0; while (n > 0) { n /= 10; len++; } return len; } main() throws FileNotFoundException { Scanner sc = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter out = new PrintWriter(""result.txt""); int tests = sc.nextInt(); for (int t = 1; t <= tests; t++) { int a = sc.nextInt(); int b = sc.nextInt(); int l = numberLength(a); int tt = (int) Math.pow(10, l - 1); int r = 0; for (int j = a; j <= b; j++) { int cr = j; int val = j; int per = numberPeriod(j, l); for (int k = 0; k < per; k++) { int c = val % 10; val = val / 10 + c * tt; if (val > cr && val <= b) { r++; } } } out.printf(""Case #%d: %d\n"", t, r); } out.flush(); } public static void main(String[] args) { try { main m = new main(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }" B21176,"import java.util.Scanner; public class Main { /** * @param args */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int numTestCases = Integer.valueOf(scanner.nextLine()); for ( int i =0; i < numTestCases; i++ ) { String theCase = scanner.nextLine(); //Error checking not necessary for now. Scanner lineScanner = new Scanner(theCase); int A = lineScanner.nextInt(); int B = lineScanner.nextInt(); int numDigits = getNumDigits(A,B); int[] powersOf10 = new int[numDigits]; powersOf10[0] =1; for ( int j =1; j < numDigits; j++) { powersOf10[j] = powersOf10[j-1]*10; } //Brute force int count=0; for ( int number = A; number <=B; number ++ ) { int[] acceptedPairs = new int[numDigits]; // Defaults to 0 for ( int firstDigit = 1; firstDigit < numDigits; firstDigit++ ) { //Make a new number. int newNum = (number%powersOf10[firstDigit])*powersOf10[numDigits-firstDigit] + number/powersOf10[firstDigit]; if ( newNum > B || newNum <= number) { continue; } for ( int j=0; j < acceptedPairs.length; j++) { if ( acceptedPairs[j] == newNum ) { //Duplicate number break; } else if ( acceptedPairs[j] == 0 ) { //New number acceptedPairs[j] = newNum; break; } } } // Count non-zero accepted pairs for ( int j = 0; j < acceptedPairs.length; j++ ) { if ( acceptedPairs[j] == 0 ) { break; } count++; } } StringBuilder builder = new StringBuilder(""Case #""); builder.append(i+1).append("": ""); builder.append(count); System.out.println(builder.toString()); } } private static int getNumDigits(int a, int b) { int count = 0; while ( a > 0) { count++; a /= 10; } return count; } } " B21887,"package qualifying; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class C { public static void main(String[] args) throws Exception { String fs_in = ""/Users/ctynan/Downloads/test.txt""; String fs_out = ""/Users/ctynan/Documents/C-out.txt""; String line; BufferedReader br = new BufferedReader(new FileReader(fs_in)); BufferedWriter bw = new BufferedWriter(new FileWriter(fs_out)); line=br.readLine(); line=line.toLowerCase(); int tst = Integer.valueOf(line); for(int ii=0;iii&&tm<=B) { boolean have = false; for(int l=0;l counted = new ArrayList(); while(t++= a && !counted.contains(temp)){ counted.add(temp); count++; } } } out.println(count); } } static InputReader in; static OutputWriter out; public static void start(){ in = new InputReader(System.in); out = new OutputWriter(System.out); } public static void finish() throws Exception{ out.close(); } public static void main(String[] args) throws Exception { start(); solve(); finish(); } } class InputReader extends BufferedInputStream{ public InputReader(InputStream In){ super(In); } public char readChar() throws Exception{ int c = read(); while(isStringEnd(c)) c = read(); return (char) c; } public int readInt() throws Exception { int sign = 1; int cur = 0; int c = read(); while(isStringEnd(c)) c = read(); if(c == '-'){ sign = -1; c = read(); } do{ cur *= 10; cur += c - '0'; c = read(); }while(!isStringEnd(c)); return cur*sign; } public long readLong() throws Exception { long sign = 1; long cur = 0; int c = read(); while(isStringEnd(c)) c = read(); if(c == '-'){ sign = -1; c = read(); } do{ cur *= 10; cur += c - '0'; c = read(); }while(!isStringEnd(c)); return cur*sign; } public double readDouble() throws Exception { double sign = 1; double cur = 0; int c = read(); while(isStringEnd(c)) c = read(); if(c == '-'){ sign = -1; c = read(); } do{ cur *= 10; cur += c - '0'; c = read(); }while(!isStringEnd(c) && c!= '.'); if(c == '.'){ c = read(); double r = 0.1; do{ cur += r*(c - '0'); r *= 0.1; c = read(); }while(!isStringEnd(c) && c!= '.'); } return cur*sign; } public String readStr() throws Exception{ int c = readChar(); while(isStringEnd(c)) c = read(); StringBuilder res = new StringBuilder(); do{ res.append((char)c); c = read(); }while(!isStringEnd(c)); return res.toString(); } public String readLine() throws Exception{ int c = readChar(); while(isStringEnd(c)) c = read(); StringBuilder res = new StringBuilder(); do{ res.append((char)c); c = read(); }while(!isEOL(c)); return res.toString(); } public char[] readCharArray(int s) throws Exception{ char[] a = new char[s]; for(int i=0; i void printArray(T[] a, String del){ for(int i=0; i void printMat(T[][] a, String delRows, String delCols){ for(int i=0; i void printCollection(Iterable c, String del){ boolean b = true; for(T i : c){ if(b) b = false; else print(del); print(i); } } }" B21372,"import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { private String mInputFileName; private String mOutputFileName; private long A; private long B; private Set mPairSet = new HashSet(); public RecycledNumbers(String inputFileName, String outputFileName) { mInputFileName = inputFileName; mOutputFileName = outputFileName; } public void solve() { long start = System.currentTimeMillis(); Scanner scanner = null; try { scanner = new Scanner(new FileReader(mInputFileName)); Writer output = new BufferedWriter(new FileWriter(mOutputFileName)); int cases = scanner.nextInt(); for (int i = 1; i <= cases; i++) { mPairSet.clear(); A = scanner.nextLong(); B = scanner.nextLong(); System.out.println(""CASE: "" + i + "" / "" + cases); if (i > 1) output.write(""\n""); output.write(""Case #"" + i + "": ""); output.write(getAnswer()); } output.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (scanner != null) scanner.close(); } System.out.println(""TIME: "" + (System.currentTimeMillis() - start)); } private String getAnswer() { int res = 0; for (long i = A; i <= B; i++) { res += getNumPairs(i); } //System.out.println(res); return """" + res; } private int getNumPairs(long num) { int res = 0; String numStr = """" + num; int len = numStr.length(); if (len > 1) { for (int i = 1; i < len; i++) { String newStr = numStr.substring(i) + numStr.substring(0, i); long newNum = Long.parseLong(newStr); if (newNum > num && newNum <= B) { String pair = num + "" "" + newNum; if (!mPairSet.contains(pair)) { mPairSet.add(pair); res++; } } } } return res; } public static void main(String[] args) { String fileName = ""test""; String extension = "".txt""; String outputSuffix = ""_output""; new RecycledNumbers(fileName + extension, fileName + outputSuffix + extension).solve(); } } " B22196,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args){ FileInputStream fstream = null; DataInputStream in = null; BufferedReader br = null; FileWriter fw = null; BufferedWriter out = null; try{ fstream = new FileInputStream(args[0]); in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); fw = new FileWriter(args[1]); out = new BufferedWriter(fw); String strLine; int i = 0; int tc = 0; while ((strLine = br.readLine()) != null) { if(i == 0){ tc = Integer.parseInt(strLine); i++; continue; } if( i <= tc){ String[] arr = strLine.split("" ""); int minLimit = Integer.parseInt(arr[0]); int maxLimit = Integer.parseInt(arr[1]); int count = 0; int len = arr[0].length(); if(len <= 1){ count = 0; }else{ for(int j = minLimit; j <= maxLimit ; j++){ int num = j; List ls = new ArrayList(); for(int k = 1; k < len ; k++ ){ int dp = (int)Math.pow(10, len -k); int mp = (int)Math.pow(10, k); int first = num / dp; int last = num % dp; int number = last*mp + first; if(num != number){ if(number <= maxLimit && number >= minLimit){ if(!ls.contains(number+"""")){ ls.add(number+""""); count++; } } } } } } count = count/2; System.out.println(""Case #""+i+"": ""+count); out.write(""Case #""+i+"": ""+count); out.write(System.getProperty( ""line.separator"" )); } i++; } in.close(); out.close(); }catch (Exception e){ e.printStackTrace(); System.err.println(""Error: "" + e.getMessage()); } } } " B21278," public class Recycled { static String test = ""4\n1 9\n10 40\n100 500\n1111 2222""; static String val = ""50\n1049802 1946314\n1019242 1999787\n332841 815293\n1443938 1907548\n5125 9748\n1037227 1960407\n1053187 1952673\n1043225 1910832\n100000 100000\n351349 556470\n68 80\n116204 961036\n504 844\n1086291 1964681\n100000 999999\n21207 36868\n38 50\n54134 64312\n1526010 1747987\n1736162 1783904\n100000 100001\n10486 11651\n1820549 1880905\n1097653 1971323\n1087139 1993152\n1090695 1961364\n4541 8166\n1046409 1315179\n897387 957090\n1024733 1940114\n1000415 1945733\n534 685\n1019180 1921115\n1076227 1860470\n502 748\n10000 99999\n7821 9852\n353200 479493\n3 8\n4977 7152\n36645 46007\n1166938 1166938\n45802 72650\n1085149 1982470\n1037947 1935060\n1634839 1802893\n1056643 1989496\n1001424 1975827\n752384 752384\n778195 833983\n""; public static void main(String[] args) { String[][] cases = CaseReader.getCases(val, 1); for (int i = 0;i < cases.length;i++) { parseCase(i + 1, cases[i][0]); } } static void parseCase(int caseNum, String caseString) { String[] args = caseString.split("" ""); int current, recycles = 0; int leftMin = Integer.parseInt(args[0]); int rightMax = Integer.parseInt(args[1]); current = leftMin; int currentLen = (int) Math.pow(10,(int)(Math.log10(leftMin))); int nextLen = currentLen * 10; while (current <= rightMax) { recycles += recycledCount(current, leftMin, rightMax, currentLen); current++; if (current == nextLen) { nextLen *= 10;currentLen *= 10; } } System.out.println(""Case #"" + caseNum + "": "" + recycles); } static int recycledCount(int current, int leftMin, int rightMax, int len) { int working = moveIt(current, len); int c = 0;/* if (current == 29 && antimax == 10) return -1;*/ while (working != current) { if (working >= leftMin && current <= rightMax && working < current) { c++; } working = moveIt(working, len); } return c; } static int moveIt(int v, int e10) { return v / 10 + (e10 * (v % 10)); } } " B20320,"package se.pathed.codejam.practice.recycled; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; public class RecycledNumbers { public static void main(String[] args) throws NumberFormatException, IOException{ new RecycledNumbers().run(); } public File getFileFromDisk(String fileName){ String dataFolder = ""C:\\Users\\Patrik\\workspaces\\codejam\\Practis\\data\\""; return new File(dataFolder + fileName); } public static class Problem { int first; int last; } public Problem[] parseInput() throws NumberFormatException, IOException{ Problem[] probs; File f = getFileFromDisk(""C-large.in""); FileReader fReader = new FileReader(f); BufferedReader reader = new BufferedReader(fReader); int numCases = Integer.parseInt(reader.readLine()); probs = new Problem[numCases]; for(int i = 0; i < numCases; i++){ String[] res = reader.readLine().split("" ""); Problem p = new Problem(); p.first = Integer.parseInt(res[0]); p.last = Integer.parseInt(res[1]); probs[i] = p; } reader.close(); return probs; } private void run() throws NumberFormatException, IOException { Problem[] problems = parseInput(); File outputFile = getFileFromDisk(""out.txt""); if( outputFile.exists()) outputFile.delete(); PrintWriter outFile = new PrintWriter(outputFile); for(int i = 0; i < problems.length; i++){ int solution = solve(problems[i]); outFile.println(""Case #"" + (i+1) + "": "" + solution); } outFile.flush(); } private int solve(Problem p){ int first = p.first; int last = p.last; int count = 0; HashMap found = new HashMap(); int[] foundInts = new int[Integer.toString(p.last).length() ]; for(int x = first; x <= last; x++){ String s = Integer.toString(x); int foundCount = 0; if(s.length() > 1){ //System.out.println(""Testing value: "" + x); for(int v=1; v < s.length(); v++){ String next = s.substring(v) + s.substring(0,v); //System.out.println(""Testing value: "" + next); if(next.charAt(0) != '0'){ int val = Integer.parseInt(next); if( val <= last && val > x){ // Already submitted boolean f = false; for(int i = 0; i < foundCount; i++){ if( foundInts[i] == val){ f = true; } } if(f != true){ foundInts[foundCount] = val; foundCount++; if( found.containsKey(val) && found.get(val) == x){ System.out.println(""ERROR found duplicate: "" + val); count++; } else { found.put(val, x); count++; } } } } } } } return count; } } " B21444,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; public class Main { /** * @param args */ public static void main(String[] args) throws Exception { if(args.length != 1) { return; } FileInputStream inputStream = new FileInputStream(args[0]); InputStreamReader istReader = new InputStreamReader(inputStream); BufferedReader buffReader = new BufferedReader(istReader); // T:問題数 String tStr = buffReader.readLine(); int t = Integer.valueOf(tStr); for(int i = 1; i <= t; i++) { StringBuilder caseBuilder = new StringBuilder(""Case #""); caseBuilder.append(i); caseBuilder.append("": ""); // A and B:問題 String abStr = buffReader.readLine(); String[] aandbStrs = abStr.split("" ""); int a = Integer.valueOf(aandbStrs[0]); int b = Integer.valueOf(aandbStrs[1]); int y = 0; for(int n = a; n < b; n++) { String nStr = String.valueOf(n); int[] ms = new int[nStr.length() - 1]; for(int k = 1; k < nStr.length(); k++) { String mStr = nStr.substring(nStr.length() - k).concat(nStr.substring(0, nStr.length() - k)); int m = Integer.valueOf(mStr); if(m <= a || b < m || m <= n) continue; boolean already = false; for(int j = 0; j < nStr.length() - 1; j++) { if(m == ms[j]) { already = true; break; } } if(!already) { y++; ms[k - 1] = m; } } } caseBuilder.append(y); System.out.print(caseBuilder.toString()); if(i != t) System.out.println(); } } } " B20435," ///REMOVE ALL OUTPUT AND USE STRINGTOKENIZER! /* ID: mfranzs1 LANG: JAVA TASK: RecycledNumbers */ import java.io.*; import java.util.*; public class RecycledNumbers { static BufferedReader f; public static void main (String [] args) throws IOException { long unixTime = System.currentTimeMillis(); // Use BufferedReader rather than RandomAccessFile; it's much faster f = new BufferedReader(new FileReader(""RecycledNumbers.in"")); // input file name goes above PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""RecycledNumbers.out""))); // Use StringTokenizer vs. readLine/split -- lots faster //StringTokenizer st = new StringTokenizer(f.readLine(),"" ""); //int i = Integer.parseInt(st.nextToken()); int cases=Integer.parseInt(f.readLine()); for(int c=0;c workingPairs = new ArrayList(); String stringN=""""+n; for(int swap=1;swap 0; --idx) { String candidateString = string.substring(idx, string.length()) + string.substring(0, idx); Integer candidate = Integer.parseInt(candidateString); if (candidate.compareTo(value) > 0 && candidate.compareTo(min) >= 0 && candidate.compareTo(max) <= 0) { addToMatches(value, candidate); } } return result; } private static void addToMatches(int value, int match) { boolean inserted = false; for (int cnt = 0; cnt < MATCHES[value].length; ++cnt) { if (MATCHES[value][cnt] == 0) { MATCHES[value][cnt] = match; inserted = true; break; } else if (MATCHES[value][cnt] == match) return; } if (!inserted) { int[] save = MATCHES[value]; MATCHES[value] = new int[save.length * 2]; int cnt; for (cnt = 0; cnt < save.length; ++cnt) { MATCHES[value][cnt] = save[cnt]; } MATCHES[value][cnt] = match; } } } " B22257,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashSet; public class ProblemB { static HashSet pairs = new HashSet(); public static void main(String args[]) { ReadInFile(); } private static void ReadInFile() { try { FileWriter ofstream = new FileWriter(""c:/cygwin/out.txt""); BufferedWriter out = new BufferedWriter(ofstream); // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream( ""c:/cygwin/C-large.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line int i = 0; strLine = br.readLine(); while ((strLine = br.readLine()) != null) { pairs.clear(); // Print the content on the console System.out.println(strLine); String[] tokens = strLine.split(""\\s+""); System.out.println(""Case #"" + (++i) + "": "" + ReturnCount(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]))); out.write(""Case #"" + (i) + "": "" + ReturnCount(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1])) + ""\n""); } // Close the input stream in.close(); out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } static int ReturnCount(int n, int m) { HashSet cycles = new HashSet(); for (int i = n; i <= m; i++) { // if (!cycles.contains(i)) cycles.addAll(GetCycles(i, n, m)); } return pairs.size(); } static private HashSet GetCycles(int in, int n, int m) { String s = String.valueOf(in); HashSet out = new HashSet(); for (int i = 0; i < s.length(); i++) { String sub1 = s.subSequence(0, i + 1).toString(); String sub2 = s.subSequence(i + 1, s.length()).toString(); int permutation = Integer.parseInt(sub2 + sub1); out.add(permutation); } for (int i : out) if (i >= n && i <= m && i > in) { pairs.add(in + "","" + i); // return out; } return out; } } " B21413,"package RecycledNumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class RecyledNumbers { public RecyledNumbers() { } public static int findRecycled(int low, int high) { Set pairs = new HashSet(); for (int i = low; i <= high; i++) { String s = String.valueOf(i); for (int j = 1; j < s.length(); j++) { String newString = s.substring(j) + s.substring(0, j); int newValue = Integer.parseInt(newString); if (newValue <= high && newValue >= low && newValue != i && !newString.startsWith(""0"")) { if (!pairs.contains(new Pair(newValue, i))) { pairs.add(new Pair(i, newValue)); } } } } return pairs.size(); } private static int parse(String input) { StringTokenizer st = new StringTokenizer(input, "" ""); if (st.countTokens() != 2) throw new IllegalArgumentException(""Wrong no of values""); int low = Integer.parseInt(st.nextToken()); int high = Integer.parseInt(st.nextToken()); return findRecycled(low, high); } public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException(""No file specified""); List data = new ArrayList(); List results = new ArrayList(); try { FileInputStream fstream = new FileInputStream(args[0]); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { data.add(strLine); } in.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } if (data.size() == 0) throw new IllegalArgumentException(""No data in file""); int noTestCases = Integer.parseInt(data.get(0)); if (data.size() != noTestCases + 1) throw new IllegalArgumentException(""Number of test cases is not "" + noTestCases); for (int i = 1; i <= noTestCases; i++) { results.add(""Case #"" + i + "": "" + parse(data.get(i))); } try { FileWriter fostream = new FileWriter(args[1]); BufferedWriter out = new BufferedWriter(fostream); for (int i =0;i checked = new LinkedHashSet(); int recycledPairNumber = 0; for (int i = A; i <= B; i++) { if (checked.contains(i)) continue; String s = Integer.toString(i); String ss = s + s; Set recycled = new LinkedHashSet(); recycled.add(i); for (int j = 0; j < s.length(); j++) { int candidate = Integer.parseInt(ss.substring(j, j + s.length())); if (candidate >= A && candidate <= B) recycled.add(candidate); } if (recycled.size() == 1) continue; checked.addAll(recycled); recycledPairNumber += (recycled.size() * (recycled.size() - 1)) / 2; } out.write(""Case #"" + t + "": "" + recycledPairNumber + ""\n""); } in.close(); out.close(); } } " B20809,"import java.util.*; import java.lang.*; import java.io.*; class recycle { public static void main(String args[]) { try { PrintWriter pw=new PrintWriter(""out.txt""); //creating file reader instance and reading first line BufferedReader br=new BufferedReader(new FileReader(args[0])); String line=br.readLine(); int T=Integer.parseInt(line); //number of test cases T //------------------------- //processing each test case for(int i=0;in && m<=B) { result++; // System.out.println(""valid""); } ++ilen; } } // System.out.println(""Case #""+(i+1)+"": "" + result); pw.println(""Case #""+(i+1)+"": "" + result); /*------------------------**/ } br.close(); pw.close(); }//end of try catch(Exception e) { System.out.println(""Exception caught: ""+e); } } }" B20048,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; public class RecycledNumbers { public static void main(String[] args) throws IOException { new RecycledNumbers().solveAll(); } BufferedReader reader; int T; int[] POW10 = new int[]{1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; int A, B; private void solveAll() throws IOException { //reader = new BufferedReader(new InputStreamReader(System.in)); reader = new BufferedReader(new InputStreamReader(new FileInputStream(""C-large.in""))); T = Integer.parseInt(reader.readLine()); for (int i = 0; i < T; i++) { solve(i + 1); } } private void solve(int caseNumber) throws IOException { String line = reader.readLine(); String[] strings = line.split("" ""); A = Integer.parseInt(strings[0]); B = Integer.parseInt(strings[1]); HashSet distinctPairs = new HashSet(); for (int number = A; number <= B; number++) { List pairs = generatePairsFromNumber(number, numDigits(number)); distinctPairs.addAll(pairs); } int result = distinctPairs.size(); //System.out.println(distinctPairs); System.out.println(""Case #"" + caseNumber + "": "" + result); } private List generatePairsFromNumber(int number, int digits) { List result = new ArrayList(digits); for (int pow = 1; pow < digits; pow++) { int xnumber = (number % POW10[pow]) * POW10[digits - pow] + number / POW10[pow]; if (xnumber < A || xnumber > B || xnumber == number || xnumber < POW10[digits - 1]) { continue; } Pair pair = new Pair(number, xnumber); result.add(pair); } return result; } private int numDigits(int number) { int digits = 0; while (number >= POW10[digits]) { digits++; } return digits; } class Pair { int x, y; Pair(int x, int y) { if (x < y) { this.x = x; this.y = y; } else { this.x = y; this.y = x; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (x != pair.x) return false; if (y != pair.y) return false; return true; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } @Override public String toString() { return ""{"" + x + "", "" + y + '}'; } } } " B20379,"import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.HashSet; public class Googlerecycle { public static void main (String[] args) { FileReader fr = null; BufferedReader br = null; Writer out = null; Writer debug = null; try { fr = new FileReader(args[0]); br = new BufferedReader(fr); out = new OutputStreamWriter(new FileOutputStream(""googlerecycle-result.txt"")); debug = new OutputStreamWriter(new FileOutputStream(""googlerecycle-debug.txt"")); String numOfLine = br.readLine(); int line = 0; if (numOfLine != null) { line = Integer.valueOf(numOfLine); } else { return; } String lineData; String[] recycleArray; for (int i = 1; i <= line; i++) { HashMap> resultMap = new HashMap>(); String resultLine = """"; int recycledCounter = 0; lineData = br.readLine(); recycleArray = lineData.split("" ""); if (recycleArray[1].length() != 1) { int lowerLimit = Integer.valueOf(recycleArray[0]); int upperLimit = Integer.valueOf(recycleArray[1]); String iterator; for (int j = lowerLimit; j <= upperLimit; j++) { iterator = String.valueOf(j); String doubleLower = iterator + iterator; String iteratorCycled; int iteratorLength = iterator.length(); for (int k = 1; k < iteratorLength; k++) { iteratorCycled = doubleLower.substring(k, k + iteratorLength); if (!iteratorCycled.startsWith(""0"") && (!iteratorCycled.equals(iterator))) { int recycled = Integer.valueOf(iteratorCycled); if (recycled <= upperLimit && recycled >= lowerLimit) { if (!resultMap.isEmpty()) { if (resultMap.containsKey(iteratorCycled)) { HashSet resultSet = resultMap.get(iteratorCycled); if (resultSet.contains(iterator)) { debug.write(""already exist pair: "" + iterator + "", "" + iteratorCycled + ""\n""); } else { if (resultMap.containsKey(iterator)){ HashSet resultSet2 = resultMap.get(iterator); if (!resultSet2.contains(iteratorCycled)) { recycledCounter++; debug.write(iterator + "", "" + iteratorCycled + ""\n""); resultSet2.add(iteratorCycled); resultMap.put(iterator, resultSet2); } else { debug.write(""already exist exact pair: "" + iterator + "", "" + iteratorCycled + ""\n""); } } else { recycledCounter++; debug.write(iterator + "", "" + iteratorCycled + ""\n""); HashSet resultSet2 = new HashSet(); resultSet2.add(iteratorCycled); resultMap.put(iterator, resultSet2); } } } else { if (resultMap.containsKey(iterator)){ HashSet resultSet = resultMap.get(iterator); if (!resultSet.contains(iteratorCycled)) { recycledCounter++; debug.write(iterator + "", "" + iteratorCycled + ""\n""); resultSet.add(iteratorCycled); resultMap.put(iterator, resultSet); } else { debug.write(""already exist exact pair: "" + iterator + "", "" + iteratorCycled + ""\n""); } } else { recycledCounter++; debug.write(iterator + "", "" + iteratorCycled + ""\n""); HashSet resultSet = new HashSet(); resultSet.add(iteratorCycled); resultMap.put(iterator, resultSet); } } } else { recycledCounter++; debug.write(iterator + "", "" + iteratorCycled + ""\n""); HashSet resultSet = new HashSet(); resultSet.add(iteratorCycled); resultMap.put(iterator, resultSet); } } } else { debug.write(""not valid recycled: "" + iterator + "", "" + iteratorCycled + ""\n""); } } } } debug.write(""\n""); resultLine = ""Case #"" + i + "": "" + recycledCounter; out.write(resultLine); if (i != line) { out.write(""\n""); } System.out.println(resultLine); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { br.close(); fr.close(); out.close(); debug.close(); } catch(Exception e) {} } } } " B20396,"import java.util.Scanner; import java.io.*; import java.util.HashSet; import java.util.LinkedList; public final class problem2 { public static HashSet hash; public static String decode(int min, int max){ int total = 0; hash = new HashSet (); try{ //FileWriter fw = new FileWriter(""final1.txt""); for(int i = min ; i <= max ; i++){ String n = Integer.toString(i); int len = n.length(); n = n.concat(n); int count = 0; for(int j = 0 ; j <= len ; j++){ String tmp = n.substring(j, j+len); if(tmp.charAt(0) != '0'){ int m = Integer.valueOf(tmp); if(m >= min && m <= max){ if(!hash.contains(tmp)){ hash.add(tmp); count++; //fw.write(tmp + ""\n""); } } } } if(count > 1) count = count * (count - 1) / 2; else count = 0; total += count; } //fw.write(total); //fw.close(); }catch(Exception e){} return Integer.toString(total); } public static void main(String[] args){ try{ //Scanner sc = new Scanner(new File(""yo.txt"")); Scanner sc = new Scanner(new File(""C-large.in"")); FileWriter fw = new FileWriter(""Large.txt""); String tmp = sc.nextLine(); int step = Integer.valueOf(tmp); int counter = 1; while(sc.hasNextLine()){ //System.out.print(""Case #"" + counter + "": ""); String s = sc.nextLine(); Scanner ssc = new Scanner(s); int A = ssc.nextInt(); int B = ssc.nextInt(); //System.out.println(A + "" "" + B); String xx = decode(A, B); System.out.println(""Case #"" + counter + "": "" + xx); fw.write(""Case #"" + counter + "": "" + xx); fw.write(""\n""); counter++; if(step < counter) break; } fw.close(); }catch(Exception e){} } }" B21248,"import java.io.*; import java.util.*; // read file name frome command line public class ProblemC{ public static void main(String args[]){ try{ // reading file initialization String filename = args[0]; FileReader frStream = new FileReader( filename); BufferedReader brStream = new BufferedReader( frStream); // writing file initializtion FileWriter fwStream = new FileWriter( filename.substring(0, filename.length()-3)+""Output.in"" ); BufferedWriter bwStream = new BufferedWriter( fwStream ); PrintWriter pwStream = new PrintWriter( bwStream ); String text = brStream.readLine(); int numCase = Integer.parseInt( text ); for( int i = 0 ; i < numCase ; i++){ text = brStream.readLine(); StringTokenizer currLine = new StringTokenizer( text ); int min = Integer.parseInt(currLine.nextToken()); int max = Integer.parseInt(currLine.nextToken()); int counter = 0; for( int j = min ; j < max ; j++){ String number =""""+j; for( int k = 1 ;k < number.length(); k++){ String pairnumber=number.substring(k)+number.substring(0,k); int pair=Integer.parseInt(pairnumber); if(pair > j && pair <= max ){ counter++; continue; } } } pwStream.println (""Case #"" + (i+1) + "": "" +counter); } // close all I/O files brStream.close(); pwStream.close(); } catch(IOException e){} } }" B21073,"package template; //standard libraries potentially used: //Apache commons http://http://commons.apache.org/ //Google Guava http://code.google.com/p/guava-libraries/ import java.util.ArrayList; public class Template { public static void main(String[] args) { //test(); //Utils.die(""Done testing""); String folder = ""C:\\Users\\Paul Thomson\\Documents\\CodeJam\\RecycledNumbers\\""; Utils.logfile = folder + ""log.txt""; String infile = folder + ""data.in""; String outfile = infile.substring(0, infile.lastIndexOf(""."")) + "".out""; ArrayList tcList = TestCaseIO.loadFromFile(infile); //ArrayList tcList = TestCaseIO.mockUp(); int numThreads = 8; if (numThreads == 1) { TestCaseSolver tcSolver = new TestCaseSolver(tcList, 1); tcSolver.run(); } else { //split into separate lists ArrayList> tcSubLists = new ArrayList<>(); for (int i = 0; i < numThreads; i++) { tcSubLists.add(new ArrayList()); } int i = 0; for (TestCase tc : tcList) { tcSubLists.get(i).add(tc); i++; if (i == numThreads) { i = 0; } } //run each sublist in its own thread ArrayList threadList = new ArrayList<>(); int ref = 1; for (ArrayList tcl : tcSubLists) { TestCaseSolver tcs = new TestCaseSolver(tcl, ref); Thread h = new Thread(tcs); threadList.add(h); h.start(); ref++; } //wait for completion for (Thread h : threadList) { try { h.join(); } catch (InterruptedException ex) { Utils.die(""InterruptedException waiting for threads""); } } } TestCaseIO.writeSolutions(tcList, outfile); double totalTime = 0; for (TestCase tc : tcList) { totalTime += tc.getTime(); } double avTime = totalTime / (double)tcList.size(); Utils.sout(""Total compute time "" + String.format(""%.2f"", totalTime) + "" secs.""); Utils.sout(""Average compute time "" + String.format(""%.2f"", avTime) + "" secs.""); Utils.sout(""Done.""); } public static void test() { } } " B22222,"package tr0llhoehle.cakemix.googleCodeJam.recycledNumbers; import java.util.ArrayList; import tr0llhoehle.cakemix.utility.googleCodeJam.Solver; public class RNSolver implements Solver { @Override public String solve(RNProblem p) { int amount = 0; for (Integer i = p.getLowerBorder(); i < p.getUpperBorder(); i++) { ArrayList usedPermutations = new ArrayList(); String nmbr = String.valueOf(i); // for each permutation... for (int j = 0; j < nmbr.length(); j++) { String tempPermutation = nmbr.substring(j) + nmbr.substring(0, j); if (tempPermutation.charAt(0) != '0' && !usedPermutations.contains(tempPermutation)) { int permutation = Integer.parseInt(tempPermutation); usedPermutations.add(tempPermutation); if (permutation > i && permutation <= p.getUpperBorder()) { amount++; } } } } return amount + """"; } } " B20254,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ex3; /** * * @author Jean-Nicolas */ public class Pair { private int m; private int n; public Pair(int n, int m) { this.m = m; this.n = n; } public int getM() { return m; } public void setM(int m) { this.m = m; } public int getN() { return n; } public void setN(int n) { this.n = n; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Pair other = (Pair) obj; if (this.m != other.m) { return false; } if (this.n != other.n) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 89 * hash + this.m; hash = 89 * hash + this.n; return hash; } } " B20996,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class C { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader br= new BufferedReader(new FileReader(args[0])); BufferedWriter bw= new BufferedWriter(new FileWriter(args[0]+"".out"")); String line= br.readLine(); int cases= Integer.parseInt(line); for (int i= 0; i != cases; i++) { Scanner sc= new Scanner(br.readLine()); bw.write(""Case #""+(i+1)+"": ""+recycle(sc.nextInt(), sc.nextInt())+""\n""); } br.close(); bw.close(); } public static int recycle(int a, int b) { int pairs= 0; for (int n= a; n != b; n++) { char[] num= (""""+n).toCharArray(); for (int i= 0; i != num.length-1; i++) { char[] rec= new char[num.length]; rec[0]= num[num.length-1]; // put last digit at beginning for (int j= 0; j != num.length-1; j++) rec[j+1]= num[j]; num= rec; int m= Integer.parseInt(new String(num)); if (m > n && m <= b) { pairs++; //System.out.println(q+"" ""+n); } } } return pairs; } } " B20111,"import java.io.FileInputStream; import java.util.HashMap; import java.util.Scanner; import java.util.TreeSet; // Recycled Numbers // https://code.google.com/codejam/contest/1460488/dashboard#s=p2 public class C { private static String process(Scanner in) { int A = in.nextInt(); int B = in.nextInt(); int res = 0; int len = Integer.toString(A).length(); for(int n = A; n < B; n++) { String str = Integer.toString(n); TreeSet set = new TreeSet(); for(int i = 1; i < len; i++) { int m = Integer.parseInt(str.substring(i, len) + str.substring(0, i)); if ( m > n && m <= B && ! set.contains(m) ) { set.add(m); res++; } } } return Integer.toString(res); } public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in.available() > 0 ? System.in : new FileInputStream(Thread.currentThread().getStackTrace()[1].getClassName() + "".practice.in"")); int T = in.nextInt(); for(int i = 1; i <= T; i++) System.out.format(""Case #%d: %s\n"", i, process(in)); } } " B21924,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class ProblemC { public static void main(String[] args){ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try{ String line = in.readLine(); int numLines = Integer.parseInt(line); for(int i = 1; i <= numLines; i++){ System.out.print(""Case #"" + i + "": ""); line = in.readLine(); String[] nums = line.split("" ""); int A = Integer.parseInt(nums[0]); int B = Integer.parseInt(nums[1]); int size = nums[0].length(); int count = 0; for(int n = A; n < B; n++){ String nStr = String.valueOf(n); ArrayList pairs = new ArrayList(); for(int k = 1; k < size; k++){ String mStr = nStr.substring(k, size) + nStr.substring(0, k); int m = Integer.parseInt(mStr); if(m > n && m <= B){ String nm = n + "","" + m; if(!pairs.contains(nm)){ pairs.add(nm); count++; } } } } System.out.println(count); } }catch(IOException e){ } } }" B21810,"import com.sun.org.apache.bcel.internal.generic.NEW; import java.io.IOException; import java.util.List; public class WaterSheds extends JamProblem { public static void main(String[] args) throws IOException { WaterSheds p = new WaterSheds(); p.go(); } Character[][] res; WSCase cs; char curr; @Override String solveCase(JamCase jamCase) { cs = (WSCase) jamCase; curr = 'a'; res = new Character[cs.h][cs.w]; for (int y = 0; y < cs.h; y++) { for (int x = 0; x < cs.w; x++) { res[y][x] = ' '; } } for (int y = 0; y < cs.h; y++) { for (int x = 0; x < cs.w; x++) { res[y][x] = update(y, x); } } return ""\n"" + JamUtil.printTable(res); //To change body of implemented methods use File | Settings | File Templates. } private char update(int y, int x) { if (res[y][x] != ' ') { return res[y][x]; } int min = cs.table[y][x]; int dir = -1; if (y > 0) { int curr = cs.table[y - 1][x]; if (curr < min) { min = curr; dir = 0; } } if (x > 0) { int curr = cs.table[y][x - 1]; if (curr < min) { min = curr; dir = 1; } } if (x < cs.w - 1) { int curr = cs.table[y][x + 1]; if (curr < min) { min = curr; dir = 2; } } if (y < cs.h - 1) { int curr = cs.table[y + 1][x]; if (curr < min) { min = curr; dir = 3; } } if (dir == -1) { return res[y][x] = curr++; } else { switch (dir) { case 0: return res[y][x] = update(y - 1, x); case 1: return res[y][x] = update(y, x - 1); case 2: return res[y][x] = update(y, x + 1); case 3: return res[y][x] = update(y + 1, x); default: throw new RuntimeException(); } } } @Override JamCase parseCase(List file, int line) { int i = line; String firstLine = file.get(i++); int[] pair = JamUtil.parseIntList(firstLine, 2); WSCase cas = new WSCase(); cas.h = pair[0]; cas.w = pair[1]; cas.lineCount = cas.h + 1; cas.table = new int[cas.h][]; for (int ih = 0; ih < cas.h; ih++) { cas.table[ih] = JamUtil.parseIntList(file.get(i++), cas.w); } return cas; } } class WSCase extends JamCase { int w, h; int[][] table; } " B20887,"import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { new RecycledNumbers().fun(); } private void fun() { String file = ""D:/CodeJam/input.in""; int result = 0; try { scan = new Scanner(new File(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } int cases = scan.nextInt(); for(int i = 1; i <= cases ; i++) { int lowLimit = scan.nextInt(); int highLimit = scan.nextInt(); result = findResult(lowLimit, highLimit); System.out.println(""Case #""+i+"": ""+result); } } private int findResult(int lowLimit, int highLimit) { if(highLimit < 10) return 0; int[] lowArr = null; int count = 0; int shift = 0; ArrayList list = new ArrayList(); for(int i = lowLimit; i <= highLimit; i++) { list.clear(); lowArr = toArray(i); for(int j = 0; j < lowArr.length-1; j++) { int[] shiftArr = shift(lowArr); if(lowArr.length == shiftArr.length) { shift = arrayToInt(shiftArr); if(i < shift && shift >= lowLimit && shift <= highLimit) { if(!list.contains(shift)) { list.add(shift); count++; } } } } } return count; } private int[] shift(int[] array) { int i = 0; int temp = array[array.length-1]; for(i = array.length-1 ; i > 0; i--) { array[i] = array[i-1]; } array[0] = temp; return array; } private int arrayToInt(int[] array) { int result = 0; for(int i =0; i < array.length ; i++) { result = array[i] + result * 10; } return result; } private int[] toArray(int value) { int array[] = new int[100]; int count = 0; while(value > 0) { int temp = value % 10; value = value / 10; array[count++] = temp; } int array2[] = new int[count]; int j = count - 1; for(int i = 0; i < count ; i++ , j--) { array2[j] = array[i]; } return array2; } Scanner scan = null; } " B20907,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib; public abstract class SolverBase { private InputReader inputReader; protected int[] params; public SolverBase(int initParamCount) { if (initParamCount > 0) { params = new int[initParamCount]; } } public void init(InputReader inputReader) { this.inputReader = inputReader; if (params != null) { try { String line = inputReader.readLine(); params = Utils.convertToIntArray(line, params.length); } catch (Exception e) { System.err.println(""Error while reading initial parameters""); e.printStackTrace(); } } } public final String solveNext() { String solution = null; T input = inputReader.readInput(); if (input != null) { solution = solve(input); } return solution; } protected abstract String solve(T input); } " B22070,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { public static void main(String[] args) throws IOException { new ProblemC(); } private int numOfTest; private static final int ATTEMPT_NO = 0; private static int SOLVE_HARD = 1; int A, B; int ans; int[] cache = new int[2000002]; public ProblemC() throws IOException { //Scanner input = new Scanner(new File(""input.txt"")); Scanner input = new Scanner(new File(""C-small-attempt"" + ATTEMPT_NO + "".in"")); Writer output = new FileWriter(""C-small-attempt"" + ATTEMPT_NO + "".out""); if (SOLVE_HARD != 0) { input = new Scanner(new File(""C-large.in"")); output = new FileWriter(""C-large.out""); } //output = new BufferedWriter(new OutputStreamWriter(System.out)); numOfTest = input.nextInt(); for (int test = 1; test <= numOfTest; test++) { // read from input A = input.nextInt(); B = input.nextInt(); process(); output.write(""Case #"" + test + "": "" + ans + ""\n""); } input.close(); output.flush(); output.close(); } private void process() { ans = 0; for (int num = A; num < B; num++) { int left = num; int right = 0; int mul10 = 1; Set checked = new HashSet(); boolean lastGood = false; while (left > 0) { if (lastGood) { int m = Integer.parseInt(String.valueOf(right) + String.valueOf(left)); if (m > num && m <= B && !checked.contains(m)) { //System.err.println(num + "" "" + m + "" "" + ans); checked.add(m); ans++; } } int lastDigit = left % 10; right = lastDigit * mul10 + right; left /= 10; mul10 *= 10; lastGood = (lastDigit != 0); } } } }" B21038,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader f = new BufferedReader(new FileReader(""test.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""recycled.out""))); int numberCases = Integer.parseInt(f.readLine()); String log; StringTokenizer st; int lower; int upper; int pairs; for (int i = 1; i <= numberCases; i++) { log = ""Case #"" + i + "": ""; st = new StringTokenizer(f.readLine()); lower = Integer.parseInt(st.nextToken()); upper = Integer.parseInt(st.nextToken()); pairs = calculatePairs(lower,upper); out.println(log + pairs); } out.close(); System.exit(0); } private static int calculatePairs(int lower, int upper) { String baseString; int base; String tempString; int temp; int pairs = 0; HashSet h = new HashSet(); //i = n for (int i = lower; i <= upper; i++) { base = i; baseString = Integer.toString(base); h.clear(); //j = number of digits to swap //if leading 0, then automatically smaller/not valid for (int j = 1; j < baseString.length(); j++) { tempString = baseString; tempString = shiftDigits(tempString, j); temp = Integer.parseInt(tempString); if ((temp > base) && (temp <= upper)) { if (!h.contains(tempString)) { h.add(tempString); pairs++; } } } } return pairs; } private static String shiftDigits(String temp, int n) { return temp.substring(temp.length() - n) + temp.substring(0, temp.length() - n); } } " B20573," import java.util.ArrayList; import java.util.Scanner; public class CodeJam3 { public static void main(String[] args) { Scanner kb=new Scanner(System.in); int cases=kb.nextInt(); for(int i=0;i al=new ArrayList(); for(long k=value1;k map = new HashMap<>(); for(int n = A;n <=B;n++){ String N[] = (n+"""").split(""""); int base = (int) (Math.floor(Math.log10(n) + 1.0)); String[] num = new String[base]; for(int j=0;j j && check >= A){ boolean found = false; for(int z=0; z < size; z++){ if(myNumbers[z] == check) found = true; } if(!found){ count++; myNumbers[myNumIndex]=check; myNumIndex = myNumIndex+1; //System.out.println(""(""+j+"", ""+newNumber+"")""); } } } j++; } System.out.println(""Case #""+(i+1)+"": ""+count); } } catch (NumberFormatException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } " B20900,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam; import com.isotopeent.codejam.lib.SolverBase; import com.isotopeent.codejam.lib.Utils; import com.isotopeent.codejam.lib.converters.IntArrayLine; public class Solver extends SolverBase { private static final String FILE_PATH = ""C:\\codejam\\""; private static final String FILE_NAME = ""C-large""; private static final int INIT_PARAM_COUNT = 1; private static final int MAX_DIGITS = 8; // digits go from low to high place in array private static final int[] tempNumberArr = new int[MAX_DIGITS]; public static void main(String [] args) { Utils.solve(FILE_PATH, FILE_NAME, new IntArrayLine(2), new Solver()); } public Solver() { super(INIT_PARAM_COUNT); } @Override protected String solve(int[] input) { int[] min = getNumberArr(input[0]); int[] max = getNumberArr(input[1]); int length = min.length; int leadDigit = length - 1; int minLeadDigit = min[leadDigit]; int maxLeadDigit = max[leadDigit]; int permutationCount = 0; for (int shift = 1; shift < length; shift++) { for (int lead = minLeadDigit; lead <= maxLeadDigit; lead++) { int[] n = new int[length]; int[] m = new int[length]; int mLockStart = shift - 1; n[leadDigit] = lead; m[mLockStart] = lead; for (int shiftLead = lead; shiftLead <= maxLeadDigit; shiftLead++) { int nLockStart = leadDigit - shift; n[nLockStart] = shiftLead; m[leadDigit] = shiftLead; permutationCount += permutate(min, max, shift, n, nLockStart, m, mLockStart, leadDigit - 1, shiftLead > lead); } } } return Integer.toString(permutationCount); } private static int permutate(int[] min, int[] max, int shift, int[] n, int nLockStart, int[] m, int mLockStart, int digit, boolean onlyCheckBounds) { int permutationCount = 0; int nMin; int nMax; if (digit <= nLockStart) { nMin = n[digit]; nMax = nMin; } else { // TODO: optimization possible nMin = 0; nMax = 9; } int mMin; int mMax; // TODO: optimization possible if (digit <= mLockStart) { mMin = m[digit]; mMax = mMin; } else { mMin = 0; mMax = 9; } int compareSize = n.length - digit; for (int i = nMin; i <= nMax; i++) { n[digit] = i; int shiftDigit = shift - n.length + digit; if (shiftDigit >= 0) { m[shiftDigit] = i; } if (compare(n, min, compareSize) >= 0) { // still in range, so continue int j; if (!onlyCheckBounds && mMin < i) { j = i; } else { j = mMin; } for (/*j = mMin*/; j <= mMax; j++) { m[digit] = j; shiftDigit = digit - shift; if (shiftDigit >= 0) { n[shiftDigit] = j; } if (compare(m, max, compareSize) <= 0) { if (digit > 0) { permutationCount += permutate(min, max, shift, n, nLockStart, m, mLockStart, digit - 1, onlyCheckBounds || j > i); } else if (onlyCheckBounds || j > i) { // check for repetition (which causes duplicate results), can ignore if shift <= repetition size (count first instance) int start = n[0]; for (int k = 2; k < shift; k++) { if (n[k] == start) { boolean repeated = true; for (int offset = n.length - 1 - k; repeated && offset > 0; offset--) { repeated = (n[offset] == n[offset + k]); } if (repeated) { permutationCount--; } } } permutationCount++; } } } } } return permutationCount; } private static int[] getNumberArr(int number) { int length = 0; tempNumberArr[length++] = number % 10; while (number >= 10) { number /= 10; tempNumberArr[length++] = number % 10; } int[] numberArr = new int[length]; System.arraycopy(tempNumberArr, 0, numberArr, 0, length); return numberArr; } private static int compare(int[] n, int[] m, int digits) { int result = 0; int min = n.length - digits; for (int i = n.length - 1; i >= min && result == 0; i--) { result = n[i] - m[i]; } return result; } } " B21407," import codejam.StoreCredit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author java */ public class RecycledNumbers { static BufferedReader in; private static void open() { in = new BufferedReader(new InputStreamReader(System.in)); } private static void close() { try { in.close(); } catch (IOException ex) { Logger.getLogger(StoreCredit.class.getName()).log(Level.SEVERE, null, ex); } } private static int readInt() throws IOException { Integer i = Integer.parseInt(in.readLine()); return i; } private static int[] readInts() throws IOException { String[] vals = in.readLine().split("" ""); int[] arr = new int[vals.length]; for (int i = 0; i < vals.length; i++) { arr[i] = Integer.parseInt(vals[i]); } return arr; } public static void main(String[] args) throws IOException { open(); int T = readInt(); for (int t = 0; t < T; t++) { int[] arr = readInts(); int A = arr[0]; int B = arr[1]; Set set = new LinkedHashSet(); Set additionalSet = new HashSet(); while (A <= B) { String v = String.valueOf(A); set.add(A); A++; } Iterator it = set.iterator(); Set used = new LinkedHashSet(); StringBuilder b = new StringBuilder(); while (it.hasNext()) { int val = it.next(); it.remove(); b.delete(0, b.length()); b.append(val); int iteration = b.length(); boolean added = false; if (iteration > 1) { for (int i = 0; i < iteration - 1; i++) { char c = b.charAt(0); b.deleteCharAt(0); b.append(c); String newItem = b.toString(); // remove leading 0 int j = 0; // for (; j < newItem.length() && newItem.charAt(j) == '0'; j++); // newItem = newItem.sub1string(j); int newNumber = Integer.parseInt(newItem); if ((set.contains(newNumber) || additionalSet.contains(newNumber)) && !used.contains(val + ""#"" + newNumber)) { used.add(val + ""#"" + newNumber); added = true; } } } if (!added) { additionalSet.add(val); } } System.out.println(""Case #"" + (t + 1) + "": "" + used.size()); // System.out.println(used); } close(); } } " B21979,"package google.codejam; public interface GoogleSolver { String solve(String str); } " B21584,"package com.gnooo; import java.util.HashMap; import java.util.Scanner; public class Solution { static final boolean DBG = false; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); long dStart = System.currentTimeMillis(); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= T; i++) { OneTask task = new OneTask(sc.nextInt(), sc.nextInt()); long res = task.getSolution(); sb.append(""Case #""); sb.append(i); sb.append("": ""); sb.append(res); sb.append('\n'); } if (DBG) { sb.append(""time :""); sb.append(System.currentTimeMillis() - dStart); } System.out.print(sb.toString()); } static class OneTask { long a, b; public OneTask(long a, long b) { this.a = a; this.b = b; } long getSolution() { long c = 0; for (long i = a; i < b; i++) { c += numberHasRecycledPairs(a, b, i); } return c; } } static long numberHasRecycledPairs(long min, long max, long no) { String str = String.valueOf(no); final int len = str.length(); int res = 0; HashMap map = new HashMap(); for (int i = 1; i < len; i++) { long tmp = Long.parseLong(str.substring(len - i) + str.substring(0, len - i)); if (min <= tmp && tmp <= max && tmp > no) { if (!map.containsKey(tmp)) { res++; map.put(tmp, 0); } } } return res; } } " B21940,"import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Locale; import java.util.Scanner; import java.util.Set; public class C { final static String PREFIX = ""C:\\codejam\\C""; // final static String FILE_NAME = PREFIX + ""-test""; // final static String FILE_NAME = PREFIX + ""-small-attempt0""; final static String FILE_NAME = PREFIX + ""-large""; private Scanner in; private PrintWriter out; public static void main(String[] args) throws Exception { Locale.setDefault(Locale.US); new C().solveAll(); } private void solveAll() throws Exception { in = new Scanner(new File(FILE_NAME + "".in"")); out = new PrintWriter(new File(FILE_NAME + "".out"")); int tcn = in.nextInt(); for (int tc = 1; tc <= tcn; tc++) { solve(tc); } out.close(); } private void solve(int tc) { int a = in.nextInt(); int b = in.nextInt(); long res = 0; for (int i = a; i <= b; i++) { String is = String.valueOf(i); Set set = new HashSet(); for (int j = 1; j < is.length(); j++) { String x = is.substring(j) + is.substring(0, j); if (x.startsWith(""0"")) { continue; } int c = Integer.parseInt(x); if (c > i && c <= b) { set.add(c); } } res += set.size(); } out.format(""Case #%d: %s\n"", tc, res); System.out.format(""Case #%d: %s\n"", tc, res); } } " B20791,"package Qual; import java.io.*; import java.math.*; import java.util.*; public class C { static void start() throws IOException { new C().run1(); } private final String dir = ""D:\\contest\\gcj\\2012\\"" + getClass().getPackage().toString().split("" "")[1] + ""\\"" + getClass().getSimpleName(); // private final String inputFileName = ""sample.txt""; private final String inputFileName = ""C-large.in""; private final String outputFileName = ""res.txt""; int A, B; final Set st = new HashSet(); int pair(int v) { if(st.contains(v)) { return 0; } int res = 0; String s = v + """"; for(int i = 0; i < s.length(); i++) { s = s.charAt(s.length() - 1) + s.substring(0, s.length() - 1); if(s.charAt(0) != '0') { final int x = Integer.parseInt(s); if(A <= x && x <= B && !st.contains(x)) { st.add(x); res++; } } } return res * (res - 1) / 2; } final int MAX = 2000000; boolean[] visited = new boolean[MAX * 10]; int dfs(int x, int d) { if(d == 0) { // System.err.println(x + "" "" + pair(x)); return pair(x); } if(st.contains(x)) { return 0; } pair(x); int res = 0; for(int i = 0; i <= 9; i++) { if(x != 0 || i != 0) { res += dfs(x * 10 + i, d - 1); } } return res; } void run() throws IOException { int T = IOFast.nextInt(); while(T-- != 0) { A = IOFast.nextInt(); B = IOFast.nextInt(); st.clear(); int res = 0; for(int i = A; i <= B; i++) { if(!st.contains(i)) { res += pair(i); } } printCase(); IOFast.out.println(res); IOFast.out.flush(); } } void run1() throws IOException { IOFast.setReader(new FileReader(dir + ""\\"" + inputFileName)); IOFast.setWriter(new FileWriter(dir + ""\\"" + outputFileName)); run(); } private static int CASE; private static void printCase() { IOFast.out.print(""Case #"" + ++CASE + "": ""); } public static void main(String[] args) throws IOException { start(); IOFast.out.flush(); IOFast.in.close(); IOFast.out.close(); } static public class IOFast { private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter out = new PrintWriter(System.out); // private static final int BUFFER_SIZE = 50 * 200000; private static final StringBuilder buf = new StringBuilder(); private static boolean[] isDigit = new boolean[256]; private static boolean[] isSpace = new boolean[256]; static { for(int i = 0; i < 10; i++) { isDigit['0' + i] = true; } isDigit['-'] = true; isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true; } static boolean endInput; public static void setReader(Reader r) { in = new BufferedReader(r); } public static void setWriter(Writer w) { out = new PrintWriter(w); } private static int nextInt() throws IOException { boolean plus = false; int ret = 0; while(true) { final int c = in.read(); if(c == -1) { endInput = true; return Integer.MIN_VALUE; } if(isDigit[c]) { if(c != '-') { plus = true; ret = c - '0'; } break; } } while(true) { final int c = in.read(); if(c == -1 || !isDigit[c]) { break; } ret = ret * 10 + c - '0'; } return plus ? ret : -ret; } private static long nextLong() throws IOException { boolean plus = false; long ret = 0; while(true) { final int c = in.read(); if(c == -1) { endInput = true; return Integer.MIN_VALUE; } if(isDigit[c]) { if(c != '-') { plus = true; ret = c - '0'; } break; } } while(true) { final int c = in.read(); if(c == -1 || !isDigit[c]) { break; } ret = ret * 10 + c - '0'; } return plus ? ret : -ret; } private static String next() throws IOException { buf.setLength(0); while(true) { final int c = in.read(); if(c == -1) { endInput = true; return ""-1""; } if(!isSpace[c]) { buf.append((char)c); break; } } while(true) { final int c = in.read(); if(c == -1 || isSpace[c]) { break; } buf.append((char)c); } return buf.toString(); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } } } " B20984,"import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * @author Jelle Prins */ public class RecycledNumbers { public static void main(String[] args) { String input = ""input.txt""; String output = ""output.txt""; if (args.length >= 1) { input = args[0]; if (args.length >= 2) { output = args[1]; } } new RecycledNumbers(input, output); } public RecycledNumbers(String inputString, String outputString) { init(); File input = new File(inputString); File output = new File(outputString); if (!input.isFile()) { System.err.println(""input file not found""); System.exit(1); } if (output.exists()) { output.delete(); } try { String[] cases = readInput(input); String[] results = executeCases(cases); writeOutput(output, results); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private String[] readInput(File file) throws Exception { Scanner scanner = new Scanner(file); int lines = scanner.nextInt(); scanner.nextLine(); String[] cases = new String[lines]; for (int i = 0; i < lines; i++) { cases[i] = scanner.nextLine().trim(); if (cases[i] == null) { throw new Exception(""not enough input lines""); } } scanner.close(); return cases; } private String[] executeCases(String[] cases) { String[] output = new String[cases.length]; for (int i = 0; i < cases.length; i++) { output[i] = executeCase(i + 1, cases[i]); } return output; } private String parseOutput(int caseID, String answer) { String output = ""Case #"" + caseID + "": "" + answer; System.out.println(output); return output; } private void writeOutput(File output, String[] results) throws Exception { PrintWriter pw = new PrintWriter(new FileWriter(output)); for (int i = 0; i < results.length; i++) { pw.println(results[i]); } pw.close(); } private void init() { } private String executeCase(int caseID, String input) { String[] split = input.split("" ""); int start = Integer.parseInt(split[0]); int end = Integer.parseInt(split[1]); int answer = 0; char[] chars; for (int n = start; n < end; n++) { chars = getNumberChars(n); if (chars == null) { continue; } answer += recycle(n, chars, end); } return parseOutput(caseID, """" + answer); } /** * Returns null if the number can't be recycled */ private char[] getNumberChars(int n) { if (n < 10) { return null; } char[] chars = Integer.toString(n).toCharArray(); int validChars = 0; for (char c : chars) { if (c != '0') { validChars++; } } if (validChars < 2) { return null; } return chars; } private int recycle(int n, char[] chars, int end) { char[] recycle = new char[chars.length]; Set found = new HashSet(); String str; int answer; int recycleTimes = 0; for (int i = 1; i < chars.length; i++) { System.arraycopy(chars, i, recycle, 0, chars.length - i); System.arraycopy(chars, 0, recycle, chars.length - i, i); str = new String(recycle); answer = Integer.parseInt(str); if (answer > n && answer <= end) { if (found.add(str)) { recycleTimes++; } } } return recycleTimes; } } " B20685,"import java.util.*; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); C th = new C(); for (int i = 0; i < T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int c = th.getAnswer(A, B); System.out.println(""Case #"" + (i+1) + "": "" + c); } } public int getAnswer(int A, int B) { if (A == B) { return 0; } int count = 0; for (int i = A; i < B; i++) { String s = """" + i; int l = s.length(); int[] it = new int[l]; for (int j = 0; j < l; j++) { String t = getRotate(s, j+1); it[j] = Integer.parseInt(t); if (it[j] <= B && it[j] > i) { boolean f = true; for (int k = 0; k < j; k++) { if (it[k] == it[j]) f = false; } if (f) count++; } } } return count; } public String getRotate(String s, int r) { char[] ch = s.toCharArray(); int n = ch.length; char[] buf = new char[n]; for (int i = 0; i < r; i++) { buf[n-r+i] = ch[i]; } for (int i = 0; i < n-r; i++) { buf[i] = ch[r+i]; } return new String(buf); } } " B20227,"import java.io.File; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File(""input"")); System.setOut(new PrintStream(""output"")); int T = in.nextInt(); for (int t = 1; t <= T; t++) { System.out.print(""Case #"" + t + "": ""); int a = in.nextInt(), b = in.nextInt(); int count = 0; for (int i = a; i <= b; i++) { HashSet set = new HashSet(); char[] x = String.valueOf(i).toCharArray(); int n = x.length; char[] y = new char[n]; for (int j = 0; j < n; j++) if (x[j] != '0') { for (int k = 0; k < n; k++) y[k] = x[(j + k) % n]; int k = Integer.parseInt(String.valueOf(y)); if (set.contains(k)) continue; set.add(k); if (k != i && a <= k && k <= b) count++; } } System.out.println(count/2); } } } " B20648,"package codejam.qualification; import java.io.IOException; import java.util.HashSet; import java.util.Set; import codejam.Task; public class C extends Task { private int t; private String[][] testCases; private String[] resultset; public C(String[] args) { super(args); } public static void main(String[] args) throws IOException { Task taskC = new C(args); taskC.execute(); } protected void catchInputData() throws IOException { t = Integer.parseInt(readLine()); testCases = new String[t][]; // iterates over cases for (int c = 0; c < t; c++) { testCases[c] = readLine().split("" ""); } } protected void processInputData() { resultset = new String[t]; // iterates over cases for (int c = 0; c < t; c++) { String[] testCase = testCases[c]; int a = Integer.parseInt(testCase[0]); int b = Integer.parseInt(testCase[1]); int y = 0; for (int n = a; n < b; n++) { Set mset = new HashSet(); String sn = String.valueOf(n); for (int i = 1; i < sn.length(); i++) { if (sn.charAt(i) != '0') { String sm = sn.substring(i) + sn.substring(0, i); int m = Integer.parseInt(sm); if (m > n && m <= b && !mset.contains(m)) { y++; mset.add(m); } } } } resultset[c] = """"+y; } } protected void generateOutputFile() throws IOException { // iterates over cases for (int c = 0; c < t; c++) { writeLine(""Case #"" + (c + 1) + "": "" + resultset[c]); } } } " B21874,"import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { static ArrayList list=new ArrayList(); public static void main(String[] args) { int pow[]=new int[10]; for(int i=0;i<10;i++){ pow[i]=(int)Math.pow(10, i); } Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i0;k*=10) keta++; list.clear(); for(int k=0;k found = new HashSet(); int div = 1, mul = (int) Math.pow(10, si.length()); for (int j = 1; j < si.length(); j++) { div *= 10; mul /= 10; int other = (i % div) * mul + (i / div); //String sj = si.substring(j) + si.substring(0, j); //int other = Integer.parseInt(sj); if (!found.contains(other) && other > i && other <= b) { found.add(other); count++; } } } System.out.println(""Case #"" + (test+1) + "": "" + count); } } } " B20617,"import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static int[] POWER_OF_10 = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; public static int rotate(int n, int offset) { return (n % POWER_OF_10[offset]) * POWER_OF_10[(int) Math.log10(n) + 1 - offset] + (n / POWER_OF_10[offset]); } public static int count(int low, int high) { int count = 0; if (low < 10) { low = 10; } HashSet group = new HashSet(); for (int i = low; i < high; i++) { int numDigit = (int) Math.log10(i) + 1; while (numDigit > 0) { int num = rotate(i, numDigit--); if (num > i && num <= high && !group.contains(num)) { count++; group.add(num); } } group.clear(); } return count; } public static void main(String[] args) { final Scanner in = new Scanner(System.in); final int numCase = in.nextInt(); in.nextLine(); for (int i = 0; i < numCase; i++) { int low = in.nextInt(); int high = in.nextInt(); System.out.println(""Case #"" + (i+1) + "": "" + count(low, high)); in.nextLine(); } } } " B21284," import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class ProblemC { public static int eval(int A, String n, int B){ int r = 0; for(int i = 1; i < n.length(); i++){ int nn = Integer.parseInt((n)); String ini = n.substring(0, n.length() - i); String end = n.substring(n.length() - i); if(Integer.parseInt(String.valueOf(end.charAt(0))) >= Integer.parseInt(String.valueOf(ini.charAt(0)))){ int m = Integer.parseInt((end+ini)); if( A <= m && nn < m && m <= B ){ r++; } } } return r; } public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); PrintWriter pw = new PrintWriter(new FileWriter(""C.out"")); int cas = s.nextInt(); for( int i = 0; i < cas; i++){ int r = 0; int A = s.nextInt(); int B = s.nextInt(); for(int n = A; n <= B; n++){ r += eval(A,String.valueOf(n),B); } //System.out.println(""Case #""+(i+1)+"": ""+r); pw.println(""Case #""+(i+1)+"": ""+r); } pw.close(); s.close(); } } " B21054," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; public class reycle { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-large.out""))); boolean state[] = new boolean[2000001]; HashSet mem=new HashSet(); int t = Integer.parseInt(in.readLine()); for (int q = 1; q <= t; q++) { String[] st = in.readLine().split("" ""); int A = Integer.parseInt(st[0]); int B = Integer.parseInt(st[1]); int count = 0; for (int i = A; i <= B; i++) { state[i] = true; String temp = i + """"; for (int j = 1; j < temp.length(); j++) { String r = temp.substring(j) + temp.substring(0, j); int b = Integer.parseInt(r); if ((b + """").length() == temp.length() && b >= A && b <= B && !state[b]&&!mem.contains(b)) { mem.add(b); count++; } } mem.clear(); } out.write(""Case #""+q+"": ""+count+""\n""); Arrays.fill(state, false); } out.close(); } } " B20610,"package qualification; import java.io.FileInputStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Created by IntelliJ IDEA. * User: Yuri * Date: 14.04.12 * Time: 12:18 * To change this template use File | Settings | File Templates. */ public class Task3 { static int divider; static int recycle(int a) { int mod = a % divider; int digit = a / divider; return (mod * 10) + digit; } public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(new FileInputStream(""task32.txt"")); int N = scanner.nextInt(); Set set = new HashSet(); for (int n = 0; n < N; n++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int digitsCount = String.valueOf(a).length(); divider = (int) Math.pow(10, digitsCount - 1); int count = 0; for (int c = a; c <= b; c++) { set.clear(); int recycled = c; for (int i = 0; i < digitsCount - 1; i++) { recycled = recycle(recycled); if (recycled <= b && recycled > c) { if (! set.contains(recycled)) { set.add(recycled); count++; } } } } System.out.println(""Case #"" + (n + 1) + "": "" + count); } } } " B20233,"import java.io.*; import java.util.*; import java.math.*; public class Main implements Runnable { static Scanner scanner; static BufferedReader input; static PrintWriter pw; public static void main(String[] args) throws Exception { new Thread(new Main()).start(); } public void run() { try { input = new BufferedReader(new FileReader(""input.txt"")); scanner = new Scanner(input); pw = new PrintWriter(new File(""output.txt"")); solve(); pw.close(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } public void solve() throws Exception { int T = scanner.nextInt(); for(int t = 0; t < T; t++) { int A = scanner.nextInt(); int B = scanner.nextInt(); String AA = String.valueOf(A); String BB = String.valueOf(B); int dd = AA.length(); // digit int ans = 0 ; int n,idx; int[] m = new int[dd]; int[] f = new int[dd]; for ( n = A ; n < B ; n++ ) { for (idx = 1 ; idx < dd ; idx++ ) { m[idx] = this.recycle ( n , idx ); f[idx] = 0 ; if ( String.valueOf(m[idx]).length() == dd ) { if ( m[idx] > n && m[idx] <= B ) { f[idx]=1; ans++; } } } for ( int i=0 ; i < dd ; i++ ){ if ( f[i] == 1 ) { for ( int j = i+1 ; j < dd ; j++) { if ( m[i] == m[j] ) { ans--; } } } } } pw.println(""Case #"" + (t+1) + "": "" + ans); } } public int recycle (int i, int index){ return Integer.parseInt ( this.recycle ( String.valueOf(i),index ) ) ; } public String recycle (String s, int index){ return s.substring(index, s.length()) + s.substring( 0, index ); } } " B21165,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.common; import java.io.IOException; /** * * @author jim */ public class AbstractMain { public static void main(String[] args, AbstractProcessor p) { FileLoader fileLoader = new FileLoader(); try { Input input = new Input(fileLoader.loadFile(args[0]), 1); Output output = p.process(input); output.export(args.length < 2 ? null : args[1]); } catch (IOException ioe) { System.out.println(ioe); ioe.printStackTrace(); } } } " B21339,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Ari */ public class ProblemC { static String in = ""src/c.in""; static String out = ""src/c.out""; public static void main(String[] args) throws FileNotFoundException, IOException { Scanner scan = new Scanner(new File(in)); BufferedWriter write = new BufferedWriter(new FileWriter(out)); int numlines = scan.nextInt(); String mini; String maxi; byte[] min = new byte[7]; byte[] max = new byte[7]; byte[] iter = new byte[7]; int numDigits; int numPossible; int answer; int[] rots = new int[7]; byte currentRots; byte compare = 0; //Loop vars: int x; int y; int d; int m; int n; int rot; int count; for(x = 0; x < numlines; x++) { write.write(""Case #"" + (x+1) + "": ""); mini = scan.next(); maxi = scan.next(); answer = 0; numPossible = Integer.parseInt(maxi) - Integer.parseInt(mini); numDigits = mini.length(); for(y = 0; y < numDigits; y++) { min[y] = Byte.parseByte(""""+mini.charAt(y)); iter[y] = min[y]; max[y] = Byte.parseByte(""""+maxi.charAt(y)); } for(count = 0; count < numPossible; count++) { currentRots = 0; for(rot = 1; rot < numDigits; rot++) { compare = 0; for(d = 0; d < numDigits - 1; d++) { compare = iter[(d + rot) % numDigits]; if(compare > iter[d]) { compare = -2; break; } else if(compare < iter[d]) { compare = -1; break; } } if(compare > -1) { if(iter[(numDigits + rot - 1) % numDigits] > iter[numDigits - 1]) { compare = -2; } } if(compare == -2) {//rotation is greater for(d = 0; d < numDigits; d++) { compare = iter[(d + rot) % numDigits]; if(compare > min[d]) { compare = 1; break; } else if(compare < min[d]) { compare = -1; break; } } if(compare > -1) {//>=min for(d = 0; d < numDigits; d++) { compare = iter[(d + rot) % numDigits]; if(compare > max[d]) { compare = -1; break; } else if(compare < max[d]) { compare = 1; break; } } if(compare > -1) {//<=max rots[currentRots] = rot; currentRots++; answer++; } } } } for(n = 0; n < currentRots-1; n++) { for(m = n+1; m < currentRots; m++) { for(d = 0; d < numDigits; d++) { compare = iter[(d + rots[n]) % numDigits]; compare -= iter[(d + rots[m]) % numDigits]; if(compare != 0) { compare = 1; break; } } if(compare == 0) { answer--; break; } } } for(d = numDigits-1; d >= 0; d--) { if(iter[d] == 9) { iter[d] = 0; } else { iter[d]++; break; } } } write.write("""" + answer); write.write('\n'); } scan.close(); write.close(); } private static void print(byte[] iter, int rot) { for(int d = 0; d < iter.length; d++) { System.out.print(""""+iter[(d + rot) % iter.length]); } } private static int get(byte[] iter, int rot, int length) { String s = """"; for(int d = 0; d < length; d++) { s+=iter[(d + rot) % length]; } return Integer.parseInt(s); } } " B20813,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; public class C { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(""c.in""))); PrintStream out = new PrintStream(new FileOutputStream(""c.out"")); long start = System.currentTimeMillis(); long count = readInt(in); for (int i = 0; i < count; i++) { String[] data = in.readLine().split("" ""); int a = Integer.parseInt(data[0]); int b = Integer.parseInt(data[1]); int ans = 0; HashSet st = new HashSet(); for (int k = a; k<=b ; k++) { String s = """" + k; char c = s.charAt(0); st.clear(); for (int p = 1; p < s.length(); p++) { if (s.charAt(p) >= c) { String ts = s.substring(p) + s.substring(0, p); int t = Integer.parseInt(ts); if (t > k && a<= t && t <=b) { if (!st.contains(t)) { ans++; //System.out.println(k + "" "" + t); st.add(t); } } } } } out.println(""Case #"" + (i + 1) + "": "" + ans); } out.flush(); out.close(); System.out.println(System.currentTimeMillis() - start); } private static long readInt(BufferedReader in) { try { return Long.parseLong(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } } " B20161,"package com.google.codejam.recyclednumbers; import java.io.*; import java.util.*; public class RecycledNumbers { private static String filename = ""large""; public static void main(String[] args) throws Exception { RandomAccessFile input = new RandomAccessFile(filename + ""_in.txt"", ""r""); RandomAccessFile output = new RandomAccessFile(filename + ""_out.txt"", ""rw""); int cases = Integer.valueOf(input.readLine()); for(int i = 0; i < cases; i++){ String[] nrs = input.readLine().split("" ""); int A = Integer.valueOf(nrs[0]); int B = Integer.valueOf(nrs[1]); long solved = solve(A, B); System.out.println(""Case #"" + (i + 1) + "": "" + solved); output.writeBytes(""Case #"" + (i + 1) + "": "" + solved + ""\n""); } output.close(); input.close(); } private static long solve(int A, int B){ long count = 0L; HashMap> hash = new HashMap>(); for(int n = A; n <= B; n++){ String a = String.valueOf(n); hash.put(a, new ArrayList()); for(Integer i : permute(a)){ if((i <= n) || (i > B))continue; if(hash.get(a).contains(i))continue; hash.get(a).add(i); count++; } } return count; } private static ArrayList permute(String a){ ArrayList permuted = new ArrayList(); for(int n = 1; n < a.length(); n++){ if(a.charAt(n) == '0')continue; Integer p = Integer.valueOf(a.substring(n) + a.substring(0, n)); if(!permuted.contains(p))permuted.add(p); } return permuted; } @SuppressWarnings(""unused"") private static long solved(int A, int B){ long count = 0; String a; String b; for(int n = A; n < B; n++){ a = String.valueOf(n); for(int k = n + 1; k <= B; k++){ b = String.valueOf(k); if(a.length() != b.length())continue; for(int i = 0; i < b.length(); i++){ if(a.charAt(i) == b.charAt(0)){ boolean match = true; for(int j = 0; j < b.length(); j++){ if(b.charAt(j) != a.charAt((i + j) % b.length())){ match = false; break; } } if(match){ count++; i++; break; } } } } } return count; } } " B20502,"import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.TreeSet; public class C { public ArrayList hash = new ArrayList(); public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); for (int i = 0; i < t; i++) { C c = new C(); int y = 0; int A = scanner.nextInt(); int B = scanner.nextInt(); for (int j = A; j <= B; j++) { // if(!c.hash.contains(j)) { // System.out.println(""j=""+j); y += c.permut(j, A, B); // } } System.out.println(""Case #""+(i+1)+"": ""+y); } } public int permut(int j, int A, int B) { int y = 0; String sj = """"+j; int newJ = 0; while(newJ != j) { char lastDigit = sj.charAt(sj.length()-1); String frontNumber = sj.substring(0, sj.length()-1); sj = lastDigit + frontNumber; newJ = Integer.parseInt(sj); // System.out.print(newJ); if(newJ >= A && newJ <= B && newJ > j) { y++; // if(!hash.contains(newJ)) { // hash.add(newJ); // System.out.print("" p""); // } } // System.out.println(); } // System.out.println(); return y; } } " B22242,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class ProblemC { public static void main(String[] args) throws NumberFormatException, IOException{ BufferedReader reader=new BufferedReader(new FileReader(new File(args[0]))); int numTestCases=Integer.parseInt(reader.readLine()); String[] split; for (int testCase=0; testCase iCanHasPair=new HashSet(); int result=0; for (int i=a; i<=b; i++){ curr=String.valueOf(i); boolean inRange; for (int k=1; kb){ inRange=false; break; } } if (currVal L = new ArrayList(); int caseIdx; for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { L.add(freader.nextLine()); } for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { System.out.print(""Case #"" + (caseIdx + 1) + "": ""); char chr [] = L.get(caseIdx).toCharArray(); for(int i = 0; i < chr.length; i++) { if(chr[i] == ' ') continue; chr[i] = GtoE[chr[i] - 'a']; } System.out.println(chr); } } catch(Exception e) { e.printStackTrace(); } } public static void solveRC() { try{ freader = new Scanner( new File(""C:/Users/Ben/Documents/NetBeansProjects/CodeJam/src/1a2011/C-large.in"")); caseCount = freader.nextInt(); freader.nextLine(); int caseIdx; for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { System.out.print(""Case #"" + (caseIdx+1) + "": ""); int A = freader.nextInt(); int B = freader.nextInt(); int result = RC(A,B); System.out.println(result); freader.nextLine(); } } catch(Exception e) { e.printStackTrace(); } } public static int RC(int A, int B) { int count = 0; ArrayList iL, T; T = new ArrayList(); for(int i = A; i < B; i++) { iL = convertNumToArray(i); T.clear(); for(int j = 0; j < iL.size()-1; j++) { shift(iL); int v = value(iL); if(v > i && v <= B){ if(!T.contains(v)) T.add(v); } } count += T.size(); } return count; } public static void shift(ArrayList L) { int size = L.size(); Integer temp = L.get(size-1); for(int j = size-1; j > 0; j--) { L.set(j, L.get(j-1)); } L.set(0, temp); } public static int value(ArrayList L) { int value = 0; for(Integer I : L) { value = (value * 10) + I.intValue(); } return value; } public static boolean recycled(ArrayList iL, ArrayList jL) { boolean equal; int size = iL.size(); for(int i = 0; i < size; i++) { equal = true; //compare iL and jL for(int j = 0; j < size; j++) { if(iL.get(j).intValue() != jL.get(j).intValue()) { equal = false; break; } } if(equal) return true; //shift iL Integer temp = iL.get(size-1); for(int j = size-1; j > 0; j--) { iL.set(j, iL.get(j-1)); } iL.set(0, temp); } return false; } public static ArrayList convertNumToArray(int x) { ArrayList L = new ArrayList(); while(x > 0) { int r = x % 10; L.add(0, new Integer(r)); x = x / 10; } return L; } public static void sovleDWG() { try{ freader = new Scanner( new File(""C:/Users/Ben/Documents/NetBeansProjects/CodeJam/src/1a2011/B-large.in"")); caseCount = freader.nextInt(); freader.nextLine(); int caseIdx; for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { System.out.print(""Case #"" + (caseIdx+1) + "": ""); int n = freader.nextInt(); int s = freader.nextInt(); int p = freader.nextInt(); int T [] = new int [n]; for(int i = 0; i < n; i++){ T[i] = freader.nextInt(); } int count = DWG(T, n, s, p); System.out.println(count); freader.nextLine(); } } catch(Exception e) { e.printStackTrace(); } } public static int DWG(int [] T, int n, int s, int p) { int minSup = p + 2 * max(p-2,0); int minNonSup = p + 2 * max(p-1,0); int count = 0; int maybe = 0; for(int i = 0; i < n; i++) { int curr = T[i]; if(curr >= minNonSup) { count++; } else if(curr < minNonSup && curr >= minSup) { maybe++; } } count = count + min(maybe, s); return count; } public static int min(int x, int y) { if (x < y){ return x; } return y; } public static int max(int x, int y) { if (x > y){ return x; } return y; } public static void solveKiller() { try{ freader = new Scanner( new File(""C:/Users/Ben/Documents/NetBeansProjects/CodeJam/src/1a2011/B-large-practice.in"")); caseCount = freader.nextInt(); freader.nextLine(); int caseIdx; for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { System.out.print(""Case #"" + (caseIdx+1) + "": ""); int n = freader.nextInt(); int m = freader.nextInt(); ArrayList L = new ArrayList(n); for(int i = 0; i < n; i++){ L.add(freader.next()); } String kword = null; int score, worst; for(int j = 0; j < m; j++) { String todo = freader.next(); worst = 1; for(int i = 0; i < n; i++) { score = killer(L.get(i), todo, (ArrayList)L.clone()); if(score < worst) { worst = score; kword = L.get(i); } } if(j == m-1) System.out.print(kword); else System.out.print(kword + "" ""); freader.nextLine(); } System.out.println(); } } catch(Exception e) { e.printStackTrace(); } } public static int killer(String word, String todo, ArrayList dict) { int score = 0; int index [] = new int [26]; updateTodo(todo, dict, index); char guess [] = new char [word.length()]; for(int i = 0; i < word.length(); i++) { guess[i] = '*'; } dict = updateDict(dict, guess); int j = 0; while(j < 26) { while(index[j] == 0) { ++j; if(j >= 26) return score; } if(!updateGuess(guess, word, todo.charAt(j))){ score--; dict = filter(dict, todo.charAt(j)); } dict = updateDict(dict, guess); updateTodo(todo, dict, index); ++j; } return score; } public static ArrayList filter(ArrayList dict, char c) { ArrayList result = new ArrayList(); for(String str : dict) { if(str.indexOf(c) < 0) { result.add(str); } } return result; } public static ArrayList updateDict(ArrayList dict, char [] guess) { ArrayList result = new ArrayList(); for(String str : dict){ if(matches(str,guess)){ result.add(str); } } return result; } public static boolean matches(String str, char [] guess) { if(str.length() != guess.length) return false; for(int i = 0; i < guess.length; i++) { if(guess[i] == '*') { continue; } else if(guess[i] != str.charAt(i)) { return false; } } return true; } public static void updateTodo(String todo, ArrayList dict, int [] index) { for(int i = 0; i < index.length; i++) index[i] = 0; for(String str : dict) { for(int i = 0; i < str.length(); i++) { index[todo.indexOf(str.charAt(i))] = 1; } } } public static boolean updateGuess(char [] guess, String word, char c) { boolean found = false; for(int i = 0; i < word.length(); i++){ if(word.charAt(i) == c){ guess[i] = c; found = true; } } return found; } public static void solveFreeCell() { try{ freader = new Scanner( new File(""C:/Users/Ben/Documents/NetBeansProjects/CodeJam/src/1a2011/A-large-practice.in"")); caseCount = freader.nextInt(); freader.nextLine(); int caseIdx; for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { System.out.print(""Case #"" + (caseIdx+1) + "": ""); BigInteger n = new BigInteger(freader.next()); long pd = freader.nextInt(); long pg = freader.nextInt(); if(pd > 0 && pg == 0) { System.out.println(""Broken""); continue; } if(pd == 0 && pg == 100) { System.out.println(""Broken""); continue; } if(pd == 0 && pg != 100) { System.out.println(""Possible""); continue; } if(pd < 100 && pg == 100) { System.out.println(""Broken""); continue; } if(n.compareTo(new BigInteger(""100"")) >= 0){ System.out.println(""Possible""); continue; } double den; long div; div = gcd(pd, 100); den = (double)100/div; if(den > n.intValue()) { System.out.println(""Broken""); continue; } System.out.println(""Possible""); freader.nextLine(); } } catch(Exception e) { e.printStackTrace(); } } public static long gcd(long x, long y) { while(x != y) { //System.out.println(x + "" "" + y); if(x > y) { x = x - y; } else{ y = y - x; } } return x; } public static void solveMagika() { try{ freader = new Scanner( new File(""C:/Users/Ben/Documents/NetBeansProjects/CodeJam/src/codejam/B-large-practice.in"")); caseCount = freader.nextInt(); freader.nextLine(); int caseIdx; for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { TreeMap oppMap = new TreeMap(); TreeMap comMap = new TreeMap(); ArrayList list = new ArrayList(); int c = freader.nextInt(); for(int i = 0; i < c; i++) { String str = freader.next(); String rev = new StringBuffer(str.substring(0,2)).reverse().toString(); comMap.put(str.substring(0, 2), str.substring(2)); comMap.put(rev.substring(0, 2), str.substring(2)); } int d = freader.nextInt(); for(int i = 0; i < d; i++) { String str = freader.next(); String rev = new StringBuffer(str).reverse().toString(); oppMap.put(str, str); oppMap.put(rev, rev); } int n = freader.nextInt(); String todo = freader.next(); //System.out.println(todo); Magika(caseIdx+1, n, todo, comMap, oppMap, list); freader.nextLine(); } } catch(Exception e) { e.printStackTrace(); } } public static void Magika(int caseIdx, int n, String todo, TreeMap comMap, TreeMap oppMap, ArrayList list) { list.add(todo.substring(0,1)); for(int i = 1; i < n; i++) { list.add(todo.substring(i,i+1)); int size = list.size(); if(size >= 2){ String newElement = comMap.get( list.get(size-2).concat(list.get(size-1)) ); if(newElement != null) { list.remove(list.size()-1); list.remove(list.size()-1); list.add(newElement); } } check(oppMap, list); } System.out.print(""Case #"" + caseIdx + "": [""); if(list.isEmpty()) { System.out.println(""]""); } else { for(int i = 0; i < list.size()-1; i++) { System.out.print(list.get(i) + "", ""); } System.out.println(list.get(list.size()-1) + ""]""); } } public static void check(TreeMap oppMap, ArrayList list) { int size = list.size(); for(int j = 0; j < size-1; j++) { for(int k = 0; k < size; k++) { if(oppMap.containsKey(list.get(j).concat(list.get(k)))) { list.clear(); return; } } } } public static void solveBotTrust() { try{ freader = new Scanner( new File(""C:/Users/Ben/Documents/NetBeansProjects/CodeJam/src/codejam/A-large-practice.in"")); caseCount = freader.nextInt(); freader.nextLine(); int caseIdx; for(caseIdx = 0; caseIdx < caseCount; caseIdx++) { int n = freader.nextInt(); int buttons [] = new int [n]; String robots [] = new String [n]; int i; for(i = 0; i < n; i++) { robots[i] = freader.next(); buttons[i] = freader.nextInt(); } BotTrust(caseIdx+1, robots, buttons, n); freader.nextLine(); } } catch(Exception e) { e.printStackTrace(); } } public static void BotTrust(int caseIdx, String [] robots, int [] buttons, int n) { int turn, seconds; boolean buttonPressed; Robot B, O, active, passive; turn = 0; seconds = 0; B = new Robot(""B""); O = new Robot(""O""); for(int i = 0; i < n; i++) if(robots[i].equals(""B"")){ B.nextPosition = buttons[i]; break; } for(int i = 0; i < n; i++) if(robots[i].equals(""O"")){ O.nextPosition = buttons[i]; break; } // System.out.println(""orange pos : "" + O.nextPosition); // System.out.println(""blue pos : "" + B.nextPosition); while(turn < n) { seconds++; buttonPressed = false; if(robots[turn].equals(""O"")){ active = O; passive = B; } else{ active = B; passive = O; } int moveIncr; if(active.currPosition == active.nextPosition){ moveIncr = 0; }else if(active.currPosition < active.nextPosition){ moveIncr = 1; }else{ moveIncr = -1; } if(moveIncr == 0) { buttonPressed = true; } else{ active.currPosition = active.currPosition + moveIncr; } if(passive.currPosition == passive.nextPosition){ moveIncr = 0; }else if(passive.currPosition < passive.nextPosition){ moveIncr = 1; }else{ moveIncr = -1; } passive.currPosition = passive.currPosition + moveIncr; if(buttonPressed){ turn++; for(int i = turn; i < n; i++){ if(robots[i].equals(active.name)) { active.nextPosition = buttons[i]; break; } } } } System.out.println(""Case #"" + caseIdx + "": "" + seconds); } private static class Robot { int currPosition, nextPosition; String name; public Robot(String _name) { currPosition = 1; nextPosition = 0; name = _name; } } } " B22109," public class Par { Integer A,B; public Par(Integer a,Integer b) { A=a; B=b; } public boolean equals(Object o) { boolean res=false; Par P=(Par) o; if ((P.A.equals(A) && P.B.equals(B))||(P.A.equals(B) && P.B.equals(A))) { res=true; } return res; } public int hashCode() { return (A*B+A.hashCode()+B.hashCode()); } public String toString() { return ""(""+A+"", ""+B+"")""; } } " B20209,"import java.io.*; import java.util.*; public class Recycled { public static class Pair { public String a; public String b; public Pair(String a, String b) { this.a = a; this.b = b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (a != null ? !a.equals(pair.a) : pair.a != null) return false; if (b != null ? !b.equals(pair.b) : pair.b != null) return false; return true; } @Override public int hashCode() { int result = a != null ? a.hashCode() : 0; result = 31 * result + (b != null ? b.hashCode() : 0); return result; } } public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(new FileWriter(""C-large.out"")); int cases = Integer.valueOf(in.readLine().trim()); for (int i =0; i < cases; i++) { StringTokenizer st = new StringTokenizer(in.readLine().trim()); int a = Integer.valueOf(st.nextToken().trim()); int b = Integer.valueOf(st.nextToken().trim()); int pairs = solve(a, b); out.println(String.format(""Case #%d: %d"", i+1, pairs)); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static int solve(int a, int b) { Set pairs = new HashSet(); String aStr = String.valueOf(a); String bStr = String.valueOf(b); int digits = aStr.length(); for (int i = a; i < b; i++) { String iStr = String.valueOf(i); String s = iStr+iStr; for (int j = 0; j < digits; j++) { String recycled = s.substring(j, j + digits); if (recycled.compareTo(iStr) > 0 && recycled.compareTo(bStr) <= 0) { pairs.add(new Pair(iStr, recycled)); } } } return pairs.size(); } } " B20497,"package com.google.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import javax.sound.sampled.DataLine; public class RecycleNumber { /** * @param args */ public static void main(String[] args) { recycleNumbers(args[0]); // System.out.println(""No. of recycled possibilities: "" + recycleNumber(""128 986"")); } private static void recycleNumbers(String fileName) { File f = new File(fileName); BufferedReader fin; try { fin = new BufferedReader(new InputStreamReader(new FileInputStream(f))); int noOfInputs = Integer.valueOf(fin.readLine()); String[] inputs = readSamplesFromFile(noOfInputs, fin); BufferedWriter fout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(""/Users/asachwani/Desktop/CodeJam/Output.txt""))); for (int i = 0; i < noOfInputs; i++) { System.out.println(i + 1 + "" "" + inputs[i]); fout.write(""Case #"" + (i + 1) + "": "" + recycleNumber(inputs[i]) + ""\n""); } fout.flush(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static int recycleNumber(String input) { String[] data = input.split("" ""); int minValue = Integer.valueOf(data[0]); int maxValue = Integer.valueOf(data[1]); int noOfPossibilities = 0; char[] minValueChar = String.valueOf(minValue).toCharArray(); HashSet uniquePairs = new HashSet(); if (minValueChar.length > 1) { for (int j = 0; j < minValueChar.length - 1; j++) { for (int k = minValue; k < maxValue; k++) { int lastDigits = k % (int) Math.pow(10, j + 1); int firstDigits = k / (int) Math.pow(10, j + 1); int replacement = 0; if (lastDigits != firstDigits) { replacement = Integer.valueOf("""" + lastDigits + firstDigits); } if (replacement > k && replacement <= maxValue) { if (!uniquePairs.contains(k + "" "" + replacement) || uniquePairs.contains(replacement + "" "" + k)) { noOfPossibilities++; uniquePairs.add(k + "" "" + replacement); System.out.println(k + "" "" + j + "" "" + lastDigits + "" "" + firstDigits + "" "" + replacement); } } } } } return noOfPossibilities; } private static String[] readSamplesFromFile(int noOfInputs, BufferedReader fin) throws IOException { String[] samples = new String[noOfInputs]; for (int i = 0; i < noOfInputs; i++) { samples[i] = fin.readLine(); } return samples; } } " B20475,"import java.util.*; import java.io.*; import java.lang.*; class RecycledNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = Integer.parseInt(sc.nextLine()); boolean[] taken = new boolean[2000001]; for (int i=0; i 1) { //System.out.println(j+"" ""+c); int r = 0; for (int k=c-1; k>=1; k--) r += k; count += r; } } } /*int cc= 0; for (int a=A; a<=B; a++) { for (int b=a+1; b<=B; b++) { boolean found = false; for (int k=1; k0) { goo=0; A = sc.nextInt(); B = sc.nextInt(); temp = A; len=1; while(temp>=10) { temp = temp/10; len++; } System.out.println(A+ "" "" +B+ "" "" +len); for(int i=A; iA && no<=B && no>i){ //pw.println(i+"",""+no+"",""+j); goo++; } } } System.out.println(goo); pw.println(""Case #""+ ++count +"": ""+ goo); pw.flush(); T--; } pw.close(); }catch(Exception e){} } } " B21115,"/** * * @author amit */ import java.io.*; import java.util.HashSet; import java.util.Set; //import java.util.Arrays; //import java.math.BigInteger; public class GCJ { BufferedReader rin; BufferedWriter wout; int numCases; public String calculate(long A, long B) { long count =0; for(long i=A;i set = new HashSet(); for(int k=0;k<=Bl-Al;k++) { //System.out.println(""\n""+s); for(int j=0;j=A && num<=B && i 0){ n++; a /= 10; } return n; } public static void main(String[] args){ File in = new File(args[0]); File out = new File(""c.out""); FileOutputStream w = null; Scanner s = null; try{ w = new FileOutputStream(out); s = new Scanner(in); } catch (FileNotFoundException e) {} int n = s.nextInt(); for (int i = 1; i <= n; i++){ long a = s.nextLong(); long b = s.nextLong(); byte an = numberOfDigits(a); long count = 0; for(long j = a; j<=b; j++){ List l = new LinkedList(); long num = j; for (byte k = 1; k < an; k++){ num = shift(num, an); if ((num > j) && (num <= b) && !l.contains(num)){ l.add(num); count++; } } } try { w.write((""Case #""+ i +"": ""+count+""\r\n"").getBytes()); } catch (IOException e) { } } try { w.close(); s.close(); } catch (IOException e) {} } } " B20226,"package bsevero.codejam.qualification; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private static Set FOUND_PAIRS = new HashSet(); public static int recycle(String minStr, String maxStr) { FOUND_PAIRS = new HashSet(); int min = Integer.valueOf(minStr); int max = Integer.valueOf(maxStr); int total = 0; for(int i = min; i <= max; i++) { total += calculate(i, min, max); } return total; } private static int calculate(int value, int min, int max) { String valueStr = String.valueOf(value); if(valueStr.length() < 2) { return 0; } int count = 0; for(int numDigits = 1; numDigits < valueStr.length(); numDigits++) { String newValueStr = valueStr.substring(valueStr.length() - numDigits, valueStr.length()) + valueStr.substring(0, valueStr.length() - numDigits); int newValue = Integer.valueOf(newValueStr); if(newValue > value && newValue <= max) { if(!FOUND_PAIRS.contains(value + "" "" + newValue)) { FOUND_PAIRS.add(value + "" "" + newValue); count++; } } } return count; } } " B20143,"package CodeJam2012.Qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class ProblemC { private static final String DIRECTORIO = ""D:\\CodeJam\\CodeJam2012\\Qualification\\ProblemC\\""; private static final String FILE_IN = ""ejemplo.in""; // private static final String FILE_IN = ""A-small-practice.in""; // private static final String FILE_IN = ""A-small-attempt0.in""; // private static final String FILE_IN = ""A-large.in""; private static final String FILE_OUT = ""ejemplo.out""; // private static final String FILE_OUT = ""a-small-practice.out""; // private static final String FILE_OUT = ""a-small.out""; // private static final String FILE_OUT = ""a-large.out""; public static void main(String[] args) throws Exception { // Se prepara para leer del fichero y escribir FileReader fr = new FileReader(DIRECTORIO + FILE_IN); BufferedReader bf = new BufferedReader(fr); File ficheroOut = new File(DIRECTORIO + FILE_OUT); ficheroOut.delete(); BufferedWriter bw = new BufferedWriter(new FileWriter(ficheroOut)); int casosPrueba = Integer.parseInt(bf.readLine()); // Se hace cada caso de prueba for (int index = 1; index <= casosPrueba; index++) { String[] entrada = bf.readLine().split("" ""); long A = Integer.parseInt(entrada[0]); long B = Integer.parseInt(entrada[1]); int parejasEncontradas = 0; for (long i=A; i<=B; i++){ long digitos = (long) Math.ceil(Math.log10(B)); ArrayList listaFijos = new ArrayList(); for (int j = 1; j < digitos; j++) { long maximo = (long) Math.pow(10, j); long candidato = (long) Math.floor((i / maximo)); candidato = (long) (candidato + (i % maximo) * Math.pow(10, digitos - j)); if (candidato <= B && candidato > i && !listaFijos.contains(candidato)) { listaFijos.add(candidato); parejasEncontradas++; } } } // Se escribe la solución del caso en pantalla y en fichero String solucion = ""Case #"" + index + "": "" + parejasEncontradas; bw.write(solucion); bw.newLine(); System.out.println(solucion); } // Se cierra el buffer de escritura bw.close(); } } " B20054,"import java.io.*; import java.util.*; public class Recycled { static boolean[] vis; static int pairs; static int countDig(int a) { int res = 1; while(a >= 10) { a /= 10; res++; } return res; } static void solve() throws IOException { int T = nextInt(); for(int c = 1; c <= T; c++) { int A = nextInt(); int B = nextInt(); vis = new boolean[B+1]; int res = 0; for(int i = A; i <= B; i++) { int pairs = 1; if(!vis[i]) { vis[i] = true; int dig = countDig(i); for(int j = 1; j < dig; j++) { int suf = i % (int)Math.pow(10, j); int temp = i; temp /= Math.pow(10, j); if(countDig(suf) != j || suf == 0) continue; temp += suf * Math.pow(10, dig - j); if(temp <= B && temp >= A) { if(vis[temp]) continue; vis[temp] = true; pairs++; } } } res += pairs * (pairs - 1) / 2; } out.println(""Case #"" + c + "": "" + res); } } public static void main(String[] args) { try { br = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(new BufferedWriter(new FileWriter(""output.txt""))); solve(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(239); } } static BufferedReader br; static StringTokenizer st; static PrintWriter out; static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } } " B20845,"package codezam.util; import java.io.File; import java.io.FileReader; import java.io.LineNumberReader; public class InputFile { private File file; FileReader freader; LineNumberReader lnreader; public void setFile(String filename) { try { file = new File(filename); freader = new FileReader(file); lnreader = new LineNumberReader(freader); } catch (Exception e) { e.printStackTrace(); } } public String readLine() { String line = null; try { line = lnreader.readLine(); //System.out.println(""Line: "" + lnreader.getLineNumber() + "": "" + line); if (line==null) { close(); } } catch (Exception e) { e.printStackTrace(); } return line; } private void close() { try { freader.close(); lnreader.close(); } catch (Exception e) { e.printStackTrace(); } } } " B20019,"import java.util.ArrayList; import java.util.HashSet; public class DancingWithTheGooglers { private static String inputFile = ""C:\\PERSONAL-WORKSPACE\\GCJ-2012\\src\\input-output\\Input.txt""; private static String outputFile = ""C:\\PERSONAL-WORKSPACE\\GCJ-2012\\src\\input-output\\Output.txt""; public static void main(String[] args) { InputReader ir = new InputReader(inputFile); OutputWriter ow = new OutputWriter(outputFile); ArrayList lines = ir.loadLines(); for(int i=1;i hs = new HashSet(); String[] sNums = lines.get(i).split("" "",lines.get(i).length()); Long[] minMaxArr = GCJUtils.getLongArray(sNums); for(long l=((minMaxArr[0]<12)?12:minMaxArr[0]);l<=minMaxArr[1];l++){ String sCurrVal = Long.toString(l); for(int j=sCurrVal.length()-1;j>0;j--){ String sTmp = sCurrVal.substring(j)+ sCurrVal.substring(0,j); Long sLong = Long.parseLong(sTmp); if(sLong>l && sLong<=minMaxArr[1]){ hs.add(sLong+""-""+l); } } } ow.writeCaseLine(hs.size()+""""); } ow.flushAndClose(); } } " B20100,"import java.awt.Point; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class Prob2 { private static String doAlgorithm(String[] lines) { StringBuilder ans = new StringBuilder(); int numCase = Integer.parseInt(lines[0]); for (int i = 0; i < numCase; i++) ans.append(""Case #"" + (i + 1) + "": "") .append(doActualAlgorithm(lines[i + 1])).append('\n'); return ans.toString(); } private static Point createAns(int x, int y) { if (x == y) throw new IllegalArgumentException(); int lesser = Math.min(x, y); int more = Math.max(x, y); return new Point(lesser, more); } static String doActualAlgorithm(String s) { Set answerPair = new HashSet(); String[] separated = s.trim().split("" ""); int i1 = Integer.parseInt(separated[0]), i2 = Integer .parseInt(separated[1]); for (int i = i1; i <= i2; i++) { String stringForm = i + """"; for (int j = 0; j < stringForm.length(); j++) { String testingString = stringForm.substring(j) + stringForm.substring(0, j); if (testingString.charAt(0) == '0') continue; int testingInt = Integer.parseInt(testingString); if (testingInt <= i2 && testingInt >= i1 && testingInt != i) answerPair.add(createAns(i, testingInt)); } } return answerPair.size() + """"; } private static void initAlgorithm() { } public static void main(String[] args) throws IOException { File inputFile = new File(""input.txt""); File outputFile = new File(""output.txt""); FileReader reader = new FileReader(inputFile); BufferedReader br = new BufferedReader(reader); String line; ArrayList input = new ArrayList(); while ((line = br.readLine()) != null) { input.add(line); } br.close(); initAlgorithm(); String output = doAlgorithm(input.toArray(new String[0])); FileWriter writer = new FileWriter(outputFile); writer.write(output.trim()); writer.close(); } } " B21152,"import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String... args) throws IOException { // BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedReader reader = new BufferedReader(new FileReader(""C-large.in"")); // PrintWriter writer = new PrintWriter(System.out); PrintWriter writer = new PrintWriter(""C-large.out""); int len, cases = Integer.parseInt(reader.readLine()); Set unique = new HashSet(); String [] inputs; int A, B, k, mod, div, num; long res; for(int i = 1; i <= cases; i++){ inputs = reader.readLine().split("" ""); A = Integer.parseInt(inputs[0]); B = Integer.parseInt(inputs[1]); res = 0l; for(int j = A; j <= B; j++){ unique.clear(); k = j; int start = 10; while(k / start > 0){ mod = k % start; if(mod >= (start / 10)){ div = k / start; num = Integer.parseInt(mod + """" + div); if(num > j && num <= B){ unique.add(num); } } start *= 10; } res += unique.size(); } System.out.println(""Case "" + i + "" complete""); writer.println(""Case #"" + i + "": "" + res); } writer.flush(); } } " B21836,"import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class C { public static void main(String[] args) throws Exception{ new C().solve(args[0]); } private void solve(String file) throws Exception { Scanner s = new Scanner(new File(file)); int x=s.nextInt(); for(int i=1;i<=x;i++) { int y = calculate(s.nextInt(),s.nextInt()); System.out.format(""Case #%d: %d\n"",i,y); } } private int calculate(int a, int b) throws Exception { int r = 0; for ( int w=a; w<=b ; w++) { String A = Integer.toString(w); int l = A.length(); List list=new ArrayList(); for(int i=0;ib ) continue; if ( list.contains(bb))continue; list.add(bb); r++; } } return r; } } " B20177,"package codejam2; public interface CodejamCase { public void compute(); public String getOutput(); } " B20825,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package problem.c; import java.util.Scanner; import java.io.*; /** * * @author Jason */ public class ProblemC { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner input = new Scanner(System.in); System.out.println(""Enter name of input file: ""); File inputFile = new File(input.next()); File outputFile = new File(""output.txt""); Scanner file = null; PrintWriter output = null; while(file == null) { try{ file = new Scanner(inputFile); output = new PrintWriter(outputFile); } catch(Exception E){ System.out.println(""invalid file""); } } int cases = file.nextInt(); file.nextLine(); for (int i = 0; i < cases;) { int pairs = 0; int A = file.nextInt(); int B = file.nextInt(); for(;A < B;A++) { int[] newA = null; if (A>999999) newA = new int[7]; else if (A>99999) newA = new int[6]; else if (A>9999) newA = new int[5]; else if (A>999) newA = new int[4]; else if (A>99) newA = new int[3]; else if (A>9) newA = new int[2]; else newA = new int[1]; int tempA = A; for(int j = newA.length-1; j >= 0;j--) { newA[j] = tempA % 10; tempA = tempA / 10; } int[] savedFound = {0, 0, 0, 0, 0, 0}; int foundIterator = 0; for(int j = 0; j < newA.length-1; j++) { int temp = newA[newA.length-1]; for(int k = 0; k < newA.length; k++) { int temp2 = newA[k]; newA[k] = temp; temp = temp2; } temp = 0; for(int k = newA.length-1, tens = 1; k >= 0;k--,tens*=10) { temp += newA[k]*tens; } if (temp > A && temp <= B && temp != savedFound[0] && temp != savedFound[1] && temp != savedFound[2] && temp != savedFound[3] && temp != savedFound[4] && temp != savedFound[5] ) { pairs++; savedFound[foundIterator++] = temp; } } } output.println(""Case #"" + ++i + "": "" + pairs); } output.close(); } }" B22206,"import java.io.*; import java.util.*; import java.util.ArrayList; public class CodeJamProblem implements Runnable { //Problem C public boolean InRisultati(ArrayList array, String controllo) { for(int i =0; i risultati = new ArrayList(); if(caso==3) System.out.println("" ""); for (int i = 0; i < range.length; i++) { current_n = range[i]; current_m = range[i]; String rot_m = """"+current_m; //if(caso==3) // System.out.println(""Numero: "" +current_m); int len = (range[i]+"""").length(); for (int j = 0; j < len; j++) { if(caso==3) System.out.print("" "" + rot_m.substring(rot_m.length()-1) + rot_m.substring(0,len-1)); rot_m = ( rot_m.substring(rot_m.length()-1) + rot_m.substring(0,len-1) ); // A ² n < m ² B if (Integer.parseInt(rot_m) <= B && Integer.parseInt(rot_m) > current_n && Integer.parseInt(rot_m) >= A) { //if(InRisultati(risultati,current_n+rot_m)==false) { // risultati.add(current_n+rot_m); vincitori++; //} } } if(caso==3) System.out.println("" ""); } if(caso==3) System.out.println(""Winner :""+ vincitori); return vincitori; } public void solve() throws IOException { String test = ""small""; //String test = ""large""; Scanner in = new Scanner(new File(""C-large.in"")).useDelimiter(System.getProperty(""line.separator"")); PrintWriter out = new PrintWriter(new File(""C-large.out"")); int lineNum = 0; int testNum = 0; int totalTests = 0; int[] points = new int[1]; while (in.hasNext()) { String currentLine = in.next(); if(lineNum ==0 ) { //Do Nothing! totalTests = Integer.parseInt(currentLine); lineNum++; continue; } if(lineNum>0) { String[] x = currentLine.split("" ""); points = new int[x.length]; for(int i = 0;i mapping; public Q1Solver(){ mapping = new HashMap(); mapping.put('y','a'); mapping.put('n','b'); mapping.put('f','c'); mapping.put('i','d'); mapping.put('c','e'); mapping.put('w','f'); mapping.put('l','g'); mapping.put('b','h'); mapping.put('k','i'); mapping.put('u','j'); mapping.put('o','k'); mapping.put('m','l'); mapping.put('x','m'); mapping.put('s','n'); mapping.put('e','o'); mapping.put('v','p'); mapping.put('z','q'); mapping.put('p','r'); mapping.put('d','s'); mapping.put('r','t'); mapping.put('j','u'); mapping.put('g','v'); mapping.put('t','w'); mapping.put('h','x'); mapping.put('a','y'); mapping.put('q','z'); mapping.put(' ',' '); } public String convertString(String encrypted){ StringBuilder resString = new StringBuilder(""""); for (int i = 0 ; i < encrypted.length() ; i++){ char decryptedChar = mapping.get(encrypted.charAt(i)); resString.append(decryptedChar); } return resString.toString(); } } " B20619,"package utils; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Fabien Renaud */ public class File { public static boolean delete(String filename) { java.io.File f = new java.io.File(filename); if (f != null) { return f.delete(); } return false; } public static String[] readAllLines(String filename) { return readAllLines(new java.io.File(filename)); } public static String[] readAllLines(java.io.File file) { List list = new ArrayList(); try { BufferedReader input = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = input.readLine()) != null) { list.add(line); } } finally { input.close(); } } catch (IOException ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } String[] s = new String[list.size()]; return list.toArray(s); } public static String readAllText(String filename) { return readAllText(new java.io.File(filename)); } public static String readAllText(java.io.File file) { StringBuilder content = new StringBuilder(); String lf = System.getProperty(""line.separator""); try { BufferedReader input = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = input.readLine()) != null) { content.append(line); content.append(lf); } } finally { input.close(); } } catch (IOException ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } return content.toString(); } public static byte[] readAllBytes(String filename) { return readAllBytes(new java.io.File(filename)); } public static byte[] readAllBytes(java.io.File file) { byte[] bytes = new byte[0]; InputStream is = null; try { is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { // File is too large } bytes = new byte[(int) length]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException(""Could not completely read file "" + file.getName()); } is.close(); } catch (Exception ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } finally { try { is.close(); } catch (IOException ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } } return bytes; } public static void writeAllLines(String filename, String[] lines) { writeAllLines(new java.io.File(filename), lines); } public static void writeAllLines(java.io.File file, String[] lines) { String lf = System.getProperty(""line.separator""); try { FileWriter fw = new FileWriter(file); for (String l : lines) { fw.write(l); fw.write(lf); fw.flush(); } fw.close(); } catch (IOException ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } } public static void writeAllText(String filename, String text) { writeAllText(new java.io.File(filename), text); } public static void writeAllText(java.io.File file, String text) { String lf = System.getProperty(""line.separator""); try { FileWriter fw = new FileWriter(file); fw.write(text); fw.flush(); fw.close(); } catch (IOException ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } } public static void writeAllBytes(String filename, byte[] bytes) { writeAllBytes(new java.io.File(filename), bytes); } public static void writeAllBytes(java.io.File file, byte[] bytes) { try { FileOutputStream fos = new FileOutputStream(file); fos.write(bytes); fos.close(); } catch (Exception ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); } } } " B20119,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { static int[] pow = { 1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000}; public static void main(String[] args) { PrintStream theOut=null; try { FileOutputStream o = new FileOutputStream(""./output.txt"", false); theOut = new PrintStream(o); } catch (Exception e) { e.printStackTrace(); return; } Scanner sc=null; try { //sc = new Scanner(new File(""./C-small.in"")); sc = new Scanner(new File(""/home/duck/Downloads/C-large.in"")); //sc = new Scanner(new File(""/home/duck/Downloads/C-small-attempt0.in"")); } catch (FileNotFoundException e) { e.printStackTrace(); } int nbCases = sc.nextInt(); mainloop: for(int curCase=1; curCase <= nbCases ;++curCase) { sc.nextLine(); long res = 0; int min = sc.nextInt(); int max = sc.nextInt(); ArrayList found = new ArrayList(); for(int i=min; i <= max ;++i) { int nbDigit = (int)Math.ceil(Math.log10((double)i)); found.clear(); for(int j= 1; j < nbDigit ; j++) { int low = i% pow[j]; int swap = low * pow[nbDigit - j] + (i-low) /pow[j]; if(swap > i && swap <= max && !found.contains(swap)) { found.add(swap); ++res; //System.out.println(i+"" ""+swap); } } } /*******************************************************************/ theOut.format(""Case #%d: %d\n"",curCase,res); System.out.format(""Case #%d: %d\n"",curCase,res); } } } " B21906,"package com.google.recyclednumbers; import java.util.Scanner; import com.google.util.FileUtil; public class RecycledNumbers { public static void main(String[] args) { String orgFilePath = ""E:\\Google_Jam\\RecycledNumbers\\C-large.in""; Scanner scanner = FileUtil.openFile(orgFilePath); StringBuilder sb = new StringBuilder(); int caseNum = Integer.valueOf(scanner.nextLine()); for (int i = 0; i < caseNum; i++) { sb.append(""Case #"" + (i + 1) + "": ""); int n = 0; int a = scanner.nextInt(); int b = scanner.nextInt(); /*int a = 1111; int b = 2222;*/ if (b <= 20) { n = 0; sb.append(n); sb.append(""\n""); continue; } else { for (int k = a; k <= b; k++) { String left = String.valueOf(k); int length = left.length();// ×ó±ßÊýµÄλÊý int temp = 0;// ÓÃÓڼǼÄÜת»»³öÀ´µÄÊýµÄ¸öÊý int[] tempCase = new int[20]; for (int j = 0; j < length; j++) { String sub1 = left.substring(0, j + 1); String sub2 = left.substring(j + 1, length); String newNum = sub2 + sub1; int right = Integer.valueOf(newNum); if (right <= b && k < right) { if (temp == 0) { n++; tempCase[temp] = right; temp++; } else { int p; for (p = 0; p < temp && tempCase[p] != right; p++); if (p == temp) { tempCase[temp] = right; temp++; n++; } } //System.out.println(k + ""&&"" + right); //sb.append(k + ""&&"" + right); //sb.append(""\n""); } } } } sb.append(n); sb.append(""\n""); } FileUtil.writeFile(sb, ""RecycledNumbers\\large.in""); } } " B20070,"import java.io.*; import java.util.*; public class ProblemC { public static void main(String[] args) { try { Set alltuples = new HashSet(); PrintWriter fout = new PrintWriter(new FileWriter(""CJ"")); BufferedReader fin = new BufferedReader(new FileReader(""C-large.in"")); String l; String[] p; Integer i, j, k, m, n, ans,tests = Integer.valueOf(fin.readLine()); for(i = 1; i <= tests; ++i) { ans = 0; p = fin.readLine().split("" ""); j = Integer.valueOf(p[0]); k = Integer.valueOf(p[1]); for(j = j; j < k; ++j) { alltuples.clear(); l = j.toString(); for(m = 1; m < l.length(); ++m) { n = Integer.valueOf(l.substring(m) + l.substring(0,m)); if(n > j && n <= k) alltuples.add(n); } ans += alltuples.size(); } fout.println(""Case #"" + i +"": "" + ans); } fin.close(); fout.close(); } catch (Exception e) { e.printStackTrace(); } } } " B21978,"package google.codejam; import java.util.HashMap; public class RecycledNumberSolver implements GoogleSolver { @Override public String solve(String str) { String [] numbers = str.split("" ""); int min = Integer.parseInt(numbers[0]); int max = Integer.parseInt(numbers[1]); int digits = numbers[0].length(); System.out.println(""min:""+min + "" max:""+ max); HashMap map = new HashMap(); int count = 0; for(int i=min; i<=max ; i++){ for(int move=1 ; movei && testNum>=min && testNum<=max){ //System.out.println(""(""+temp + "" , "" + testNum+ "")""); if(map.get(i)==null || map.get(i)!=testNum){ map.put(i, testNum); count++; } } } map.clear(); } return count+""""; } } " B21518,"import java.io.*; import java.math.BigInteger; import java.util.Arrays; import java.util.InputMismatchException; /** * @author Mikeldi Latorre (mikeldi10@gmail.com) */ public class RecycledNumbers implements Runnable { private InputReader in; private PrintWriter out; public static void main(String[] args) { new Thread(new RecycledNumbers()).start(); } public RecycledNumbers() { try { System.setIn(new FileInputStream(""C-large.in"")); System.setOut(new PrintStream(new FileOutputStream(""C-large.out""))); } catch (FileNotFoundException e) { throw new RuntimeException(); } in = new InputReader(System.in); out = new PrintWriter(System.out); } public void run() { int numTests = in.readInt(); for (int testNumber = 0; testNumber < numTests; testNumber++) { out.println(""Case #"" + (testNumber + 1) + "": ""+algorithm()); } out.close(); } private int b; private int algorithm(){ int a = in.readInt(); b = in.readInt(); int x = (int)Math.pow(10, (""""+a).length()-1); int ret = 0; for (int i = a; i <= b; i++) { ret += check(i,i,x); } return ret; } private int check(int num, int base, int x){ num = num%10*x+num/10; int ret = 0; if(num == base){ return 0; } if((num > base)&&(num <=b)){ ret++; } ret += check(num,base,x); return ret; } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } } " B20689,"import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import java.util.Scanner; public class ProblemC { static long[] pow = new long[12]; private static long solve(int a, int b) { HashMap> f = new HashMap>(); long res = 0; for (int i = a; i <= b; i++) { int s = (i + """").length(); for (int j = 1; j < s; j++) { int c = (int) ((i / pow[j]) + pow[s - j] * (i % pow[j])); if (c <= b && c >= a && c != i && (c + """").length() == s) { boolean k = f.containsKey(i); if (!k)f.put(i, new LinkedList()); if (f.containsKey(c))k = f.get(c).contains(i); if (!k) {f.get(i).add(c);res++; } } } } return res; } public static void main(String[] args) throws IOException { pow[1] = 10; for (int i = 2; i < 12; i++) pow[i] = pow[i - 1] * 10; Scanner input = new Scanner(new FileReader(""input"")); BufferedWriter output = new BufferedWriter(new FileWriter(""output"")); long res; int n = input.nextInt(); for (int j = 1; j <= n; j++) { res = solve(input.nextInt(), input.nextInt()); output.write(""Case #"" + j + "": "" + res); output.newLine(); } output.close(); } }" B21272,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class RecycledNumbers { public static void main(String[] args) { int cases = 0, a = 0, b = 0, answer = 0; String in = ""C-large""; try { BufferedReader br = readFile(new FileReader(in + "".in"")); FileWriter fstream = new FileWriter(in + "".out""); BufferedWriter out = new BufferedWriter(fstream); String inline; int i = 0; while ((inline = br.readLine()) != null) { if (i++ == 0) { cases = Integer.parseInt(inline); } else { String result = ""Case #"" + (i - 1) + "": ""; String[] input = inline.trim().split("" "", 2); answer = 0; a = Integer.parseInt(input[0].trim()); b = Integer.parseInt(input[1].trim()); if (b > 10) { int sub = 0; Map map = new HashMap(); for (int n=a; n<=b; n++) { if (n < 10) {n = 10; continue;} String sn = String.valueOf(n); sub = sn.length(); int m = 0; for (int o=0; o n && m <= b && !map.containsKey(n + "","" + m)) { //System.out.println(n + "","" + m); map.put(n + "","" + m, n + "","" + m); answer++; } } } } writeOutput(result + answer, out); } } out.close(); } catch(Exception e) { e.printStackTrace(); } } private static BufferedReader readFile(FileReader in) throws FileNotFoundException { return new BufferedReader(in); } private static void writeOutput(String text, BufferedWriter out) throws IOException { out.write(text); out.write(""\n""); } } " B22069,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class QuestionC { public static void doPuzzle() { try { File questionfile = new File(""C.in""); BufferedReader questionreader = new BufferedReader(new FileReader(questionfile)); File answerfile = new File(""C.out""); PrintWriter answerwriter = new PrintWriter(new BufferedWriter(new FileWriter(answerfile))); String[] params = null; String question = questionreader.readLine(); int T = Integer.parseInt(question); int[] A = new int[T]; int[] B = new int[T]; for (int i = 0; i < T; i++) { question = questionreader.readLine(); params = question.split("" ""); A[i] = Integer.parseInt(params[0]); B[i] = Integer.parseInt(params[1]); } int[] answer = analyze(T, A, B); for (int i = 0; i < T; i++) { answerwriter.println(""Case #"" + (i+1) + "": "" + answer[i]); } answerwriter.close(); questionreader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } } private static int[] analyze(int T, int[] A, int[] B) { int[][] blockA = new int[9][T]; int[][] blockB = new int[9][T]; int[][] blockT = new int[9][T]; int[][] blockX = new int[9][T]; int[] blockLen = new int[9]; for (int i = 0; i < T; i++) { int len = String.valueOf(A[i]).length(); blockA[len][blockLen[len]] = A[i]; blockB[len][blockLen[len]] = B[i]; blockT[len][blockLen[len]] = i; blockLen[len]++; } for (int i = 1; i <= 20000000; i++) { String str = String.valueOf(i); int len = str.length(); StringBuilder sb = new StringBuilder(str); for (int j = 1; j < len; j++) { sb = sb.append(sb.charAt(0)).deleteCharAt(0); int value = Integer.parseInt(sb.toString()); if (i == value) break; for (int k = 0; k < blockLen[len]; k++) { if (blockA[len][k] > i) continue; if (blockA[len][k] > value) continue; if (blockB[len][k] < i) continue; if (blockB[len][k] < value) continue; blockX[len][k]++; } } } int[] answer = new int[T]; for (int i = 0; i < 9; i++) { for (int j = 0; j < blockLen[i]; j++) { answer[blockT[i][j]] = blockX[i][j] / 2; } } return answer; } } " B22051,"package google.contest.B; import google.loader.Challenge; import google.problems.AbstractChallenge; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class BChallenge extends AbstractChallenge implements Challenge { private int numberOfGooglers; private int numberOfSurprise; private int desiredScore; List scores; private String resultNumber; private static HashMap map; public BChallenge(int number, String line) { super(number); String[] tokens = line.split("" ""); numberOfGooglers = Integer.parseInt(tokens[0]); numberOfSurprise = Integer.parseInt(tokens[1]); desiredScore = Integer.parseInt(tokens[2]); scores = new ArrayList(); for(int i=0;i bigger = new ArrayList(); List biggerAndSurprising = new ArrayList(); List smaller = new ArrayList(); List smallerAndSuprising = new ArrayList(); for(Integer score : scores ){ ScoreInfo info = getScoreInfo(score); if(info.canBeBigger(desiredScore)){ if(info.mustBeSuprisingBeingBigger(desiredScore)){ biggerAndSurprising.add(score); }else{ bigger.add(score); } }else{ if(info.canBeSuprising()){ smallerAndSuprising.add(score); }else{ smaller.add(score); } } } int biggerSize = bigger.size(); int biggerAndSuprSize = biggerAndSurprising.size(); int smallerSize = smaller.size(); int smallerAndSupSize = smallerAndSuprising.size(); if(biggerAndSuprSize>=numberOfSurprise){ resultNumber = """"+ ( biggerSize + numberOfSurprise); return; } resultNumber = """"+ (biggerSize + biggerAndSuprSize); } private ScoreInfo getScoreInfo(Integer score) { return map.get(score); } private void init() { map = new HashMap(); for(int i=0;i<11;i++){ for(int j=0;j<11;j++){ for(int k=0;k<11;k++){ addTripple(i,j,k); } } } } private void addTripple(int i, int j, int k) { int sum = i+j+k; if(! map.containsKey(sum)){ map.put(sum, new ScoreInfo(sum)); } map.get(sum).addTripple(i,j,k); } private static class ScoreInfo{ private List tripples; public ScoreInfo(int sum) { tripples = new ArrayList(); } public boolean mustBeSuprisingBeingBigger(int desiredScore) { for(Tripple tripple : tripples){ if(tripple.isBigger(desiredScore)){ if(!tripple.isSuprising()){ return false; } } } return true; } public boolean canBeBiggerAndSuprising(int desiredScore) { for(Tripple tripple : tripples){ if(tripple.isBigger(desiredScore)){ if(tripple.isSuprising()){ return true; } } } return false; } public boolean canBeBigger(int desiredScore) { for(Tripple tripple : tripples){ if(tripple.isBigger(desiredScore)){ return true; } } return false; } public boolean canBeSuprising() { for(Tripple tripple : tripples){ if(tripple.isSuprising()){ return true; } } return false; } public void addTripple(int i, int j, int k) { Tripple tripple = new Tripple(i,j,k); if(tripple.isValid()){ tripples.add(tripple); } } } private static class Tripple{ private final int i; private final int j; private final int k; public Tripple(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } public boolean isBigger(int desiredScore) { return i>=desiredScore || j>=desiredScore || k>=desiredScore; } public boolean isSuprising() { return 2==getMaxDifference(); } private boolean isValid() { int max = getMaxDifference(); return max<3; } private int getMaxDifference() { int a1 = Math.abs(i-j); int a2 = Math.abs(i-k); int a3 = Math.abs(k-j); int max = Math.max(Math.max(a1,a2), a3); return max; } } } " B20827,"import java.io.*; import java.util.*; public class C implements Runnable { //private String IFILE = ""input.txt""; //private String IFILE = ""C-small-attempt0.in""; private String IFILE = ""C-large.in""; private Scanner in; private PrintWriter out; public void Run() throws IOException { in = new Scanner(new File(IFILE)); out = new PrintWriter(""output.txt""); int ntest = in.nextInt(); for(int test = 1; test <= ntest; test++) { out.print(""Case #"" + test + "": ""); int a = in.nextInt(); int b = in.nextInt(); int result = 0; for(int i = a; i <= b; i++) { int z = 1; while (z * 10 <= i) z *= 10; int ii = i; while (true) { ii = ii / 10 + (ii % 10) * z; if (ii == i) break; if (ii % z > 0 && i < ii && ii <= b) result++; } } out.println(result); } in.close(); out.close(); } public void run() { try { Run(); } catch(IOException e) { } } public static void main(String[] args) throws IOException { new C().Run(); //new Thread(new XXX()).start(); } } " B21991,"import java.io.*; import java.util.*; public class ProblemC { public static void main(String[] args) { String txtfile=""C-large.in""; try { Scanner scan = new Scanner(new FileInputStream(txtfile)); FileWriter fstream = new FileWriter(""C-large.out""); BufferedWriter out = new BufferedWriter(fstream); int T = scan.nextInt(); int y = 0,A,B,l,ban; String temp,sban; boolean copy; int[] z; for (int x=1;x<=T;x++) { A = scan.nextInt(); B = scan.nextInt(); y = 0; for (int i=A;i=A && ban<=B && ban>i && copy==false) { y++; } } } out.write(""Case #"" + x + "": "" + y + ""\n""); } out.close(); } catch (IOException ex) { System.out.println(ex); System.exit(1); } } }" B21559,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private static final String fname = ""C-large.in""; public static void main(String[] args) throws Exception { new RecycledNumbers().run(); } private void run() throws Exception { BufferedReader reader = new BufferedReader(new FileReader(""./"" + fname)); BufferedWriter writer = new BufferedWriter(new FileWriter(""./"" + fname + "".out"")); int T = Integer.parseInt(reader.readLine().trim()); for (int i = 1; i <= T; i++) { String[] line = reader.readLine().trim().split(""[ ]""); int lower = Integer.parseInt(line[0]); int upper = Integer.parseInt(line[1]); int retval =0; for (int j = lower ; j <= upper; j++) { Set set = new HashSet(2); int l = length10(j); int mult = l/10; for (int k = 10; k <= l; k = k*10) { int x = (j % k) * mult + (j / k); if (x >= lower && x <= upper && x != j && j < x && !set.contains(x)) { set.add(x); retval++; } mult /=10; } } writer.write(""Case #"" + i + "": "" + retval); if (i < T) writer.write(""\n""); } reader.close(); writer.close(); } private static int length10(int n) { int div = 1; while (n / div > 0) { div *= 10; } return div; } } " B20920,"package recycledNumbers; import java.util.ArrayList; public class Algorithms { public static OutputData getOutput(InputData inputdata) { // TODO Auto-generated method stub int [] Results = new int[inputdata.getTest_Number()]; for(int i=0;i number = new ArrayList(); ArrayList numbers = new ArrayList(); int temp = i; while(temp/10>0){ number.add(temp%10); temp = temp/10; } number.add(temp%10); for(int j=0;j part = new ArrayList(); for(int k=0;k set = new HashSet(); for (int i = a; i <= b; ++i) { set.add("""" + i); } HashSet ans = new HashSet(); for (int i = a; i <= b; ++i) { String s = """" + i; for (int pref = 1; pref < s.length(); ++pref) { String t = s.substring(pref) + s.substring(0, pref); if (t.charAt(0) == '0') { continue; } if (set.contains(t) && !s.equals(t)) { long aa = i; long bb = Integer.parseInt(t); if (aa > bb) { long tt = aa; aa = bb; bb = tt; } long key = (aa << 30) + bb; if (ans.add(key)) { // System.err.println(s + "" "" + t); } } } } println(ans.size()); writer.flush(); } // char[] map = new char[26]; // Arrays.fill(map, '#'); // for (int i = 0; i < 3; ++i) { // String a = reader.readLine(); // String b = reader.readLine(); // for (int j = 0; j < a.length(); ++j) { // if (a.charAt(j) == ' ') { // continue; // } // int c = a.charAt(j) - 'a'; // char d = b.charAt(j); // if (map[c] != '#' && map[c] != d) { // throw new AssertionError(); // } // map[c] = d; // } // } // map['z' - 'a'] = 'q'; // map['q' - 'a'] = 'z'; // System.err.println(new String(map)); } private void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(new OutputStreamWriter(System.out)); reader = new BufferedReader(new FileReader(TASKNAME + "".in"")); writer = new PrintWriter(TASKNAME + "".out""); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(13); } } public static void main(String[] args) { long time = System.currentTimeMillis(); Locale.setDefault(Locale.US); new Main().run(); System.err.printf(""%.3f\n"", (System.currentTimeMillis() - time) * 1e-3); } private StringTokenizer tokenizer; private PrintWriter writer; private BufferedReader reader; private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private void print(Object o) { writer.print(o); } private void println(Object o) { writer.println(o); } private void printf(String format, Object... args) { writer.printf(format, args); } } " B21203,"import java.lang.*; import java.io.*; import java.util.*; public class Solution { public static BufferedReader br; public static PrintWriter out; public static StringTokenizer stk; // ///////////////// TO CHANGE /////////////////////////// public static boolean isServer = false; // ///////////////// TO CHANGE /////////////////////////// public static void main(String[] args) throws IOException { if (isServer) { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { br = new BufferedReader(new FileReader(""in.txt"")); out = new PrintWriter(new File(""out.txt"")); } (new Solution()).run(); } public void loadLine() { try { stk = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } public String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return """"; } } public String nextWord() { while (stk == null || !stk.hasMoreTokens()) loadLine(); return stk.nextToken(); } public Integer nextInt() { while (stk == null || !stk.hasMoreTokens()) loadLine(); return Integer.valueOf(stk.nextToken()); } public Long nextLong() { while (stk == null || !stk.hasMoreTokens()) loadLine(); return Long.valueOf(stk.nextToken()); } public Double nextDouble() { while (stk == null || !stk.hasMoreTokens()) loadLine(); return Double.valueOf(stk.nextToken()); } public Float nextFloat() { while (stk == null || !stk.hasMoreTokens()) loadLine(); return Float.valueOf(stk.nextToken()); } public void run() { int tt = nextInt(); for (int t = 0; t < tt; t++) { int a = nextInt(); int b = nextInt(); long ans = 0; for (int i = a; i <= b; i++) { String s = Integer.toString(i); HashSet set = new HashSet(); set.add(i); for (int j = 1; j < s.length(); j++) { StringBuilder ss = new StringBuilder(); for (int k = 0; k < s.length(); k++) { ss.append(s.charAt((j+k)%s.length())); } int y = Integer.parseInt(ss.toString(), 10); if (y >= a && y <= b) { set.add(y); } } ans += set.size()-1; } out.printf(""Case #%d: "", t+1); out.println(ans/2); } out.flush(); } } " B20018,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class InputReader { private BufferedReader br = null; public InputReader(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public ArrayList loadLines() { ArrayList lines = new ArrayList(); String[] arrLines = null; String tmp = null; try { while ((tmp = br.readLine()) != null) { lines.add(tmp); } br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return lines; } } " B20408,"package codejam.morl99.c; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class ProblemC { public void solveSet(PrintWriter pw, BufferedReader reader) throws IOException { String firstLine = reader.readLine(); Scanner scanner = new Scanner(firstLine); scanner.useDelimiter("" ""); int T = scanner.nextInt(); for (int i = 1; i <= T; i++) { scanner = new Scanner(reader.readLine()); scanner.useDelimiter("" ""); int n = scanner.nextInt(); int m = scanner.nextInt(); System.out.println(""-- n: "" + n + "" m: "" + m); int solution = solveLine(n, m); pw.printf(""Case #%d: %d"", i, solution); System.out.println(""Solved "" + i); pw.println(); } } public int solveLine(int A, int B) { int oldSize = 0; Set pairs = new HashSet(); for (int i = A; i <= B; i++) { Set newPairs = getPermutations(i); for (Pair p: newPairs) { if (p.isInBoundaries(A, B)) { pairs.add(p); } } if (pairs.size() > oldSize) { oldSize = pairs.size(); // System.out.println(""New Pairs for ""+ i + "": "" + setToString(pairs) ) ; } } return pairs.size(); } public Set getPermutations(int i){ Set pairs = new HashSet<>(); String number = """" + i; //we will now create the pairs by cutting the number in half and moving the second half in front of the first int position = number.length()-1; final int endIndex = number.length(); while (position > 0) { String recycled = number.substring(position, endIndex) + number.substring(0, position); int r= Integer.parseInt(recycled); if (i != r) { pairs.add(new Pair(i,r)); // System.out.println(number + "" <-> "" + recycled); } position--; } return pairs; } public static String setToString(Set set) { StringBuilder s = new StringBuilder(); for (Pair p:set) { s.append(p); } return s.toString(); } public static void main(String[] args) throws IOException { ProblemC p = new ProblemC(); OutputStream output = new FileOutputStream(""res/C.out"", false); PrintWriter pw = new PrintWriter(output); BufferedReader reader = new BufferedReader(new FileReader(""res/C-large.in"")); p.solveSet(pw, reader); pw.close(); reader.close(); } } class Pair { int n, m; public Pair(int x, int y) { if (x < y) { n = x; m = y; } else { m = x; n = y; } } @Override public boolean equals(Object obj) { if (obj instanceof Pair) { Pair other = (Pair) obj; if (n == other.n && m == other.m) return true; if (n == other.m && m == other.n) return true; return false; } return super.equals(obj); } public boolean isInBoundaries(int A, int B) { return n >= A && m <= B; } @Override public int hashCode() { return n+m; } @Override public String toString() { return ""(""+n+"",""+m+"")""; } }" B21301,"import java.util.*; import java.io.*; public class SOURCE041312_CJ_Qual_DancingWithGooglers { public static void main(String sargs[])throws IOException { System.setOut(new PrintStream(new File(""LargeOUTPUT041312_CJ_Qual_DancingWithGooglers.dat""))); Scanner oScan=new Scanner(new File(""C-large.in"")); int T=Integer.parseInt(oScan.nextLine().trim()); int Case=0; while(T-->0) { Set l=new HashSet(); int A=oScan.nextInt();int B=oScan.nextInt(); for(int i=A;i<=B;++i) { String n=i+""""; for(int ind=1;indInteger.parseInt(n)) l.add(""""+n+"" ""+m); } } System.out.println(""Case #""+ ++Case+"": ""+l.size()); } } }" B20797,"import java.util.*; class c { public static void main(String [] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int t=1;t<=T;++t) { int a,b; a = in.nextInt(); b = in.nextInt(); long pairs = 0; for(int i=a;i<=b;++i) { HashSet m = new HashSet(); String istr = """" + i; int numDigits = istr.length(); for(int j=1;j i && newnum <= b) { if(!m.contains(newnum)) { ++pairs; m.add(newnum); } } } } System.out.println(""Case #""+t+"": "" + pairs); } } } " B21214,"import java.util.LinkedList; import java.util.Scanner; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; /** *Recycled Numbers */ /** * @author Avengee */ public class Demo { public static void main(String[] args) throws IOException { //Reading and Writing Files Scanner scan = new Scanner(new File(""C-large.in"")); FileWriter writer = new FileWriter(""C-large-output.txt""); PrintWriter pw = new PrintWriter(writer); //variable declaration int T,A,B; //code T = scan.nextInt(); for (int i=1;i<=T;i++) { A = scan.nextInt(); B = scan.nextInt(); int y=0; int num=String.valueOf(A).length();//number of digits int nl=A; while(nl<=B) { int n=nl; LinkedList s=new LinkedList(); for(int j=1;jnl && m<=B) { if(index>=0); else{y++; s.add(m);} } n=m; } nl++; } System.out.println(""Case #""+i+"": ""+y); pw.println(""Case #""+i+"": ""+y); } scan.close(); writer.close(); } } " B21425,"import java.awt.geom.*; import java.io.*; import java.math.*; import java.util.*; import java.util.regex.*; import static java.lang.Math.*; public class Main { public Main() throws IOException { String input; int t; input = br.readLine(); t = Integer.valueOf(input); for (int i = 0; i < t; i++) { if (i > 0) sb.append(""\r\n""); input = br.readLine(); work(input, i); } System.out.print(sb); } private int rightShiftDec(int num) { int num2 = 10; if (num < 10) return num; while (true) { if (num < num2) break; num2 *= 10; } return num / 10 + (num % 10) * num2 / 10; } private void work(String input, int t) { //debug(input); int ret = 0; String[] inputArray = input.split("" ""); int min = Integer.valueOf(inputArray[0]); int max = Integer.valueOf(inputArray[1]); boolean[] doneList = new boolean[2000001]; int total; for (int i = min; i <= max; i++) doneList[i] = false; for (int i = min; i <= max; i++) { int num = i; int multiply = 1; if (doneList[i]) continue; doneList[i] = true; while (true) { num /= 10; if (num == 0) break; multiply *= 10; } num = i; total = 0; while (true) { num = num / 10 + (num % 10) * multiply; //debug(""i:"", i, "" num:"", num); if (num < multiply) continue; if (num == i) break; if ((min <= num) && (num <= max)) { //debug(""i:"", i, "" num:"", num, "" 1111""); total++; doneList[num] = true; } } ret += (total + 1) * total / 2; } sb.append(""Case #""); sb.append(String.valueOf(t + 1)); sb.append("": ""); sb.append(String.valueOf(ret)); } StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { new Main(); } public static void debug(Object... arr) { System.err.println(Arrays.deepToString(arr)); } } " B20512,"import java.util.HashSet; import java.util.Scanner; public class recycled { public static void main(String[] args){ int t; Scanner s = new Scanner(System.in); t=s.nextInt(); for(int k=1;k<=t;k++){ int a,b; a=s.nextInt(); b=s.nextInt(); int al=a/10,d=1; while(al>0){ d++; al/=10; } int count=0; for(int i=a;i<=b;i++){ HashSet hs = new HashSet(); for(int j=1;j=a && n<=b && n!=i) { if(!hs.contains(n)){ count++; hs.add(n); } } } } System.out.println(""Case #""+k+"": ""+(count/2)); } } } " B21695,"package reusable; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public abstract class CodeJamBase { private final List inputLines; private final String filename; private int testCases; private int index = 0; public CodeJamBase(String filename) { this.filename = (filename != """") ? filename : ""sample""; try { inputLines = Files.readAllLines(Paths.get(""data/"" + this.filename + "".in""), Charset.defaultCharset()); } catch (IOException e) { throw new RuntimeException(""Failed to read file: '"" + this.filename + ""'""); } setup(); } protected void setup() { setTestCases(nextInt()); } protected abstract String solution(); public void run() { long startTime = System.currentTimeMillis(); List outputLines = new ArrayList<>(); for (int i = 0; i < testCases; i++) { String outputLine = ""Case #"" + (i + 1) + "": "" + solution(); outputLines.add(outputLine); System.out.println(outputLine); } try { Files.write(Paths.get(""data/"" + filename + "".out""), outputLines, Charset.defaultCharset()); } catch (IOException e) { throw new RuntimeException(""Failed to write file: '"" + filename + ""'""); } System.out.println(); System.err.println(""Total run time: "" + ((System.currentTimeMillis() - startTime) / 1000d) + ""s""); } protected final String nextString() { return inputLines.get(index++); } protected final int nextInt() { return Integer.parseInt(nextString()); } protected final String[] nextStringArray() { return inputLines.get(index++).split("" ""); } protected final int[] nextIntArray() { String[] items = nextStringArray(); int[] result = new int[items.length]; for (int i = 0; i < items.length; i++) { result[i] = Integer.parseInt(items[i]); } return result; } public final void setTestCases(int testCases) { this.testCases = testCases; } } " B21697,"import java.io.*; import java.util.StringTokenizer; public class Ricky { public static void main(String []args) { try{ FileInputStream fstream = new FileInputStream(""input.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int n=0; FileWriter fstream1 = new FileWriter(""out.in""); BufferedWriter out = new BufferedWriter(fstream1); int i; while ((strLine = br.readLine()) != null) { n=n+1; if (n==1) i = Integer.parseInt(strLine); else { System.out.println (parse(strLine,n-1)); out.write(parse(strLine,n-1)+""\n""); } } out.close(); in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private static String parse(String string1,int oo) { String str=""""; int count =0; long aa = 0; long bb = 0; StringTokenizer stringTokenizer = new StringTokenizer(string1); while(stringTokenizer.hasMoreTokens()) { aa = Integer.parseInt(stringTokenizer.nextToken()); bb = Integer.parseInt(stringTokenizer.nextToken()); } for (long i = aa ; i < bb; i = i+1) { if(i<10) { count = 0; } else if(i>=10 && i<100) { int m = (int) (i/10); int n = (int) (i%10); int nm = 10*n + m; if(i=100 && i<1000) { int mn = (int) (i/10); int z = (int) (i%10); int zmn = 100*z + mn; if(i=1000 && i<10000) { int mnz = (int) (i/10); int t = (int) (i%10); int tmnz = 1000*t + mnz; if(i=10000 && i<100000) { int mnzt = (int) (i/10); int w = (int) (i%10); int wmnzt = 10000*w + mnzt; if(i=100000 && i<1000000) { int mnzt = (int) (i/10); int w = (int) (i%10); int wmnzt = 100000*w + mnzt; if(i=1000000 && i<10000000) { int mnzt = (int) (i/10); int w = (int) (i%10); int wmnzt = 1000000*w + mnzt; if(i=10000000 && i<100000000) {} else {} } return ""Case #""+oo+"": ""+count; } }" B20601,"package GoogleCodeJam.ed2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.concurrent.Semaphore; public class QualificationC2012 { private String inputFile; private String outputFile; private BufferedReader reader = null; private BufferedWriter writer = null; private static int[] sollutions = null; private static int[][] inputs = null; private int totalSollutions = 0; private int currentSollution = 0; private Semaphore deathSignal = new Semaphore(0); private Object synchObject = new Object(); /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { QualificationC2012 qualificationC2012 = new QualificationC2012(""QualificationC2012.in"", ""QualificationC2012.out""); qualificationC2012.run(); } private void run() throws Exception { openFiles(); solve(); closeFiles(); } private void solve() throws Exception { long startTime = System.currentTimeMillis(); totalSollutions = Integer.valueOf(reader.readLine()); inputs = new int[totalSollutions][2]; sollutions = new int[totalSollutions]; for (int i = 0; i= totalSollutions) { break; } } int a = inputs[currentInput][0]; int b = inputs[currentInput][1]; int sum = 0; for (int i=a; i 0) } public static int solve(int n, int i, int len, int upper, HashMap hash){ // say n=123 i=2 len=3 int count=0; //System.out.println(""n= ""+n+"" i=""+i+"" len=""+len); int i2=n/power(10, i); ///i2=1 //System.out.println(""i2= ""+i2); int b=i2*power(10, i); ////b=100 int j1=n-b; ///// j1=23 int i1=j1*(power(10, (len-i))); int n2=i1+i2; /// now we have 231 //System.out.println(""n2= ""+n2); if (n2>n && n2<=upper) { if (hash.containsKey(n2)) { count+=0; } else { count+=1; hash.put(n2,1); } } return count; } } class solve{ public static void main(String[] args) { BufferedReader bf= null; String line; int n; int n1,n2; int ans=0; try { bf = new BufferedReader(new InputStreamReader(System.in)); int indicator=0; int playerno=0; String output=""""; BufferedWriter f=new BufferedWriter(new FileWriter(""output.txt"")); while ((line=bf.readLine())!=null) { HashMap hash=new HashMap(); if (indicator==0) { n=Integer.parseInt(line); } else { String[] a=line.split("" ""); int len=a[0].length(); n1=Integer.parseInt(a[0]); n2 =Integer.parseInt(a[1]); /////////////////////////////////// now solve this int number=n1; for (; number pInputCases) { File tFile = new File(pFileName); try { BufferedReader tBufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(tFile)), 4096); String tLineRead = tBufferedReader.readLine().trim(); int tCaseSize = Integer.valueOf(tLineRead); int tLineIndex = 0; while(tLineIndex < tCaseSize) { tLineRead = tBufferedReader.readLine().trim(); pInputCases.add(tLineRead); tLineIndex++; } } catch(FileNotFoundException pException) { pException.printStackTrace(); } catch(IOException pException) { pException.printStackTrace(); } } public static final int[] UNITS = { 1, 1, 10, 100, 1000, 10000, 100000, 1000000 }; public static void main(String[] pArgs) { if(pArgs.length == 0) { System.out.println(""no input""); return; } List tInputCases = new ArrayList(); readInput(pArgs[0], tInputCases); for(int tCaseIndex = 0; tCaseIndex < tInputCases.size(); tCaseIndex++) { String[] tInputs = tInputCases.get(tCaseIndex).split(""[ ]+""); int tLower = Integer.valueOf(tInputs[0]); int tUpper = Integer.valueOf(tInputs[1]); int tPairs = 0; Map tMapPairs = new HashMap(); for(int tNumber = tLower; tNumber < tUpper; ++tNumber) { int tLength = String.valueOf(tNumber).length(); int tValue = tNumber; List tValues = new ArrayList(); tValues.add(tNumber); for(int i = 1; i < tLength; ++i) { int tHead = tValue / UNITS[tLength]; int tTail = tValue - tHead * UNITS[tLength]; int tNewValue = tTail * 10 + tHead; if((tLower <= tNewValue) && (tNewValue <= tUpper)) { tValues.add(tNewValue); } tValue = tNewValue; } if(tValues.size() > 1) { for(int i = 0; i < tValues.size() - 1; ++i) { for(int j = i + 1; j < tValues.size(); ++j) { int tOldValue = tValues.get(i); int tNewValue = tValues.get(j); long tKey = tOldValue * 10000000l + tNewValue; if((tOldValue < tNewValue) && (tOldValue != tNewValue)) { if(!tMapPairs.containsKey(tKey)) { ++tPairs; tMapPairs.put(tKey, 1); } } } } } } System.out.println(""Case #"" + (tCaseIndex + 1) + "": "" + tPairs); } } } " B20733,"package fixjava; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * A work queue that allows the work queue to continue to increase in size if it is discovered that subdivision of work is * necessary. Call hasIdleWorkers() to see if there are idle workers, and have the worker subdivide their work further by calling * enqueueWork(). */ public class ParallelWorkQueueDynamic { private int numThreads; private ExecutorService threadPool; private CompletionService completionService; private int numWorkUnitsEnqueued = 0; private Object lock = new Object(); public ParallelWorkQueueDynamic(int numThreads) { this.numThreads = numThreads; threadPool = Executors.newFixedThreadPool(numThreads); completionService = new ExecutorCompletionService(threadPool); } /** * Enqueue work. Called by the main thread to start processing, and can also be called by workers to subdivide their work. */ public void enqueueWork(Callable workUnit) { synchronized (lock) { numWorkUnitsEnqueued++; } completionService.submit(workUnit); } /** * Test if there are any idle workers. Should only be called from within a worker so that the total number of workers is greater * than zero (to avoid a race). */ public boolean hasIdleWorkers() { return numWorkUnitsEnqueued < numThreads; } /** * Wait for all work submitted by workers to be completed. Throws IllegalArgumentException if any of the worker threads throw an * exception (this causes an ExecutionException). */ public void waitForAllWorkersToQuit() { try { while (numWorkUnitsEnqueued > 0) { // .take() waits for completion of next task and returns a Future for it completionService.take().get(); synchronized (lock) { numWorkUnitsEnqueued--; } } } catch (InterruptedException e) { e.printStackTrace(); throw new IllegalArgumentException(""waitForAllWorkersToQuit() failed with "" + e.getMessage(), e); } catch (ExecutionException e) { e.printStackTrace(); throw new IllegalArgumentException(""waitForAllWorkersToQuit() failed with "" + e.getMessage(), e); } } public void shutdown() { threadPool.shutdown(); } } " B21813,"public abstract class JamCase { int lineCount; } " B21788,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.Writer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class Main { public static void main(String arg[]) { try { FileInputStream fIn = new FileInputStream(""input.txt""); Charset cs = Charset.forName(""UTF-8""); InputStreamReader iRd = new InputStreamReader(fIn,cs); BufferedReader bRd = new BufferedReader(iRd); String str = bRd.readLine(); Integer line = Integer.parseInt(str); Writer output = null; File file = new File(""output.txt""); output = new BufferedWriter(new FileWriter(file)); for(int i = 0 ; i < line; ++i) { String inLine = bRd.readLine(); String[] nums = inLine.split("" ""); String start = nums[0]; String stop = nums[1]; int result = calculate(Integer.parseInt(start),Integer.parseInt(stop)); // System.out.println(""Case #"" + (i+1) + "": "" + result); output.write(""Case #"" + (i+1) + "": "" + result + ""\n""); } output.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static int calculate(Integer start, Integer stop) { int sum = 0; List ranges = separate(start,stop); for(int i = 0 ; i < ranges.size() ;) { Integer lowBound = ranges.get(i); Integer upBound = ranges.get(i+1); // System.out.println(ranges.get(i) + "" : "" + ranges.get(i+1)); sum += countCyclic(lowBound , upBound); i+=2; } return sum; } public static int countCyclic(Integer start,Integer stop) { int count = 0; int dec = start; boolean mark[] = new boolean[stop-start+1]; for(int i = start ; i < stop ; ++i) { if(!mark[i-dec]) { List shiftRes = shifting(i,start,stop); switch(shiftRes.size()) { case 2 : ++count;break; case 3 : count+=3;break; case 4 : count+=6;break; case 5 : count+=10;break; case 6 : count+=15;break; case 7 : count+=21;break; case 8 : count+=28;break; } for(int j = 0 ; j < shiftRes.size() ; ++j) { Integer num = shiftRes.get(j); mark[num-dec] = true; } } } return count; } public static List shifting(Integer seed ,Integer lowerBound, Integer upperBound) { List result = new ArrayList(); result.add(seed); String num = seed.toString(); int n = num.length()-1; for(int i = 0 ; i < n ; ++i) { num = num.substring(1) + num.charAt(0); Integer intNum = Integer.parseInt(num); if(num.charAt(0)!='0' && !result.contains(intNum) && intNum <= upperBound && intNum >= lowerBound) { result.add(intNum); } } return result; } public static List separate(Integer start, Integer stop) { List shift = null; if(stop.toString().length() > start.toString().length()) { int n = start.toString().length(); String wall = """"; while(wall.length() < n) { wall += 9; } Integer upBound = Integer.parseInt(wall); shift = separate(upBound+1,stop); shift.add(start); shift.add(upBound); } else { shift = new ArrayList(); shift.add(start); shift.add(stop); } return shift; } } " B22162,"package com.vp.iface; public interface Problem{ public static int SPEAKGOOGLERESE = 1; public static int DANCINGWITHGOOGLERS = 2; public static int RECYCLENUMBERS = 3; public String solve(String dataset[]); }" B21964,"import java.io.*; import java.util.*; public class problemC{ public static void main(String args[]) { try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.valueOf(br.readLine()); int count, a, b, base; String line; String[] lineSplit; for(int i = 0; i < T; i++){ line = br.readLine(); lineSplit = line.split("" ""); count = 0; a = Integer.valueOf(lineSplit[0]); b = Integer.valueOf(lineSplit[1]); base = base(a); for(int j = a; j < b; j++){ count += switchAround(j, b, base); } System.out.println(""Case #"" + (i+1) + "": "" + count); } } catch(Exception e){ } } int div = 10; public static int switchAround(int num, int max, int base){ int copy = num; int count = 0; ArrayList listN = new ArrayList(); for(int i = 1; i < base; i *= 10) { if(num % 10 == 0) { num = num/10; continue; } num = num/10 + (num % 10) * base; if(num <= max && num > copy && !listN.contains(num)) { count++; listN.add(num); } } return count; } public static int base(int num){ int base = 1; while(num/base != 0){ base *= 10; } return base/10; } }" B20946,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); int T = Integer.valueOf(str); int[] A = new int[T]; int[] B = new int[T]; int[] res = new int[T]; for (int i = 0; i < T; i++) { A[i] = sc.nextInt(); B[i] = sc.nextInt(); } for (int i = 0; i < T; i++) { for (int n = A[i]; n < B[i]; n++) { Set pairs = new HashSet(); String jstr = String.valueOf(n); for (int j = 0; j < jstr.length() - 1; j++) { jstr = jstr.charAt(jstr.length() - 1) + jstr.substring(0, jstr.length() - 1); int m = Integer.valueOf(jstr); if (n < m && m <= B[i]) { if (!pairs.contains(n + "","" + m)) { pairs.add(n + "","" + m); res[i]++; } } } } System.out.println(""Case #"" + (i + 1) + "": "" + res[i]); } } } " B21582,"import java.io.*; public class Palindrome { public static void main(String args[]) throws IOException { int N; int a,b,i; String s[]; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); N=Integer.parseInt(br.readLine()); for(i=1;i<=N;i++) { s=br.readLine().split("" ""); a=Integer.parseInt(s[0]); b=Integer.parseInt(s[1]); System.out.println(""Case #""+i+"": ""+calc(a,b)); } } public static int calc(int a,int b) { int i,j,k,p1,p2,cnt=0; int tmp[]; p1=-1; p2=-1; for(i=a;i=0;i--) { vals[cnt++]=Integer.parseInt(s.substring(i,digits)+s.substring(0,i)); } return vals; } } " B22250,"import java.io.*; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.ArrayList; public class ReadWriter { public ArrayList readFile(String path){ File file = new File(path); ArrayList strings = new ArrayList(); BufferedReader reader = null; try{ reader = new BufferedReader(new FileReader(file)); String text = null; while((text=reader.readLine())!=null){ strings.add(text); } return strings; } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(reader!=null){ reader.close(); } } catch(Exception e){ e.printStackTrace(); } } return null; } public void writeFile(ArrayList list, String path){ BufferedWriter out=null; try{ FileWriter fstream = new FileWriter(path); out = new BufferedWriter(fstream); for(String s : list){ out.write(s); out.write(""\r\n""); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(out!=null){ out.close(); } } catch(Exception e){ e.printStackTrace(); } } } } " B21798,"import java.io.IOException; import java.util.*; public class AlienLanguage extends JamProblem { private int wordsC; private int wordsL; List words = new ArrayList(); TreeNode startNode; public static void main(String[] args) throws IOException { AlienLanguage p = new AlienLanguage(); p.go(); } @Override void parseFirstLine(List file) { int[] firstLine = JamUtil.parseIntList(file.get(0), 3); caseCount = firstLine[2]; wordsC = firstLine[1]; wordsL = firstLine[0]; startNode = new TreeNode(null); for (int i=0; i curr = new HashSet<>(); curr.add(startNode); List> pattern = cas.pattern; for (int i = 0; i < pattern.size(); i++) { Set characters = pattern.get(i); Set next = new HashSet<>(); for (Character ch : characters) { for (TreeNode node : curr) { if (node.childred.containsKey(ch)) { next.add(node.childred.get(ch)); } } } curr = next; } return """" + curr.size(); } @Override JamCase parseCase(List file, int lineI) { ALCase cas = new ALCase(); cas.lineCount = 1; String line = file.get(lineI); boolean inGroup = false; char[] chars = line.toCharArray(); Set current = new HashSet<>(); for (int i = 0; i < chars.length; i++) { char ch = chars[i]; switch (ch) { case '(': inGroup = true; current = new HashSet<>(); cas.pattern.add(current); break; case ')': inGroup = false; break; default: if (inGroup) { current.add(ch); } else { current = new HashSet<>(); cas.pattern.add(current); current.add(ch); } } } return cas; } void buildTree(String str, TreeNode node) { char c = str.charAt(0); String remain = str.substring(1); if (node.childred.get(c) == null) { TreeNode newNode = new TreeNode(c); node.childred.put(c,newNode); } if (!remain.isEmpty()) { buildTree(remain,node.childred.get(c)); } } } class ALCase extends JamCase { TreeNode startNode = new TreeNode(null); List> pattern = new ArrayList>(); } class TreeNode { TreeNode(Character ch) { this.ch = ch; } Character ch; Map childred = new HashMap(); } " B20184,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package codejam.practice; /** * * @author Saikat Roy */ import java.io.*; public class Main2 { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public void input() throws IOException { int k=1; int n=Integer.parseInt(br.readLine()); while(n--!=0) { int flag=0; String[] str2=new String[25]; String str1=br.readLine(); String stcpy=""""; str2=str1.split(""[ ]""); int i=(int) Math.pow(10,str2[0].length()-1); for(int x=Integer.parseInt(str2[0]);x<=Integer.parseInt(str2[1]);x++) { if(i!=1){ String mx=String.valueOf(x); for(int l=1;lInteger.parseInt(mx)&&Integer.parseInt(st)<=Integer.parseInt(str2[1])) { if(stcpy.equals(st)) mark=0; if(mark!=0) { flag++; stcpy=""""; stcpy+=st; //System.out.println(mx+"":""+st); }} } } else flag=0; } System.out.print(""Case #""+k+"": ""+flag); System.out.println(); //System.out.println(Integer.parseInt(""201"")= min) { int small = Math.min(result, i); int big = Math.max(result, i); if (!recycled.containsKey(small)) { ArrayList empty = new ArrayList(); empty.add(big); recycled.put(small,empty); } else { ArrayList list = (ArrayList) recycled.get(small); if (!list.contains(big)) list.add(big); recycled.put(small,list); } } } } int result = 0; for (Object list : recycled.values()) { result += ((ArrayList)list).size(); } return result; } private int move(int i, int j) { String whole = String.valueOf(i); String suffix = whole.substring(whole.length()-j); String prefix = whole.substring(0, whole.length()-j); return Integer.parseInt(suffix+prefix); } private int nbDigits(int j) { return String.valueOf(j).length(); } } " B20065,"/* ID: lovelacer LANG: JAVA PROG: candy */ import java.io.*; import java.util.*; public class recycle { public static void main (String [] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader(""recycle.txt"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""recycle1.txt""))); int T = Integer.parseInt(f.readLine()); HashSet checked; String[] nums; for(int k = 1; k <= T; k++) { nums = f.readLine().split("" ""); int A = Integer.parseInt(nums[0]), B = Integer.parseInt(nums[1]), ans = 0; for(int n = A; n < B; n++) { checked = new HashSet(); String a = """" + n; String tmp = a.substring(1) + a.substring(0, 1); while(!tmp.equals(a)) { if(Integer.parseInt(tmp) <= B && Integer.parseInt(tmp) > n && !checked.contains(tmp)) { ans++; checked.add(tmp); } tmp = tmp.substring(1) + tmp.substring(0, 1); } } out.println(""Case #"" + k + "": "" + ans); } out.close(); System.exit(0); } }" B20582,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class RecylcedNumbers { public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File(""input.in"")); BufferedWriter bfrw = new BufferedWriter(new FileWriter(""output.out"")); long N = in.nextLong(); String output = """"; for(long i = 0; i < N;i++){ long A = in.nextLong(); long B = in.nextLong(); output += ""Case #""+(i+1)+"": "" + solve(A,B) + ""\n""; } bfrw.write(output); in.close(); bfrw.close(); } private static long solve(long A,long B){ long ans = 0; if(B <= 9) return 0; HashSet set = new HashSet(); for(long i = A; i <=B; i++){ String s = i+""""; for(int j = 0; j < s.length();j++){ String one = s.substring(s.length()-j); String two = s.substring(0,s.length()-j); if(Integer.parseInt(one+two) <= B && i < Integer.parseInt(one+two)) { ans++; //System.out.println(s + "" --> "" + one + two); set.add(i+"",""+Integer.parseInt(one+two)); } } } return set.size(); } } " B22023," //package c; import java.io.*; import java.util.*; public class Main { public static void main(String args[]) throws IOException{ BufferedReader in = new BufferedReader(new FileReader(""C.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C.out""))); int T = Integer.parseInt(in.readLine()); for(int C = 1; C <= T ; C++) doit(C, in, out); in.close(); out.close(); System.exit(0); } public static void doit(int C, BufferedReader in, PrintWriter out) throws IOException{ StringTokenizer tok = new StringTokenizer(in.readLine()); int A = Integer.parseInt(tok.nextToken()); int B = Integer.parseInt(tok.nextToken()); //SOLUTION long ans = 0; for(int i = A; i <= B; i++){ int[] arr = rotateString( i + """" ); int kl = arr.length; for(int k = 0; k < kl; k++){ if(arr[k] >= A && arr[k] <= B && arr[k] > i) ans++; } } out.println(""Case #"" + C + "": "" + ans); } public static int[] rotateString(String s){ Set list = new HashSet(); int L = s.length(); if(L == 1) return new int[]{}; for(int i = 1; i < L ; i++) { list.add(Integer.parseInt( s.substring(i) + s.substring(0, i))); } int size = list.size(); int[] arr = new int[size]; int now = 0; for(Integer num : list) arr[now++] = num; return arr; } }" B21470,"package qual; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { new RecycledNumbers().run(); } private void run() { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int t = 0; t < T; t++) { int A = sc.nextInt(); int B = sc.nextInt(); int result = solve(A, B); System.out.printf(""Case #%d: %d\n"", t + 1, result); } } public int solve(int A, int B) { int result = 0; for (int i = A; i <= B; i++) { int dig = (int) Math.log10(A/*same as B*/) + 1; int aa = i; for (int d = 0; d < dig - 1; d++) { aa = (aa % 10) * (int)Math.pow(10, dig - 1) + (aa / 10); if (i == aa) { break; } if (i < aa && aa <= B) { // System.out.printf(""(%d, %d) "", i, aa); result++; } } } return result; } } " B20615,"import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T=in.nextInt(); for(int t=1; t<=T; t++) { int N=0; int A=in.nextInt(), B=in.nextInt(); int num = (int) Math.log10(B); for(int n=A; n n && m <= B) N++; } } System.out.println(""Case #""+t+"": ""+N); } } } " B21008,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.StringTokenizer; public class Main { public static int keta; public static void main(String[] args) throws Exception { FileReader in = new FileReader(""F:\\download\\C-large.in""); BufferedReader br = new BufferedReader(in); FileWriter out = new FileWriter(""F:\\download\\out.txt""); BufferedWriter bw = new BufferedWriter(out); int t = Integer.parseInt(br.readLine()); for (int c = 0; c < t; c++){ String line = br.readLine(); StringTokenizer aSt = new StringTokenizer(line, "" ""); int a = Integer.valueOf(aSt.nextToken()).intValue(); int b = Integer.valueOf(aSt.nextToken()).intValue(); keta = (int)Math.log10(a) + 1; int pairs = 0; for (int n = a; n <= b; n++){ pairs += pairs(a, b, n); } bw.write(String.format(""Case #%d: %d\n"", c+1, pairs)); } br.close(); in.close(); bw.close(); out.close(); } public static int pairs(int a, int b, int num){ int numbers = 1; int[] stock = new int[keta]; stock[0] = num; for (int x = 1; x < keta; x++){ int recycle = (num % (int)Math.pow(10, keta - x)) * (int)Math.pow(10, x) + (int)(num / (int)Math.pow(10, keta - x)); if ((a <= recycle)&&(recycle <= b)){ if (recycle < num) return 0; boolean flag = false; for (int st = 0; st < numbers; st++){ if (stock[st] == recycle) flag = true; } if (!flag){ stock[numbers] = recycle; numbers ++; } } } return numbers * (numbers - 1) / 2; } } " B22079,"package com.unitedcoders.examples.codejam; import java.io.File; import java.io.PrintStream; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(new File(""/Users/nh/c.in"")); PrintStream out = new PrintStream(new File(""/Users/nh/c.out"")); int testcases = scanner.nextInt(); scanner.nextLine(); for (int casenr = 1; casenr <= testcases; casenr++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int p = solve(a, b); System.out.printf(""Case #%d: %d\n"", casenr, p); out.printf(""Case #%d: %d\n"", casenr, p); } } public static int solve(int a, int b) { int result = 0; String sA = intToString(a); String sB = intToString(b); for (int i = a; i <= b; i++) { if (i < 10) { continue; } String k = intToString(i); for (int j = 0; j < sA.length()-1; j++) { k = cycle(k); if((stringToInt(k)>i) && (stringToInt(k)<=b)){ result++; } } } return result; } public static String intToString(int i) { StringBuffer sb = new StringBuffer(); while (i > 0) { sb.append(i % 10); i = i / 10; } return sb.reverse().toString(); } public static int stringToInt(String s) { return Integer.valueOf(s); } public static String cycle(String s) { StringBuffer sb = new StringBuffer(); for (int i = 1; i < s.length(); i++) { sb.append(s.substring(i, i + 1)); } sb.append(s.substring(0, 1)); return sb.toString(); } } " B21335,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class testC { public static void main(String args[]){ int count=0; int A=1111; int B=2222; String str=""""; String a=""""; String b=""""; int n=0; int m=0; boolean flag=false; char s[] = ((B)+"""").toCharArray(); char t[]; int digits = 0; List list = new ArrayList(); try{ FileReader fr = new FileReader(""2.txt""); BufferedReader br = new BufferedReader(fr); int size = Integer.parseInt(br.readLine()); for(int loop=0;loop=A && n>i && !list.contains(n) && i>=A) { count++; // System.out.println(i+"" ""+n); list.add(n); } } list.clear(); } System.out.println(""Case #""+(loop+1)+"": ""+count); //System.out.println(""Case #""+(loop+1)+"": ""+count+"" For ""+A+"" ""+B); } br.close(); fr.close(); }catch(IOException ex){ ex.printStackTrace(); } } private static char[] findRecyclingNumber(char[] s,int digits) { // TODO Auto-generated method stub char t[] = new char[s.length]; for(int i=0;i<=digits;i++){ t[i] = s[s.length-digits-1+i]; } int index=0; for(int i=digits+1;i k && p <= b) count++; } } out.write(""Case #"" + i + "": "" + count + ""\n""); } in.close(); out.close(); } } " B20066,"import java.io.*; public class Recycle { int t=0,A=0,B=0; String output=""""; int count=1; public void readFile(String fn) { String data=""""; try{ File in=new File(fn); BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(in))); data=br.readLine(); t=Integer.parseInt(data); while(count<=t) { data=br.readLine(); String s[]=data.split("" ""); A=Integer.parseInt(s[0]); B=Integer.parseInt(s[1]); computeRecycle(); count++; } br.close(); }catch(Exception e){} } public static void main(String args[]) { Recycle rc=new Recycle(); rc.readFile(args[0]); rc.writeToFile(); } public void computeRecycle() { int sum=0; for(int i=A;i<=B;i++) { String s=""""+i; String t=s; int nm=0; int l=s.length(); do { char c[]=t.toCharArray(); char ch=c[0]; for(int j=0;j=A && nm<=B) { sum++; } }while(nm!=i); } sum=sum/2; output+=""Case #""+count+"": ""+sum+""\n""; } public void writeToFile(){ try { File fout= new File(""output.in""); DataOutputStream dos = new DataOutputStream(new FileOutputStream(fout)); dos.writeBytes(output); dos.close(); } catch (Exception ex) {} } }" B21142,"import java.io.*; public class Test3 { final static String INPUT_FILE_NAME = ""input3""; int T = 0; int q = 0; public static void main(String args[]) { try { Test3 tst = new Test3(); tst.getInput(); } catch (Exception e) { e.printStackTrace(); } } private void getInput() throws Exception { File file = new File(INPUT_FILE_NAME); FileReader fis = new FileReader(file); BufferedReader br = new BufferedReader(fis); String strT = br.readLine(); T = getInt(strT); for (int i=0; i0) { counts[sortNumber(i)]++; } } for (int i=0; i<=B;i++) { //System.out.println(""i=""+i+"" counts=""+counts[i]); rtn += counts[i] * (counts[i]-1) / 2; } System.out.println(""Case #""+(t+1)+"": ""+rtn); //System.out.println(""Hello WorldI""); } private int sortNumber(int i) { String str = String.valueOf(i); int keta = str.length(); int min = i; String slideStr = str; for (int k=0; k getInt(slideStr)) { min = getInt(slideStr); } } return min; } private int getInt(String a) { return Integer.parseInt(a, 10); } private int getIntx(String a) { if (a.equals(""."")) { return 0; } return 1; } } " B21316,"import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; public class Utils { public static ArrayList readFile(String filename){ //replace local file with remote file from peerInfo address ArrayList ret= new ArrayList(); try { FileInputStream fstream = new FileInputStream(filename); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console ret.add(strLine); } //Close the input stream in.close(); } catch (Exception e) { e.printStackTrace(); } return ret; } public static void writeFile(ArrayList input, String filename){ //replace local file with remote file from peerInfo address try{ // Create file FileWriter fstream = new FileWriter(filename); BufferedWriter out = new BufferedWriter(fstream); for (String string : input) { out.write(string+""\n""); } //Close the output stream out.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public static void compare(String filename1, String filename2){ //replace local file with remote file from peerInfo address try { FileInputStream fstream1 = new FileInputStream(filename1); // Get the object of DataInputStream DataInputStream in1 = new DataInputStream(fstream1); BufferedReader br1 = new BufferedReader(new InputStreamReader(in1)); String strLine1; FileInputStream fstream2 = new FileInputStream(filename2); // Get the object of DataInputStream DataInputStream in2 = new DataInputStream(fstream2); BufferedReader br2 = new BufferedReader(new InputStreamReader(in2)); String strLine2; boolean isDup=false; //Read File Line By Line while ((strLine1 = br1.readLine()) != null) { strLine2 = br2.readLine(); // Print the content on the console if(!strLine1.equals(strLine2)){ isDup=true; System.out.println(""1=""+strLine1+"", 2=""+strLine2); } } if(!isDup){ System.out.println(""same""); } //Close the input stream in1.close(); in2.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public static void sort(String input, String output){ //replace local file with remote file from peerInfo address ArrayList l= readFile(input); Collections.sort(l, new Comparator(){ public int compare(Object arg0, Object arg1) { String st1=(String)arg0; String st2=(String)arg1; int i1=Integer.parseInt(st1.substring(st1.indexOf('#')+1, st1.indexOf(':'))); int i2=Integer.parseInt(st2.substring(st2.indexOf('#')+1, st2.indexOf(':'))); return i1-i2; } }); writeFile(l, output); } } " B21108,"package cj2012; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class c { static PrintWriter pw; static int testOut = 1; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new FileReader( ""C://CODEJAM//2012//C-large-0.in"")); pw = new PrintWriter(new FileWriter(""C://CODEJAM//2012//C-large-0.out"")); int ntest = sc.nextInt(); // sc.nextLine(); for (int test = 1; test <= ntest; ++test) { // sc.next(); int A = sc.nextInt(); int B = sc.nextInt(); int pairs = 0; for (int i = A; i <= B; i++) { // System.out.println(i); if (i > 9) { String is = """" + i; HashSet results = new HashSet(); for (int j = 1; j < is.length(); j++) { String changed = is.substring(is.length() - j, is.length()) + is.substring(0, is.length() - j); if (!results.contains(changed)) { int ci = Integer.parseInt(changed); if (ci > i && ci <= B) { //System.out.println(is + ""-"" + changed); pairs++; results.add(changed); } } } } } wc("""" + pairs); } pw.close(); sc.close(); System.out.println(""finished""); } // static int Digits(int number) { // int digits = 0; // int step = 1; // while (step <= number) { // digits++; // step *= 10; // } // if (digits == 0) // return 1; // else // return digits; // } private static void wc(String text) { String tt = ""Case #"" + testOut++ + "": "" + text; pw.print(tt); pw.println(); System.out.println(tt); } } " B21380,"package main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.StringReader; import java.io.StringWriter; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.management.ImmutableDescriptor; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; public class Problem3 { public static void main(String[] args) throws Exception { new Problem3().prepareAndSolve(); } private void prepareAndSolve() throws Exception { File inout = new File(""inout""); final String testSuffix; if (getClass().getSimpleName().endsWith(""1"")) { testSuffix = ""A""; } else if (getClass().getSimpleName().endsWith(""2"")) { testSuffix = ""B""; } else if (getClass().getSimpleName().endsWith(""3"")) { testSuffix = ""C""; } else { testSuffix = ""D""; } File ioDir = inout.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(testSuffix) == 0; } })[0]; // SAMPLE File sampleIn = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(""sample.in"") == 0; } })[0]; StringWriter buffer = new StringWriter(); BufferedWriter writer = new BufferedWriter(buffer); long time = System.currentTimeMillis(); solve(new BufferedReader(new FileReader(sampleIn)), writer); System.out.println(""Sample checked: "" + (System.currentTimeMillis() - time) + "" ms""); writer.close(); File sampleOut = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(""sample.out"") == 0; } })[0]; if (checkCorrectness(buffer.toString(), sampleOut) == false) { System.out.println(""NOT CORRECT:""); System.out.println(buffer.toString()); return; } // ADDITIONAL File[] additionalTest = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(""add.in"") == 0; } }); if (additionalTest.length == 1) { buffer = new StringWriter(); writer = new BufferedWriter(buffer); time = System.currentTimeMillis(); solve(new BufferedReader(new FileReader(additionalTest[0])), writer); System.out.println(""Additional checked: "" + (System.currentTimeMillis() - time) + "" ms""); writer.close(); File additionalTestAnswer = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(""add.out"") == 0; } })[0]; if (checkCorrectness(buffer.toString(), additionalTestAnswer) == false) { System.out.println(""NOT CORRECT:""); System.out.println(buffer.toString()); return; } } // SMALL File[] smallTest = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.contains(""small"") && name.contains(""in""); } }); if (smallTest.length == 1) { buffer = new StringWriter(); writer = new BufferedWriter(buffer); time = System.currentTimeMillis(); solve(new BufferedReader(new FileReader(smallTest[0])), writer); System.out.print(""Small runned: "" + (System.currentTimeMillis() - time) + "" ms""); writer.close(); File smallAnswer[] = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(""small.out"") == 0; } }); if (smallAnswer.length == 1) { if (checkCorrectness(buffer.toString(), smallAnswer[0]) == false) { System.out.println(""NOT CORRECT:""); System.out.println(buffer.toString()); return; } System.out.println("", verified""); } else { BufferedWriter solutionWriter = new BufferedWriter(new FileWriter(""inout"" + File.separatorChar + testSuffix + File.separatorChar + ""small.out"")); solutionWriter.write(buffer.toString()); solutionWriter.close(); System.out.println("", written""); } } // RANDOM GENERATED if (testWithRandom == true) { StringWriter sw = new StringWriter(); BufferedWriter bw = new BufferedWriter(sw); bw.write("""" + randomInputTestNum); bw.newLine(); for (int i = 0; i < randomInputTestNum; i++) { generateOneRandomInputTest(bw); } time = System.currentTimeMillis(); bw.flush(); solve(new BufferedReader(new StringReader(sw.toString())), new BufferedWriter(new StringWriter())); System.out.print(""Random runned: "" + (System.currentTimeMillis() - time) + "" ms""); } // LARGE File[] largeTest = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.contains(""large"") && name.contains(""in""); } }); if (largeTest.length == 1) { buffer = new StringWriter(); writer = new BufferedWriter(buffer); time = System.currentTimeMillis(); solve(new BufferedReader(new FileReader(largeTest[0])), writer); System.out.print(""Large runned: "" + (System.currentTimeMillis() - time) + "" ms""); writer.close(); File largeAnswer[] = ioDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.compareTo(""large.out"") == 0; } }); if (largeAnswer.length == 1) { if (checkCorrectness(buffer.toString(), largeAnswer[0]) == false) { System.out.println(""NOT CORRECT:""); System.out.println(buffer.toString()); return; } System.out.println("", verified""); } else { BufferedWriter solutionWriter = new BufferedWriter(new FileWriter(""inout"" + File.separatorChar + testSuffix + File.separatorChar + ""large.out"")); solutionWriter.write(buffer.toString()); solutionWriter.close(); System.out.println("", written""); } } } private boolean checkCorrectness(String answer, File correctAnswerFile) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(correctAnswerFile)); try { BufferedReader stringReader = new BufferedReader(new StringReader(answer)); String answerLine = stringReader.readLine(); String solutionLine = reader.readLine(); while (answerLine != null && solutionLine != null) { if (answerLine.compareTo(solutionLine) != 0) { return false; } answerLine = stringReader.readLine(); solutionLine = reader.readLine(); } if (solutionLine != null) { solutionLine = reader.readLine(); } if (solutionLine != null || answerLine != null) { return false; } return true; } finally { reader.close(); } } private int tasksRunning = 0; @SuppressWarnings(""unchecked"") public void solve(BufferedReader reader, BufferedWriter writer) throws Exception { int T = Integer.parseInt(reader.readLine()); ExecutorService xs = Executors.newFixedThreadPool(4); Future[] outputs = new Future[T]; for (int i = 0; i < outputs.length; i++) { final Solution s = new Solution(); tasksRunning++; s.readInput(reader); outputs[i] = xs.submit(new Callable() { @Override public String call() throws Exception { try { return s.solveInput(); } finally { tasksRunning--; } } }); } new Thread() { public void run() { try { while (true) { sleep(10000); if (tasksRunning == 0) { interrupt(); } System.out.println(""Tasks remaining:"" + tasksRunning); } } catch (InterruptedException e) { } }; }.start(); for (int i = 0; i < outputs.length; i++) { writer.write(""Case #"" + (i + 1) + "": "" + outputs[i].get()); writer.newLine(); } xs.shutdown(); } // ------------------------START OF THE SOLUTION------------------------------ public static boolean testWithRandom = false; public static int randomInputTestNum = 1; public void generateOneRandomInputTest(BufferedWriter bw) throws Exception { bw.write(500 + """"); bw.newLine(); } public static class Solution { private int getIntegerLength(int i) { return (i + """").length(); } private int recycleInt(int integer, int position) { return Integer.parseInt((integer + """").substring(position) + (integer + """").substring(0, position)); } private ImmutableSet getRecycleds(int integer) { ImmutableSet.Builder res = ImmutableSet.builder(); for (int i = 1; i < getIntegerLength(integer); i++) { res.add(recycleInt(integer, i)); } return res.build(); } private ImmutableSet getGreaterRecycledsBetween(final int integer, final int min, final int max) { return ImmutableSet.copyOf(Collections2.filter(getRecycleds(integer), new Predicate() { public boolean apply(Integer arg0) { return arg0 >= min && arg0 <= max && arg0 > integer; }; })); } private int getAllRecycledsNumBetween(int min, int max) { int result = 0; for (int i = min; i <= max; i++) { result += getGreaterRecycledsBetween(i, min, max).size(); } return result; } private int minParam; private int maxParam; public void readInput(BufferedReader reader) throws Exception { String line = reader.readLine(); minParam = Integer.parseInt(line.split(""[ ]"")[0]); maxParam = Integer.parseInt(line.split(""[ ]"")[1]); } public String solveInput() throws Exception { return getAllRecycledsNumBetween(minParam, maxParam) + """"; } } } " B21396,"import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class CodejamC { public static final String TEST = ""test.in"", SMALL = ""C-small-attempt0.in"", LARGE = ""C-large.in""; public static final String OUTPUT = ""out.txt""; static int count = 0; public static void main(String[] args) throws Exception { solve(LARGE); } public static void solve(String filename) throws Exception { Scanner in = new Scanner(new File(filename)); int cases = in.nextInt(); in.nextLine(); PrintWriter out = new PrintWriter(new File(OUTPUT)); for(int num = 1; num <= cases; num++) { int a = in.nextInt(); int b = in.nextInt(); count = 0; in.nextLine(); int result = 0; Set perms = new HashSet(); for(int i = a; i <= b; i++) { String str = String.valueOf(i); for(int j = 0; j < str.length(); j++) { String newStr = str.substring(str.length() - j, str.length()) + str.substring(0, str.length() - j); int val = Integer.parseInt(newStr); if(val >= a && val <= b && !newStr.equals(str) && newStr.charAt(0)!='0') { perms.add(new Pair(str, newStr)); } } //perms.remove(str); } result = perms.size(); out.println(""Case #""+num+"": ""+result); System.out.println(""Case #""+num+"": ""+result); } out.close(); } } class Pair { String n, m; public Pair(String str, String newStr) { n = str; m = newStr; } @Override public boolean equals(Object o) { Pair other = (Pair) o; return (n.equals(other.n)&& m.equals(other.m)) || (m.equals(other.n) && n.equals(other.m)); } @Override public int hashCode() { // TODO Auto-generated method stub return n.hashCode() + m.hashCode(); } } " B20891,"package qualifyingRound; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class RecycledNumbers { public static void main (String [] args) throws FileNotFoundException { Scanner in = new Scanner (new File (""input.txt"")); int numLines = Integer.parseInt(in.nextLine()); int i = 1; for (int j = 0; j < numLines; j++)// (in.hasNextLine()) { System.out.print(""Case #"" + i + "": ""); int low = in.nextInt(); int high = in.nextInt(); int count = 0; for (int c = low; c < high; c++) { // int temp = computePermutations(c,high); // System.out.println(c + "" "" + temp); // count+=temp; count += computePermutations(c,high); } System.out.println(count); i = i+1; } // System.out.println(computePermutations(2212,2222)); } private static int computePermutations (int low, int high) { String str = """" + low; int length = str.length(); int count = 0; int temp = low; for (int i = 0; i < length; i++) { int last = temp % 10; temp = temp/10 + last * pow10(length - 1); // System.out.println(low + "" "" + temp); if (temp > low && temp <= high) { // System.out.println(low + "" "" + temp); count++; } } return count; } private static int pow10 (int pow) { int toReturn = 1; for (int i = 0; i < pow; i++) { toReturn *= 10; } return toReturn; } } " B20655,"import java.util.*; import java.lang.*; public class recyce{ public static int count(int A, int B) { HashSet set; int count = 0; int n = (int) Math.log10(A)+1; for(int num = A; num <= B; num++) { int rem = num; int base = 1; set = new HashSet(); for(int k = 1; k < n; k++) { base *= 10; int love = rem/base + (num%base)*((int)Math.pow(10.,n-k)); if(love > num && love >= A && love <= B) { if(!set.contains(love)) { set.add(love); count++; // System.out.println(num + "" "" + love); } } } } return count; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); int A,B; for(int i = 0; i < T; i++) { A = in.nextInt(); B = in.nextInt(); System.out.println(""Case #"" + (i+1) + "": "" + count(A,B)); } } } " B20981,"import java.io.*; import java.util.*; import static java.lang.Integer.*; import static java.lang.Math.*; public class CodeJamC { public static void main(String args[]) throws Throwable { System.setOut(new PrintStream(""C-Large.out"")); BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); for (int t=0,T=parseInt(in.readLine().trim());t++ set=new TreeSet(new Comparator() { public int compare(int[] o1, int[] o2) { return o1[0]!=o2[0]?o1[0]-o2[0]:o1[1]-o2[1]; } }); for(int i=A;i<=B;i++){ String a=i+""""; for(int j=a.length()-1;j>0;j--){ int b=parseInt(a.substring(j)+a.substring(0,j)); if(i!=b&&b>=A&&b<=B&&(b+"""").length()==a.length()){ set.add(new int[]{min(i,b),max(i,b)}); } } } sb.append(""Case #""+t+"": ""+set.size()+""\n""); } System.out.print(new String(sb)); } }" B20270,"import java.io.*; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) { try { BufferedReader ifStream = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter ofStream = new PrintWriter(new FileWriter(""C.out"")); int numCase; String inputCase; numCase = Integer.parseInt(ifStream.readLine()); for (int i=1; i<=numCase; i++) { ofStream.println(""Case #""+i+"": ""+recycledNumbers(ifStream.readLine())); } ifStream.close(); ofStream.close(); } catch (IOException e) { System.out.println(""IOException.""); } } private static int recycledNumbers(String input) { StringTokenizer st = new StringTokenizer(input, "" "", false); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int numDigits = String.valueOf(A).length(); int[] mArr = new int[numDigits]; int count, m; int result = 0; for (int n=A; n n && m <= B) { mArr[count++] = m; } } result += count; for (int i=0; i res=new HashSet(); for (int j=a; j<=b; j++) { String s=Integer.toString(j); for (int k=0; k=a && j!=j2) { if (j= bases[i]; i++); return i; } static int shift(int value, int len) { int last = value % 10; return (int)(Math.pow(10, len - 1)) * last + (value / 10); } static int countRecycled(int value, int B) { int shifted = value; int len = digits(value); int[] cache = new int[len]; int ck = 0; out: for (int i = 0; i < len - 1; i++) { shifted = shift(shifted, len); if (shifted > value && shifted <= B) { for (int j = 0; cache[j] != 0; j++) if (cache[j] == shifted) continue out; //System.out.println(""n="" + value + "", m="" + shifted); cache[ck++] = shifted; } } return ck; } /** * @param args */ public static void main(String[] args) { /*int A = 1; int B = 2000000; int count = 0; for (int val = A; val <= B; val++) { count += countRecycled(val, B); } System.out.println(count); /**/ Scanner scan = new Scanner(System.in); int test = scan.nextInt(); for (int t = 1; t <= test; t++) { int A = scan.nextInt(); int B = scan.nextInt(); int count = 0; for (int val = A; val <= B; val++) { count += countRecycled(val, B); } System.out.println(""Case #"" + t + "": "" + count); }/**/ } } " B21709,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; /** * */ /** * @author chuck.rolek * */ public class Problem2 { /** * @param args */ public static void main(String[] args) { ArrayList input = new ArrayList(); ArrayList output = new ArrayList(); Scanner scanner = null; try { //scanner = new Scanner(new File(""\\\\filesrv/stufiles$/matt.tough/Google.txt"")); scanner = new Scanner(new File(""E:/GoogleIn.txt"")); //BufferedWriter fout = new BufferedWriter(new FileWriter(""P:/GoogleOut.txt"")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } while(scanner.hasNext()){ input.add(scanner.nextLine()); } scanner.close(); /* * 4 1 9 10 40 100 500 1111 2222 */ String temp = """"; String modified = """"; String line = """"; int left = 0; int right = 0; int min = 0; int max = 0; String[] split; int count = 0; int previous = 0; int current = 0; for(int i = 1; i < input.size(); i++){ line = input.get(i); split = line.split("" ""); min = Integer.parseInt(split[0]); max = Integer.parseInt(split[1]); for(int x = min; x < max; x++){ temp = x + """"; //current = x; for(int z = temp.length()-1; z >= 0; z--){ modified = temp.substring(z) + temp.substring(0, z); if(Integer.parseInt(temp) != Integer.parseInt(modified)){ //if(Integer.parseInt(temp) <= ((max + min) / 2) if(Integer.parseInt(modified) <= max && Integer.parseInt(modified) >= min){ if(Integer.parseInt(modified) > x){ //System.out.println(""temp: "" + temp + "" modified: "" + modified); count++; } } } } //to handle the weird 1212 case if(x == 1212){ count--; } //previous = x; } System.out.println(count); output.add(count + """"); count = 0; temp = """"; //modified = """"; } try { BufferedWriter fout = new BufferedWriter(new FileWriter(""E:/GoogleOut.txt"")); for(int i = 0; i < output.size(); i++){ fout.write(""Case #"" + (i+1) + "": "" + output.get(i)); fout.newLine(); } fout.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B21476,"import java.io.DataInputStream; import java.io.EOFException; import java.io.FileInputStream; import java.io.FileWriter; import java.util.HashSet; public class shift { /** * @param args */ public static void main(String[] args) { try{ FileInputStream infile = new FileInputStream(""in""); DataInputStream datain = new DataInputStream(infile); //Reader reader = new InputStreamReader(new FileInputStream(infile)); FileWriter writer = new FileWriter(""out"", false); String s = datain.readLine(); Integer k = new Integer(s); for (int i=1;i<=k;i++){ s = datain.readLine(); String [] ABstring = s.split("" ""); Integer A = new Integer(ABstring[0]); Integer B = new Integer(ABstring[1]); int numShift = ABstring[0].length()-1; int numRecycledNum = 0; for (int n=A;n nSet = new HashSet(); int roundShift = 1; String stringN = Integer.toString(n); stringN = stringN.substring(1) + stringN.charAt(0); //nSet.add(stringN); while (roundShift<=numShift){ Integer shiftedNum = new Integer(stringN); if (n 0) { if (Integer.parseInt(numStr) <= num2) count++; } } while (!numStr.equals(originalStr)); } System.out.println(""Case #"" + (i+1) + "": "" + count); } } catch (IOException e) { e.printStackTrace(); } } } " B21094,"import java.util.*; import java.math.*; public class recycledNumbers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); int numStrings = scan.nextInt(); for(int i =1; i <= numStrings; i++){ int lowerBound = scan.nextInt(); int upperBound = scan.nextInt(); int numDigits = Integer.toString(lowerBound).length(); int ten = 10; int count = 0; for(int j = lowerBound; j <= upperBound ; j++){ int temp = j; for(int k = 1; k <= numDigits; k++){ int temp_rem = temp % ten; int temp_quot = temp /ten; int temp1 = temp_quot + (int )(Math.pow(ten, numDigits-1))*temp_rem; if (temp1 > j && temp1 <= upperBound){ count = count + 1; } temp = temp1; //System.out.println(""\n"" + j + "" "" + temp + "" "" + upperBound + "" "" + count); } } //System.out.println(""LowerBound: "" + lowerBound + ""\n""); //System.out.println(""UpperBound: "" + upperBound + ""\n""); //System.out.println(""numDigits: "" + numDigits + ""\n""); System.out.format(""Case #%d: %d\n"", i, count); } } } " B21553,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codajam2012; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.util.Vector; /** * * @author dectroo */ public class Recycled { public static Vector tabl; static long[] RotationList(String N) { long result[] = new long[N.length() - 1]; long n = Long.parseLong(N); long number = n; long start = number; int i = 0; int numdigits = (int) Math.log10((double) number); // would return numdigits - 1 int multiplier = (int) Math.pow(10.0, (double) numdigits); while (true) { long q = number / 10; long r = number % 10; number = number / 10; number = number + multiplier * r; if (number == start) { break; } else { result[i] = number; i++; } } return result; } static void ComputePair(long A, long B) { long index = A; int numbrPair = 0; tabl = new Vector(); String indexString; while (index < B) { if (index != 0) { indexString = String.valueOf(index); long result[] = RotationList(indexString); for (int i = 0; i < result.length; i++) { /* * if(tabl.contains(new Long(result[i]))){ * * } */ if (index < result[i] && result[i] <= B) { tabl.add(new Long(result[i])); //System.out.println(result[i]); } } } index++; } } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Scanner in = new Scanner(new File(""test.in"")); PrintWriter out = new PrintWriter(""recycled.out""); /* * for(int i=0;i in = null; try { in = readFile(""input.txt""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String result = doit(Integer.parseInt(in.remove(0)), in); try { writeFile(result, ""output.txt""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static ArrayList readFile(String filename) throws IOException{ ArrayList out = new ArrayList(); // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(filename); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null){ // Print the content on the console out.add(strLine); } //Close the input stream in.close(); return out; } public static String doit(int c, ArrayList cases){ // Main logic StringBuilder out = new StringBuilder(); for(int i = 0; i < c; i++){ String s = cases.get(i); ArrayList sa = new ArrayList(); for(String l : s.split("" "")){ sa.add(Integer.parseInt(l)); } int A = sa.get(0); int B = sa.get(1); int recycles = 0; String t = """"; int size = (A+"""").length(); for(int n = A; n <= B; n++){ t = n+""""; ArrayList passed = new ArrayList(); for(int l = 1; l < size; l++){ int m = Integer.parseInt(t.substring(l)+t.substring(0, l)); if(n >= m || m > B){ continue; } if(passed.contains(m)){ continue; } recycles++; passed.add(m); } } out.append(""Case #""+(i+1)+"": ""+recycles); if(i != c-1){ out.append(""\n""); } } return out.toString(); } public static void writeFile(String output, String file) throws IOException{ FileWriter fstream = new FileWriter(file); BufferedWriter out = new BufferedWriter(fstream); out.write(output); out.close(); } } " B21533,"package q2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); String input = ""C-large.in""; String output = ""C-large.out""; Scanner scan = new Scanner(new BufferedReader(new FileReader(input))); PrintWriter pw = new PrintWriter(new BufferedWriter( new FileWriter(output))); int T = Integer.parseInt(scan.nextLine()); for (int t = 1; t <= T; t++) { String[] info = scan.nextLine().split("" ""); int A = Integer.parseInt(info[0]); int B = Integer.parseInt(info[1]); HashSet set = new HashSet(); long count = 0; for (int i = A; i <= B; i++) { String num = String.valueOf(i); int len = num.length(); set.clear(); for (int j = 1; j < len; j++) { String n = num.substring(j) + num.substring(0, j); int s = Integer.parseInt(n); if (s > i && s <= B) set.add(s); } count += set.size(); } System.out.println(""Case #"" + t + "": "" + count); pw.println(""Case #"" + t + "": "" + count); } scan.close(); pw.close(); long end = System.currentTimeMillis(); System.out.println((end - start) / 1000.0); } }" B21557,"package mar2012; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { public static void main(String[] args) throws Exception { PrintStream out = new PrintStream(new File( ""/Users/asingh/Desktop/gcj2012/prob.c.out.txt"")); ProblemC prob = new ProblemC(); InputStream in = new FileInputStream(new File( ""/Users/asingh/Desktop/gcj2012/prob.c.in.txt"")); prob.solveAll(in, out); // prob.solveTestCase(1, 1000000, 2000000, out); // prob.solveTestCase(1, 1111, 2222, out); } private void solveAll(InputStream in, PrintStream out) throws Exception { Scanner scanner = new Scanner(in); int numTestCases = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < numTestCases; i++) { int min = scanner.nextInt(); int max = scanner.nextInt(); if (i < numTestCases - 1) scanner.nextLine(); solveTestCase(i + 1, min, max, out); } } private static class Tuple { int one; int two; public Tuple(int one, int two) { this.one = Math.min(one, two); this.two = Math.max(one, two); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + one; result = prime * result + two; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Tuple other = (Tuple) obj; if (one != other.one) return false; if (two != other.two) return false; return true; } @Override public String toString() { return ""{"" + one + "", "" + two + ""}""; } } private void solveTestCase(int testCaseId, int min, int max, PrintStream out) { // System.out.println(""testCaseId: "" + testCaseId + "", min: "" + min // + "", max: "" + max); int[] minDigits = getDigits(min); int[] maxDigits = getDigits(max); Set found = new HashSet(); for (int n = min; n <= max; n++) { // debug(""Doing: "" + n); int[] digits = getDigits(n); int prevD = digits[0]; boolean allSame = true; for (int d : digits) { if (prevD != d) { allSame = false; break; } } if (allSame) { // debug("" skipping as same digits""); continue; } for (int i = 1; i <= digits.length - 1; i++) { if (digits[i] > maxDigits[0]) { // formed num will be greater, skip // debug("" skipping as will be greater than "" + max + // "", i="" + i + "", digits[i]="" + digits[i]); continue; } if (digits[i] < minDigits[0]) { // formed num will be smaller, skip // debug("" skipping as will be smaller than "" + min // + // "", i="" + i + "", digits[i]="" + digits[i]); continue; } int[] newNumDigits = swapBlockToBack(digits, i); int num = getNum(newNumDigits); if (num == n) { // debug("" skipping as same nums: "" + n); continue; } if (num >= min && num <= max) { Tuple tuple = new Tuple(n, num); if (found.contains(tuple)) { // debug("" skipping as already found: "" + num); continue; } else { found.add(tuple); //debug(""SOLUTION: "" + tuple); } } else { // debug("" skipping as not in range - min: "" // + min + "", max: "" + max + "", num: "" + num); } } } out.println(""Case #"" + testCaseId + "": "" + found.size()); System.out.println(""Case #"" + testCaseId + "": "" + found.size()); } private int getNum(int[] digits) { int rv = 0; for (int i = digits.length - 1, factor = 1; i >= 0; i--) { int digit = digits[i]; rv += factor * digit; factor *= 10; } return rv; } private int[] swapBlockToBack(int[] digits, int blockSize) { int[] newDigits = new int[digits.length]; System.arraycopy(digits, blockSize, newDigits, 0, digits.length - blockSize); System.arraycopy(digits, 0, newDigits, digits.length - blockSize, blockSize); return newDigits; } private int[] getDigits(int min) { char[] digitChars = String.valueOf(min).toCharArray(); int[] digits = new int[digitChars.length]; for (int i = 0; i < digits.length; i++) { digits[i] = digitChars[i] - '0'; } return digits; } } " B21479,"import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(new File(""recycled.in"")); System.setOut(new PrintStream(new File(""recycled.out""))); int T = sc.nextInt(); HashSet p; int A,B; String sA,sB,sN; for(int set=1; set<=T; set++){ A = sc.nextInt(); B = Integer.parseInt(sB = sc.next()); char max = sB.charAt(0); p = new HashSet((B-A)*4,.99f); for(int n=A; nmax) continue; String sM = sN.substring(j)+sN.substring(0,j); int m = Integer.parseInt(sM); if(A-m<1 && m-B<1 && n!=m){ int small, large; if(n { abstract boolean accept(T item); public static ArrayList list(Iterable collection, Filter filter) { ArrayList filtered = new ArrayList(); for (U item : collection) if (filter.accept(item)) filtered.add(item); return filtered; } public static HashSet set(Set set, Filter filter) { HashSet filtered = new HashSet(); for (U item : set) if (filter.accept(item)) filtered.add(item); return filtered; } public static HashMap mapKeys(Map map, Filter keyFilter) { HashMap filtered = new HashMap(); for (Entry ent : map.entrySet()) if (keyFilter.accept(ent.getKey())) filtered.put(ent.getKey(), ent.getValue()); return filtered; } public static HashMap mapValues(Map map, Filter valueFilter) { HashMap filtered = new HashMap(); for (Entry ent : map.entrySet()) if (valueFilter.accept(ent.getValue())) filtered.put(ent.getKey(), ent.getValue()); return filtered; } } " B21592,"package com.mademoisellegeek.googlecodejam; import com.mademoisellegeek.googlecodejam.y2012.qualround.DancingWithTheGooglers; import com.mademoisellegeek.googlecodejam.y2012.qualround.RecycledNumbers; import com.mademoisellegeek.googlecodejam.y2012.qualround.SpeakingInTongues; public class GoogleCodeJam { public static void main(String[] args) { new Thread(new RecycledNumbers()).start(); } } " B21202,"import java.util.*; /** * * @author Izhari Ishak Aksa */ public class ProblemC { static int ret = 0; static void check(String a, int A) { int x = Integer.parseInt(a); HashMap map = new HashMap(); for (int i = 1; i < a.length(); i++) { String c = a.substring(i) + a.substring(0, i); int y = Integer.parseInt(c); if (y >= A && y < x && !map.containsKey(y)) { ret++; map.put(y, 1); } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = Integer.parseInt(sc.nextLine()); for (int t = 1; t <= T; t++) { int a = sc.nextInt(); int b = sc.nextInt(); ret = 0; for (int i = a + 1; i <= b; i++) { check(i + """", a); } System.out.println(""Case #"" + t + "": "" + ret); } } } " B21358,"package com.my; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { try { RecycledNumbers r = new RecycledNumbers(); String fileLocation = ""C://Training//Google//RecycledNumbers//src//com//my//smallInput.txt""; BufferedReader reader = r.getInputFile(fileLocation); String line = reader.readLine(); int count =1; while ( ( line = reader.readLine()) != null ) { String inputs[] = line.split("" "" ); int numCount = r.recycle(Integer.parseInt(inputs[0]),Integer.parseInt(inputs[1])); System.out.println(""Case #"" + count + "": "" + numCount); ++count; } //System.out.println(r.recycle(100,999)); } catch (Exception e) { // TODO: handle exception } } } class RecycledNumbers { public BufferedReader getInputFile(String fileLocation) throws Exception{ BufferedReader reader = new BufferedReader(new FileReader(new File(fileLocation))); return reader; } int recycle(int first, int second) throws Exception{ int count = 0; for( int i=first; i<=second; ++i) { String str = Integer.toString(i); Set set = new HashSet(); int div = 1; for( int j =0 ; j= a && z > x) { count++; } } } result += count; out.write(result); out.newLine(); } out.close(); } catch (Exception e) { System.out.println(""error""); } } } " B22218,"package tr0llhoehle.cakemix.utility.googleCodeJam; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.LinkedList; import java.util.Scanner; /** * {@link IOManager} is used to manage all input and output operations needed * for your java-solution of a Google codejam problem. * * It uses the class/interface {@link Problem} and {@link Solver}. * * @author Cakemix * * @param * The type of your concrete Solver-implementation which solves the * Problem P. * @param

* The type of your concrete Problem. * @see Problem * @see Solver */ public class IOManager, P extends Problem> { private S solver; private Class

clazz; private LinkedList

problems; /** * Creates a new IOManager. * * @param solver * The solver-instance which is to be used for solving the * problems. * @param clazz * A Class object of one exemplary concrete Problem P. This is * needed to correctly instantiate new concrete Problems. */ public IOManager(S solver, Class

clazz) { this.clazz = clazz; this.solver = solver; } private P createProblem() throws InstantiationException, IllegalAccessException { return clazz.newInstance(); } /** * Starts the IO-operations and solves the Problems contained in the file * pointed to by the filePath. * * @param filePath * A String describing the location of an input-file (usually * *.in) * @throws IOException * @throws ParseException */ public void start(String filePath) throws IOException, ParseException { int amountOfProblems; File out; Scanner lineScanner; File in = new File(filePath); Scanner scanner; FileWriter writer; System.out.print(""Creating files... ""); if (filePath.length() >= 3 && filePath.substring(filePath.length() - 3).equals("".in"")) { filePath = filePath.substring(0, filePath.length() - 3); } filePath += "".out""; out = new File(filePath); out.createNewFile(); System.out.println(""Done!""); System.out.print(""Creating file reader and writers... ""); scanner = new Scanner(in); writer = new FileWriter(out); System.out.println(""Done!""); System.out.print(""Parsing the input file... ""); amountOfProblems = scanner.nextInt(); scanner.nextLine(); problems = new LinkedList

(); for (int probID = 0; probID < amountOfProblems; probID++) { P problem = null; try { problem = createProblem(); SupportedTypes[] probTypes = problem.getTypes(); for (SupportedTypes t : probTypes) { switch (t) { case INT: lineScanner = new Scanner(scanner.nextLine()); problem.addValue(lineScanner.nextInt()); break; case DOUBLE: lineScanner = new Scanner(scanner.nextLine()); problem.addValue(lineScanner.nextDouble()); break; case BOOLEAN: lineScanner = new Scanner(scanner.nextLine()); problem.addValue(lineScanner.nextBoolean()); break; case STRING: problem.addValue(scanner.nextLine()); break; case LIST_INT: lineScanner = new Scanner(scanner.nextLine()); ArrayList ints = new ArrayList(); while (lineScanner.hasNext()) { ints.add(lineScanner.nextInt()); } problem.addValue(ints); break; case LIST_DOUBLE: lineScanner = new Scanner(scanner.nextLine()); ArrayList doubles = new ArrayList(); while (lineScanner.hasNext()) { doubles.add(lineScanner.nextDouble()); } problem.addValue(doubles); break; case LIST_BOOLEAN: lineScanner = new Scanner(scanner.nextLine()); ArrayList booleans = new ArrayList(); while (lineScanner.hasNext()) { booleans.add(lineScanner.nextBoolean()); } problem.addValue(booleans); break; case LIST_STRING: lineScanner = new Scanner(scanner.nextLine()); ArrayList strings = new ArrayList(); while (lineScanner.hasNext()) { strings.add(lineScanner.next()); } problem.addValue(strings); break; default: System.err .print(""Default case! This is not a good sign... ""); } } } catch (IllegalAccessException e) { System.err.println(""Couldn't instantiate the problem!""); e.printStackTrace(); } catch (InstantiationException e) { System.err.println(""Couldn't instantiate the problem!""); // TODO Auto-generated catch block e.printStackTrace(); } if (problem != null) { problems.add(problem); } } System.out.println(""Done!""); System.out.print(""Closing the input file... ""); scanner.close(); System.out.println(""Done!""); System.out.print(""Solving the problems... ""); for (int i = 0; i < problems.size(); i++) { writer.append(""Case #"" + (i+1) + "": "" + solver.solve(problems.get(i)) + System.getProperty(""line.separator"")); } System.out.println(""Done!""); System.out.print(""Closing the writer... ""); writer.close(); System.out.println(""Done!""); System.out.println(""Shutting down, output lies here:""); System.out.println(filePath); } } " B21607,"package com.google.codejam; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class DancingWithGooglers { private int limit(long min, long max){ if (min>max) return 0; int count = 0; for (long i = min; i <= max; i++) { int loopCount = 1; long start = i; long rotation = i; do { rotation = rotate(start,loopCount); if ( rotation <= max && rotation > start) { // System.out.println(""pair numbers : "" + start + "","" + rotation); count+=1; } // else{ // System.out.println(""!!not pair numbers : "" + start + "","" + rotation); // } loopCount++; } while (loopCount<=Long.toString(start).length()); } return count; } // private long rotate(long x){ // if (x<9) { // return x; // } // long firstpart = x/10; // long secondpart = x%10; // double firstpartlen = (String.valueOf(firstpart)).length(); // int mul = (int) Math.pow(10, firstpartlen); // long fin = (secondpart * mul) + firstpart; // return fin; // } private long rotate(long x,int index){ if (x<9) { return x; } String s = Long.toString(x); String s1 = s.substring(0, s.length()-index); String s2 = s.substring(s.length()-index, s.length()); String s3 = s2+s1; return Long.parseLong(s3); } public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new FileReader(""resources/googlecodejam/dancingwiththegooglers.txt"")); String strLine; int caseLine = 0; int lineCount = 0; DancingWithGooglers dancingWithGooglers = new DancingWithGooglers(); while ((strLine = in.readLine()) != null) { // Print the content on the console if (lineCount == 0) { lineCount+=1; continue; } caseLine += 1; long min = Long.parseLong(strLine.split("" "")[0]); long max = Long.parseLong(strLine.split("" "")[1]); System.out.println(""Case #"" + caseLine + "": "" + dancingWithGooglers.limit(min,max)); } } } " B21748,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam3; import java.io.File; import java.io.*; import java.util.*; /** * * @author saad */ public class Codejam3 { /** * @param args the command line arguments */ static int convert(Integer min,Integer max){ int n=min.toString().length() ; int res=0 ; List l=new LinkedList() ; for(int i=min;ii&&a<=max){ if(!l.contains(a)){ res++ ; l.add(a) ; } } } } return res ; } public static void main(String[] args) throws FileNotFoundException { Scanner in=new Scanner(new File(""C-large.in"")) ; PrintWriter out=new PrintWriter(""C-large.out"") ; int n=in.nextInt() ; for(int i=0;i pairs = new HashSet(); for (int n = A; n < B; ++n) { l = String.valueOf(n).length(); pow1 = (int)Math.pow(10, l); pow2 = 1; pairs.clear(); for (int j = 1; j < l; ++j) { pow1 /= 10; pow2 *= 10; m = ((n % pow1) * pow2 + n / pow1); if (m <= B && m > n && pairs.add(n + "" "" + m)) { cnt++; } } } String res = String.format(""%d"", cnt); pw.println(String.format(""Case #%d: %s"", CASE, res)); left = (System.currentTimeMillis() - start) * (NUM_CASES - CASE) / CASE; System.out.println(String.format(""%s (%dms, ~%dms left)"", res, (System.currentTimeMillis() - t1), left)); } pw.close(); scan.close(); } catch (Exception e) { e.printStackTrace(); } } } " B22009,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; public class RecycledNumbers { public static void main(String[] args){ try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(args[0]); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line int numTest = Integer.parseInt(br.readLine()); for(int i = 0; i < numTest; i ++){ String str = br.readLine(); String numbers[] = str.split("" ""); int count = recycledNumbers(Integer.parseInt(numbers[0]),Integer.parseInt(numbers[1])); int x = i + 1; System.out.println(""Case #"" + x + "": "" + count); } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } public static int recycledNumbers(int min, int max){ int digits = Integer.toString(min).length(); int current = min; int count = 0; while(current <= max){ ArrayList newNumbers = new ArrayList(); for(int i = 1; i < digits; i++){ String movedDigits = Integer.toString(current).substring(i); String remainingDigits; if(i == 1){ remainingDigits = Character.toString(Integer.toString(current).charAt(0)); } else{ remainingDigits = Integer.toString(current).substring(0,i); } int newNumber = Integer.parseInt(movedDigits + remainingDigits); if(newNumber != current && newNumber <= max && newNumber >= min ){ boolean alreadyExists = false; for(Integer no : newNumbers){ if(no.intValue() == newNumber){ alreadyExists = true; } } if(!alreadyExists){ if(current < newNumber){ count ++; //System.out.println(""("" + current + "","" + newNumber + "")""); newNumbers.add(new Integer(newNumber)); } } } } current++; } return count; } } " B22216,"package tr0llhoehle.cakemix.utility.googleCodeJam; public interface Solver { public String solve(T p); } " B20174,"import java.net.*; import java.io.*; import java.lang.*; public class RecycledNumbers { public static void clear(int[] arr){ for(int i=0; i<30; i++) arr[i] = -1; } public static boolean checkEntry(int x, int[] arr){ for(int i=0; i<30; i++) { if(x == arr[i]) return true; } return false; } public static void main(String[] args) throws IOException { String[] spl; int counter = 1; int count = 0; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String input; int a,b,e = 0; String xform; int[] arr = new int[30]; int arrCounter = 0; clear(arr); while((input = in.readLine()) != null){ spl = input.split("" ""); a = Integer.parseInt(spl[0]); b = Integer.parseInt(spl[1]); int bLength = (Integer.toString(b)).length(); for(int i=a; i xform.charAt(k)) { if( (bLength > l) || (b >= (e = Integer.parseInt(xform.substring(j) + xform.substring(0 , j)))) ) { //System.out.println(""number:"" + xform + '\t' + Integer.parseInt(xform.substring(j) + xform.substring(0 , j))); if(!checkEntry(e , arr)){ count++; arr[arrCounter] = e; arrCounter++; } break; } else break; } else continue; } } } System.out.println(""Case #"" + counter + "": "" + count ); counter++; count = 0; } }} " B20081,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class Recycled { private static String in; private static String[] ins; private static BufferedReader buf; private static int cases; private static File arquivo = new File(""output.txt""); private static FileOutputStream fos; public static void main(String[] args) { buf = new BufferedReader(new InputStreamReader(System.in)); try { fos = new FileOutputStream(arquivo); } catch (FileNotFoundException e1) { e1.printStackTrace(); System.exit(0); } try { in = buf.readLine(); cases = Integer.parseInt(in); } catch (IOException e) { e.printStackTrace(); System.exit(0); } for (int i = 1; i <= cases; i++) { int result = 0; try { in = buf.readLine(); ins = in.split("" ""); } catch (IOException e) { e.printStackTrace(); System.exit(0); } int A = Integer.parseInt(ins[0]); int B = Integer.parseInt(ins[1]); for (int numb = A; numb <= B; numb++) { result += reciclar(numb, A, B); } try { String res = ""Case #"" + i + "": "" + result + System.getProperty(""line.separator""); fos.write(res.getBytes()); } catch (IOException e) { e.printStackTrace(); System.exit(0); } } } public static int reciclar(int numb, int A, int B) { int result = 0; ArrayList usados = new ArrayList(); char[] numbvec = String.valueOf(numb).toCharArray(); for (int i = 1; i < numbvec.length; i++) { String rot = new String(); for (int j = i; j < numbvec.length + i; j++) { if (j >= numbvec.length) { rot += numbvec[j-numbvec.length]; } else { rot += numbvec[j]; } } int numbrot = Integer.parseInt(rot); if (numbrot >= A && numbrot <= B && numb != numbrot && !usados.contains(numbrot)) { if (numb < numbrot){ result++; usados.add(numbrot); } } } return result; } } " B20450,"package com.snap.training; import java.io.*; import java.util.ArrayList; public class RecycledNumbers { public static ArrayList readFromFile() { ArrayList inputList = new ArrayList(); try { FileReader fr = new FileReader(""C:\\Users\\sanath\\Downloads\\code\\input.in""); BufferedReader br = new BufferedReader(fr); String readLine = null; while((readLine=br.readLine())!=null) { inputList.add(readLine); } } catch (IOException e) { inputList = null; e.printStackTrace(); } return inputList; } public static void writeToFile(ArrayList outputList) { try { FileWriter fw = new FileWriter(""C:\\Users\\sanath\\Downloads\\code\\output.out""); BufferedWriter br = new BufferedWriter(fw); for(int i = 0; i < outputList.size(); i++) { br.write(""Case #"" + (i+1) + "": "" + outputList.get(i)); br.newLine(); } br.close(); } catch (IOException e) { e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { ArrayList inputList = readFromFile(); String inputStr = null; String finalStr = null; ArrayList outputList = new ArrayList(); int noOfTestCases = Integer.parseInt(inputList.get(0).toString()); int a, b, count = 0; for(int i = 1; i < noOfTestCases + 1; i++) { inputStr = inputList.get(i); finalStr = """"; String[] splitStr = inputStr.split("" ""); a = Integer.parseInt(splitStr[0]); b = Integer.parseInt(splitStr[1]); for(int j = a; j <= b; j++) { char[] tempChar = String.valueOf(j).toCharArray(); char[] tempCharConverted = new char[tempChar.length]; ArrayList checkList = new ArrayList(); for(int k = 1; k < tempChar.length; k++) { for(int l = 0, x = k; l < tempChar.length; l++) { tempCharConverted[l] = tempChar[x]; x++; if(x == tempChar.length) x = 0; } if(tempCharConverted[0] != '0') { int value = Integer.parseInt(new String(tempCharConverted)); if(value > j && value <= b && !checkList.contains(new Integer(value))) { checkList.add(new Integer(value)); count++; } } } } finalStr = """" + count; count = 0; outputList.add(finalStr.trim()); } writeToFile(outputList); } } " B20991,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class RecycledNumbers { public static String input = ""easy.txt""; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(input)); int n = Integer.parseInt(in.readLine()); for (int i = 1; i <= n; i++) { String line = in.readLine(); int idx1 = line.indexOf(' '); int a = Integer.parseInt(line.substring(0, idx1)); int b = Integer.parseInt(line.substring(idx1 + 1)); long totalCount = 0; Map, Long> signatureMap = new HashMap, Long>(); for (int x = a; x <= b; x++) { totalCount += recycledNums(x, b); } System.out.println(""Case #"" + i + "": "" + totalCount); } } private static int recycledNums (int n, int max) { List digits = new LinkedList(); int remaining = n; while (remaining > 0) { int digit = remaining % 10; digits.add(digit); remaining /= 10; } //System.out.println(""<<"" + n + "">>""); Set nums = new HashSet(); for (int i = 0; i < digits.size() - 1; i++) { int n0 = digits.remove(0); digits.add(n0); int recycled = numFromList(digits); //System.out.println(recycled); if (recycled > n && recycled <= max) nums.add(recycled); } //System.out.println(n + "": "" + nums); return nums.size(); } private static int numFromList(List list) { int num = 0; for (int i = list.size() - 1; i >= 0; i--) { num *= 10; num += list.get(i); } return num; } } " B20089,"import com.sun.xml.internal.messaging.saaj.packaging.mime.util.LineInputStream; import sun.tools.tree.ReturnStatement; import javax.swing.*; import java.io.*; import java.util.ArrayList; /** * Date: 14/4/12 * Time: 9:19 AM */ public class GoogleFileStream { public static ArrayList getInput() throws IOException { JFileChooser fc = new JFileChooser(); fc.showOpenDialog(null); File f = fc.getSelectedFile(); ArrayList ret = new ArrayList(); LineInputStream lis = new LineInputStream(new FileInputStream(f)); String line; while( (line = lis.readLine()) != null ) { ret.add(line); } // number of lines: ret.remove(0); return ret; } public static void setOutput(ArrayList ret) throws IOException { JFileChooser fc = new JFileChooser(); fc.showSaveDialog(null); File f = fc.getSelectedFile(); StringBuilder sb = new StringBuilder(); FileWriter fw = new FileWriter(f); for( int i = 0; i < ret.size(); i++ ) { sb.delete(0, sb.length()); sb.append(String.format( ""Case #%d: "", i + 1)); sb.append( ret.get(i) ); sb.append( ""\n"" ); String o = sb.toString(); fw.write( o ); System.out.print(o); } fw.close(); } } " B21952,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; import java.util.TreeMap; class Recycled { public static void main(String args[]) throws IOException{ Scanner in = new Scanner(new File(""recycle.txt"")); PrintWriter fw = new PrintWriter(new FileWriter(new File(""recycle.out""))); TreeMap > map = new TreeMap >(); for(int i = 1; i <= 2000000; i++){ ArrayList arr = new ArrayList(); String it = """" + i; for(int k = 0; k < it.length(); k++){ int temp = Integer.parseInt(it.substring(k + 1, it.length()) + it.substring(0, k+1)); if(temp > i){ boolean add = true; for(int ad = 0; ad < arr.size(); ad++){ if(temp==arr.get(ad)) add = false; } if(add) arr.add(temp); } } Collections.sort(arr); map.put(i, arr); } int cases = in.nextInt(); for(int c = 1; c <= cases; c++){ int A = in.nextInt(); int B = in.nextInt(); int pass = 0; for(int a = A; a < B; a++){ if(map.get(a)==null) continue; ArrayList list = map.get(a); for(int l = 0; l < list.size(); l++){ if(list.get(l) <= B) pass++; else break; } } String out = ""Case #"" + c + "": "" + pass; fw.println(out); } fw.close(); } } " B20341," import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Scanner; public class TemplateClass { protected Scanner sc; protected BufferedWriter bw; protected int testCases = 0; File ficheroEntrada; File ficheroSalida; public TemplateClass() { } public TemplateClass(String nombreFicheroEntrada, String nombreFicheroSalida) throws Exception { ficheroEntrada = new File (nombreFicheroEntrada); ficheroSalida = new File (nombreFicheroSalida); sc = new Scanner(ficheroEntrada); testCases = sc.nextInt(); bw = traeBufferSalida(ficheroSalida); } protected BufferedWriter traeBufferSalida(File ficheroSalida) throws Exception { return new BufferedWriter(new FileWriter(ficheroSalida)); } protected void procesaTestCase() throws Exception{ } } " B21527,"/* ========================================================== * (C) Copyright 2007-present Facebook. All rights reserved. * ========================================================== */ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * . * * @author */ public class Recycle { public static void main( String[] args ) throws NumberFormatException, IOException { final BufferedReader in = new BufferedReader( new FileReader( ""/Users/oded/a/ttt/src/in.txt"" ) ); final int numLines = Integer.parseInt( in.readLine() ); for( int i = 0; i < numLines; i++ ) { handleLine( in.readLine(), i ); } } private static int countDigits( int a ) { int count = 0; while( a > 0 ) { count++; a = a / 10; } return count; } private static void handleLine( String readLine, int i ) { String[] numbers = readLine.split( "" "" ); int a = Integer.parseInt( numbers[ 0 ] ); int b = Integer.parseInt( numbers[ 1 ] ); int count = 0; int digits = countDigits( a ); if( digits > 1 ) { int den = 1; while( digits > 1 ) { den *= 10; digits--; } for( int n = a; n < b; n++ ) { int perm = shift( n, den ); while( perm != n ) { if( perm > n && perm <= b ) { count++; } perm = shift( perm, den ); } } } System.out.println( ""Case #"" + ( i + 1 ) + "": "" + count ); } private static int shift( int n, int den ) { return ( n / den ) + ( n % den ) * 10; } } " B22224,"import java.util.*; public class ProblemC { public static void main(String... args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int t=1; t<=T; t++) { int A = sc.nextInt(); int B = sc.nextInt(); int digit = String.valueOf(A).length(); Set set = new HashSet<>(); for ( int i=digit-1; i>0; i-- ) { for (int n=A; n<=B; n++) { String ns = String.valueOf(n); String ms = (ns.substring(digit-i) + ns.substring(0,digit-i)); int m = Integer.parseInt(ms); if( m>B ) continue; if( n values = new ArrayList (); try{ BufferedReader in = new BufferedReader (new FileReader(f)); String s; testcases = Integer.parseInt(in.readLine()); for (int i = 1; i<=testcases; i++){ String temp [] = in.readLine().split("" ""); A = Integer.parseInt(temp[0]); B = Integer.parseInt(temp[1]); int count = 0; for (int j=A; j<=B; j++){ ArrayList v = new ArrayList (); v.add(j); String number = Integer.toString(j); int val; for (int k=0; k ll; for(int j = 0 ; j < i ; j++) { a = s.nextInt(); b = s.nextInt(); sa = getlength(a); cnt = 0; for( int k = a ; k <= b; k++) { r = k; ll = new LinkedList(); if(getlength(r)>1) for (int l = 0 ; l < sa-1 ; l++) { c = r/(int)Math.pow(10, sa-1); r = (r-c*(int)Math.pow(10, sa-1))*10+c; if(r<=b&&r>k&&!ll.contains(r)) { ll.add(r); cnt++; } } } System.out.println(""Case #""+(j+1)+"": ""+(cnt)); } } } " B22205,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Scanner; public class C { static Scanner s; /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub s = new Scanner(new File(""a.txt"")); int T = s.nextInt(); for(int a=1;a<=T;a++) { int A = s.nextInt(); int B = s.nextInt(); int res = 0; for(int i=A; i hm = new HashMap(); for(int j=1; ji && n<=B && !hm.containsKey(n)) { res++; hm.put(n, 1); } } } System.out.println(""Case #""+a+"": ""+res); } s.close(); } } " B22097,"package qualification.common; import java.io.*; /** * Created by IntelliJ IDEA. * User: ofer * Date: 14/04/12 * Time: 17:21 * To change this template use File | Settings | File Templates. */ public class InputReader { public static String[] getInputLines(String filename){ String[] input = null; File file = new File(filename); try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); int size = Integer.parseInt(line); input = new String[size + 1]; input[0] = line; for (int i=0 ; i L = new TreeSet(); for(int j=1;jn && n2<=B) { if(!L.contains(n2)) { L.add(n2); count ++; } } } } System.out.println(""Case #""+(i+1)+"": ""+count); } } } " B20898,"import java.util.*; public class C { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); for(int ca=1;ca <= T;ca++) { int A = scan.nextInt(); int B = scan.nextInt(); int rtn = 0; String str = ""1""; while(str.length() < (A+"""").length()) str += ""0""; int MOD = Integer.parseInt(str); for(int i=A;i <= B;i++) { int k = i; HashSet h = new HashSet(); for(int j=0;j < str.length();j++) { //str = str.substring(1) + str.substring(0,1); //int k = Integer.parseInt(str); k = (k % MOD) * 10 + (k / MOD); if(k > i && k <= B && !h.contains(k)) rtn++; h.add(k); } } System.out.println(""Case #"" + ca + "": ""+ rtn); } } }" B21241,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Hashtable; /** * Input * @author jiptan * */ public class SolveC { static int isRecycledNum(char[] val, int n, int a, int b) { int recNum = 0; for (int i=0; i= a && shiftVal > n && shiftVal <= b) { recNum = recNum + 1; // System.out.println(n + "" "" + shiftVal); } } return recNum; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(args[0])); int num = Integer.parseInt(br.readLine()); FileWriter fw = new FileWriter(new File(""test"")); StringBuilder sb2 = new StringBuilder(); String[] values = null; for (int i=1; i<=num; i++) { String line = br.readLine(); String[] abPair = line.split("" ""); int a = Integer.parseInt(abPair[0]); int b = Integer.parseInt(abPair[1]); // System.out.println(a + "" "" + b); int recNum = 0; for (int j=a; j<=b; j++) { int tmp = isRecycledNum(String.valueOf(j).toCharArray(), j, a, b); if (tmp > 0) { recNum = recNum + tmp; } } // System.out.println(recNum); String output = String.format(""Case #%d: %d"", i, recNum); sb2.append(output + ""\n""); } fw.write(sb2.toString()); fw.close(); } }" B20370,"/** * */ package hu.herba.codejam; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; /** * Base functionality, helper functions for CodeJam problem solver utilities. * * @author csorbazoli */ public abstract class AbstractCodeJamBase { private static final String EXT_OUT = "".out""; protected static final int STREAM_TYPE = 0; protected static final int FILE_TYPE = 1; protected static final int READER_TYPE = 2; private static final String DEFAULT_INPUT = ""test_input""; private static final String DEFAULT_OUTPUT = ""test_output""; private final File inputFolder; private final File outputFolder; public AbstractCodeJamBase(String[] args, int type) { String inputFolderName = AbstractCodeJamBase.DEFAULT_INPUT; String outputFolderName = AbstractCodeJamBase.DEFAULT_OUTPUT; if (args.length > 0) { inputFolderName = args[0]; } this.inputFolder = new File(inputFolderName); if (!this.inputFolder.exists()) { this.showUsage(""Input folder '"" + this.inputFolder.getAbsolutePath() + ""' not exists!""); } if (args.length > 1) { outputFolderName = args[1]; } this.outputFolder = new File(outputFolderName); if (this.outputFolder.exists() && !this.outputFolder.canWrite()) { this.showUsage(""Output folder '"" + this.outputFolder.getAbsolutePath() + ""' not writeable!""); } else if (!this.outputFolder.exists() && !this.outputFolder.mkdirs()) { this.showUsage(""Could not create output folder '"" + this.outputFolder.getAbsolutePath() + ""'!""); } File[] inputFiles = this.inputFolder.listFiles(); for (File inputFile : inputFiles) { this.processInputFile(inputFile, type); } } /** * @return the inputFolder */ public File getInputFolder() { return this.inputFolder; } /** * @return the outputFolder */ public File getOutputFolder() { return this.outputFolder; } /** * @param input * input reader * @param output * output writer * @throws IOException * in case input or output fails * @throws IllegalArgumentException * in case the given input is invalid */ @SuppressWarnings(""unused"") protected void process(BufferedReader reader, PrintWriter pw) throws IOException, IllegalArgumentException { System.out.println(""NEED TO IMPLEMENT (reader/writer)!!!""); System.exit(-2); } /** * @param input * input file * @param output * output file (will be overwritten) * @throws IOException * in case input or output fails * @throws IllegalArgumentException * in case the given input is invalid */ protected void process(File input, File output) throws IOException, IllegalArgumentException { System.out.println(""NEED TO IMPLEMENT (file/file)!!!""); System.exit(-2); } /** * @param input * input stream * @param output * output stream * @throws IOException * in case input or output fails * @throws IllegalArgumentException * in case the given input is invalid */ protected void process(InputStream input, OutputStream output) throws IOException, IllegalArgumentException { System.out.println(""NEED TO IMPLEMENT (stream/stream)!!!""); System.exit(-2); } /** * @param type * @param input * @param output */ private void processInputFile(File input, int type) { long starttime = System.currentTimeMillis(); System.out.println(""Processing '"" + input.getAbsolutePath() + ""'...""); File output = new File(this.outputFolder, input.getName() + AbstractCodeJamBase.EXT_OUT); if (type == AbstractCodeJamBase.STREAM_TYPE) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(input); os = new FileOutputStream(output); this.process(is, os); } catch (FileNotFoundException e) { this.showUsage(""FileNotFound: "" + e.getLocalizedMessage()); } catch (IllegalArgumentException excIA) { this.showUsage(excIA.getLocalizedMessage()); } catch (Exception exc) { System.out.println(""Program failed: "" + exc.getLocalizedMessage()); exc.printStackTrace(System.out); } finally { if (is != null) { try { is.close(); } catch (IOException e) { System.out.println(""Failed to close input: "" + e.getLocalizedMessage()); } } if (os != null) { try { os.close(); } catch (IOException e) { System.out.println(""Failed to close output: "" + e.getLocalizedMessage()); } } } } else if (type == AbstractCodeJamBase.READER_TYPE) { BufferedReader reader = null; PrintWriter pw = null; try { reader = new BufferedReader(new FileReader(input)); pw = new PrintWriter(output); this.process(reader, pw); } catch (FileNotFoundException e) { this.showUsage(""FileNotFound: "" + e.getLocalizedMessage()); } catch (IllegalArgumentException excIA) { this.showUsage(excIA.getLocalizedMessage()); } catch (Exception exc) { System.out.println(""Program failed: "" + exc.getLocalizedMessage()); exc.printStackTrace(System.out); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { System.out.println(""Failed to close input: "" + e.getLocalizedMessage()); } } if (pw != null) { pw.close(); } } } else if (type == AbstractCodeJamBase.FILE_TYPE) { try { this.process(input, output); } catch (IllegalArgumentException excIA) { this.showUsage(excIA.getLocalizedMessage()); } catch (Exception exc) { System.out.println(""Program failed: "" + exc.getLocalizedMessage()); exc.printStackTrace(System.out); } } else { this.showUsage(""Unknown type given: "" + type + "" (accepted values: 0,1)""); } System.out.println("" READY ("" + (System.currentTimeMillis() - starttime) + "" ms)""); } /** * Read a single number from input * * @param reader * @param purpose * What is the purpose of given data * @return * @throws IOException * @throws IllegalArgumentException */ protected int readInt(BufferedReader reader, String purpose) throws IOException, IllegalArgumentException { int ret = 0; String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException(""Invalid input: line is empty, it should be an integer ("" + purpose + "")!""); } try { ret = Integer.parseInt(line); } catch (NumberFormatException excNF) { throw new IllegalArgumentException(""Invalid input: the first line '"" + line + ""' should be an integer ("" + purpose + "")!""); } return ret; } /** * Read array of integers * * @param reader * @param purpose * @return */ protected int[] readIntArray(BufferedReader reader, String purpose) throws IOException { int[] ret = null; String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException(""Invalid input: line is empty, it should be an integer list ("" + purpose + "")!""); } String[] strArr = line.split(""\\s""); int len = strArr.length; ret = new int[len]; for (int i = 0; i < len; i++) { try { ret[i] = Integer.parseInt(strArr[i]); } catch (NumberFormatException excNF) { throw new IllegalArgumentException(""Invalid input: line '"" + line + ""' should be an integer list ("" + purpose + "")!""); } } return ret; } /** * Read array of strings * * @param reader * @param purpose * @return */ protected String[] readStringArray(BufferedReader reader, String purpose) throws IOException { String[] ret = null; String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException(""Invalid input: line is empty, it should be a string list ("" + purpose + "")!""); } ret = line.split(""\\s""); return ret == null ? new String[0] : ret; } /** * Basic usage pattern. Can be overwritten by current implementation * * @param message * Short message, describing the problem with given program * arguments */ protected void showUsage(String message) { if (message != null) { System.out.println(message); } System.out.println(""Usage:""); System.out.println(""\t"" + this.getClass().getName() + "" program""); System.out.println(""\tArguments:""); System.out.println(""\t\t:\tpath of input folder (default: "" + AbstractCodeJamBase.DEFAULT_INPUT + "").""); System.out.println(""\t\t \tAll files will be processed in the folder""); System.out.println(""\t\t:\tpath of output folder (default: "" + AbstractCodeJamBase.DEFAULT_OUTPUT + "")""); System.out.println(""\t\t \tOutput file name will be the same as input""); System.out.println(""\t\t \tinput with extension '.out'""); System.exit(-1); } } " B20411,"package qualification; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; /* * Problem Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers. Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros. Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A ² n < m ² B? Input The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B. Output For each test case, output one line containing ""Case #x: y"", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A ² n < m ² B. Limits 1 ² T ² 50. A and B have the same number of digits. Small dataset 1 ² A ² B ² 1000. Large dataset 1 ² A ² B ² 2000000. Sample Input Output 4 1 9 10 40 100 500 1111 2222 Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 Are we sure about the output to Case #4? Yes, we're sure about the output to Case #4. * * * */ public class RecycledNumber { public static void main(String[] args) throws IOException{ BufferedReader file = new BufferedReader(new FileReader(new File(""src/input""))); String firstline = file.readLine(); int casenum = Integer.parseInt(firstline); StringWriter s= new StringWriter(); for(int i=0;ij && s<=b && n==q) { for(int l=0;l<(z-1);l++) { if(s==pos[l]) f++; } if(f==0) { count++; // System.out.println(j+"" ""+s+"" ""+count+"" ""+p+"" ""+q+"" ""+m); } // else // System.out.println(j+"" ""+s+"" ""+count+"" ""+p+"" ""+q+"" ""+m+""gjkhgjhgjhgjhgjhgjhyj""); } m=s%10; p=s/10; } } ans[i]=count; } for(int i=0;i upper || checked[num-lower]) continue; checked[num-lower] = true; items++; } counter += binom[items]; } return counter; } } " B20836,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String[] args) { try { Scanner in = new Scanner(new File(""C.in"")); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(""C.out""))); int T = in.nextInt(); in.nextLine(); for (int i=0; i set = new HashSet(); for (int j=1; j X && C <= B && !(set.contains(C))) { set.add(C); res++; //System.out.println(""X=""+X + "", C=""+C); } } } writer.append(""Case #"" + (i+1) + "": "" + res + ""\n""); } writer.close(); } catch (IOException e) { e.printStackTrace(); } } public static int moveLast(int X, int digits) { int last = 0; int p = 1; int p2 = 1; for (int i=0; i 0) { X /= 10; k++; } return k; } } " B21640,"import java.util.*; import java.io.*; class Caso{ int a; int b; public void leer(Scanner s){ a=s.nextInt(); b=s.nextInt(); } public Caso(){ } public String obtenerRespuesta(){ long resultado=0; for(int i=a;i<=b;i++){ int j=1; int nd=(int)Math.log10(i)+1; HashMaph=new HashMap(); while(j(); mCaseCounter = 1; } public void addString(String res) { mResultList.add(res); } public void addCase(String res) { mResultList.add(""Case #"" + mCaseCounter + "": "" + res); mCaseCounter++; } public void clear() { mResultList.clear(); mCaseCounter = 1; } public Iterator iterator() { return mResultList.iterator(); } private long mCaseCounter; private List mResultList; } " B20437,"import java.io.File; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.Set; import java.util.HashSet; public final class RecycledNumbersAnalyzer { private static boolean isRecycledPair (final int n, final int m) { if (n < 10) return false; final String nFirstDigit = Character.toString((Integer.toString(n)).charAt(0)); final String mString = Integer.toString(m); final int mLength = mString.length(); int mIndexSearch = 0; int mIndex; while ((mIndex = mString.indexOf(nFirstDigit, mIndexSearch)) != -1) { final int recycledM = Integer.valueOf(mString.substring(mIndex, mLength) + mString.substring(0, mIndex)); if (recycledM == n) return true; //else mIndexSearch = mIndex+1; //increment } return false; } private static Integer[] recycledPairs (final int n, final int b) { final String nString = Integer.toString(n); final int nLength = nString.length(); int nDigitIndex = 1; final Set recycledNs = new HashSet(); while (nDigitIndex < nLength) { final int recycledN = Integer.valueOf(nString.substring(nDigitIndex, nLength) + nString.substring(0, nDigitIndex)); if (recycledN > n && recycledN <= b) { //n is a possible m /*if (!isRecycledPair(n, recycledN)) //debug throw new RuntimeException (""bad recycled N ; n="" + n + "", recycledN="" + recycledN);*/ recycledNs.add(recycledN); } ++nDigitIndex; //loop increment } return recycledNs.toArray(new Integer[] {}); } public static int findRecycledPairsNumber (final int a, final int b) { int recycledPairsNumber = 0; for (int n = a; n < (b-1); ++n) { recycledPairsNumber += (recycledPairs(n, b)).length; } return recycledPairsNumber; } private static final String OUTPUT_FILE_EXTENSION = ""out""; private static final String OUTPUT_LINE_FORMAT = ""Case #%d: %s""; public static void main (final String[] args) throws Exception { //input init if (args.length < 1) throw new IllegalArgumentException(); final String inputFileName = args[0]; final int lastDotIndex = inputFileName.lastIndexOf('.'); final String fileName = (lastDotIndex < 0) ? inputFileName : inputFileName.substring(0, lastDotIndex); final String outputFileName = fileName + ""."" + OUTPUT_FILE_EXTENSION; final File inputFile = new File(inputFileName); final File outputFile = new File(outputFileName); Scanner inputScanner = null; PrintWriter outputWriter = null; try { inputScanner = new Scanner(inputFile); outputWriter = new PrintWriter(outputFile); final int numberLines = inputScanner.nextInt(); inputScanner.nextLine(); //go to first text line for (int i = 0; i < numberLines; ++i) { final int n = inputScanner.nextInt(); final int m = inputScanner.nextInt(); final int recycledPairsNumber = findRecycledPairsNumber(n, m); outputWriter.println(String.format(OUTPUT_LINE_FORMAT, i+1, recycledPairsNumber)); } } catch (final NoSuchElementException noSuchElementException) { System.err.println(""invalid input""); throw noSuchElementException; } finally { if (inputScanner != null) { inputScanner.close(); } if (outputWriter != null) { outputWriter.flush(); outputWriter.close(); } } } } " B20625,"package codejam; import codejam.y12.round0.RecycledNumbers; import utils.Jam; /** * * @author Fabien Renaud */ public class MainEntryPoint { public static void main(String[] args) { Jam j = new RecycledNumbers(""/home/fabien/C-large.in""); j.run(); } } " B20422,"package CodeJam; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; public class Recycled_Numbers { /** * @param args */ String rotation(String A, int nRot) { String rotA = A.substring(0, nRot); A = A.substring(nRot, A.length()); A = A + rotA; return A; } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // TODO Auto-generated method stub String outputFile = System.getenv(""USERPROFILE"")+ ""\\Documents\\C-small.out""; String inputFile = System.getenv(""USERPROFILE"") + ""\\Documents\\C-small-attempt1.in""; BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile)); DataInputStream reader = new DataInputStream(new FileInputStream(inputFile)); Recycled_Numbers re = new Recycled_Numbers(); int T = Integer.valueOf(reader.readLine()); for (int s = 1; s <= T; s++) { String line = reader.readLine(); long A = Long.valueOf(line.substring(0, line.indexOf("" ""))); long B = Long.valueOf(line.substring(line.indexOf("" "") + 1,line.length())); int n = 0; for (long i = A; i < B; i++) { String rot = Long.toString(i); String k = rot; for (int j = 1; j < rot.length(); j++) { k = re.rotation(rot, j); if (k.equals(rot)) break; if ((Long.valueOf(k) >= i) && (Long.valueOf(k) <= B)) { n++; } } } writer.write(""Case #"" + s + "": "" + n); writer.newLine(); } writer.close(); reader.close(); } }" B21295,"package gcj; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class Recycled { public static void main(String args[]) throws Exception { BufferedReader br=new BufferedReader(new FileReader(""c:/c.in"")); BufferedWriter out=new BufferedWriter(new FileWriter(""c:/out.txt"")); String s; int t=Integer.parseInt(br.readLine()); for(int i=0;i0) { s=s.substring(s.length()-1)+s.substring(0,s.length()-1); if(s.charAt(0)=='0') { l--; continue; } else { if(Integer.parseInt(s)==j) { l--; continue; } if(check(arr,dupidx,Integer.parseInt(s))&Integer.parseInt(s)>j&&Integer.parseInt(s)<=b&&Integer.parseInt(s)>=a) { arr[dupidx]=Integer.parseInt(s); dupidx++; res++; } } l--; } } out.write(""Case #""+(i+1)+"": ""+res+""\n""); } out.close(); } public static boolean check(int arr[],int maxid,int val) { for(int i=0;i 0){ counter++; //Here put the code..:) int a = nextInt(); int b = nextInt(); int ret=0; for (int i = a; i <= b; i++) { char [] aa = (""""+i).toCharArray(); for (int j = 1; j < aa.length; j++) { char [] z = new char[aa.length]; for (int k = 0; k < z.length; k++) { z[k]=aa[(k+j)%aa.length]; } int s = Integer.parseInt(new String(z)); if(s>i&&s<=b)ret++; } } writeln(""Case #""+counter+"": ""+ret); } //------------------------------------------------------------------------- //closing up end(); //-------------------------------------------------------------------------- } private static boolean cir(String a, String b) { // TODO Auto-generated method stub for (int i = 0; i < a.length(); i++) { boolean t = true; for (int j = 0; j < a.length(); j++) { if(a.charAt(j)!=b.charAt((j+i)%b.length())){t=false;break;} } if(t)return true; } return false; } public RQC() throws IOException { //Input Output for Console to be used for trying the test samples of the problem in = new BufferedReader(new InputStreamReader(System.in)); // out = new PrintWriter(System.out); //------------------------------------------------------------------------- //Input Output for File to be used for solving the small and large test files // in = new BufferedReader(new FileReader(""RQC.in"")); out = new PrintWriter(""RQC.txt""); //------------------------------------------------------------------------- //Initalize Stringtokenizer input input = new StringTokenizer(in.readLine()); } private static int nextInt() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Integer.parseInt(input.nextToken()); } private static long nextLong() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Long.parseLong(input.nextToken()); } private static double nextDouble() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Double.parseDouble(input.nextToken()); } private static String nextString() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return input.nextToken(); } private static void write(String output){ out.write(output); out.flush(); } private static void writeln(String output){ out.write(output+""\n""); out.flush(); } private static void end() throws IOException{ in.close(); out.close(); System.exit(0); } } " B20058,"import java.io.*; import java.util.*; /** * @author Chris Dziemborowicz * @version 2012.0414 */ public class RecycledNumbers { public static void main(String[] args) throws Exception { // Get input files File dir = new File(""/Users/Chris/Documents/UniSVN/code-jam/recycled-numbers/data""); File[] inputFiles = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith("".in""); } }); // Process each input file for (File inputFile : inputFiles) { System.out.printf(""Processing \""%s\""...\n"", inputFile.getName()); String outputPath = inputFile.getPath().replaceAll(""\\.in$"", "".out""); BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath)); Scanner scanner = new Scanner(inputFile); System.out.printf(""Number of test cases: %s\n"", scanner.nextLine()); int count = 0; while (scanner.hasNext()) { String line = scanner.nextLine(); String output = String.format(""Case #%d: %d\n"", ++count, process(line)); System.out.print(output); writer.write(output); } writer.close(); System.out.println(""Done.\n""); } // Compare to reference files (if any) for (File inputFile : inputFiles) { System.out.printf(""Verifying \""%s\""...\n"", inputFile.getName()); String referencePath = inputFile.getPath().replaceAll(""\\.in$"", "".ref""); String outputPath = inputFile.getPath().replaceAll(""\\.in$"", "".out""); File referenceFile = new File(referencePath); if (referenceFile.exists()) { InputStream referenceStream = new FileInputStream(referencePath); InputStream outputStream = new FileInputStream(outputPath); boolean matched = true; int referenceRead, outputRead; do { byte[] referenceBuffer = new byte[4096]; byte[] outputBuffer = new byte[4096]; referenceRead = referenceStream.read(referenceBuffer); outputRead = outputStream.read(outputBuffer); matched = referenceRead == outputRead && Arrays.equals(referenceBuffer, outputBuffer); } while (matched && referenceRead != -1); if (matched) { System.out.println(""Verified.\n""); } else { System.out.println(""*** NOT VERIFIED ***\n""); } } else { System.out.println(""No reference file found.\n""); } } } public static int process(String line) { Scanner scanner = new Scanner(line); final int a = scanner.nextInt(); final int b = scanner.nextInt(); final int[] pow10 = new int[] { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; int count = 0; for (int n = a; n < b; n++) { Set set = new HashSet(); int numDigits = numDigits(n); for (int d = 1; d < numDigits; d++) { int back = n % pow10[d]; int front = n / pow10[d]; int m = front + back * pow10[numDigits - d]; if (n < m && m <= b && numDigits == numDigits(m)) { set.add(m); } } count += set.size(); } return count; } public static int numDigits(int n) { if (n < 0) { return numDigits(-n); } else if (n < 1) { return 0; } else if (n < 10) { return 1; } else if (n < 100) { return 2; } else if (n < 1000) { return 3; } else if (n < 10000) { return 4; } else if (n < 100000) { return 5; } else if (n < 1000000) { return 6; } else if (n < 10000000) { return 7; } else if (n < 100000000) { return 8; } else if (n < 1000000000) { return 9; } else { return 10; } } }" B21209,"import java.util.*; public class Main { public static void main(String args[]) { (new Main()).solve(); } void solve() { Scanner cin = new Scanner(System.in); int T = cin.nextInt(); for(int C=1; C<=T; ++C) { int A = cin.nextInt(); int B = cin.nextInt(); int n = ("""" + A).length(); int base = 1; for(int i=1; i set = new HashSet(); int min = v + 1; for(int i=0; i testCases = new ArrayList(); boolean isCaseNo = true; int testCount = 0; FileReader fr = new FileReader(""C-large.in""); BufferedReader br = new BufferedReader(fr); String s; while ((s = br.readLine()) != null) { if (isCaseNo) { testCount = Integer.parseInt(s); isCaseNo = false; } else { testCases.add(s); } } fr.close(); Solve(testCount, testCases); } public static void Solve(int testCount, ArrayList testCases) throws IOException { FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < testCount; i++) { int A = 0, B = 0, count = 0; String s = testCases.get(i); String[] ar = s.split("" ""); A = Integer.parseInt(ar[0]); B = Integer.parseInt(ar[1]); for(int j = A; j <= B; j++) { ArrayList nums = new ArrayList(); String num = String.valueOf(j); for(int k =0; k < num.length(); k++) { String num1 = num.substring(0, k); String num2 = num.substring(k, num.length()); String newNum = num2 + num1; int newI = Integer.parseInt(newNum); NumberPair np = new NumberPair(j, newI); if (newI >= A && newI <= B && newNum.equals(String.valueOf(newI)) && !num.equals(newNum) && !nums.contains(np)) { count++; nums.add(np); } } } out.write(""Case #"" + (i + 1) + "": "" + count/2 + ""\n""); } out.close(); } } class NumberPair { int m, n; public NumberPair(int m, int n) { this.m = m; this.n = n; } @Override public boolean equals(Object obj) { NumberPair np = (NumberPair)obj; return (np.m == this.m && np.n == this.n) || (np.m == this.n && np.n == this.m); } @Override public int hashCode() { int hash = 7; hash = 61 * hash + this.m; hash = 61 * hash + this.n; return hash; } } " B20162,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int lines = Integer.parseInt(in.readLine()); for (int i = 0; i < lines; i++) { long res = 0; String line = in.readLine(); StringTokenizer st = new StringTokenizer(line); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); for (int j = a; j <= b; j++) { res += (long) recycleNum(j, b); } System.out.println(""Case #"" + (i + 1) + "": "" + res); } } private static int recycleNum(int n, int b) { Set set = new HashSet(); int result = 0; String num = (n + """"); for (int i = 1; i < num.length(); i++) { String part1 = """"; String part2 = """"; part1 = num.substring(0, i); part2 = num.substring(i, num.length()); int temp = Integer.parseInt(part2 + part1); if (n < temp && temp <= b && !set.contains(temp)) { set.add(temp); result++; } } return result; } } " B21749,"import java.util.ArrayList; import java.util.List; public class RecycledNumbers { private int A; private int B; public RecycledNumbers(int A, int B) { this.A = A; this.B = B; } public int calculate() { int result = 0; int digitCount = Integer.toString(A).length(); if (digitCount == 1) return 0; List numbers = new ArrayList(); for (int i = A; i < B + 1; i++) { numbers.add(Integer.toString(i)); } for (int i = 0; i < numbers.size(); i++) { String number = numbers.get(i); for (int j = 1; j < digitCount; j++) { String reverseNumber = number.substring(j) + number.substring(0, j); int reversInt = Integer.parseInt(reverseNumber); if ((reversInt <= B) && (reversInt > Integer.parseInt(number))) { // System.out.println(""A("" + A + "") <= "" + number + "" < "" + reverseNumber + "" <=B("" + B + "")""); result++; } } } return result; } public static List parseFromFile(List readInput) { List result = new ArrayList(); int testCaseCount = Integer.parseInt(readInput.get(0)); for (int i = 0; i < testCaseCount; i++) { String line[] = readInput.get(i + 1).split("" ""); result.add(new RecycledNumbers(Integer.parseInt(line[0]), Integer.parseInt(line[1]))); } return result; } @Override public String toString() { return ""A = "" + A + ""; B = "" + B; } } " B21841," import java.io.*; import java.util.*; public class rec { public static void main (String [] args) throws Exception { BufferedReader f = new BufferedReader(new FileReader(""rec.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""rec.out""))); int N = Integer.parseInt(f.readLine()); for(int ie = 0; ie()); // s.get(""""+i).add(""""+j); // } for(String e:s.keySet()) count+=s.get(e).size(); out.println(""Case #""+(ie+1)+"": ""+count); } out.close(); System.exit(0); } static Map> s = new TreeMap>(); static int cont(int w, int a, int b){ int c = 0; String e = w+""""; if(e.charAt(0) == '0') return 0; for(int i = 1; i=a && q<= b && q()); s.get(""""+q).add(""""+w); } } return c; } static boolean o(String a, String b){ int pos = 0; while(pos set = new HashSet(); for (int val = min; val < max; val++) { String str = String.valueOf (val); int nbDigits = str.length(); // System.out.println(""Val : "" + val + "" with "" + nbDigits + "" digits""); int major = String.valueOf (max).charAt (0) - '0'; set.clear(); for (int j = 1; j < nbDigits; j++) { char last = str.charAt (nbDigits - 1); str = str.charAt (nbDigits - 1) + str.substring (0, nbDigits - 1); if (last != '0' && (last - '0') <= major) { // System.out.println ("" Trying "" + str); int res = Integer.valueOf (str); if (res <= max && res > val && ! set.contains (res)) { // System.out.printf ("" (%d, %d)\n"", val, res); set.add (res); if (! (val != res && val < res && val >= min && res <= max && isPermut (res, val))) { System.out.println(""ERROR""); } counter++; } } } } // System.out.println (""Counter : "" + counter); writer.println (""Case #"" + (i + 1) + "": "" + counter); } writer.close(); reader.close(); } }" B21583,"import java.io.*; import java.util.Scanner; public class C { public static void main(String[] args) throws FileNotFoundException, IOException { Scanner sc = new Scanner(new FileReader(""input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int noOfCases = sc.nextInt(); for (int caseNum = 0; caseNum < noOfCases; caseNum++){ int A = sc.nextInt(); int B = sc.nextInt(); int result =0; int numDigits = numdigits(A); if(A<10){ pw.print(""Case #"" + (caseNum + 1) + "": 0""); } else if(A<100){ for (int i = A; i <= B; i++) { if(A<=shift(i, 1) && shift(i, 1)<=B && i != shift(i, 1)){ result++; } } pw.print(""Case #"" + (caseNum + 1) + "": ""+ result/2); } else { for (int i = A; i <= B; i++) { int iterator = i; for(int j=0; j< numDigits; j++){ if(A<=shift(iterator, numDigits) && shift(iterator, numDigits)<=B && i <= shift(iterator, numDigits)){ if(i == shift(iterator, numDigits) ) { break; } result++; //System.out.println(result+ "" "" +i+ "" "" + shift(iterator, numDigits)); } iterator = shift(iterator, numDigits); } } pw.print(""Case #"" + (caseNum + 1) + "": ""+ result); } if(caseNum < noOfCases-1) pw.println(""""); } pw.flush(); pw.close(); sc.close(); } public static int shift(int number, int numdigits){ int multiplier = (int) Math.pow(10.0, (double)numdigits); int r = number % 10; int result = number/10; result = result + multiplier * r; return result; } public static int numdigits(int number){ int numdigits = (int) Math.log10((double)number); // would return numdigits - 1 return numdigits; } } " B20765,"import java.io.*; import java.util.HashSet; import java.util.Set; public class C { private static final String FILE = ""C-large""; private static final boolean SAVE_OUT = true; public static void main(String[] args) throws IOException { BufferedReader in = createReader(); FileWriter out; if (SAVE_OUT) { out = new FileWriter(FILE + "".out""); } int t = Integer.parseInt(in.readLine()); int c = 0; while (t-- > 0) { String row = in.readLine(); String[] split = row.split("" ""); int a = Integer.parseInt(split[0]); int b = Integer.parseInt(split[1]); int num = 0; for (int i = a; i <= b; ++i) { num += calc(i, a, b); } String res = String.format(""Case #%d: %d"", ++c, num / 2); System.out.println(res); if (SAVE_OUT) { out.append(res); out.append(""\n""); } } if (SAVE_OUT) { out.close(); } } private static int calc(int c, int a, int b) { int num = 0; String s = Integer.toString(c); Set seen = new HashSet(); for (int i = 1; i < s.length(); ++i) { int cc = flip(s, i); while (cc <= b) { if (seen.contains(cc)) { break; } if (cc >= a && c != cc) { ++num; seen.add(cc); } cc *= 10; } } return num; } private static int flip(String s, int k) { String first = s.substring(0, k); StringBuilder sb = new StringBuilder(); sb.append(s.substring(k)); sb.append(first); while (sb.charAt(0) == '0') { sb.deleteCharAt(0); } return Integer.parseInt(sb.toString()); } private static BufferedReader createReader() throws FileNotFoundException { return new BufferedReader(new FileReader(FILE + "".in"")); } } " B22251,"import java.util.ArrayList; import java.util.Arrays; public class Problem3 { public void solve(){ ReadWriter rw = new ReadWriter(); ArrayList input = rw.readFile(""C-large.in""); ArrayList ans = new ArrayList(); int num; boolean first = true; int count=0; for(String s : input){ if(first){ num=Integer.parseInt(s); first=false; } else{ String[] nums = s.split("" ""); ans.add(""Case #""+count+"": ""+countResults(nums)); } count++; } rw.writeFile(ans, ""output3.txt""); } public int countResults(String[] nums){ int min = Integer.parseInt(nums[0]); int max = Integer.parseInt(nums[1]); int temp = min; int count=0; while(temp checked = new ArrayList(); String s = """"+temp; for(int i = 0;itemp&&comp<=max&&checked.indexOf(""""+temp+"" ""+x)==-1){ count++; checked.add(""""+temp+"" ""+x); } } temp++; } return count; } } " B21336,"package com.google.codejam.util; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class CodeJamInputFile extends File { /** * */ private static final long serialVersionUID = 8294095294390757204L; private BufferedReader reader; private int cases; public CodeJamInputFile(String pathname) { super(pathname); try { this.setReader(); } catch (FileNotFoundException e) { } try { this.setCases(Integer.valueOf(this.getReader().readLine())); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void setReader() throws FileNotFoundException { reader = new BufferedReader(new FileReader(this)); } public BufferedReader getReader() { return reader; } public void setCases(int cases) { this.cases = cases; } public int getCases() { return cases; } public void close() { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getLine() { String line = """"; try { line = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return line; } } " B21696,"package codejam2012; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import reusable.CodeJamBase; public class RecycledNumbers { public static void main(String[] args) { new CodeJamBase(""C-large"") { private int rotate(int value, int rotations, int totalRotations) { int tens = (int) Math.pow(10, rotations); int left = (int) Math.pow(10, totalRotations - rotations); return left * (value % tens) + (value / tens); } @Override protected String solution() { int[] input = nextIntArray(); int lowerBound = input[0]; int upperBound = input[1]; Map> distinctPairs = new HashMap<>(); int result = 0; for (int n = lowerBound; n <= upperBound; n++) { int totalRotations = String.valueOf(lowerBound).length(); for (int rotations = 1; rotations < totalRotations; rotations++) { int m = rotate(n, rotations, totalRotations); if (String.valueOf(m).length() != totalRotations) { continue; } if (distinctPairs.get(n) == null) { distinctPairs.put(n, new ArrayList()); } if (distinctPairs.get(n).contains(m)) { continue; } if ((lowerBound <= n) && (n < m) && (m <= upperBound)) { distinctPairs.get(n).add(m); result++; } } } return String.valueOf(result); } }.run(); } } " B21438,"package jp.funnything.competition.util; import java.util.List; import com.google.common.collect.Lists; public class Lists2 { public static < T > List< T > newArrayListAsArray( final int length ) { final List< T > list = Lists.newArrayListWithCapacity( length ); for ( int index = 0 ; index < length ; index++ ) { list.add( null ); } return list; } } " B20628,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam.y12.round0; import utils.Jam; import utils.JamCase; /** * * @author fabien */ public class RecycledNumbers extends Jam { public RecycledNumbers(String filename) { super(filename); } @Override public JamCase getJamCase(int number) { return new Line(this, number, lines[number]); } private class Line extends JamCase { private int a; private int b; private String line; private int count; public Line(Jam parent, int number, String line) { super(parent, number); this.line = line; } @Override public void parse() { String[] integers = line.split("" ""); a = Integer.parseInt(integers[0]); b = Integer.parseInt(integers[1]); } @Override public void solve() { count = 0; for (int i = a; i <= b; i++) { countRecycles(i); } result = Integer.toString(count); } private void countRecycles(int number) { int len = 0; int n = number; while (n != 0) { n /= 10; len++; } n = number; int exp = (int) Math.pow(10, len - 1); for (int i = 0; i < len; i++) { n = nextRecycled(n, exp); if (n == number) { return; } if (n <= b && n > number) { count++; } } } private int nextRecycled(int i, int exp) { int r = i % 10; i = (i - r) / 10; i += r * exp; return i; } } } " B20062,"package qual2012.C; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { //private static String inputFileName = ""sample.in""; //private static String inputFileName = ""C-small-attempt0.in""; private static String inputFileName = ""C-large.in""; //private static String outputFileName = ""sample.out""; //private static String outputFileName = ""C-small.out""; private static String outputFileName = ""C-large.out""; private static int nbrOfTests; private static String inputFolder = ""input/""; private static String outputFolder = ""output/""; /** * @param args */ public static void main(String[] args) { RecycledNumbers mainDefault = new RecycledNumbers(); MyTestCase[] input = mainDefault.readInputCodeJam(inputFileName); StringBuffer output = mainDefault.createOutput(input); printToFile(output, outputFileName); } public MyTestCase[] readInputCodeJam(String fileName) { MyTestCase[] testCases = null; File file = new File(inputFolder + fileName); try { Scanner scanner = new Scanner(file); nbrOfTests = Integer.valueOf(scanner.nextLine()); testCases = new MyTestCase[nbrOfTests]; for (int i = 0; i < nbrOfTests; i++) { String tmp = scanner.nextLine(); String[] testCaseInput = tmp.split("" ""); MyTestCase obj = new MyTestCase(testCaseInput); testCases[i] = obj; } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } return testCases; } public StringBuffer createOutput(MyTestCase[] myTestCases) { StringBuffer buffer = new StringBuffer(); int count = 1; for (int i = 0; i < nbrOfTests; i++) { buffer.append(""Case #"" + count++ + "": ""); MyTestCase myTestCase = myTestCases[i]; buffer.append(myTestCase.getAnswer()); buffer.append(""\n""); } return buffer; } public static void printToFile(StringBuffer output, String fileName) { try { FileWriter fstream = new FileWriter(outputFolder + fileName); BufferedWriter out = new BufferedWriter(fstream); out.write(output.toString()); out.close(); } catch (IOException e) { e.printStackTrace(); } } class MyTestCase { private String answer; private BigInteger second; private BigInteger first; public MyTestCase(String[] input) { first = new BigInteger(input[0]); second = new BigInteger(input[1]); int sum = 0; BigInteger value = first; while (value.compareTo(second) <= 0) { sum += solve(value); value = value.add(BigInteger.ONE); } answer = String.valueOf(sum); } public String getAnswer() { return answer; } private int solve(BigInteger value) { HashSet uniquePairs = new HashSet(); String inputValue = value.toString(); if (inputValue.length() <= 1) { return 0; } for (int i = 1; i < inputValue.length(); i++) { String tmp = inputValue; int split = i; String firstPart = tmp.substring(0, split); String secondPart = tmp.substring(split); String connected = secondPart + firstPart; if (inputValue.compareTo(connected) < 0) { BigInteger tmp2 = new BigInteger(connected); if (tmp2.compareTo(second) <= 0) { // System.out.println(inputValue + "" => "" + connected); uniquePairs.add(inputValue + connected); } } } return uniquePairs.size(); } } } " B21970," public class RecycledPair { public int num1; public int num2; public RecycledPair(int n1, int n2) { this.num1 = n1; this.num2 = n2; } @Override public String toString() { return ""("" + num1 + "", "" + num2 + "")""; } @Override public boolean equals(Object obj) { if(obj instanceof RecycledPair) { RecycledPair other = (RecycledPair) obj; if((other.num1 == this.num1 && other.num2 == this.num2) || (other.num2 == this.num1 && other.num1 == this.num2)) { return true; } } return false; } @Override public int hashCode() { int prime = 31; return (num1 * prime) + (num2 * prime); } } " B20193,"package core; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public abstract class Template { /************* TO BE IMPLEMENTED ******************************************/ public abstract void feedData(ExtendedBufferedReader iR); public abstract StringBuffer applyMethods(); /**************************************************************************/ public void readData(File iFile){ try { FileReader aReader = new FileReader(iFile); ExtendedBufferedReader aBufferedReader = new ExtendedBufferedReader(aReader); feedData(aBufferedReader); aBufferedReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void writeResult(File iFile,StringBuffer iResult){ System.out.println(iResult.toString()); try { FileWriter aWriter = new FileWriter(iFile); aWriter.write(iResult.toString()); aWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void play(String[] args) { if (args.length>1) { File aFile = new File(args[0]); readData(aFile); StringBuffer result = applyMethods(); File aResultFile= new File(args[1]); writeResult(aResultFile,result); } else { System.out.println(""Your a bastard ! missing argument !""); } } } " B20430,"package base; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import assignments.AssignmentC; public class Solver { public static void main(String... args) throws IOException { List assignments = readAssignments(""test""); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int i = 0; for (Assignment assignment : assignments) { String answer = ""Case #"" + ++i + "": "" + assignment.solve(); pw.println(answer); System.out.println(answer); } pw.flush(); pw.close(); } private static List readAssignments(String filename) throws FileNotFoundException { Scanner scanner = new Scanner(new File(filename)); int amountOfAssignments = scanner.nextInt(); scanner.nextLine(); List result = new ArrayList(); for (int i = 0; i < amountOfAssignments; i++) { result.add(AssignmentC.createFromScanner(scanner)); } scanner.close(); return result; } } " B20613,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; public class CRecycledNumbers { static int recycle(int a, int b) { // System.out.println(""-------------------------""); // System.out.println(a + "" "" + b); int count = 0; Set used = new HashSet(); for(int i = a; i < b; ++i) { String s = Integer.toString(i); for(int j = 1; j < s.length(); ++j) { String pre = s.substring(0, j); String suf = s.substring(j); if(suf.startsWith(""0"")) continue; int c = Integer.parseInt(suf + pre); if(c <= b && c != i && i < c) { String p = i < c? (i + ""-"" + c) : (c + ""-"" + i); if(!used.contains(p)) { used.add(p); // System.out.println(p); ++count; } } } } return count; } public static void main(String[] args) throws NumberFormatException, IOException { String filename = ""C-large.in""; BufferedReader r = new BufferedReader(new FileReader(filename)); int n = Integer.parseInt(r.readLine()); PrintWriter p = new PrintWriter(""c.out""); for(int i = 0; i < n; ++i) { String[] test = r.readLine().split("" ""); int j = i + 1; p.println(""Case #"" + j + "": "" + recycle(Integer.parseInt(test[0]), Integer.parseInt(test[1]))); } p.flush(); p.close(); } } " B20634,"import java.io.*; import java.util.HashSet; public class C { int a, b; int countRec(int num){ char[] digits = String.valueOf(num).toCharArray(); int n = digits.length; char[] rec = new char[n]; HashSet set = new HashSet(); int cnt=0; for(int i=1; i=n) index%=n; rec[j] = digits[index]; } int out = Integer.parseInt(String.valueOf(rec)); if(out > num && out <= b && !set.contains(out)){ cnt++; set.add(out); } } return cnt; } public void run() throws IOException{ BufferedReader bf = new BufferedReader(new FileReader(""c.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""c.out"")); int kases = Integer.parseInt(bf.readLine()); for(int kase=1; kase<=kases; kase++){ String[] in = bf.readLine().trim().split(""[ ]+""); a = Integer.parseInt(in[0]); b = Integer.parseInt(in[1]); long ret = 0; for(int i=a; i<=b; i++) ret+= countRec(i); pw.println(""Case #"" + kase + "": "" + ret); } pw.close(); } public static void main(String[] args) throws IOException { new C().run(); } } " B21604,"import java.util.*; class QC{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int kase = sc.nextInt(); for(int k = 1; k<=kase; k++){ int A = sc.nextInt(); int B = sc.nextInt(); int count = 0; for(int x= A; xx && cyc[i] <=B && (i==0 || cyc[i]!=cyc[i-1])) count++; } } System.out.println(""Case #""+k+"": ""+count); } } } " B20192,"package qualification; import java.util.ArrayList; import java.util.List; import java.util.Vector; import core.ExtendedBufferedReader; import core.Template; public class ProblemC extends Template { int _numberOfCases; Vector> _cases = new Vector>(); @Override public void feedData(ExtendedBufferedReader iR) { // TODO Auto-generated method stub _numberOfCases = iR.getIntFL(); for (int i=0; i<_numberOfCases; i++){ _cases.add(iR.getIntListFL()); } } public String rotRight(String iData){ return iData.charAt(iData.length()-1)+iData.substring(0,iData.length()-1); } @Override public StringBuffer applyMethods() { // TODO Auto-generated method stub StringBuffer aBF = new StringBuffer(); for (int i=0; i<_cases.size(); i++){ List aCase = _cases.elementAt(i); int A = aCase.get(0); int B = aCase.get(1); int count = 0; for (int n=A; n<=B; n++){ String repN = (new Integer(n)).toString(); String repM = repN; int aSize = repN.length(); if (aSize>1) { List aMExists = new ArrayList(); for (int j=0;j forbidden return -1; } int left = n / pow10[i]; return right * pow10[s-i] + left; } private static int process(String l) { String[] parts = l.split("" ""); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); HashSet set = new HashSet(); int count = 0; for(int n=A; n n && m <= B) set.add(m); //System.out.println(n + "", "" + m); } count += set.size(); } return count; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(args[0])); PrintWriter out = new PrintWriter(args[1]); // number of testcases String sCount = in.readLine(); int count = Integer.parseInt(sCount); for(int idx=1; idx<=count; idx++) { String l = in.readLine(); out.println(""Case #"" + idx + "": "" + process(l)); } out.close(); } } " B20141,"import java.util.Scanner; import java.util.TreeSet; public class C { static TreeSet s; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner kb = new Scanner(System.in); int t = kb.nextInt(); int c = 1; int cnt, a, b; while(t-- > 0) { cnt = 0; a = kb.nextInt(); b = kb.nextInt(); for(int i=a; i(); for(int r=0; r xInt) { if(!s.contains(tmpInt)) { cnt++; s.add(tmpInt); } // System.out.println(""(""+x+"",""+tmp+"")""); } } } System.out.println(""Case #""+c+++"": ""+cnt); // for(int k=0; k= start && xNum <= end) { count++; } } } outputStrings[i] = ""Case #"" + (i + 1) + "": "" + count; } for (String string : outputStrings) { System.out.println(string); } } public static int[] reverse(Integer num) { String string = num.toString(); int[] retArray = new int[num.toString().length() - 1]; for (int i = 0; i < retArray.length; i++) { char x = string.charAt(string.length() - 1); string = x + string.substring(0, string.length() - 1); if(Integer.parseInt(string) > num) retArray[i] = Integer.parseInt(string); } return retArray; } } " B20817,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; public class RecycleNumber { public static void solution(String fileName) throws IOException { FileReader fileReader = new FileReader(new File(fileName)); BufferedReader bufferedReader = new BufferedReader(fileReader); String textLine = bufferedReader.readLine(); int lines = Integer.parseInt(textLine); int[] ret = new int[lines]; for (int i = 0; i < lines; i++) { textLine = bufferedReader.readLine(); String[] t = textLine.split("" ""); if (t.length < 2) { ret[i] = 0; continue; } long start = Long.parseLong(t[0]); long end = Long.parseLong(t[1]); int c = 0; for (long j = start; j < end; j++) { if (start < 10) break; c += getNumber(Long.toString(j), start, end); } ret[i] = c; } for (int i = 0; i < ret.length; i++) { System.out.println(""Case #"" + (i + 1) + "": "" + ret[i]); } } public static int getNumber(String n, long s, long e) { int ret = 0; String t = n; long lo = Long.parseLong(n); HashSet map = new HashSet(); for (int i = 1; i < n.length(); i++) { t = n.substring(i) + n.substring(0, i); String ts = n+"";""+t; if (map.contains(ts)) continue; else map.add(ts); long l = Long.parseLong(t); if (l <= e && l >= s && lo < l) ret++; } return ret; } public static void main(String[] args) throws Exception { solution(""c:\\sql\\C-large.in""); } } " B21809,"import java.io.IOException; import java.lang.reflect.Array; import java.util.*; public class MBHappy extends JamProblem { Map baseMap; Map minMap = new HashMap<>(); int ile = 0; void prepare() { SetUtil.cycleSubsets(bases.size(), new SetUtil.SubsetCallBack() { @Override public void run(long subset, int size) { clearCache(); System.out.println(minMap.size()); if (size == 0) { return; } List list = SetUtil.getList(subset, bases.size()); List bas = ArrayUtil.fromIndexList(list, bases); long forList = SetUtil.getForList(baseMap, bas); int max = 2; for (int j = 0; j < bases.size(); j++) { long without = subset ^ SetUtil.getOne(j); Integer withMin = minMap.get(without); if (withMin != null) { max = Math.max(max, withMin); } } int num = max; while (true) { int tested = 0; for (Integer base : bas) { System.out.println("""" + ca + ""\t"" + base + ""\t"" + num); if (!isHappy(num, base)) { break; } tested++; } if (tested == bas.size()) { ca++; minMap.put(subset, num); return; } if (cache.size() > 100000) { clearCache(); } num++; } } }); } private void clearCache() { cache.clear(); for (Integer base : bases) { cache.put(new MBAddr(1, base), Happy.HAPPY); } } public MBHappy() { for (int i = 2; i <= 10; i++) { bases.add(i); } baseMap = ArrayUtil.listToMap(bases); } Map cache = new HashMap<>(); List bases = new ArrayList<>(); public static void main(String[] args) throws IOException { MBHappy h = new MBHappy(); h.prepare(); h.go(); } boolean isHappy(int num, int base) { MBAddr addr1 = new MBAddr(num, base); Happy isHappy = cache.get(addr1); if (isHappy != null) { if (isHappy == Happy.HAPPY) { return true; } if (isHappy == Happy.UNHAPPY) { return false; } } List integers = MathUtil.convertToBase(num, base); int sum = MathUtil.sumSquaredList(integers); isHappy = cache.get(new MBAddr(sum, base)); if (isHappy != null) { if (isHappy == Happy.HAPPY) { cache.put(addr1, Happy.HAPPY); return true; } if (isHappy == Happy.UNHAPPY) { cache.put(addr1, Happy.UNHAPPY); return false; } if (isHappy == Happy.UNKNOWN) { cache.put(addr1, Happy.UNHAPPY); return false; } } cache.put(addr1, Happy.UNKNOWN); boolean happy = isHappy(sum, base); if (happy) { cache.put(addr1, Happy.HAPPY); return true; } else { cache.put(addr1, Happy.UNHAPPY); return false; } } int ca = 0; @Override String solveCase(JamCase jamCase) { int num = 2; MBHCase cas = (MBHCase) jamCase; return """" + minMap.get(SetUtil.getForList(baseMap, cas.bases)); } @Override JamCase parseCase(List file, int line) { MBHCase cas = new MBHCase(); cas.lineCount = 1; cas.bases = JamUtil.parseIntList(file.get(line)); return cas; } } class MBHCase extends JamCase { List bases; } class MBAddr { int number; int base; MBAddr(int number, int base) { this.number = number; this.base = base; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MBAddr mbAddr = (MBAddr) o; if (base != mbAddr.base) return false; if (number != mbAddr.number) return false; return true; } @Override public int hashCode() { int result = number; result = 31 * result + base; return result; } } class MBNum { int number; int base; boolean isHappy; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MBNum mbNum = (MBNum) o; if (base != mbNum.base) return false; if (isHappy != mbNum.isHappy) return false; if (number != mbNum.number) return false; return true; } @Override public int hashCode() { int result = number; result = 31 * result + base; result = 31 * result + (isHappy ? 1 : 0); return result; } } enum Happy { HAPPY, UNHAPPY, UNKNOWN; } " B20072,"import java.io.*; import java.util.*; public class C implements Runnable{ public void run(){ try{ Scanner in = new Scanner(new File(""C-large.in"")); PrintWriter out = new PrintWriter(""C-large.out""); int a, b, t = in.nextInt(), ans, x, l; String min, buf, max; Set set = new HashSet(); for (int k = 1; k <= t; k++){ ans = 0; a = in.nextInt(); b = in.nextInt(); max = Integer.toString(b); for (int i = a; i < b; i++){ set.clear(); x = i; min = buf = Integer.toString(x); l = min.length(); for (int j = 0; j < l-1; j++){ buf = min.substring(l - j - 1) + min.substring(0, Math.max(0, l - j - 1)); if ((buf.length() == l) && (min.compareTo(buf) < 0) && (buf.compareTo(max) <= 0)) { if (!set.contains(buf)){ set.add(buf); ans++; } } } } out.println(""Case #"" + k + "": "" + ans); } out.close(); } catch(Exception e){ } } public static void main(String[] args){ (new Thread(new C())).start(); } } " B22208,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.util.Scanner; public class C { static String inner = ""input.in""; static Scanner scan; public static void main (String[]args) throws IOException { File f = new File (inner); File out = new File(""output.out""); FileWriter wr; wr = new FileWriter(out); scan = new Scanner(f); int test = scan.nextInt(); scan.nextLine(); for(int i = 0 ;i < test ; i++) wr.write( ""Case #""+ (i+1)+"": ""+testcase( new BigInteger(""""+scan.nextInt()) , new BigInteger(""""+scan.nextInt()) ) + ""\n""); wr.flush(); } public static int testcase (BigInteger A , BigInteger B) { int ret = 0; int len = A.toString().length(); for(BigInteger b = A ; b.compareTo(B) < 1 ;b= b.add(BigInteger.ONE) ) { String []ff = new String [len-1]; String s =b.toString(); for(int i = 1 ;i testList = new ArrayList(); public static void main(String[] args) { try { Problem p = new Problem(); p.init(); p.printResult(); p.end(); } catch (Exception e) { e.printStackTrace(); } } public void printResult() throws ProblemException { long i = 1; for (Test p : testList) { print(""Case #"" + i + "": "" + p.check()); i++; } } public static boolean flag = true; FileWriter outputFile = null; public void print(String str) throws ProblemException { try { // ƒtƒ@ƒCƒ‹‚̍폜Aƒtƒ@ƒCƒ‹‚̐V‹KƒI[ƒvƒ“ if (flag) { flag = false; File fw01 = new File(OUTPUT_FILE); fw01.delete(); outputFile = new FileWriter(OUTPUT_FILE, true); } outputFile.write(str + ""\r\n""); System.out.println(str); } catch (IOException e) { throw new ProblemException(e.getMessage(),e); } } public void end() throws ProblemException { try { outputFile.close(); } catch (IOException e) { throw new ProblemException(e.getMessage(),e); } } public void init() throws ProblemException { try { FileReader in = new FileReader(INPUT_FILE); BufferedReader br = new BufferedReader(in); String line; testN = Long.parseLong(br.readLine()); while ((line = br.readLine()) != null) { String[] ch = line.split("" ""); System.out.println(line); ch = line.split("" ""); long a = Long.parseLong(ch[0]); long b = Long.parseLong(ch[1]); Test test = new Test(a,b); testList.add(test); } br.close(); in.close(); } catch (IOException e) { System.out.println(e); throw new ProblemException(e.getMessage(),e); } } public class ProblemException extends Exception { private static final long serialVersionUID = 2080823058826051635L; public ProblemException(String message) { super(message); } public ProblemException(String message, Throwable e) { super (message, e); } } // ‚±‚±‚æ‚èã‚͏‰Šú‰»‚Æ‚©ƒtƒ@ƒCƒ‹ˆ—B // ‚±‚±‚æ‚艺‚̓Aƒ‹ƒSƒŠƒYƒ€ public class Test { long a = -1; long b = -1; public Test (long a, long b) { this.a = a; this.b = b; } public String check () { HashMap map = new HashMap (); for (long i = a; i <= b; i++) { long small = getSmall(i); AB newAB = new AB(small); AB ab = map.get(small); if (ab == null){ map.put(small, newAB); } else { ab.plus(); } } long result = 0; for (long small : map.keySet()) { AB ab = map.get(small); if (ab.getN() == 1) { continue; } long kumi = ab.getN() * (ab.getN() - 1) / 2; result += kumi; /* System.out.println(""ab="" + ab.getN() + "", "" + ab.getSmall() + "", kumi="" + kumi); */ } return """" + result; } private long getSmall (long hoge) { long ret = 0; long keta = getKeta(hoge); ret = hoge; for (int i = 0; i < keta; i++) { hoge = hoge % 10 * kaijo10(keta-1) + hoge / 10; if (hoge < ret) { ret = hoge; } } return ret; } /** * @param keta * @return output = 10 ^ input */ private long kaijo10 (long keta) { long ret = 1; for (int i = 0; i < keta; i ++) { ret *= 10; } return ret; } /** * @param hoge * @return —^‚¦‚ç‚ꂽ”‚ÌŒ…”‚ð•Ô‚·B */ private long getKeta (long hoge) { if (hoge == 0){ return 0; } else { return getKeta(hoge / 10) + 1; } } @Override public String toString() { // String list = "" ""; return ""("" + a + "","" + b + "")""; } } public class AB { long small; long n = 1; public AB (long small) { this.small = small; } public long getSmall() { return small; } public long getN() { return n; } public void plus() { n ++; } @Override public boolean equals(Object o) { AB ab = (AB) o; return (small == ab.getSmall()); } @Override public int hashCode () { return (int)small; } } /* * Case #1: 1 Case #2: 256 Case #3: 4 Case #4: 674 Case #5: 461 * */ } " B21254," import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class ProblemC_Qual_2012 implements Runnable{ BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""""); void init() throws FileNotFoundException{ in = new BufferedReader(new FileReader(""C-large.in"")); out = new PrintWriter(""output.txt""); } String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new Thread(null, new ProblemC_Qual_2012(), """", 256 * (1L << 20)).start(); } long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println(""Time = "" + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory(){ memoryFree = Runtime.getRuntime().freeMemory(); System.err.println(""Memory = "" + ((memoryTotal - memoryFree) >> 10) + "" KB""); } void debug(Object... objects){ if (DEBUG){ for (Object o: objects){ System.err.println(o.toString()); } } } public void run(){ try{ timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); time(); memory(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } boolean DEBUG = false; void solve() throws IOException{ int t = readInt(); for (int it = 1; it <= t; it++){ out.print(""Case #"" + it + "": ""); int a = readInt(); int b = readInt(); boolean[] used = new boolean[b+1]; int x = a; int pow = 1; while (x >= 10){ x /= 10; pow *= 10; } long res = 0; for (int i = a; i <= b; i++){ if (used[i]) continue; x = i; long count = 0; do{ if (x / pow != 0 && x >= a && x <= b){ used[x] = true; count++; } x = x % pow * 10 + (x / pow); }while (x != i); used[i] = true; res += (count - 1) * count / 2; } out.println(res); } } } " B21848,"import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) { try { System.setOut(new PrintStream(new FileOutputStream(""output.txt""))); Scanner scanner = new Scanner(new File(args[0])); int testsNum = scanner.nextInt(); String solution; for (int i=1; i<=testsNum; i++) { solution = solve(scanner); System.out.println(""Case #""+i+"": ""+solution); System.err.println(""Case #""+i+"": ""+solution); } } catch (Exception e) {e.printStackTrace();} } static class Pair { private int n; private int m; public Pair(int n, int m) {this.n=n; this.m=m;} public int hashCode() {return n^m;} public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair p = (Pair)o; return n==p.n && m==p.m; } } private static String solve(Scanner scanner) { int A = scanner.nextInt(); int B = scanner.nextInt(); int ret=0; int r; int digits; Set pairs = new HashSet(); Pair pair; for (int n=A; n<=B; n++) { digits = (int)Math.ceil(Math.log10(n)); if (n>10) { for (int d=1; d set = new HashSet(); for (int testNum = 1; testNum <= numberOfTests; testNum++) { out.print(""Case #"" + testNum + "": ""); int a = in.nextInt(); int b = in.nextInt(); int res = 0; for (int num = a; num <= b; num++) { StringBuilder sb = new StringBuilder(); String s = String.valueOf(num); sb.append(s); sb.append(s); set.clear(); for (int i = 0; i < s.length(); i++) { int cc = Integer.parseInt(sb.substring(i, i + s.length())); if (num < cc && cc >= a && cc <= b && !set.contains(cc)) { res++; set.add(cc); } } } out.println(res); } } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } " B20543,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class RecycledNumbers { private BufferedReader reader; private BufferedWriter writer; /** * @param args */ public static void main(String[] args) { RecycledNumbers rn = new RecycledNumbers(args[0]); rn.executeTests(); } public RecycledNumbers(String filename) { // Open file File file = new File(filename); try { reader = new BufferedReader(new FileReader(file)); writer = new BufferedWriter(new FileWriter(file+"".out"")); } catch (IOException e) { // Failed to open new buffered reader System.err.println(""Failed to open FileReader""); e.printStackTrace(); System.exit(-1); } } private void executeTests() { // Read number of test cases int numberOfTests = 0; try { // Read number of tests (first line) numberOfTests = Integer.parseInt(reader.readLine()); } catch (NumberFormatException | IOException e) { // Failed to read a line System.err.println(""Failed to read a line""); e.printStackTrace(); System.exit(-1); } for (int testCase = 1; testCase <= numberOfTests; testCase++) { String[] input; try { input = reader.readLine().split(""\\s""); int min = Integer.parseInt(input[0]); int max = Integer.parseInt(input[1]); List scores = new ArrayList(); int answer = totalRecycledPairs(min, max); writer.write(""Case #"" + testCase + "": "" + answer + '\n'); } catch (IOException e) { e.printStackTrace(); } } try { reader.close(); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } private static int totalRecycledPairs(int min, int max) { // Number -> Unique Pair Count Map uniquePairCount = new HashMap(); int total = 0; for (int number = min; number <= max; number++) { int count = 0; for (Integer recycled : getRecycledPairs(number)) { if (!uniquePairCount.containsKey(recycled) && recycled <= max && recycled >= min) { count++; } } uniquePairCount.put(number, count); total += count; } return total; } private static Set getRecycledPairs(int number) { Set pairs = new HashSet(); String numberString = String.valueOf(number); for (int i = 1; i < numberString.length(); i++) { String rcirc = numberString.substring(numberString.length() - i) + numberString.substring(0, numberString.length() - i); int pair = Integer.parseInt(rcirc); if (numberString.length() == String.valueOf(pair).length() && pair != number) { pairs.add(Integer.parseInt(rcirc)); } } return pairs; } } " B21889,"package googlecodejam2012.qualification.recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { String lineSep = System.getProperty(""line.separator""); BufferedReader br = new BufferedReader( args.length > 0 ? new FileReader(args[0]) : new InputStreamReader(System.in)); try { Writer out = new BufferedWriter(args.length > 1 ? new FileWriter(args[1]): new OutputStreamWriter(System.out)); try { int numLines = Integer.parseInt(br.readLine().trim()); for (int i = 1; i <= numLines;++i) { String line = br.readLine(); out.write(""Case #"" + i + "": ""+count(line) + lineSep); } } finally { out.close(); } } finally { br.close(); } } private static int count(String line) { String[] parts = line.split(""\\s+""); return count(Integer.parseInt(parts[0]), Integer.parseInt(parts[1])); } private static int count(int a, int b) { if (b < 10) { return 0; } int digits = 1+(int) Math.log10(a); int count = 0; for (int i = a; i < b; ++i) { int[] prevs = new int[digits]; for (int j = 1; j < digits; ++j) { prevs[j - 1] = shift(i, j, digits); if (recycled(prevs, i, a, b, j)) { // System.out.println(shift(i, j) + "" <- "" + i); ++count; } } } return count; } private static boolean recycled(final int[] prevs, final int orig, final int a, final int b, final int j) { boolean recycled = recycled(prevs[j - 1], orig, a, b); if (recycled) { for (int i = 0; i < j - 1; ++i) { if (prevs[i] == prevs[j - 1]) recycled = false; } } return recycled; } private static boolean recycled(int shifted, int orig, int a, int b) { return shifted > orig && shifted >= a && shifted <= b; } private static final int[] powers = new int[] {1, 10, 100, 1000, 10000, 100000, 1000000}; private static int shift(int num, int shift, int digits) { int power = powers[shift]; int pow2 = powers[digits - shift]; return num % power * pow2 + num / power; } private static int shift(int num, int shift) { String str = Integer.toString(num); return Integer.parseInt(str.substring(shift) + str.substring(0, shift)); } } " B20832,"import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; /** * User: Sasha * Date: 09.04.12 * Time: 19:13 */ public class Main { private Scanner sc; private PrintWriter wr; private HashSet set; private void prepare() throws Exception { sc = new Scanner(new File(""C:\\Projects\\C-large.in"")); File file = new File(""C:\\Projects\\out.txt""); wr = new PrintWriter(file); // wr = new PrintWriter(System.out); } private void solve() { int n = sc.nextInt(); for (int i = 0; i < n; ++i) { set = new HashSet(); wr.print(String.format(""Case #%d: "", (i + 1))); int a, b; a = sc.nextInt(); b = sc.nextInt(); int res = 0; for (int j = a; j < b; ++j) { res += cnt(j, a, b); } wr.println(res); } wr.flush(); } private int cnt(int c, int left, int right) { int res = 0; String s = """" + c; for (int i = 0; i < s.length() - 1; ++i) { if (s.charAt(i + 1) == '0') continue; String t = s.substring(i + 1) + s.substring(0, i + 1); int d = Integer.parseInt(t); if (left <= d && d <= right && c < d && s.length() == ("""" + d).length()) { if (set.contains(s + t)) continue; set.add(s + t); ++res; } } return res; } public static void main(String args[]) throws Exception { Main main = new Main(); main.prepare(); main.solve(); } } " B21326,"/** * Created by IntelliJ IDEA. * User: ashevenkov * Date: 14.04.12 * Time: 11:17 */ package codejam.codejam2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * @author ashevenkov */ public class QualificationC { public static void main(String[] args) throws Exception { new QualificationC().calculate( ""/home/ashevenkov/projects/codejam/C-large.in"", ""/home/ashevenkov/projects/codejam/C-large.out""); } public void calculate(String in, String out) throws Exception { BufferedReader br = new BufferedReader(new FileReader(in)); FileWriter fw = new FileWriter(out); String line = br.readLine(); int cases = Integer.parseInt(line); for(int i = 0; i < cases; i++) { line = br.readLine(); String[] parts = line.split("" ""); int a = Integer.parseInt(parts[0]); int b = Integer.parseInt(parts[1]); String result = recycle(a, b); System.out.println(""Case #"" + (i + 1) + "": "" + result); fw.write(""Case #"" + (i + 1) + "": "" + result); fw.write(""\n""); } fw.flush(); fw.close(); } Map> cache = new HashMap>(); private String recycle(int a, int b) { int result = 0; for(int i = a; i <= b; i++) { Set set = cache.get(i); if(set == null) { String s = Integer.toString(i); String s1 = s + s; set = new HashSet(); for(int j = 1; j < s.length(); j++) { int k = Integer.parseInt(s1.substring(j, j + s.length())); set.add(k); } cache.put(i, set); } for(Integer k : set) { if(a <= k && k <= b && i < k) { result++; } } } return Integer.toString(result); } } " B20002,"import java.io.*; import java.util.*; public class Qual3 { private static Set set = new HashSet(); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File(""C-large.in"")); FileWriter fw = new FileWriter(""C-output.txt""); int total = sc.nextInt(); for(int i = 1; i <= total; i++) { set.clear(); int count = 0, st = sc.nextInt(), end = sc.nextInt(); for(int j = st; j < end; j++) process(j, end); fw.write(""Case #"" + i + "": "" + set.size() + ""\n""); System.out.println(""Case #"" + i + "": "" + set.size()); } fw.close(); } private static void process(int num, int max) { int digit = 10; while(digit < num) { int div = num / digit, rem = num % digit; int switched = Integer.parseInt("""" + rem + div); if(num < switched && switched <= max) { String s = num + "", "" + switched; set.add(s); } digit *= 10; } } } " B21954,"import java.util.Scanner; public class RecycledSmall { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int cases = scan.nextInt(); for (int trial = 1; trial <= cases; trial++) { System.out.print(""Case #"" + trial + "": ""); int a = scan.nextInt(); int b = scan.nextInt(); int rots = 0; for (int v = a; v < b; v++) { rots += countRotations(v, b); } System.out.println(rots); } } private static int countRotations(int v, int b) { String vString = Integer.toString(v); String nextString = vString; int count = 0; while (true) { nextString = rotate(nextString); if (nextString.equals(vString)) break; int newV = Integer.parseInt(nextString); if (newV > v && newV <= b) count++; } return count; } private static String rotate(String nextString) { return nextString.substring(1) + nextString.charAt(0); } } " B21502," import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; public class gjam { public static void main(String[] args) { int TestCases = 0; int currentCase = 0; try { FileInputStream fstream = new FileInputStream(""C-small-attempt0.in""); DataInputStream dstream = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(dstream)); String inputStr = br.readLine(); TestCases = Integer.parseInt(inputStr); while(currentCase != TestCases) { ArrayList results = new ArrayList(); inputStr = br.readLine(); int result = 0; String[] inputs = inputStr.split("" ""); int size = inputs[0].length(); int A = Integer.parseInt(inputs[0]); int B = Integer.parseInt(inputs[1]); if(A >= 10 && B > A) for(int i = A; i <= B; i++) { for(int j = 1; j <= size; j++) { int moved = moveDigits(j,i); if(A <= i && i < moved && moved <= B) { results.add(i); results.add(moved); result++; } } } System.out.println(""Case #"" + (currentCase +1) + "": "" + result); currentCase++; } } catch(Exception e) { System.err.println(""Err: "" + e.getMessage()); } } public static int moveDigits(int numTomove,int input) { String original = """" + input; int length = original.length(); String sub1 = original.substring(length - numTomove); String sub2 = original.substring(0,length - numTomove); String output = sub1 + sub2; return Integer.parseInt(output); } } " B21368,"/** * @author Saifuddin Merchant * */ package com.sam.googlecodejam.helper; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class InputReader { BufferedReader iFileBuffer; long iCurrentLineNumber; public InputReader(String pFileName) { try { iFileBuffer = new BufferedReader(new FileReader(pFileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } iCurrentLineNumber = 0; } public String readNextLine() { try { return iFileBuffer.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public void close() { try { iFileBuffer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B20432,"package assignments; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import base.Assignment; public class AssignmentC implements Assignment { private int min; private int max; @Override public String solve() { int total = 0; int length = (int) Math.log10(min) + 1; for (int i = min; i < max; i++) { List counted = new ArrayList(); for (int j = 1; j < length; j++) { int shifted = shift(i, j, length); if (shifted > i && shifted <=max && !counted.contains(shifted)) { counted.add(shifted); total++; } } } return Integer.toString(total); } private int shift(int i, int shift, int length) { int temp = (int) Math.pow(10, shift); int result = (i % temp) * ((int)Math.pow(10, length - shift)) + ((int)i / temp); return result; } public static Assignment createFromScanner(Scanner scanner) { AssignmentC assignment = new AssignmentC(); assignment.min = scanner.nextInt(); assignment.max = scanner.nextInt(); return assignment; } } " B21960,"/* ID: 14vikra1 LANG: JAVA TASK: recycled */ import java.io.*; import java.util.*; class recycled { public static void main (String [] args) throws IOException { long start = System.currentTimeMillis(); BufferedReader br = new BufferedReader(new FileReader(""recycled.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""recycled.out""))); int T = Integer.parseInt(br.readLine()); for (int i = 0; i < T; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int pairs = 0; for (int j = A; j < B; j++) { pairs += checkPairsNew(j, A, B); } out.println(""Case #"" + (i+1) + "": "" + pairs); } long end = System.currentTimeMillis(); System.out.println(end-start); out.close(); System.exit(0); } public static int checkPairsNew(int num, int A, int B) { int numpairs = 0; String Bs = Integer.toString(B); String nums = Integer.toString(num); int size = Bs.length(); ArrayList used = new ArrayList(); for (int i = 1; i < size; i++) { String moves = nums.substring(size-i,size); String tests = nums.substring(0,i); String testBs = Bs.substring(0,i); int move = Integer.parseInt(moves); int test = Integer.parseInt(tests); int testB = Integer.parseInt(testBs); //System.out.println(move + "" "" + test + "" "" + testB + "" "" + num); if (move >= test && move <= testB) { String newnums = nums.substring(0, size-i); newnums = moves + newnums; int newnum = Integer.parseInt(newnums); //System.out.println(move + "" "" + test + "" "" + testB + "" "" + num + "" "" + newnum); if (newnum > num && newnum <= B && !used.contains(newnum)) { numpairs++; used.add(newnum); } } } return numpairs; } public static int checkPairs(int num, int A, int B, int size) { int numpairs = 0; ArrayList used = new ArrayList(); for (int i = 1; i < size; i++) { int move = (int)(num%Math.pow(10, i)); int test = (int)((num)/Math.pow(10,size-i+1)); int testB = (int)((B)/Math.pow(10,size-i+1)); if (move >= test && move <= testB) { int newnum = (int)((num - move)/Math.pow(10,i)); newnum = newnum + move*(int)(Math.pow(10,size-i)); if (newnum > num && newnum <= B && !used.contains(newnum)) { numpairs++; used.add(newnum); } } } return numpairs; } } " B20093,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejam; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; /** * * @author Muhammad Zahran */ public class recycleNumber { public static void main(String[] args) throws IOException { PrintWriter w = new PrintWriter(new FileWriter(""out.txt"")); BufferedReader r = new BufferedReader(new FileReader(""input.txt"")); int testcases = Integer.parseInt(r.readLine()); for (int i = 0; i < testcases; i++) { int result=0; String[] tokens = r.readLine().split("" ""); String strA = tokens[0]; int a = Integer.parseInt(tokens[0]); int b = Integer.parseInt(tokens[1]); String strB = tokens[1]; int currentNo = a; while(true) { if(currentNo > b) break; int scratch = currentNo; String strScratch = String.valueOf(currentNo); for (int d = 1; d < strScratch.length(); d++) { String sub1 = strScratch.substring(strScratch.length()-d,strScratch.length()); //LSD String sub2 = strScratch.substring(0,strScratch.length()-d); //MSD if(!sub1.substring(0, 1).equals(""0"")) { String strRotated = sub1+sub2; if(!strRotated.equals(strScratch)) { int rotated = Integer.parseInt(strRotated); if(rotated <= b && rotated > scratch) { // w.println(scratch + "" : ""+rotated); // System.out.println(scratch + "" : ""+rotated); result++; } } } } currentNo++; } int asd = i+1; w.println(""Case #"" + asd + "": "" + result); System.out.println(""Case #"" + asd + "": "" + result); } w.close(); } } " B20036," package codejam; import java.io.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * * @author Ronak */ public class C { public static void main(String[] args) throws FileNotFoundException, IOException { File f = new File(""C-large.in""); FileInputStream fstream = new FileInputStream(f); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = """"; int count = 0, T = 0; List left = new ArrayList(); while ((strLine = br.readLine()) != null) { if (count == 0) { T = Integer.parseInt(strLine.trim()); } else { strLine.trim(); String[] l = strLine.split("" ""); int min = Integer.parseInt(l[0]); int max = Integer.parseInt(l[1]); System.out.print(""Case #"" + count + "": ""); for (int n = min; n <= max; n++) { String str = String.valueOf(n); for (int i = 1; i < str.length(); i++) { String temp = str.substring(i, str.length()) + str.substring(0, i); if (temp.charAt(0) != '0') { int m = Integer.parseInt(temp); if (n < m && m <= max && n >= min) { left.add(n + """" + m + """"); } } } } System.out.println(new ArrayList(new HashSet(left)).size()); left.clear(); } count++; } } } " B20178,"package codejam2.recycled; import java.util.HashSet; import java.util.Scanner; import codejam2.CodejamCase; import codejam2.CodejamRunner; public class Recycled extends CodejamRunner implements CodejamCase { private int min; private int max; private String result; @Override public void compute() { int r = 0; for(int i = min; i <= max; i++) { HashSet ss = new HashSet(); String s = String.valueOf(i); for(int j = 1; j < s.length(); j++) { String n = s.substring(j) + s.substring(0, j); int in = Integer.valueOf(n); if (in > i && in <= max) { ss.add(n); } } r += ss.size(); } result = String.valueOf(r); } @Override public String getOutput() { return result; } @Override public CodejamCase parseCase(Scanner s) { Recycled r = new Recycled(); r.min = s.nextInt(); r.max = s.nextInt(); return r; } /** * @param args */ public static void main(String[] args) { new Recycled().run(args); } } " B21087,"import java.io.*; import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.util.Arrays.*; import static java.util.Collections.*; import java.math.*; import java.util.*; import static java.lang.Math.*; public class RecycledNumbers { public static void main (String [] args) throws IOException { String[]filename=""test A-small A-large B-small B-large C-small C-large D-small D-large"".split("" ""); ////////////////// 0 1 2 3 4 5 6 7 8 String fn=filename[6]; f = new BufferedReader(new FileReader(fn+"".in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fn+"".out""))); nl(); int[]p10=new int[]{1,10,100,1000,10000,100000,1000000,10000000}; int t = ip(tk()); for (int i = 0; i < t; i++) { nl(); boolean[]mark=new boolean[2000001]; int a = ip(tk()),b=ip(tk()); int res=0; int bitcnt=1; for (int j = 1;j=p10[j])bitcnt=j+1; } for (int j = a; j <= b; j++) { if(mark[j])continue; if(j>=p10[bitcnt])bitcnt++; int cur=j; int cnt=0; for (int k = 0; k < bitcnt; k++) { if(cur>=p10[bitcnt-1]&&cur>=a&&cur<=b&&mark[cur]==false){ mark[cur]=true; cnt++; } int next=cur%10*p10[bitcnt-1]+cur/10; cur=next; } if(cnt>=2){ res+=cnt*(cnt-1)/2; } } out.println(""Case #""+(i+1)+"": ""+res); } out.close(); System.exit(0); } static BufferedReader f; static StringTokenizer st; static void nl() throws IOException { st = new StringTokenizer(f.readLine()); } static String tk() { return st.nextToken(); } static void fill(Object array,int val){ if(array instanceof int[])Arrays.fill((int[])array,val); else for(Object o:(Object[])array)fill(o,val); } //static String min(String a,String b){return a.compareTo(b)<0?a:b;} static int ip(String s){return Integer.parseInt(s);} static long lp(String s){return Long.parseLong(s);} static int inf=Integer.MAX_VALUE/2; static int gcd(int a,int b){return b==0?a:gcd(b,a%b);} static boolean isPrime(int number) { if (number < 2) return false; if (number == 2) return true; if (number % 2 == 0) return false; for (int i = 3; i * i <= number; i += 2) if (number % i == 0) return false; return true; } static public class Comp implements Comparable { public int compareTo(Comp other) {// myself first asc if (len == other.len) return str.compareTo(other.str);// myself first asc return other.len - len;// other first desc } int len; String str; public Comp(int len, String str) { super(); this.len = len; this.str = str; } } } " B20801,"package QualificationRound; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintStream; public class RecycledNumbers { public static void main(String[] args) throws Exception { System.setIn(new FileInputStream(""recyclednumbers.in"")); System.setOut(new PrintStream(""recyclednumbers.out"")); BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(bf.readLine()); for(int t = 1; t <= T; t++) { System.out.print(""Case #"" + t + "": ""); String[] parts = bf.readLine().trim().split(""[ ]+""); int from = Integer.parseInt(parts[0]); int to = Integer.parseInt(parts[1]); boolean[] explored = new boolean[to - from + 1]; long result = 0l; for(int i = from; i <= to; i++) { if(explored[i - from]) continue; long count = 0L; String s = Integer.toString(i); int length = s.length(); for(int j = 0; j < length; j++) { s = s.substring(s.length() - 1) + s.substring(0, s.length() - 1); if(s.charAt(0) == '0') continue; int n = Integer.parseInt(s); if(n < from || n > to) continue; if(explored[n - from]) continue; explored[n - from] = true; count++; } result += count * (count - 1l) / 2l; } System.out.println(result); } } } " B20814,"package qualification; import java.io.*; import java.util.Arrays; import java.util.Scanner; /** * @author Roman Elizarov */ public class C { public static void main(String[] args) throws IOException { new C().go(); } Scanner in; PrintWriter out; private void go() throws IOException { init(); in = new Scanner(new File(""src\\qualification\\c.in"")); out = new PrintWriter(new File(""src\\qualification\\c.out"")); int t = in.nextInt(); for (int tn = 1; tn <= t; tn++) { out.println(""Case #"" + tn + "": "" + solveCase()); } in.close(); out.close(); } int[] p = new int[10]; int[] u = new int[2000001]; int uh; private void init() { p[0] = 1; for (int i = 1; i < p.length; i++) p[i] = p[i - 1] * 10; Arrays.fill(u, -1); } private int getP(int a) { int i = Arrays.binarySearch(p, a); return i < 0 ? -i - 2 : i; } private int solveCase() { int a = in.nextInt(); int b = in.nextInt(); int ap = getP(a); int bp = getP(b); int cnt = 0; for (int p0 = ap; p0 <= bp; p0++) { int a0 = p0 == ap ? a : p[p0]; int b0 = p0 == bp ? b : p[p0 + 1] - 1; cnt += solveCase(a0, b0, p0 + 1); } return cnt; } private int solveCase(int a, int b, int d) { int cnt = 0; for (int n = a; n < b; n++) { for (int i = 1; i < d; i++) { int m = (n % p[i]) * p[d - i] + n / p[i]; if (m > n && m <= b && u[m] < 0) { cnt++; u[m] = uh; uh = m; } } while (uh > 0) { int next = u[uh]; u[uh] = -1; uh = next; } } return cnt; } } " B20356,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class GCIFileReader { public GCIFileReader(File file) throws FileNotFoundException { mBufferedReader = new BufferedReader(new FileReader(file)); mFile = file; } public String getLine() { try { String s = mBufferedReader.readLine(); if (s == null) { mBufferedReader.close(); } return s; } catch (IOException e) { return null; } } public void reset () throws IOException { mBufferedReader.close(); mBufferedReader = new BufferedReader(new FileReader(mFile)); } private BufferedReader mBufferedReader; private File mFile; }" B21830,"import java.util.*; import static java.lang.Math.*; public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int cases = 1; cases <= T;cases++){ int A = in.nextInt(); int B = in.nextInt(); int ans = 0; for(int i = A ; i < B+1; ++i) { String stringValue = Integer.toString(i); HashSet set = new HashSet(); for(int j = 1; j = min && temp <= max && temp > j){ answer++; } temp = ((temp % 10) * (int)(Math.pow(10,length-1))) + (temp /10); } } pwStream.print(""Case #""+(i+1)+ "": ""); pwStream.print(answer); pwStream.println(); } pwStream.close(); sc.close(); } catch(Exception e){e.printStackTrace();} } }" B20382,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; public class Recycled { private static int NN = 2000010; private static BufferedReader bf; private static File f; public static void main(String[] args) throws Exception { f = new File(""rasdjfh.in""); FileWriter out = new FileWriter(new File(""recycled.txt"")); if(f.exists()) bf = new BufferedReader(new FileReader(f)); else bf = new BufferedReader(new InputStreamReader(System.in)); String line = """", pars[],s ,x; ArrayList> recycled = new ArrayList>(NN); for(int i=0;i()); for(int j=1;j i) recycled.get(i).add(I); } } System.out.println(""Ok, I'm readyÉ""); int T = Integer.parseInt(bf.readLine()), A , B; for(int t=1;t<=T;t++) { pars = bf.readLine().split(""[ ]+""); A = Integer.parseInt(pars[0]); B = Integer.parseInt(pars[1]); int ans = 0; for(int i=A;i<=B;i++) { for(Integer j : recycled.get(i)) if(j >= A && j <=B) ans++; } out.write(String.format(""Case #%d: %d\n"",t,ans)); } out.close(); } } " B21875,"import java.util.Scanner; public class Shift { public static void main(String[] args) { int a,b,c,d=10,e=0,x,T,j; int inf,sup,res=0; Scanner l = new Scanner(System.in); T=l.nextInt(); for(j=0;j0){ vixi=vixi/10; e++; } for(int i=0;ik)&&(c<=sup)&&(c>=inf)) res++; //System.out.println(c); x=c; } } System.out.println(""Case #""+(j+1)+"": ""+res); } } } " B20288,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Prob3 { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner scan = new Scanner(new File(""C-small-attempt0.in"")); PrintWriter output = new PrintWriter(new File(""output3.txt"")); String result = """"; int tests = scan.nextInt(); for(int t = 0; t < tests; t++){ int A = scan.nextInt(); int B = scan.nextInt(); int count = 0; for(int run = A; run <= B; run++){ String m = new Integer(run).toString(); for(int i = 0; i < m.length()-1; i++){ int n = Integer.parseInt(m.substring(i+1) + m.substring(0, i+1)); if(n <= B && n >= A){ if(n == run); else{ count++; } } } } System.out.print(""Case #"" + (t+1) + "": "" + (count/2)+""\n""); result += ""Case #"" + (t+1) + "": "" + (count/2)+""\n""; } output.write(result); output.close(); } } " B21816,"import com.sun.org.apache.bcel.internal.generic.AALOAD; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecycledNum extends JamProblem { public static void main(String[] args) throws IOException { RecycledNum p = new RecycledNum(); p.go(); } @Override String solveCase(JamCase jamCase) { RecNCase ca = (RecNCase) jamCase; int res = 0; for (int n = ca.A; n < ca.B; n++) { String m = """"; //print(""n ""+n); Set bag = new HashSet<>(); int length = intLength(n); for (int t = 1; t < length; t++) { int pow = (int) Math.pow(10, t); int pow2 = (int) Math.pow(10,length-t); int f = (n / pow); int s = n - (pow * f); int cand = f + (pow2 * s); //print(""m "" + cand); if (cand < ca.A || cand > ca.B || cand <= n) { continue; } if (bag.contains(cand)) { continue; } if (intLength(cand) != intLength(n)) { continue; } res++; bag.add(cand); //print(""""+ n+ "" "" + cand); } } return """" + res; } private void print(String m) { System.out.println(m); } private int intLength(int n) { return Integer.toString(n).length(); } @Override JamCase parseCase(List file, int line) { RecNCase ca = new RecNCase(); ca.lineCount = 1; String s = file.get(line); int[] ints = JamUtil.parseIntList(s, 2); ca.A = ints[0]; ca.B = ints[1]; return ca; } } class RecNCase extends JamCase { int A, B; } " B21880,"package com.theblind.problem; import java.util.HashSet; import java.util.Scanner; import com.theblind.utility.FileUtility; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); String inputFileName = in.next(); String inputData = FileUtility.readFromFile(inputFileName); RecycledNumbers problem = new RecycledNumbers(); String content = problem.solve(inputData); FileUtility.writeToFile(""output.txt"", content); } private String solve(String inputData) { // TODO Auto-generated method stub Scanner in = new Scanner(inputData); StringBuilder sb = new StringBuilder(); int testCases = in.nextInt(); for (int i = 1; i <= testCases; ++i) { sb.append(""Case #"" + i + "": ""); int A = in.nextInt(); int B = in.nextInt(); sb.append(calculate(A, B)); sb.append(""\n""); } return sb.toString(); } private int calculate(int A, int B) { // TODO Auto-generated method stub int result = 0; String b = Integer.toString(B); for (int i = A; i < B; ++i) { String n = Integer.toString(i); HashSet numbers = new HashSet(); for (int k = 1; k < n.length(); ++k) { String m = n.substring(k) + n.substring(0, k); if (numbers.contains(m)) { continue; } else { numbers.add(m); } if (m.compareTo(n) > 0 && m.compareTo(b) <= 0) { ++result; } } } return result; } } " B21364,"package com.sam.googlecodejam.dance; import com.sam.googlecodejam.helper.InputReader; public class DanceScore { int iBestScore; int iSuprize; int iMean; int iSetCount = 0; class TripletScore { public int judge1; public int judge2; public int judge3; public void setValue(int j1, int j2, int j3) { judge1 = j1; judge2 = j2; judge3 = j3; } public int sum() { //System.out.println(judge1 + judge2 + judge3); return judge1 + judge2 + judge3; } public boolean containsGreater(int value) { //System.out.println(judge1 >= value || judge2 >= value || judge3 >= value); if(judge1 >=0 && judge2 >=0 && judge3 >=0) { return judge1 >= value || judge2 >= value || judge3 >= value; } return false; } } /* * e.g. If score is 13,14,15, 15 - avg = 15/3 + (15%3==0)= 5 (3,5,5), * (4,4,5) (4,5,5) (5,5,5) (4,6,5) If score is 22,23,24 22 - avg = 22/3 * +(22%3==0) = 8 (6,8,8), (7,7,8) (7,8,8) (8,8,8), (7,8,9) */ TripletScore possibleValues[] = new TripletScore[6]; public void generateTripletFromScore(int score) { int mean = score / 3 + (score % 3 == 0 ? 0 : 1); iMean = mean; for(int i=0;i<6;i++) { possibleValues[i] = new TripletScore(); } // Non Suprizing possibleValues[0].setValue(mean - 1, mean - 1, mean); possibleValues[1].setValue(mean - 1, mean, mean); possibleValues[2].setValue(mean, mean, mean); // Suprizing possibleValues[3].setValue(mean - 2, mean, mean); possibleValues[4].setValue(mean - 1, mean + 1, mean); possibleValues[5].setValue(mean - 1, mean - 1, mean + 1); } public void isScore(int score) { // check if any combination yeilds a result that would be greater than // the better score // We first check if a non-suprizing one works and only then use up a // suprizing! for (int i = 0; i < 3; i++) { if (possibleValues[i].sum() == score) { if (possibleValues[i].containsGreater(iBestScore)) { iSetCount++; return; } } } if (iSuprize != 0) { for (int i = 3; i < 6; i++) { if (possibleValues[i].sum() == score) { if (possibleValues[i].containsGreater(iBestScore)) { iSetCount++; iSuprize--; return; } } } } } public static void main(String[] args) { InputReader reader = new InputReader(""c://input.in""); reader.readNextLine(); // read the line number off - we don't need it String lineRead = null; int i = 1; while ((lineRead = reader.readNextLine()) != null) { DanceScore score = new DanceScore(); System.out.print(""Case #"" + i + "": ""); i++; String values[] = lineRead.split("" ""); score.iSuprize = Integer.parseInt(values[1]); score.iBestScore = Integer.parseInt(values[2]); for (int LoopCount = 3; LoopCount <= Integer.parseInt(values[0])+2; LoopCount++) { score.generateTripletFromScore(Integer .parseInt(values[LoopCount])); score.isScore(Integer .parseInt(values[LoopCount])); } System.out.println(score.iSetCount); } } } " B21548,"package codej; import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class QualB { Scanner scanner = null; int caseLog = 0; int A = 0; int B = 0; /** * @param args */ public static void main(String[] args) { QualB b = new QualB(); b.go(); } public void go() { try { scanner = new Scanner(new File(""input.txt"")); } catch (FileNotFoundException e) { e.printStackTrace(); } int N = scanner.nextInt(); for (int i=1; i <= N; i++) { scanner.nextLine(); System.out.print(""Case #"" + i +"": ""); System.out.println(doCase()); } } public int doCase() { int rval = 0; A = scanner.nextInt(); B = scanner.nextInt(); caseLog = (int) Math.log10(A); if (A < 10) return 0; for (int i = A; i <= B; i++) { rval += recycle(i); } return rval; } public int recycle(int i) { Set recset = new HashSet(); for (int log = caseLog; log > 0; log--) { int recycled = 0; int dec = (int) Math.pow(10, log); int rdec = (int) Math.pow(10, caseLog - (log - 1)); recycled += (i % dec) * rdec; recycled += i / dec; if (recycled > i && recycled <= B) { recset.add(recycled); } } return recset.size(); } } " B21060,"import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { static int t, a, b; public static void main(String[] args) throws FileNotFoundException { Scanner reader = new Scanner(new File(""numbers.in"")); t = reader.nextInt(); for (int c = 1; c <= t; c++) { a = reader.nextInt(); b = reader.nextInt(); int cuenta = 0; for (int n = a; n < b; n++) { cuenta += eval(n); } System.out.println(""Case #""+c+"": ""+cuenta); } } static int eval(int n){ String s = """"+n; int l = s.length(); int cuenta = 0; int nn; ArrayList nns = new ArrayList(); for (int i = 1; i < l; i++) { s = rotar(s); if (s.charAt(0)=='0') continue; nn = Integer.parseInt(s); if (nn>n && nn<=b && !nns.contains(nn)){ cuenta++; nns.add(nn); } } return cuenta; } static String rotar(String s){ return s.substring(1) + s.charAt(0); } } " B21720,"package com.google; import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { private static int numberOfRecycledPairsPossible(int a, int lowerLimit, int upperLimit) { int length = (a + """").length(); if (length == 1) { return 0; } int[] digits = new int[length]; int b = a; boolean isRecyclePossible = false; int temp = 0; ; Set set = new HashSet(); digits[length - 1] = b % 10; b /= 10; for (int i = length - 2; i >= 0; i--) { digits[i] = b % 10; b /= 10; if (digits[i] != digits[i + 1]) { isRecyclePossible = true; } } if (!isRecyclePossible) { return 0; } for (int i = 1; i < length; i++) { temp = 0; for (int j = i; j < length; j++) { temp = temp * 10 + digits[j]; } for (int j = 0; j < i; j++) { temp = temp * 10 + digits[j]; } if (temp <= upperLimit && temp >= lowerLimit && temp > a) { set.add(a + """" + temp); } } return set.size(); } private static int getRecycledNumbers(int start, int end) { int count = 0; for (int i = start; i <= end; i++) { count += numberOfRecycledPairsPossible(i, start, end); } return count; } public static void main(String[] args) throws FileNotFoundException { File file = new File(""d:\\codeJam\\Numbers\\test.txt""); Scanner scanner = new Scanner(file); int t = scanner.nextInt(); int count = 0; for (int i = 1; i <= t; i++) { count = getRecycledNumbers(scanner.nextInt(), scanner.nextInt()); System.out.println(""Case #"" + i + "": "" + count); } } } " B20684," import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class Recycle { public static void main(String...args) throws IOException { //the result file PrintWriter writer = new PrintWriter(new FileWriter(""c:\\jam\\C-large.out"")); //reading input file the file BufferedReader reader = new BufferedReader(new FileReader(""c:\\jam\\C-large.in"")); //Reading cases number int count = Integer.parseInt(reader.readLine()); //Iterating over the cases for(int k=1;k list = new ArrayList(); for(int i=0;in && c<=B && size==size2){ res++; } old = str; } } writer.println(""Case #"" + k + "": "" + res); } reader.close(); writer.close(); } } " B20636," /** * Name: Shivam99 * email: shivthedestroyer99@gmail.com */ import java.io.*; public class ProblemC { public static void main(String[] args) throws IOException{ FileReader fr=new FileReader(args[0]); BufferedReader br=new BufferedReader(fr); String str=br.readLine(); int t=Integer.parseInt(str); String ss=""""; int c=1; while(c<=t){ str=br.readLine(); int pos=str.indexOf(' '); String f=str.substring(0,pos); String s=str.substring(++pos,str.length()); int a=Integer.parseInt(f); int b=Integer.parseInt(s); int ans=0; ss+=""Case #""+c+"": ""; if(a!=b && f.length()>1){ for(int ind=a;indind && num<=b){ arr[count]=num; boolean chk=true; for(int j=1;j<=count;j++){ if(arr[j-1]==num) chk=false; } if(chk) ans++; } count++; } } } ss+=ans+""\n""; c++; } System.out.print(ss); br.close(); fr.close(); } } " B21282,"/** * */ package org.mikeyin; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; /** * @author yincrash * */ public class RecycledNumbers { // from stackoverflow, exponentiation by squaring public static int ipow(int base, int exp) { int result = 1; while (exp != 0) { if ((exp & 1) != 0) result *= base; exp >>= 1; base *= base; } return result; } /** * @param args */ public static void main(String[] args) { try { Scanner file = new Scanner(new File(args[0])); int testCases = file.nextInt(); file.nextLine(); int currentCase = 1; final PrintStream ps = new PrintStream(new File(""numbers.out"")); while (currentCase <= testCases) { final int a = file.nextInt(); final int b = file.nextInt(); ps.append(""Case #"").print(currentCase); ps.append("": ""); ps.println(numRecycled(a, b)); currentCase++; } } catch (FileNotFoundException e) { e.printStackTrace(); } } private static class Pair { private int n,m; public Pair(int n, int m) { this.n = n; this.m = m; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } @Override public String toString() { return new StringBuilder(""("").append(n).append(',').append(m).append(')').toString(); } } private static int numRecycled(int a, int b) { HashSet recycledPairs = new HashSet(); for (int i = a; i < b; i++) { int numDigits = (int) (Math.floor(Math.log10(i))) + 1; int current = i; for (int j = 0; j < numDigits - 1; j++) { int digit = current % 10; current = current / 10 + (digit * ipow(10, (numDigits - 1))); if (current > i && current <= b) recycledPairs.add(new Pair(i, current)); } } return recycledPairs.size(); } } " B20244,"import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; public class three { public static void main(String[] args) { try { Scanner in = new Scanner(new File(args[0])); PrintWriter out = new PrintWriter( new FileWriter(args[1])); int T = in.nextInt(); for(int i=0;i ms; ms=shift(n,l); for(String key : ms.keySet()) { int m = ms.get(key); if(n shift(int n, int l) { HashMap ms = new HashMap(); String N = String.valueOf(n); String m; for(int j=1;j set = new TreeSet(new Comparator() { @Override public int compare(Point p1, Point p2) { if (p1.x != p2.x) return p1.x - p2.x; return p1.y - p2.y; } }); for (int i = a; i <= b; i++) { s = String.valueOf(i); for (int j = 0; j < s.length(); j++) { rev = Integer.valueOf(s.substring(j) + s.substring(0, j)); if ((rev > b) || (rev <= i) || (String.valueOf(rev).length() != s.length())) continue; set.add(new Point(i, rev)); } } return ""Case #"" + caseNumber + "": "" + set.size(); } /* * public static String solve(int caseNumber, int a, int b) { * if (b < 12) * return ""Case #"" + caseNumber + "": 0""; * * a = Math.max(10, a); * * int n = 0; * String s, bStr; * bStr = String.valueOf(b); * char f; * int check; * for (int i = a; i <= b; i++) { * s = String.valueOf(i); * System.out.println(""STR: "" + s); * f = s.charAt(0); * for (int j = 1; j < s.length(); j++) { * if ((s.charAt(j) < f) || (s.charAt(j) > bStr.charAt(0))) * continue; * * check = 0; * if (s.charAt(j) == f) { * while (((j + check) < s.length()) && (s.charAt(j + check) == f)) * check++; * if ((j + check) == s.length()) { * if (i == 449) * System.out.println(j + "" : "" + check + "" : "" + s.length()); * continue; * } * } * * check = 0; * if (Integer.valueOf("""" + s.charAt(j)) <= Integer.valueOf("""" * + bStr.charAt(0))) { * while (((j + check) < s.length()) * && (Integer.valueOf("""" + s.charAt(j + check)) <= Integer * .valueOf("""" + bStr.charAt(check)))) * check++; * * if ((j + check) != (s.length())) * continue; * } * * System.out.println(s + "" : "" + s.substring(j) + s.substring(0, j)); * n++; * } * } * * return ""Case #"" + caseNumber + "": "" + n; * } */ }" B21765,"package qualificationRound; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class Q3Recycled { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""qualificationRound/C-large.in"")); PrintWriter out = new PrintWriter(new File(""qualificationRound/out.txt"")); int T = sc.nextInt(); sc.nextLine(); for (int tc = 1; tc <= T; tc++) { out.print(""Case #""+tc+"": ""); System.out.print(""Case #""+tc+"": ""); int A = sc.nextInt(); int B = sc.nextInt(); int count = 0; for (int n = A; n <= B; n++) { if (n >= 10) { // must be two digits at least String s = """"+n; /*boolean same = true; for (int j=1; j getCycle(int x) { String s = Integer.toString(x); Set set = new HashSet(); set.add(x); for (int c = 1; c < s.length(); c++) { String t = s.substring(c).concat(s.substring(0, c)); set.add(Integer.parseInt(t)); } return set; } private static Set mask(Set set, int a, int b) { Set result = new HashSet(); for (int x : set) { if (x >= a && x <= b) { result.add(x); } } return result; } public static void main(String[] args) throws FileNotFoundException, IOException { String question = ""C""; String name = ""large""; // String name = ""small-attempt0""; // String name = ""test""; String filename = String.format(""%s-%s"", question, name); BufferedReader input = new BufferedReader( new FileReader(String.format(""/home/paul/Documents/code-jam/2012/qualification/%s.in"", filename))); String firstLine = input.readLine(); PrintWriter pw = new PrintWriter(new File( String.format(""/home/paul/Documents/code-jam/2012/qualification/%s.out"", filename))); int T = Integer.parseInt(firstLine); // Loop through test cases. for (int i = 0; i < T; i++) { // Read data. String[] tokens = input.readLine().split("" ""); // int N = Integer.parseInt(input.readLine()); int A = Integer.parseInt(tokens[0]); int B = Integer.parseInt(tokens[1]); // System.out.format(""%d, %d\n"", A, B); boolean[] used = new boolean[B+1]; int total = 0; for (int n = A; n <= B; n++) { if (!used[n]) { Set set = mask(getCycle(n), A, B); int k = set.size(); total += (k * (k-1))/2; for (int m : set) { used[m] = true; } } } pw.format(""Case #%d: %d\n"", i + 1, total); } pw.close(); } } " B21492,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejamqualfication; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * */ public class QualificationC { public static void main(String[] args) { File file = new File(""C:\\codejam\\plik.txt""); File result = new File(""C:\\codejam\\result.txt""); try { BufferedReader input = new BufferedReader(new FileReader(file)); FileWriter writer = new FileWriter(result); int i = -1; String line; while ((line = input.readLine()) != null) { if (i == -1) { i = 0; } else { i++; writer.write(processLine(line, i)); writer.write(""\n""); } } input.close(); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static final Pattern LINE_PATTERN = Pattern.compile(""(\\d+)\\s(\\d+)""); private static String processLine(String line, int i) { StringBuilder sb = new StringBuilder(""Case #""); sb.append(i); sb.append("": ""); Matcher m = LINE_PATTERN.matcher(line); if(m.matches()){ sb.append(generateAndCountPairs(m.group(1), m.group(2))); } return sb.toString(); } private static int generateAndCountPairs(String a, String b) { int successCounter = 0; int aInt = Integer.valueOf(a); int bInt = Integer.valueOf(b); for (int nInt = aInt; nInt <= bInt; nInt++) { String n = String.valueOf(nInt); Set obtainedMs = new HashSet(); for (int i = 1; i <= n.length(); i++) { String m = n.substring(i, n.length()) + n.substring(0, i); int mInt = Integer.valueOf(m); if (mInt > nInt && mInt <= bInt && !m.startsWith(""0"") && !obtainedMs.contains(mInt)) { successCounter++; obtainedMs.add(mInt); } } } return successCounter; } } " B20790,"import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ProblemC { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); List[] l = genRecycled(); int T = sc.nextInt(); for(int i = 0; i < T; i++){ int c = processCase(sc, l); System.out.println(""Case #"" + (i+1) + "": "" + c); } } public static List[] genRecycled(){ // gen all the possible ms for a given n List[] rec = new List[2000001]; int cmp; // generate a load of blank lists for(int i = 0; i < rec.length; i++){ // if(i % 10000 == 0) System.out.println(""hi "" + i); rec[i] = new ArrayList(); String n = Integer.toString(i); String m = rotate(n); // detect when back to the first while(!m.equals(n)){ // no leading zeros if(m.charAt(0) != '0'){ // find the numeric value cmp = Integer.parseInt(m); // number can't be greater than the max // and also has to be greater than n if(cmp < rec.length && cmp > i){ // add it to the list of possibles rec[i].add(cmp); } } m = rotate(m); } } return rec; } public static String rotate(String s){ return s.substring(1) + s.charAt(0); } public static int processCase(Scanner sc, List[] l){ int a = sc.nextInt(); int b = sc.nextInt(); int count = 0; // loop through the range for(int i = a; i < b; i++){ List li = l[i]; // find the pre-calculated things for(Integer el : li){ // if m is less than or equal to B, count it if(el <= b) count++; } } return count; } } " B20754,"package fixjava; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Set; /** * Simple multimap class. MultiMap map = MultiMapKeyToList.make(); map.put(""a"", ""x""); map.put(""a"", ""x""); map.put(""a"", ""y""); map.put(""b"", ""z""); System.out.println(Join.joinRecursive(map.entrySet(), "", "", ""["", ""]"")); * * @author luke */ public class MultiMapKeyToList { HashMap> map = new HashMap>(); public static MultiMapKeyToList make() { return new MultiMapKeyToList(); } public void put(S key, T value) { ArrayList list = map.get(key); if (list == null) { list = new ArrayList(); map.put(key, list); } list.add(value); } public ArrayList get(S key) { return map.get(key); } public boolean containsKey(S key) { return map.containsKey(key); } public int sizeKeys() { return map.size(); } public HashSet valuesUnion() { HashSet result = new HashSet<>(); for (Entry> ent : map.entrySet()) for (T val : ent.getValue()) result.add(val); return result; } public Set>> entrySet() { return map.entrySet(); } public HashMap> getRawMap() { return map; } public ArrayList>> getRawMapAsList() { ArrayList>> result = new ArrayList>>(); for (Entry> ent : map.entrySet()) result.add(Pair.make(ent.getKey(), ent.getValue())); return result; } public void putAll(S key, Iterable values) { boolean putSomething = false; for (T val : values) { put(key, val); putSomething = true; } if (!putSomething && !map.containsKey(key)) // If putting an empty collection, need to create an empty set at the key map.put(key, new ArrayList()); } public void putAll(S key, T[] values) { if (values.length == 0 && !map.containsKey(key)) // If putting an empty collection, need to create an empty set at the key map.put(key, new ArrayList()); else for (T val : values) put(key, val); } /** Invert the mapping */ public MultiMapKeyToList invert() { MultiMapKeyToList inv = new MultiMapKeyToList(); for (Entry> ent : map.entrySet()) { S s = ent.getKey(); for (T t : ent.getValue()) inv.put(t, s); } return inv; } public ArrayList>> toList() { ArrayList>> result = new ArrayList>>(); for (Entry> ent : map.entrySet()) result.add(Pair.make(ent.getKey(), ent.getValue())); return result; } /** Write out to a TSV file */ public void writeOutToFile(String tsvFile) throws IOException { PrintWriter writer = new PrintWriter(tsvFile); for (Entry> ent : map.entrySet()) { S key = ent.getKey(); StringBuilder buf = new StringBuilder(); buf.append(key); for (T val : ent.getValue()) buf.append(""\t"" + val); writer.println(buf.toString()); } writer.close(); } /** Read in a String->String map from a TSV file */ public static MultiMapKeyToList readFromFile(String tsvFile) throws IOException { MultiMapKeyToList map = new MultiMapKeyToList(); for (String line : new FileLineIterator(tsvFile)) { String[] parts = Split.split(line, ""\t""); String key = parts[0]; for (int i = 1; i < parts.length; i++) map.put(key, parts[i]); } return map; } } " B22174,"import java.io.*; import java.util.*; class Recycled { static boolean[] check = new boolean[2000001]; public static void main (String [] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-large.out""))); StringTokenizer st = new StringTokenizer(in.readLine()); int numCases = Integer.parseInt(st.nextToken()); for (int caseIndex = 0; caseIndex < numCases; caseIndex++) { out.print(""Case #"" + (caseIndex + 1) + "": ""); st = new StringTokenizer(in.readLine()); int min = Integer.parseInt(st.nextToken()); int max = Integer.parseInt(st.nextToken()); // Reset check for (int i = 0; i <= 2000000; i++) { check[i] = false; } int result = 0; for (int i = min; i <= max; i++) { result += countRecycledNumbers(i, min, max); } out.print(result); out.println(); } out.close(); } public static ArrayList generateRecycledNumbers(int x) { // Count number of digits int y = x; int numDigits = 0; while (y > 0) { numDigits ++; y /= 10; } // Get the list of digits int[] listDigits = new int[numDigits]; int index = numDigits-1; while (x > 0) { listDigits[index] = x%10; x /= 10; index --; } // Generate all possible recycled number from x ArrayList result = new ArrayList(); for (int i = 0; i < numDigits; i++) { if (listDigits[i] == 0) continue; int num = 0; for (int j = 0; j < numDigits; j++) { num = num*10 + listDigits[(i+j)%numDigits]; } if (num <= 2000000) result.add(num); } return result; } public static int countRecycledNumbers(int x, int min, int max) { if (check[x]) { return 0; } else { ArrayList recycledNumbers = generateRecycledNumbers(x); Collections.sort(recycledNumbers); int numDistinctNumbers = 0; for (int i = 0; i < recycledNumbers.size(); i++) { check[recycledNumbers.get(i)] = true; if (i > 0 && recycledNumbers.get(i) > recycledNumbers.get(i-1) && recycledNumbers.get(i) >= min && recycledNumbers.get(i) <= max) { numDistinctNumbers++; } else if (i == 0 && recycledNumbers.get(i) >= min && recycledNumbers.get(i) <= max) { numDistinctNumbers++; } } return (numDistinctNumbers*(numDistinctNumbers-1)/2); } } }" B21163,"import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; import java.util.List; import java.util.Set; public class Recycled { public static void main(String[] args) throws IOException { Path input = Paths.get(""/Users/mdymczyk/google-codejam/Tongues/src/input.in""); List lines = Files.readAllLines(input, Charset.forName(""UTF-8"")); lines.remove(0); int i = 1; for(String line : lines) { Set pairs = new HashSet(); StringBuilder sb = new StringBuilder(); sb.append(""Case #""+i+"": ""); int lower = Integer.parseInt(line.split("" "")[0]); int upper = Integer.parseInt(line.split("" "")[1]); int length = line.split("" "")[0].length(); for(int j = lower ; j <= upper ; j++) { for(int k = 1; k < length; k++) { int rearranged = rearrangeLastNDigits(j, k); if(rearranged != j && (rearranged >= lower && rearranged <= upper)){ pairs.add(new Pair(j, rearranged)); } } } sb.append(pairs.size()); System.out.println(sb); i++; } } private static int rearrangeLastNDigits(int j, int k) { String stringRepresentation = Integer.toString(j); String reordered = stringRepresentation.substring(k, stringRepresentation.length()) + stringRepresentation.substring(0, k); return Integer.parseInt(reordered); } } class Pair { int n, m; public Pair(int n, int m) { this.n = n; this.m = m; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * m*n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (m != other.m && m != other.n) return false; if (n != other.n && n != other.m) return false; return true; } } " B21018,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; public class MainImpl { public static int numberOfLines; public static int firstNumber; public static int secondNumber; public static ArrayList eachLine = new ArrayList(); public static void main(String[] args) { readFile(); for (int i = 1; i<= numberOfLines ; i++) { findSets(eachLine.get(i - 1), i); } System.out.print(""Done with conversion""); } public static void findSets(String line, int index) { StringBuffer buffer = new StringBuffer(); buffer.append(""Case #"").append(index).append("": ""); int totalUniqueCases = 0; String[] numbers = line.split("" ""); String firstNumberString = numbers[0]; String secondNumberString = numbers[0]; firstNumber = Integer.parseInt(numbers[0]); secondNumber = Integer.parseInt(numbers[1]); if (firstNumber > secondNumber) { buffer.append(String.valueOf(totalUniqueCases)); writeToFile(buffer.toString()); return; } if (firstNumberString.length() == 1 && (secondNumberString.length() == 1)) { buffer.append(String.valueOf(totalUniqueCases)); writeToFile(buffer.toString()); return; } int numberBeingConsidered = firstNumber; int totalNumberOfSets = 0; while (numberBeingConsidered <= secondNumber) { totalNumberOfSets = totalNumberOfSets + findPermutations(numberBeingConsidered); numberBeingConsidered++; } buffer.append(String.valueOf(totalNumberOfSets)); writeToFile(buffer.toString()); } public static int findPermutations(int numberBeingConsidered) { int validPermutations = 0; String numberBeingConsideredString = String.valueOf(numberBeingConsidered); ArrayList possiblePermutaions = new ArrayList(); for (int i = numberBeingConsideredString.length() - 1; i>=1; i--) { String permutationString = numberBeingConsideredString.substring(i) + numberBeingConsideredString.substring(0, i); if (!numberBeingConsideredString.equals(permutationString) && (!possiblePermutaions.contains(permutationString))) { int permutationNumber = Integer.parseInt(permutationString); if ((firstNumber <= numberBeingConsidered) && (numberBeingConsidered < permutationNumber) && (permutationNumber <= secondNumber)) { validPermutations++; possiblePermutaions.add(permutationString); } } } return validPermutations; } public static void readFile() { try { FileInputStream fstream = new FileInputStream(""src/input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; numberOfLines = Integer.parseInt(br.readLine()); while ((strLine = br.readLine()) != null) { eachLine.add(strLine); } in.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } public static void writeToFile(String line) { try { BufferedWriter bw = new BufferedWriter(new FileWriter(new File( ""src/output.txt""), true)); bw.write(line); bw.newLine(); bw.close(); } catch (Exception e) { System.out.println(""Error occured "" + e); } } } " B20976,"package Round1; /* ID: kevinle7 LANG: JAVA TASK: recycled */ import java.io.*; import java.util.*; class recycled { public static int[] pow = {1,10,100,1000,10000,100000,1000000,10000000,100000000}; public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader(""recycled.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""recycled.out""))); int t = Integer.parseInt(f.readLine()); for (int i = 0 ; i < t; i++) { StringTokenizer st = new StringTokenizer(f.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int d = (int) Math.log10(a); int count = 0; for (int n = a; n < b; n++) { HashSet set = new HashSet(); set.add(n); int temp = n; temp = temp/10 + (temp%10)*pow[d]; while (!set.contains(temp)) { set.add(temp); if (temp > n && temp <= b) count++; temp = temp/10 + (temp%10)*pow[d]; } } out.println(""Case #"" + (i+1) + "": "" + count); } out.close(); System.exit(0); } }" B21082,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * */ /** * @author alfonzzz * */ public class RecycledNumbersSolver { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); // Scanner in = getInputScanner(); int T = in.nextInt(); for (int i = 1; i <= T; i++) { in.nextLine(); int min = in.nextInt(); int max = in.nextInt(); int result = solve(min, max); System.out.format(""Case #%d: %d\n"", i, result); } } private static int solve(int min, int max) { int result = 0; for (int i = min; i <= max; i++) { result += ArrayInt.INSTANCE.setNum(i, min, max); } result /= 2; return result; } public static enum ArrayInt { INSTANCE; private char[] backingArray; private int orginalNumber; private int min; private int max; private int currentValue; private Set recycledSet = new HashSet(); public int setNum(int num, int min, int max) { this.orginalNumber = num; this.min = min; this.max = max; backingArray = Integer.toString(num).toCharArray(); calculateValue(); recycledSet.clear(); shiftLeft(); int length = length(); for (int i = 1; i < length; i++) { if (isValid()) { recycledSet.add(value()); } shiftLeft(); } return numRecycled(); } private int calculateValue() { currentValue = Integer.parseInt(new String(backingArray)); return currentValue; } public int value() { return currentValue; } public int length() { return backingArray.length; } public int numRecycled() { return recycledSet.size(); } public void shiftLeft() { char first = backingArray[0]; for (int i = 1; i < backingArray.length; i++) { int newPosition = i - 1; backingArray[newPosition] = backingArray[i]; } backingArray[backingArray.length - 1] = first; calculateValue(); } public boolean isValid() { return !isLeadingZero() && isUnique() && isInRange(); } public boolean isLeadingZero() { return backingArray[0] == '0'; } public boolean isUnique() { if (value() == orginalNumber) { return false; } char first = backingArray[0]; for (char c : backingArray) { if (c != first) { return true; } } return false; } public boolean isInRange() { int value = value(); return value >= min && value <= max; } } private static Scanner getInputScanner() { Scanner in = null; try { in = new Scanner(new File(""in.txt"")); } catch (FileNotFoundException e) { e.printStackTrace(); } return in; } } " B22028,"package qual2012; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.HashSet; public class C { public static void main(String[] args) throws FileNotFoundException { Kattio io; // io = new Kattio(System.in, System.out); // io = new Kattio(new FileInputStream(""src/qual2012/C-sample.in""), System.out); // io = new Kattio(new FileInputStream(""src/qual2012/C-small-0.in""), new FileOutputStream(""src/qual2012/C-small-0.out"")); io = new Kattio(new FileInputStream(""src/qual2012/C-large-0.in""), new FileOutputStream(""src/qual2012/C-large-0.out"")); int cases = io.getInt(); for (int i = 1; i <= cases; i++) { io.print(""Case #"" + i + "": ""); new C().solve(io); } io.close(); } private void solve(Kattio io) { int A = io.getInt(), B = io.getInt(); int noDig = 0, t = A; while (t > 0) { noDig++; t /= 10; } int cnt = 0; for(int n = A; n <= B; n++) { String s = """" + n; HashSet used = new HashSet(); for (int i = 0; i < noDig - 1; i++) { s = s.substring(1) + s.charAt(0); if (used.contains(s)) continue; used.add(s); int q = Integer.parseInt(s); if (q > n && q <= B) { cnt++; } } } io.println(cnt); } } " B21706,"package codejam.recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import codejam.common.AbstractProblemSolver; public class RecycledNumbersProblemSolver extends AbstractProblemSolver { @Override public RecycledNumbersProblem readProblem(BufferedReader reader) throws IOException { return new RecycledNumbersProblem(reader.readLine()); } @Override public Integer solveProblem(RecycledNumbersProblem problem) { return problem.solve(); } @Override public void writeSolution(int solutionNumber, Integer solution, BufferedWriter writer) throws IOException { writer.append(""Case #"" + solutionNumber + "": ""); writer.append(solution.toString()); writer.newLine(); } public static void main(String[] args) { new RecycledNumbersProblemSolver().solve(new File( ""D:/code/codejam/resources/numbers-input.txt""), new File( ""D:/code/codejam/resources/numbers-output.txt"")); } } " B22141,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import javax.management.RuntimeErrorException; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new FileInputStream(""C-large.in"")); System.setOut(new PrintStream(new FileOutputStream(""c.out""))); C c = new C(); long start = System.currentTimeMillis(); int t = sc.nextInt(); for (int i = 0; i < t; i++) System.out.println(""Case #"" + (i + 1) + "": "" + c.solve(sc.nextInt(), sc.nextInt())); long end = System.currentTimeMillis(); // System.out.println((end - start) / 1000.0); // System.out.println(""Case #"" + (i + 1) + "": "" + // c.bruteSolve(sc.nextInt(), sc.nextInt())); } private int compare(String a, String b, int shift) { int l = a.length(); int ai = 0; int bi = shift; for (int i = 0; i < l; i++) { int c = a.charAt(ai) - b.charAt(bi); if (c != 0) return c; ai++; bi++; if (bi == l) bi = 0; } return 0; } private String shift(String a, int shift) { return a.substring(shift) + a.substring(0, shift); } private long solve(int a, int b) { long count = 0; String aStr = a + """"; String bStr = b + """"; if (aStr.length() != bStr.length()) throw new RuntimeException(""Need the same length""); HashSet ready = new HashSet(); int l = aStr.length(); for (int i = a; i <= b; i++) { ready.clear(); for (int j = 1; j < l; j++) { String iStr = i + """"; String iShifted = shift(iStr, j); // debug(""Par: "" + iStr + "" and "" + iShifted); if (iShifted.equals(iStr)) continue; // Get the same // debug(""1""); if (iShifted.charAt(0) == '0') continue; // has leading zero // debug(""2""); if (iShifted.compareTo(aStr) <= 0) continue;// smaller than lower bound // debug(""4""); if (iShifted.compareTo(iStr) <= 0) continue; // smaller than first // debug(""3""); if (iShifted.compareTo(bStr) > 0) continue;// smaller than great bound // debug(""5""); if (ready.contains(iShifted)) continue; // debug(""6""); ready.add(iShifted); count++; } } return count; } private long bruteSolve(int a, int b) { long count = 0; String aStr = a + """"; String bStr = b + """"; if (aStr.length() != bStr.length()) throw new RuntimeException(""Need the same length""); HashSet ready = new HashSet(); int l = aStr.length(); for (int i = a; i <= b; i++) for (int j = i + 1; j <= b; j++) { ready.clear(); for (int k = 1; k < l; k++) { if (shift(i + """", k).equals(j + """") && !ready.contains(j + """")) { ready.add(j + """"); System.out.println(""Pair: "" + i + "" and "" + j); count++; } } } return count; } } " B22264,"import java.util.*; import java.io.*; public class C { int numLen(int n) { int ans = 0; while(n>0) { ans++; n/=10; } return ans; } int shift(int n, int pow) { int tmp = n%10; return n/10 + tmp*pow; } public C(Scanner in, PrintWriter out) { int T = in.nextInt(); in.nextLine(); for (int t=0; t seen = new HashSet(); for (int j=0; j=A && x<=B && numLen(x) == len && !seen.contains(x)) { seen.add(x); ans++; } x = shift(x,pow); } } out.printf(""Case #%d: %d\n"",t+1,ans); } out.close(); } public static void main(String[] args) throws FileNotFoundException { new C(new Scanner(new File(""c.in"")),new PrintWriter(new File(""c.out""))); } } " B22080,"import java.io.*; import java.util.*; public class RecycledNumbers { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer st; public static void main ( String [] args ) throws IOException { int T = Integer.parseInt(br.readLine()); for(int i = 0;i < T; i++) { System.out.print(""Case #"" + (i+1) + "": ""); new RecycledNumbers().cal(); } } private void cal() throws IOException { int A, B; st = new StringTokenizer(br.readLine()); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); int len = Integer.toString(A).length(); // if ( len == 1 ) System.out.println(""0""); int num = 0; for(int n = A; n < B; n++) { HashSet s = new HashSet(); for(int i = 1; i < len; i++) { int m = getRecycledNumbers(n, i); if ( n < m && m <= B && !s.contains(m)) { // System.out.println(""["" + num + ""] (n,m) = ("" + n + "","" + m + "")""); s.add(m); num++; } } } System.out.println(num); } private int getRecycledNumbers(int n, int i) { String target = Integer.toString(n); String compared = target.substring(i) + target.substring(0, i); return Integer.parseInt(compared); } } " B20047,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; public class ProblemC2 { public boolean checked[]; public int min, max; public static void main(String [] args) { new ProblemC2(); } public ProblemC2() { try { String inputFile = new String(""C-large""); BufferedReader in = new BufferedReader(new FileReader(inputFile)); PrintWriter out = new PrintWriter(new FileWriter(inputFile+"".out""),true); int numCases = Integer.parseInt(in.readLine()); String [] items = null; for(int j = 0 ; j < numCases; j++) { checked = new boolean[2000001]; items = in.readLine().split(""\\s+""); min = Integer.parseInt(items[0]); max = Integer.parseInt(items[1]); int total = 0; for(int x = min; x <= max; x++) { if(! checked[x]) total+=checkRecycled(x); } out.println(""Case #"" + (j+1) + "": "" + total); } in.close(); out.close(); } catch(Exception e) { e.printStackTrace(); } } private int checkRecycled(int x) { int matches=1; checked[x]=true; if(x<10) return 0; int numChecks = 0; if(x>=1000000) numChecks = 6; else if(x>=100000) numChecks = 5; else if(x>=10000) numChecks = 4; else if(x>=1000) numChecks = 3; else if(x>=100) numChecks = 2; else numChecks = 1; String xstr=new String(""""+x); int tmp=0; for(int i=0; i= min && tmp <= max && checked[tmp] == false) matches++; if(tmp<=2000000) checked[tmp]=true; } if(matches == 1) return 0; else if(matches == 2) return 1; else if(matches == 3) return 3; else if(matches == 4) return 6; else if(matches == 5) return 10; else if(matches == 6) return 15; else if(matches == 7) return 21; return 0; } } " B21067,"package qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class ProblemC { public static int solve(int A, int B){ int count = 0; for (int i = A; i <= B; i++){ String number = String.valueOf(i); String s = number + number; for (int j = 1; j < number.length(); j++){ int newnumber = Integer.parseInt(s.substring(j, j + number.length())); if ((newnumber > i) && (newnumber <= B)) count++; } } return count; } public static void main(String[] args){ try{ BufferedReader br = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""outputC-large"")); String line = br.readLine(); int ans = 0; int num = Integer.parseInt(line); for (int i = 0; i < num; i++){ line = br.readLine(); String[] segs = line.split(""\\s+""); ans = solve(Integer.parseInt(segs[0]), Integer.parseInt(segs[1])); bw.write(""Case #"" + (i+1) + "": "" + ans + ""\n""); } br.close(); bw.close(); }catch(Exception e){ e.printStackTrace(); } } } " B22126,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class Recycled { private static boolean contains(List results, int result){ for(int i = 0; i < results.size(); i++){ if(results.get(i) == result){ return true; } } return false; } public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader(""A-small-practice.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""A-small-practice.out""))); StringTokenizer st = new StringTokenizer(f.readLine()); int tests = Integer.parseInt(st.nextToken()); for (int t = 1; t <= tests; t++){ out.printf(""Case #%d:"", t); st = new StringTokenizer(f.readLine()); int count = 0; String a = st.nextToken(); String b = st.nextToken(); for(int i = Integer.parseInt(a); i < Integer.parseInt(b); i++){ String m = Integer.toString(i); for(int j = 1; j < m.length(); j++){ int n = 0; List results = new ArrayList(); if(m.length() - j - 1 > 0){ n = Integer.parseInt(m.substring(m.length() - j) + m.substring(0, m.length() - j)); } else { n = Integer.parseInt(m.substring(m.length() - j) + m.charAt(0)); } if (n > Integer.parseInt(m) && Integer.parseInt(b) >= n && !contains(results, n)){ results.add(n); count++; } } } out.printf("" %d\n"", count); } out.close(); System.exit(0); } } " B20152,"package gcj2012.qual; import java.util.Arrays; import common.AbstractRunner; import common.AbstractRunner.SIZE; public class C extends AbstractRunner { @Override public void handleCase(int caseNumber) throws Exception { int A = scanner.nextInt(); int B = scanner.nextInt(); int pow = 1; int n = 0; for (int p = A; p>=10; p = p/10) { n++; pow *= 10; } int res = 0; int [] rr = new int[n]; for (int x=A; x<=B; x++) { Arrays.fill(rr, 0); int rrlen = 0; int xx = x; cycle: for (int i=0; i x && xx <=B) { for (int j=0; j count = new HashMap(); for (int i = 0; i < t; i++) { int total = 0; int s = in.nextInt(); int e = in.nextInt(); for (int j = s; j <= e; j++) { if (count.containsKey(j)) { total += count.get(j); continue; } String num = j + """"; int cnt = 0; Map map = new HashMap(); for (int k = 1; k < num.length(); k++) { String pre = num.substring(0, k); String post = num.substring(k); String tnum = post + pre; int tn = Integer.parseInt(tnum); if (j < tn && tn <= e && !map.containsKey(tn)) { cnt++; total++; map.put(tn, true); } } count.put(j, cnt); } out.printf(""Case #%d: %d"", (i+1), total); out.println(); } out.flush(); } } " B22030,"import java.util.Scanner; public class QualC { public static void main(String args[]) { Scanner kb = new Scanner(System.in); int ntc = kb.nextInt(); for(int tc=0;tc0) { nn++; temp/=10; } int chk[] = new int[nn]; for(int q=1;q=a && m<=b && m/(int)Math.pow(10,nn-1)>0 && f==0) { out++; } } } System.out.println(""Case #"" + (tc+1) + "": "" + out); } } } " B20015,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class OutputWriter { private BufferedWriter bw = null; private long counter = 1; public OutputWriter(String fileName) { try { bw = new BufferedWriter(new FileWriter(new File(fileName))); } catch (IOException e) { e.printStackTrace(); } } public void writeCaseLine(String output) { try { bw.write(""Case #"" + counter + "": "" + output+""\n""); } catch (IOException e) { e.printStackTrace(); } counter++; } public void flushAndClose() { try { bw.flush(); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B21013,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; public class recycle { public static void main(String[] args) { int lines; String input; StringTokenizer strk; int start=1111; int end=2222; int count; int old[] = new int[10]; try { BufferedReader inputStream = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter writer = new BufferedWriter(new FileWriter(""output.txt"")); lines = Integer.parseInt(inputStream.readLine()); String newj; int newjint; for(int line=0; line< lines; line++){ count=0; input = inputStream.readLine(); strk = new StringTokenizer(input,"" ""); start = Integer.parseInt(strk.nextToken()); end = Integer.parseInt(strk.nextToken()); for(int j=start; j<=end;j++){ newj = j+""""; for(int k=0;k< newj.length() ;k++){ newj = (newj.substring(1) + newj.charAt(0)); newjint = Integer.parseInt(newj); if(newjint > j && newjint <= end && !inside(old,10,newjint)){ //System.out.println(j + "" "" + newjint); old[k] = newjint; count++; } } old = new int[10]; /* for(int k=j; k<=end;k++){ if(isRecycled(j+"""",k+"""")){ //System.out.println(j + "" "" + k); count++; } } */ } if(line!=lines-1) writer.write(""Case #"" + (line+1) + "": "" + count+""\r\n""); else writer.write(""Case #"" + (line+1) + "": "" + count); } writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static boolean isRecycled(String x, String y){ int len = x.length(); if(x.equals(y)){ return false; } for(int i=0; i extends BufferedReader { private final InputConverter converter; public InputReader(File file, InputConverter converter) throws FileNotFoundException { super(new FileReader(file)); this.converter = converter; } public T readInput() { String data; try { do { data = readLine(); if (data == null) { return null; } } while (converter.readLine(data)); } catch (IOException e) { // do nothing } return converter.generateObject(); } } " B21950,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.File; import java.io.PrintWriter; import java.util.Scanner; /** * * @author administrator */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { String input = ""c:\\input.in""; String output = ""c:\\output.txt""; System.out.println(""Hello World""); RecycledNumbers code1 = new RecycledNumbers(); File in = new File(input); File out = new File(output); code1.getFileContents(in, out, ""UTF-8""); } public void getFileContents(File input, File output, String charSet) { String temp = """"; try { Scanner scanner = new Scanner(input, charSet); PrintWriter out = new PrintWriter(output); int count = 0; int test_case = 0; while (scanner.hasNext()) { int A = 0, B = 0; String test = scanner.nextLine(); if (count == 0) { test_case = Integer.parseInt(test); count++; } else { String[] line_data = test.split(""\\s""); A = Integer.parseInt(line_data[0]); B = Integer.parseInt(line_data[1]); int result = 0; if (A > B) { int t = A; A = B; B = t; } for (int i = A; i < B; i++) { int list[] = getCycledNumbers(i); for (int j = 0; j < list.length; j++) { if (list[j] > i && list[j] <= B) { result++; } } } System.out.println(""Case #"" + count + "": "" + result); if (count == test_case) { out.print(""Case #"" + count + "": "" + result); } else { out.println(""Case #"" + count + "": "" + result); } count++; } temp = temp + ""\n"" + test; } out.close(); scanner.close(); } catch (Exception e) { System.out.println(""File read/write error""); return; } } private int[] getCycledNumbers(int number) { int cycled[]; int recycled[]; String num = String.valueOf(number); cycled = new int[num.length()]; for (int i = 0; i < num.length(); i++) { int part1 = number / (int) Math.pow(10, i); int part2 = number % (int) Math.pow(10, i); cycled[i] = part2 * (int) Math.pow(10, num.length() - i) + part1; } for (int i = 0; i < (num.length() - 1); i++) { for (int j = 0; j < (num.length() - (i + 1)); j++) { if (cycled[j] > cycled[j + 1]) { int temp = cycled[j]; cycled[j] = cycled[j + 1]; cycled[j + 1] = temp; } } } int save = cycled[0]; int final_len = num.length(); for (int i = 1; i < (num.length()); i++) { if (cycled[i] == save) { final_len--; } save = cycled[i]; } if (final_len == num.length()) { return cycled; } recycled = new int[final_len]; save = recycled[0] = cycled[0]; int ctr = 0; for (int i = 1; i < (num.length()); i++) { if (cycled[i] != save) { ctr++; recycled[ctr] = cycled[i]; } save = cycled[i]; } return recycled; } } " B22163,"package com.vp.fact; import com.vp.iface.Problem; import com.vp.impl.DancingWithGooglers; import com.vp.impl.RecycledNumbers; import com.vp.impl.SpeakGooglerese; public class SolutionFactory { public static Problem getInstance(int problem) { Problem s = null; switch(problem) { case 1: s= new SpeakGooglerese(); break; case 2: s= new DancingWithGooglers(); break; case 3: s= new RecycledNumbers(); break; } return s; } } " B20042,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; public class Main_c_new { public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int cases=Integer.parseInt(in.readLine()); for(int i=1;i<=cases;i++) { int count = 0; String line = in.readLine(); String parts[] = line.split("" ""); int a = Integer.parseInt(parts[0]); int b = Integer.parseInt(parts[1]); int startlen = 0; int temp1 = a; for(int k=0;k<8;k++){ startlen++; temp1/=10; if(temp1<=0){ break; } } //System.out.println(""there""); for(int j=a;j list = new ArrayList(); for(int k=1;k= (int)(Math.pow(10, k-1))){ int num = (part2*((int)Math.pow(10, length-k)))+part1; if(num>j && num<=b){ int flag = 0; for(int l=0; l pairs = new HashSet(xx.length()); int j ; for(int i=1 ; i < length ; i++ ) { j = Integer.parseInt(xx.substring(i)+xx.substring(0,i)); if(j <= m && j >=n && j !=x ) { if(!pairs.contains(x+""-""+j)) { pairs.add(x +""-""+j); count++; } } } } return count/2; } } " B20092,"import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.FileWriter; class Start{ BufferedInputStream bis=new BufferedInputStream(System.in); PrintWriter out=new PrintWriter(System.out, true); int i,j,k,l,m,n,o,p,q,r,s,t,w,x,y,z,ry,rz,rs; long a,b,c; double d,e,f,g,h; char u,v; String st; int[] in,arr,res; final double pi=3.14159265; final double l2=0.69314718; char chr()throws IOException{ while((ry=bis.read())==10 || ry==13 || ry==32){} return (char)ry; } int num()throws IOException{ rz=0;rs=0; ry=bis.read(); if(ry=='-') rs=-1; else rz+=(ry-'0'); while((ry=bis.read())>='0' && ry<='9') rz=rz*10+(ry-'0'); if(rs==-1) rz=-rz; if(ry==13) bis.read(); return rz; } String str()throws IOException{ StringBuilder sb=new StringBuilder(); while((ry=bis.read())!=10 & ry!=13 && ry!=32) sb.append((char)ry); if(ry==13) bis.read(); return sb.toString(); } String line()throws IOException{ StringBuilder sb=new StringBuilder(); while((ry=bis.read())!=10 && ry!=13) sb.append((char)ry); if(ry==13)bis.read(); return sb.toString(); } int log2(double par){return (int)(Math.log(par)/l2);} long perm(int p1,int p2){ long ret=1; int it; it=p1; while(it>p2) ret*=it--; return ret; } long comb(int p1,int p2){ long ret=1; int it; if(p2p2) ret*=it--; it=p1-p2; while(it>1) ret/=it--; return ret; } public void go()throws IOException{ out =new PrintWriter(new FileWriter(""out.txt""),true); t=num(); w=t; while(--t>=0){ a=0; y=num(); z=num(); if(y<10) y=10; p=(int)Math.log10((double)z); q=(int)Math.pow(10.0, (double)p); for(i=y; i<=z; i++) { k=i; r=p; while(r-->0){ k = (k/10) + ((k%10)*q); if(k>i && k<=z) a++; } } out.println(""Case #""+(w-t)+"": ""+a); } while(bis.available()>0)bis.read(); out.close(); } public static void main(String args[])throws IOException{new Start().go();} } " B21988,"package jpt.codejam; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Codejam2012 { static void solve_Qual_B() throws Exception { Scanner in = new Scanner(System.in); PrintStream out = System.out; int cases = in.nextInt(); for (int nCase = 1; nCase <= cases; ++nCase) { int N = in.nextInt(); int S = in.nextInt(); int p = in.nextInt(); int res = 0; for (int i=0; i=29) max2 = -1; if (max1 >= p) ++res; else if (max2 >= p && S > 0) { ++res; --S; } } out.printf(""Case #%d: %d\n"", nCase, res); } } static void solve_Qual_C() throws Exception { Scanner in = new Scanner(System.in); PrintStream out = System.out; int[] ten = new int[8]; ten[0] = 1; for (int i=1; i ms = new HashSet(); for (int n=A; n<=B; ++n) { int d = 1; for (int aux=10; aux<=n; aux*=10) ++d; ms.clear(); for (int k=1; k=m && n!=m && !ms.contains(m)) ++res; ms.add(m); } } out.printf(""Case #%d: %d\n"", nCase, res/2); } } public static void main(String[] args) throws Exception { //solve_Qual_B(); solve_Qual_C(); //solve_1A_A(); //solve_1A_B(); //solve_1A_C(); } } " B21296,"package recycling; import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; public class Main { public static int lint(int n){ if(n == 0) return 0; return 1 + lint(n / 10); } public static void permut(int[] tab){ int l = tab.length; int temp = tab[l - 1]; for(int i = l - 1; i > 0; i--){ tab[i] = tab[i - 1]; } tab[0] = temp; } public static int toInt(int[] tab){ int res = 0; int m = 1; for(int i = tab.length - 1; i >= 0; i--){ res += m * tab[i]; m *= 10; } return res; } public static int[] toTab(int n){ int[] res = new int[lint(n)]; int temp = n; for(int i = res.length - 1; i >= 0; i--){ res[i] = temp % 10; temp /= 10; } return res; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //String fileName = args[0]; String fileName = ""recycling/C-large.in""; Scanner sC = null; try { sC = new Scanner(new File(fileName)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int T = sC.nextInt(); int A, B, l; HashSet set = new HashSet(); for(int i = 0; i < T; i++){ A = sC.nextInt(); B = sC.nextInt(); l = lint(A); int[] tab; int temp; int count = 0; for(int j = A; j < B; j++){ set.clear(); tab = toTab(j); for(int k = 0; k < l - 1; k++){ permut(tab); temp = toInt(tab); //System.out.println(j + "" "" + temp); if(temp > j && temp <= B){ set.add(temp); //System.out.println(j + "" "" + temp); } } count += set.size(); } System.out.println(""Case #"" + (i + 1) + "": "" + count); } } } " B20225,"package bsevero.codejam.qualification; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; public class IOUtils { public static List readFile(String fileName) { try { File file = new File(fileName); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); List fileLines = new ArrayList(); for(String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) { fileLines.add(line); } return fileLines; } catch(Exception e) { e.printStackTrace(); return Collections.emptyList(); } } public static void writeFile(String fileName, Map casesResult) { try { File file = new File(fileName); if(file.exists()) { file.delete(); } file.createNewFile(); FileWriter fileWriter = new FileWriter(file); PrintWriter printWriter = new PrintWriter(fileWriter); StringBuffer result = new StringBuffer(); for(int i = 1; i <= casesResult.size(); i++) { result.append(""Case #"" + i + "": "" + casesResult.get(i) + ""\n""); } printWriter.print(result.toString().substring(0, result.length() - 1)); printWriter.close(); fileWriter.close(); } catch(Exception e) { e.printStackTrace(); } } } " B20434,"import java.util.Scanner; public class C { String cycle(String s) { return s.substring(1) + s.charAt(0); } void run() { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int t=1; t<=T; t++) { int A = in.nextInt(); int B = in.nextInt(); long res = 0; for (long i=A; i<=B; i++) { long cnt = 1; String str = String.valueOf(i); for (String nowstr = cycle(new String(str)); !nowstr.equals(str); nowstr = cycle(nowstr)) { if (nowstr.charAt(0) != 0) { int nowint = Integer.parseInt(nowstr); if (nowint >= A && nowint <= B) { if (nowint < i) { cnt = 0; break; } else { cnt++; } } } } res += cnt*(cnt-1)/2; } System.out.println(""Case #"" + t + "": "" + res); } } static public void main(String[] args) { C obj = new C(); obj.run(); } } " B20165,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.util.*; import java.io.*; public class RecycledNumbers{ public static void main(String[] args) throws Exception { Scanner input = new Scanner(new File(""C:\\temp\\C-large.in"")); int T = input.nextInt(); for (int t = 1; t <= T; t++) { int A = input.nextInt(); int B = input.nextInt(); double answer = 0; for (int a = A; a <= B; a++) { String aS = a + """"; for (int i = aS.length(); i > 1; i--) { int max = Integer.parseInt(aS.substring(i-1) + aS.substring(0, i-1)); if (max <= B && max >= A && max != a) { answer++; } } } System.out.println(""Case #"" + t + "": "" + (int)(answer/2)); } } public static String reverse(String s, int i) { return (i < s.length()) ? s.charAt(s.length()-1-i) + reverse(s, i+1) : """"; } } " B20416,"import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] argv) throws Exception { // Scanner s = new Scanner(System.in); Scanner s = new Scanner(new FileInputStream(""RecycledNumbers/C-large.in"")); PrintWriter pw = new PrintWriter(new FileOutputStream(""RecycledNumbers/C-large.out"")); // PrintWriter pw = new PrintWriter(System.out); int T = s.nextInt(); for(int i=1;i<=T;i++) { int A = s.nextInt(); int B = s.nextInt(); Set checked = new HashSet(); int numDigit = Integer.toString(A).length(); int pairs = 0; for(int j = A; j<=B; j++) { if(checked.contains(j)) continue; checked.add(j); int[] digits = new int[numDigit]; for(int k = 0;k < numDigit;k++) { digits[k] = (j / powers[k]) - (j / powers[k+1])*10; } // System.out.println(Arrays.toString(digits)); int count =0; for(int k =1; k< numDigit;k++ ){ shift(digits); int newnum = 0; for(int l=0;l= A && newnum <=B) { count++; } } } if(count >= 1) { pairs += (count+1)*(count)/2; } } pw.println(""Case #"" + i +"": "" + pairs); System.out.println(""Case #"" + i +"":"" +pairs); } pw.flush(); pw.close(); } static int[] powers = new int[8]; static { for(int j=0;j lines = new ArrayList(); for(int i=1;i <= size;i++){ split = arr[i].split("" ""); lines.add(""Case #"" + i + "": "" + app.permute(split[0], split[1])); } FileUtils.writeLines(new File(""output.txt""), lines); } public int permute(String a, String b){ if(a.length() <= 1) return 0; int counter = 0; int floor = Integer.parseInt(a); int ceil = Integer.parseInt(b); int buffer = floor; while(buffer < ceil){ String str = String.valueOf(buffer); for(int i=0;i < str.length() - 1;i++){ try { int result = Integer.parseInt(str.substring(str.length() - 1 - i,str.length()) + str.substring(0,str.length() - i - 1)); if( result > buffer && result <= ceil) { counter++; //System.out.println(buffer + "" "" + result + "" "" + counter); } }catch(Throwable t){ System.out.println(buffer); } } buffer++; } return counter; } } " B21320,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication7; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * * @author ucho */ public class JavaApplication7 { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { //BitSet counted = new BitSet(2000000); PrintWriter writer = new PrintWriter(new FileWriter(""output"")); Scanner scanner = new Scanner(new FileReader(""input"")); int tests = scanner.nextInt(); scanner.nextLine(); for(int t=0;t used = new HashSet(); for(int j=1;j=from && intTmp<=to && intTmp> n) { count++; used.add(tmp); } } } String msg = ""Case #""+(t+1)+"": ""+count; System.out.println(msg); writer.println(msg); scanner.nextLine(); } writer.close(); } } " B20993,"import java.io.*; import java.util.*; public class RecycledNumbers { static int A, B; public static void main(String[] args) throws IOException { Kattio io = new Kattio(System.in, new FileOutputStream(""recycle.out"")); int T = io.getInt(); for (int test = 1; test <= T; test++) { A = io.getInt(); B = io.getInt(); int res = 0; for (int i = A; i <= B; i++) { res += recycle(i); } io.println(""Case #""+test+"": ""+res); } io.close(); } static int recycle(int num) { int start = num; if (num/10 == 0) return 0; int m = 1; while (m <= num) { m*= 10; } m/= 10; int d = num/m; int res = 0; while (true) { num %= m; num *= 10; num += d; d = num/m; if (d != 0 && num > start && num <= B) res++; if (num == start) return res; } } static class Kattio extends PrintWriter { public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } private BufferedReader r; private String line; private StringTokenizer st; private String token; private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } } }" B21775,"import java.util.List; import java.util.ArrayList; import java.util.Scanner; public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int t = 0; t < T; t++){ int A = in.nextInt(); int B = in.nextInt(); int n = A; int res = 0; while (n < B) { res = res+recycledPair(n,B); n++; } System.out.println(""Case #""+(t+1)+"": ""+res); } } private static int recycledPair(int n, int B){ int count = 0; int len = Integer.toString(n).length(); //len of digits String nstr = Integer.toString(n); List solSofar = new ArrayList(); for (int i=1; i output ) { FileWriter fstream = null; BufferedWriter out = null; try { // Create file fstream = new FileWriter( fileName ); out = new BufferedWriter( fstream ); int size = output.size(); for ( int i = 1; i <= size; i++ ) { final String outputStr = new StringBuffer( ""Case #"" ).append( i ).append( "": "" ).append( output.get( i ) ).toString(); out.write( outputStr ); if ( i != size ) { out.newLine(); } } } catch ( Exception e ) {//Catch exception if any System.err.println( ""Error: "" + e.getMessage() ); } finally { //Close the output stream try { if ( out != null ) { out.close(); } if ( fstream != null ) { fstream.close(); } } catch ( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } } } " B22072,"import static java.lang.System.*; import java.util.*; import java.io.*; public class jellyfish { public static void one()throws IOException{ TreeMapt=new TreeMap(); Scanner keyb=new Scanner(new File(""A-small-attempt2.in"")); t.put(""a"",""y""); t.put(""o"",""e""); t.put(""z"",""q""); t.put(""q"",""z""); t.put(""i"",""k""); String a=""ejp mysljylc kd kxveddknmc re jsicpdrysirbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcdde kr kd eoya kw aej tysr re ujdr lkgc jv""; String b=""our language is impossible to understandthere are twenty six factorial possibilitiesso it is okay if you want to just give up""; String c[]=a.split(""""); String d[]=b.split(""""); for(int x=1;xt=new TreeSet(); for(int x=c;x0;y--){ String l=""""; l+=g.substring(y,g.length()); l+=g.substring(0,y); int q=Integer.parseInt(l); String s=Integer.toString(q); if(s.length()==g.length()&&x set = new HashSet(); for (int j = 0; j < tab.length; j++) { int K = tab[j]; if (K != -1) for (int step = 10; ; step *= 10) { int tmp = K / step; if (tmp > 0) { int last = K % step; int q = K / step; StringBuilder sb = new StringBuilder(); sb.append(last); sb.append(q); int ans = Integer.parseInt(sb.toString()); String v = Integer.toString(ans); String x = Integer.toString(K); if (ans <= B && ans >= A) { if (tab[j] != tab[ans - A] && v.length() == x.length()) { Pair p = new Pair(); p.setN(Math.min(tab[j], tab[ans - A])); p.setM(Math.max(tab[j], tab[ans - A])); set.add(p); } } } else break; } } out.println(""Case #"" + (i + 1) + "": "" + set.size()); } } class Pair { int n; int m; public int getN() { return n; } public void setN(int n) { this.n = n; } public int getM() { return m; } public void setM(int m) { this.m = m; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (m != other.m) return false; if (n != other.n) return false; return true; } private Main getOuterType() { return Main.this; } } } class Algebra { /**** * Number of co-prime numbers on [1, n]. Number a is Co-prime if gcd (a, n) * == 1 O (sqrt(n)) ****/ public static int phi(int n) { int result = n; for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { while (n % i == 0) { n /= i; } result -= result / i; } } if (n > 1) { result -= result / n; } return result; } /**** * Raise number a to power of n. O (log n) ****/ public static int binpow(int a, int n) { int res = 1; while (n != 0) { if ((n & 1) == 1) res *= a; a *= a; n >>= 1; } return res; } /**** * Finding the greatest common divisor of two numbers. O (log min(a, b)) ****/ public static int gcd(int a, int b) { return (b != 0) ? gcd(b, a % b) : a; } /**** * Finding the lowest common multiple of two numbers. O (log min(a, b)) ****/ public static int lcm(int a, int b) { return a / gcd(a, b) * b; } /**** * Eratosthenes Sieve of numbers - [0..n]. True - simple, False - not * simple. O (n log log n) ****/ public static boolean[] sieveOfEratosthenes(int n) { boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); prime[0] = prime[1] = false; for (int i = 2; i <= n; ++i) { if (prime[i]) { if (i * 1L * i <= n) { for (int j = i * i; j <= n; j += i) { prime[j] = false; } } } } return prime; } } class IO_Type { public static String CONSOLE = ""console""; public static String FILE = ""file""; public static String TEST = ""test""; } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner getScanner() { return this; } FastScanner(String type) { if (type.equals(""console"")) { FastScanner(System.in); } } FastScanner(String type, String inFileName) { if (type.equals(""file"")) { File f = new File(inFileName); try { FastScanner(new FileInputStream(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } else if (type.equals(""test"")) { File f = new File(inFileName); try { FastScanner(new FileInputStream(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } } void FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { System.err.println(e); return """"; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } BigInteger nextBigInt() { return new BigInteger(next()); } void close() { try { br.close(); } catch (IOException e) { } } } class FastWriter { PrintWriter pw; PrintWriter getWriter() { return pw; } FastWriter(String type) { FastWriter(type); } FastWriter(String type, String outFileName) { FastWriter(type, outFileName); } PrintWriter FastWriter(String type) { if (type.equals(""console"")) { pw = new PrintWriter(System.out); } return pw; } PrintWriter FastWriter(String type, String outFileName) { if (type.equals(""console"")) { pw = new PrintWriter(System.out); } else if (type.equals(""test"")) { try { pw = new PrintWriter(new File(outFileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } else if (type.equals(""file"")) { try { pw = new PrintWriter(new File(outFileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } return pw; } } " B21177,"import java.io.InputStreamReader; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { //long currentTime = System.currentTimeMillis(); Scanner inputFile = new Scanner(new InputStreamReader(System.in)); String inputLine = null; String[] numberArray; int testCaseCount = 0; int startNumber = 0; int endNumber = 0; int recycledPairCount = 0; int digitCount = 0; StringBuilder recycleNumber = new StringBuilder(); int newNumber = 0; String newNumberString; HashSet recycleNumbers = new HashSet(); while (inputFile.hasNextLine()) { inputLine = inputFile.nextLine(); numberArray = inputLine.split("" ""); if(numberArray != null && numberArray.length == 1) { /*numberOfTestCases = Integer.parseInt(numberArray[0]);*/ } else if (numberArray != null && numberArray.length == 2) { digitCount = numberArray[0].length(); startNumber = Integer.parseInt(numberArray[0]); endNumber = Integer.parseInt(numberArray[1]); while(startNumber <= endNumber) { newNumberString = """" + startNumber; for(int i = 1; i < digitCount; i++) { recycleNumber = recycleNumber.append(newNumberString.substring(i) + newNumberString.substring(0, i)); newNumber = Integer.parseInt(recycleNumber.toString()); if(newNumber > startNumber && newNumber <= endNumber) { recycleNumbers.add(recycleNumber.toString()); } recycleNumber.delete(0, digitCount); } recycledPairCount = recycledPairCount + recycleNumbers.size(); startNumber++; recycleNumbers.clear(); } System.out.println(""Case #"" + testCaseCount + "": "" + recycledPairCount); } testCaseCount++; recycledPairCount = 0; startNumber = 0; endNumber = 0; digitCount = 0; newNumber = 0; recycleNumber.delete(0, digitCount); } //System.out.println(System.currentTimeMillis() - currentTime); } } " B21994,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam.common; import java.util.ArrayList; import java.util.List; /** * * @author Lance Chen */ public class CodeHelper { private static String FILE_ROOT = ""D:/workspace/googlecodejam/meta""; public static List> loadInputsExcludes(String fileName) { List> result = new ArrayList>(); List lines = FileUtil.readLines(FILE_ROOT + fileName); int index = 0; for (String line : lines) { if (index == 0) { index++; continue; } if (index % 2 == 1) { index++; continue; } List dataList = new ArrayList(); String[] dataArray = line.split(""\\s+""); for (String data : dataArray) { if (data.trim().length() > 0) { dataList.add(data); } } result.add(dataList); index++; } return result; } public static List> loadInputs(String fileName) { List> result = new ArrayList>(); List lines = FileUtil.readLines(FILE_ROOT + fileName); for (String line : lines) { List dataList = new ArrayList(); String[] dataArray = line.split(""\\s+""); for (String data : dataArray) { if (data.trim().length() > 0) { dataList.add(data); } } result.add(dataList); } return result; } public static List loadInputLines(String fileName) { return FileUtil.readLines(FILE_ROOT + fileName); } public static void writeOutputs(String fileName, List lines) { FileUtil.writeLines(FILE_ROOT + fileName, lines); } } " B20229,"import java.io.BufferedReader; import java.io.FileReader; public class C { private static final String head = ""Case #""; public static void main(String[] args) { try{ FileReader f = new FileReader(args[0]); BufferedReader b = new BufferedReader(f); String s; boolean ff = false; int c = 0; while((s = b.readLine())!=null){ if (!ff){ff=true;continue;} else { c++; System.out.println(head + c + "": "" + C.getI(s)); } } } catch (Exception e) { e.printStackTrace(); } finally { } } private static int getI(final String line) { int r = 0; int a,b; String[] sp = line.split("" ""); a = Integer.valueOf(sp[0]); b = Integer.valueOf(sp[1]); for (int x = a; x <= b; x++) { for (int y = 0; y < String.valueOf(x).length(); y++) { if (y != 0) { int re = C.getRR(x, y); if (re <= 11 || re >= x) {continue;} else { if (re >= a && re <= b) { r++; } } } } } return r; } private static Integer getRR(final int v, final int o) { StringBuilder sb = new StringBuilder(); String str = String.valueOf(v); sb.append(str.substring(o)); sb.append(str.substring(0, o)); return Integer.valueOf(sb.toString()); } } " B21415,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package t2; /** * * @author KAMIKATAZ */ //~--- JDK imports ------------------------------------------------------------ import intjungle.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * * @author KAMIKATAZ */ public class IntJungle { /** * @param args the command line arguments */ public static void main(String[] args) { int ans=0; try { FileInputStream fstream = new FileInputStream(""C:\\Users\\KAMIKATAZ\\Desktop\\codejam\\p3\\input.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; BufferedWriter out1 = new BufferedWriter( new FileWriter( ""C:\\Users\\KAMIKATAZ\\Desktop\\codejam\\p3\\out-p3.ou"", true)); String times=br.readLine(); int T = Integer.valueOf(times); ToInteger converter=new ToInteger(); int currentCase=0; ///////////////////////////////////////////////////////////////////////////// while ((strLine = br.readLine()) != null) { ///////////////////////////////////////////////////////////////////////////// ++currentCase; out1.write(""Case #"" + String.valueOf(currentCase) + "": ""); ans=0; Map map = new HashMap(); StringTokenizer st=new StringTokenizer(strLine,"" ""); String a=st.nextToken(); String b=st.nextToken(); a=a.trim(); b=b.trim(); int A=Integer.valueOf(a); int B=Integer.valueOf(b); // //System.out.println(""A read is : ""+ A + ""B read is : ""+ B); ///////////////////// LOGIC STARTS HERE ////////// int nLen=0; //System.out.println(""starting processing set : A : ""+A+"" B : ""+ B); for (int n=A;nn && r1<=B){ if(r1!=n){ //System.out.println(""creating from : ""+nStr+"" : ""+r1); ++ans; // //System.out.println( map.put(String.valueOf(n), String.valueOf(r1))); String opop = ""gigger""; opop=map.put(String.valueOf(n), String.valueOf(r1)); String op=null; try{ if (opop.length()>0)op=opop; if(op.equals(String.valueOf(r1)) ){ //System.out.println(""\n8888888888888\n888888888888888\n\n""); --ans; } }catch(Exception e){ //System.out.println(e); } } } } } } /////////////////////// LOGIC ENDS HERE //////////// //System.out.println(""ans is : ""+ans + "" map "" +map.size() ); out1.write(String.valueOf(ans)); out1.newLine(); } // Close the input stream in.close(); out1.close(); } catch (Exception e) { // Catch exception if any //System.out.println(""Error: "" + e.getMessage() + "" "" + e); } //System.out.println(""*******************************\n\n""); } } //~ Formatted by Jindent --- http://www.jindent.com " B21575,"import java.util.*; import static java.lang.Math.*; import java.io.*; public class C { public static void main(String[] args) throws IOException { /*BufferedReader in = new BufferedReader(new FileReader(""C:/Users/Disha/Desktop/codejam/C-small.in"")); FileWriter fw = new FileWriter(""C:/Users/Disha/Desktop/codejam/C-small.out"");*/ BufferedReader in = new BufferedReader(new FileReader(""C:/Users/Disha/Desktop/codejam/C-large.in"")); FileWriter fw = new FileWriter(""C:/Users/Disha/Desktop/codejam/C-large.out""); int N = new Integer (in.readLine()); int count = 0; for (int cases = 1; cases <= N; cases++) { count = 0; String[] ss = in.readLine().split("" ""); int a = Integer.parseInt(ss[0]); int b = Integer.parseInt(ss[1]); for (int here = a; here <= b; here++) { int len = Integer.toString(here).length(); int len2 = (int) (Math.pow(10, (len-1))); int num2 = 0; int num1 = here; for(int i=0; i<= (len - 1) ; i++){ num2 = (10 * (num1 % len2)) + (num1 / len2); while(Integer.toString(num2).length() < len){ num2 = num2*10; i++; } if (num2 == here){ break; } if ((num2 <= b) && (num2 > here)){ count ++; } num1 = num2; } } fw.write (""Case #"" + cases + "": "" + count + ""\n"" ); } fw.flush(); fw.close(); }} " B20917,"package recycledNumbers; public class InputData { private int Test_Number; public int getTest_Number() { return Test_Number; } public int[] getA() { return A; } public int[] getB() { return B; } private int [] A; private int [] B; public InputData(int Test_Number, int [] A, int [] B){ this.Test_Number = Test_Number; this.A = A; this.B = B; } } " B22261,"package com.eevoskos.codejam; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private static final boolean DEBUG = false; public static void main(String... args) { RecycledNumbers instance = new RecycledNumbers(); try { BufferedReader c = new BufferedReader(new InputStreamReader(System.in)); // Number of test cases int T = Integer.valueOf(c.readLine()); System.out.println(); // Do, for each test case for (int i = 0; i < T; i++) { // Read input string String input = c.readLine(); // Process input String output = instance.solveCase(input); // Print the translated text System.out.println(""Case #"" + (i + 1) + "": "" + output); } } catch (Exception e) { e.printStackTrace(); } } Set allPairs = new HashSet(); Set countPairs = new HashSet(); private String solveCase(String input) { // Init variables countPairs = new HashSet(); String[] split = input.split("" ""); int A = Integer.valueOf(split[0]); int B = Integer.valueOf(split[1]); return getTotalRecycledPairs(A, B); } private String getTotalRecycledPairs(int a, int b) { int numOfPairs = 0; for (int i = a; i <= b; i++) { numOfPairs += countRecycledPairs(i, a, b); } return String.valueOf(numOfPairs); } private int countRecycledPairs(int num, int a, int b) { int count = 0; Set pairs = getAllPairs(num); for (Pair p : pairs) { if (p.isIncludedIn(a, b) && p.isRecycled()) { if (!countPairs.contains(p)) { countPairs.add(p); count++; if (DEBUG) { System.out.println(p + "": counts!""); } } else { if (DEBUG) { System.out.println(p + "": already count""); } } } else { if (DEBUG) { System.out.println(p + "": does not count""); } } } return count; } private Set getAllPairs(int num) { HashSet pairs = new HashSet(); String s = String.valueOf(num); for (int i = 0; i < s.length(); i++) { String s1 = s.substring(0, i); String s2 = s.substring(i); pairs.add(new Pair(Integer.valueOf(s1 + s2), Integer.valueOf(s2 + s1))); } return pairs; } class Pair { int n, m; Pair(int n, int m) { this.n = Math.min(n, m); this.m = Math.max(n, m); } @Override public String toString() { return ""("" + n + "", "" + m + "")""; } boolean isRecycled() { String N = String.valueOf(n); String M = String.valueOf(m); if (N.length() != M.length()) { return false; } for (int i = 0; i < N.length(); i++) { String n1 = N.substring(0, i); String n2 = N.substring(i); if ((n2 + n1).matches(M)) { return true; } } return false; } boolean isIncludedIn(int a, int b) { return a <= n && n < m && m <= b; } @Override public boolean equals(Object another) { if (another == null) return false; if (!(another instanceof Pair)) return false; return (this.m == ((Pair) another).m && this.n == ((Pair) another).n) || (this.m == ((Pair) another).n && this.n == ((Pair) another).m); } @Override public int hashCode() { return String.valueOf(n).hashCode() + String.valueOf(m).hashCode(); } } } " B20292,"package R0; import java.io.*; import java.util.*; public class C { private static final int res[] = new int[8]; private static long check(int A, int B, int m, int c) { long ret = 0; for (int i = A; i < B; i++) { int x = i; for (int k = 0; k < c; k++) { res[k] = x = x / 10 + m * (x % 10); if ( x <= i || x > B ) continue; boolean found = false; for (int j = 0; j < k && !found; j++) found = (res[j] == x); if ( !found ) ret++; } } return ret; } private static long solve() { int A = ni(); int B = ni(); if ( B < 10 ) return 0; if ( A == B ) return 0; int m = 10; for (int i = 1; i < 7; i++) { if ( B < m * 10 ) return check(A, B, m, i); m *= 10; } return 0; } private static final boolean STDIO = false; private static final String TASK = ""C""; private static final String ROUND = ""R0""; private static final String DATA = ""large""; private static Scanner sc; private static PrintStream out; public static void main(String[] args) throws FileNotFoundException, IOException { Locale.setDefault(Locale.ENGLISH); String DATA_IN = String.format(""tst/%s/%s.%s.in"", ROUND, TASK, DATA); String DATA_OUT = String.format(""tst/%s/%s.%s.out"", ROUND, TASK, DATA); String str = null; if ( args.length > 0 ) str = args[0]; else if ( !STDIO ) str = DATA_IN; sc = new Scanner((str != null) ? new FileInputStream(str) : System.in); str = null; if ( args.length > 1 ) str = args[1]; else if ( !STDIO ) str = DATA_OUT; out = (str != null) ? new PrintStream(str) : System.out; int TC = ni(); for (int i = 1; i <= TC; i++) { long ret = solve(); out.println(String.format(""Case #%d: %d"", i, ret)); } } private static int ni() { return sc.nextInt(); } } " B20020,"package problemC; import java.io.IOException; import java.util.HashSet; import java.util.LinkedList; import utils.InputReader; public class SolverC { public static void main(String[] args) throws IOException { LinkedList input = InputReader.read(""C:/Users/Danielle/Desktop/C-small-attempt0.in""); int num = Integer.parseInt(input.removeFirst()); int i = 1; for (String string : input) { if (i > num) { System.err.println(i+"">""+num); break; } HashSet map = new HashSet(); String[] split = string.split("" ""); int min = Integer.parseInt(split[0]); int max = Integer.parseInt(split[1]); for (int cur = min; cur < max; cur++){ String str = """"+cur; for (int k = 1; k < str.length(); k++){ int test = Integer.parseInt(str.substring(k)+str.substring(0, k)); if (test != cur && test >= min && test <= max) { map.add(new IntegerPair(test, cur)); } } } System.out.println(""Case #""+(i++)+"": ""+map.size()); } } private static class IntegerPair{ private final int i1, i2, hash; public IntegerPair(int i1, int i2) { this.i1 = i1; this.i2 = i2; hash = i1+i2; } @Override public int hashCode() { return hash; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj instanceof IntegerPair){ IntegerPair other = (IntegerPair) obj; return (other.i1 == i1 && other.i2 == i2) || (other.i2 == i1 && other.i1 == i2); } return false; } } } " B21966,"package ru.guredd.codejam; import java.io.*; import java.util.ArrayList; import java.util.List; public class Main { protected static List inputData = new ArrayList(); protected static List outputData = new ArrayList(); public static void loadInputData(String fileName) throws IOException { BufferedReader in = null; try { inputData.clear(); String line; in = new BufferedReader(new FileReader(fileName)); if (!in.ready()) throw new IOException(); while ((line = in.readLine()) != null) inputData.add(line); } finally { if(in != null) { in.close(); } } } public static void saveOutputData(String fileName) throws IOException { BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(fileName)); for (String anOutputData : outputData) { out.write(anOutputData); out.newLine(); } } finally { if(out != null) { out.close(); } } } public static void main (String [] argv) throws IOException { loadInputData(argv[0]); Qualification2012C QC = new Qualification2012C(); QC.solve(); saveOutputData(argv[1]); } } " B21543,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlerecyclenum; import java.util.*; import java.io.*; /** * * @author Aaron */ public class GoogleRecycleNum { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here try { File file = new File (""input.txt""); PrintWriter pw = new PrintWriter (new FileWriter (""output.txt"")); if (file.exists ()) { FileReader f_rd = new FileReader (file); LineNumberReader l_rd = new LineNumberReader(f_rd); String input_s; input_s = l_rd.readLine(); int num_case; if (input_s!= null) { num_case = Integer.parseInt (input_s); } else { throw new IllegalArgumentException(""Invalid Input File""); } for (int i = 0; i< num_case;i++) { int num_a; int num_b; input_s = l_rd.readLine(); String[] values = input_s.split("" ""); int result = 0; num_a = Integer.parseInt(values[0]); num_b = Integer.parseInt(values[1]); for ( int j = num_a; j<= num_b; j++) { result += valid_recycle(j, num_a, num_b); } pw.println (""Case #""+ (i+1)+"": "" + result); } pw.close(); l_rd.close (); } } catch (IOException e) { e.printStackTrace(); } } static int getNumTen (int input_num) { int n = 1; while (input_num/n > 0) n *= 10; return n/10; } static int valid_recycle (int input_num, int num_a, int num_b) { int count = 0; //try to recycle the number to check if it is valid if (input_num < 10) return 0; //input_num = 1212; int temp = getNumTen (input_num); ArrayList result = new ArrayList (); breakall: for (int n = 10; n <= input_num; n *= 10) { int upper = input_num/n; int lower = input_num%n; if (lower == 0 || lower < n/10) { temp = temp/10; continue; } int n_num = lower*temp + upper; if (n_num >= num_a && n_num <= num_b && n_num > input_num) { //System.out.println (""Getnerate "" + input_num + "" ==> "" + n_num); int len = result.size(); for (int i = 0; i < len; i++) { if (n_num == result.get(i)) { temp = temp/10; continue breakall; } } result.add (n_num); count++; } temp = temp/10; } return count; } } " B21717,"import java.util.*; import java.io.*; import java.text.CharacterIterator; import java.text.StringCharacterIterator; public class q_b { public static void main(String [] args) { // Open files try { // Open input file FileInputStream iStream = new FileInputStream(""Sample.in""); // Get the DataInputStream object DataInputStream in = new DataInputStream(iStream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); //System.out.println(""Input file opened""); // Create output file FileWriter oStream = new FileWriter(""Sample.out""); BufferedWriter out = new BufferedWriter(oStream); //System.out.println(""Output file opened""); // Read File Line By Line (and read first line) String strLine = br.readLine(); int testN = Integer.parseInt(strLine); int caseN = 1; while ((strLine = br.readLine()) != null) { String[] nums = strLine.split("" ""); int a = Integer.parseInt(nums[0]); int b = Integer.parseInt(nums[1]); int nDigits = nums[0].length(); out.write(""Case #"" + caseN + "": ""); //System.out.println(a+"" ""+b+"" \tCase #"" + caseN + "": ""); if (nDigits < 2) { out.write(""0""); out.newLine(); //System.out.println(""0""); caseN++; continue; } int pow = 1; for(int i=0;i b || j == k) continue; nPairs++; //System.out.print(""*** ""); k = j; } //System.out.println(); } String result = Integer.toString(nPairs); //System.out.println(result); out.write(result); if (caseN != testN) out.newLine(); caseN++; } // Close the streams in.close(); out.close(); }catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } System.out.println(""Complete""); } }" B21658,"package ggpackage; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.util.ArrayList; public class GgClass { private static String[] txt; private static String newtxt=""""; private static String oldtxt=""""; private static String[] oldtxt2; private static int numberC; public static void main(String[] args) throws FileNotFoundException { try{ FileInputStream fstream = new FileInputStream(""C-large.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { oldtxt+=strLine+""\n""; } in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } oldtxt2=oldtxt.split(""\n""); numberC = Integer.parseInt(oldtxt2[0]); ArrayList dub = new ArrayList(); for(int L=1;L<=numberC;L++){ int A = Integer.parseInt(oldtxt2[L].split("" "")[0]); int B = Integer.parseInt(oldtxt2[L].split("" "")[1]); int count = 0; //loop from A to mid point if(B<10){}else{ for(int i=A;i<=B;i++){ txt = String.valueOf(i).split(""""); //check for possible combination of an integer for(int k=2;ktxt.length-1){ newtxt+=txt[j+k-(txt.length-1)]; }else{ newtxt+=txt[j+k]; } } while(newtxt.startsWith(""0"")==true){ newtxt=newtxt.substring(1); //System.out.print(newtxt+""\n""); //count if an integer is recyclable } if(newtxt.isEmpty()){}else{ if(Integer.parseInt(newtxt)>i){ //System.out.print(newtxt+""\n""); if(Integer.parseInt(newtxt)<=B){ count++; dub.add(newtxt); } } newtxt=""""; } if(dub.size()==0){}else{ for(int z=0;z<=dub.size()-1;z++){ for(int y=z+1;y<=dub.size()-1;y++){ if(dub.get(z).toString().contentEquals((dub.get(y).toString()))){ count=count-1; } } } } } dub.clear(); } } System.out.print(""Case #""+L+"": ""+count+""\n""); } } } " B22107,"import java.io.*; import java.util.*; public class QualificationRoundC { public static int power(int i, int p){ int k = 1; for(int j = 0; j < p; j++) k *= i; return k; } public static int recycle(int n, int k){ int d = power(10, k); int e = power(10, numDigits(n) - k); int right = n % d; int left = n / d; return right * e + left; } public static int numDigits(int n){ int i = 1, k = 0; while(n / i > 0){ i *= 10; k++; } return k; } public static Set getRecycledNumbers(int n){ int digits = numDigits(n); Set recycled = new HashSet(digits - 1); for(int i = 0; i < digits; i++){ int m = recycle(n, i); recycled.add(m); } return recycled; } public static void main(String[] args) throws IOException { String inFile = args[0]; String outFile = args[0].replaceAll(""\\.in$"", "".out""); FileInputStream fileInputStream = new FileInputStream(inFile); Scanner scanner = new Scanner(fileInputStream); FileWriter fileWriter = new FileWriter(outFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); int cases = scanner.nextInt(); for(int i = 1; i <= cases; i++){ int A = scanner.nextInt(), B = scanner.nextInt(); int count = 0; for(int n = A; n < B; n++){ Set recycled = getRecycledNumbers(n); Iterator it = recycled.iterator(); while(it.hasNext()){ int m = it.next(); if(n < m && m <= B) count++; } } String answer = String.format(""Case #%d: %d\n"", i, count); System.out.print(answer); bufferedWriter.write(answer); } bufferedWriter.close(); fileWriter.close(); scanner.close(); fileInputStream.close(); } } " B20719,"package com.clausewitz.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public abstract class Solver { protected BufferedReader fileIn = null; protected String outFilename = ""output.out""; protected int numOfTestCase = -1; protected String answer[] = null; public void openFile(String filename) { try { fileIn = new BufferedReader(new FileReader(filename)); if(filename.substring(filename.length()-3,filename.length()).equals("".in"")) outFilename = filename.substring(0, filename.length()-3) + "".out""; } catch (IOException e) { System.out.println(""Cannot open file: "" + e.getMessage()); } } public void closeFile() { try { if(fileIn!=null) fileIn.close(); } catch (IOException e) { System.out.println(""Cannot close file: "" + e.getMessage()); } } public void setOutFilename(String filename) { this.outFilename = filename; } public int readNumber(int defaultValue) { int result = defaultValue; try { result = Integer.parseInt(fileIn.readLine()); } catch (Exception e) { System.out.println(""Cannot read a number from file: "" + e.getMessage()); } return result; } public void prepareAnswers() { answer = new String[numOfTestCase]; } public abstract void readProblem() throws IOException; public abstract void algorithm(int idx); public void printAnswer() { try { BufferedWriter fileOut = new BufferedWriter(new FileWriter(this.outFilename)); for(int i=0;i 0 ) { fileName = args[0]; } RecycledNumbers rn = new RecycledNumbers ( ); try { rn.readInputFile ( fileName ); } catch ( IOException e ) { System.err.println ( ""Problem reading the input file"" ); e.printStackTrace(); } //rn.getRotatedNumbers ( ""123456"" ); rn.processTestData ( ); } private void processTestData ( ) { for ( int i = 0; i < noOfTestCases; i++ ) { Set < String > unique = new HashSet < String >(); int from = testData[i][0]; int to = testData[i][1]; for ( int j = from; j <= to; j++ ) { int[] rotatedNumbers = getRotatedNumbers ( """" + j ); checkIfValid ( rotatedNumbers, j, from, to, unique ); } System.out.println ( ""Case #"" + (i+1) + "": "" + unique.size ( )); } } private void checkIfValid ( int[] in, int current, int from, int to, Set < String > unique ) { for ( int i = 0; i < in.length; i++ ) { int number = in[i]; if ( number < from ) { } else if ( number > to ) { } else if ( number <= current ) { } else { //System.out.println ( number ); unique.add ( """"+ number + current ); } } } private int[] getRotatedNumbers ( String input ) { int length = input.length ( ); int[] output = new int[length-1]; char[] outstring = input.toCharArray(); for (int i = 0; i < length-1; i++) { //Length-1 or length? char ch = outstring[length - 1]; for (int j = length - 1; j > 0; j--) { outstring[j] = outstring[j - 1]; } outstring[0] = ch; output[i] = Integer.parseInt ( new String(outstring ) ); } return output; } private void readInputFile ( String fileName ) throws IOException { BufferedReader br = new BufferedReader ( new FileReader ( fileName ) ); noOfTestCases = Integer.parseInt ( br.readLine ( ) ); testData = new int[noOfTestCases][2]; for ( int i = 0; i < noOfTestCases; i++ ) { String[] data = br.readLine ( ).split ( "" "" ); testData[i][0] = Integer.parseInt ( data[0] ); testData[i][1] = Integer.parseInt ( data[1] ); } } } " B21225,"import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class QrC { private CodeJamTextInputReader input = null; private CodeJamTextOutputWriter output = null; public static void main(String args[]) { // CodeJamUtils.initLineEndings(); try { QrC qrA = new QrC(); qrA.run(new File(args[0]), new File(args[1])); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidInputException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public QrC() { } public void run(File outputFile, File inputFile) throws InvalidInputException, IOException { try { input = new CodeJamTextInputReader(inputFile); output = new CodeJamTextOutputWriter(outputFile); actualRun(); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } } } private void actualRun() throws IOException { while (input.hasNextTestCase()) { String in = input.readNextLine(); final int textCaseNum = input.getLastReadTestCaseNumber(); output.outputTestCase(textCaseNum, singleTestCase(in)); } } private String singleTestCase(String in) { CodeJamLineParser parser = new CodeJamLineParser(in); final int lowerBound = parser.readNextInt(); final int upperBound = parser.readNextInt(); int numOfRecycled = 0; Set alreadyHit = new HashSet(); RecycledPair comparePair = new RecycledPair(); for (int i = lowerBound; i <= upperBound; ++i) { int leftMask = getHighestMask(i); int rightMask = 10; while (leftMask >= 10) { int recycled = buildRecycled(i, leftMask, rightMask); comparePair.set(i, recycled); if (recycled != i && recycled >= lowerBound && recycled <= upperBound && !alreadyHit.contains(comparePair)) { alreadyHit.add(new RecycledPair(comparePair)); ++numOfRecycled; } rightMask = rightMask * 10; leftMask = leftMask / 10; } } return Integer.toString(numOfRecycled); } int buildRecycled(int in, int leftMask, int rightMask) { int rightPart = in % rightMask; int leftPart = in / rightMask; return (rightPart * leftMask) + leftPart; } int getHighestMask(int in) { int mask = 10; while (in / mask != 0) { mask = mask * 10; } return mask / 10; } int getNumOfDigits(int in) { int numOfDigits = 1; int mask = 10; while (in / mask != 0) { ++numOfDigits; mask = mask * 10; } return numOfDigits; } } " B21031,"import java.util.*; public class C { public static void main(String args[]){ Scanner scanner = new Scanner(System.in); int testCount = scanner.nextInt(); HashSet hashResult = new HashSet(); for (int test = 1; test <= testCount; test++){ int min = scanner.nextInt(); int max = scanner.nextInt(); int total=0; for (Integer i=min; i<=max;i++){ char[]numChar= i.toString().toCharArray(); for (int k=0; k<=numChar.length-1;k++){ // Move ponteiro char charTemp=numChar[numChar.length-1]; for (int j=numChar.length-2;j>=0;j--){ numChar[j+1]=numChar[j]; } numChar[0]=charTemp; Integer result = Integer.parseInt(new String(numChar)); if(i 0) { multiplier *= 10; temp = temp / 10; } int ans = 0; boolean used[] = new boolean[b + 10]; for (int i = a; i <= b; i++) { int next = recycle(i, multiplier); while (next != i) { if (next >= a && next <= b) { ans++; } next = recycle(next, multiplier); } } writer.println(ans / 2); } public static void main(String[] args) { new Thread(null, new C(), """", 64 * 1024 * 1024).start(); } StringTokenizer tokenizer; BufferedReader reader; PrintWriter writer; public void run() { try { try { Locale.setDefault(Locale.US); } catch (Exception ignored) { } reader = new BufferedReader(new FileReader(""C.in"")); writer = new PrintWriter(new FileWriter(""C.out"")); tokenizer = null; int tests = nextInt(); for (int i = 0; i < tests; i++) { writer.printf(""Case #%d: "", i + 1); solve(); writer.flush(); } reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }" B20952,"import java.io.*; import java.util.*; import java.text.*; public class ProblemC { public static void main(String[] args) { try { new ProblemC().solve(); } catch (Exception e) { e.printStackTrace(); } } public void solve() throws Exception { System.setIn(new FileInputStream(""D:\\input.in"")); Scanner scan = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int T = scan.nextInt(); for (int i=0;i st = new HashSet(); for (int i=1;i s.charAt(i)) continue; String ssub = s.substring(i) + s.substring(0, i); int pn = Integer.parseInt(ssub); if (pn > n && pn <= B) { t++; if (!st.add(s+ssub)) { t--; } //System.out.println(n + "", "" + ssub + "" ++""); } else { //System.out.println(n + "", "" + ssub); } } return t; } } " B22157,"package com.vp.impl; import java.util.Arrays; import com.vp.common.CommonUtility; import com.vp.iface.Problem; public class DancingWithGooglers implements Problem { private static int currentNoOfSurprises; private static int eligibleGooglers; private static final int noOfJudges = 3; private static int noOfGooglers; private static int noOfSurprises; private static int bestScore; @Override public String solve(String[] dataset) { String strReturnValue =""""; String strDanceData = dataset[0]; String strDanceDataArr[] = strDanceData.split("" ""); int iDanceDataArr[] = CommonUtility.convertStringArraytoIntArray(strDanceDataArr); noOfGooglers = iDanceDataArr[0]; noOfSurprises = iDanceDataArr[1]; bestScore = iDanceDataArr[2]; eligibleGooglers = 0; currentNoOfSurprises =0; int totalScore; int googlers[] = new int [noOfGooglers]; int index =0 ; int scoreSplit[] = new int[noOfJudges]; CommonUtility.print(iDanceDataArr); for (int i = 3; i < iDanceDataArr.length; i++ ) { googlers[index] = iDanceDataArr[i]; index++; } Arrays.sort(googlers); for (int i = 0; i < googlers.length; i++ ) { totalScore = googlers[i]; if(isEligible(totalScore)) { scoreSplit= split(totalScore); if(isEligibleAfterConversion(scoreSplit)) { eligibleGooglers++; CommonUtility.printWithoutExtrLine(scoreSplit); System.out.println(""Eligible Googler #"" + eligibleGooglers); } } } System.out.println(""Output: "" + strReturnValue + eligibleGooglers); return strReturnValue + eligibleGooglers; } private boolean isEligibleAfterConversion(int[] scoreSplit) { boolean bReturn = false; if(currentNoOfSurprises == noOfSurprises) { return true; } int surpriseScore[]= convertToSurpriseScore(scoreSplit); for(int i=0;i= bestScore) { bReturn = true; break; } } return bReturn; } private int[] convertToSurpriseScore(int[] scoreSplit) { int diff = scoreSplit[1] - scoreSplit[0]; int diff1 = scoreSplit[2] - scoreSplit[1]; int diff2 = scoreSplit[2] - scoreSplit[0]; String strDiff = diff+""""+diff1+""""+diff2; //System.out.println(""strDiff: "" + strDiff); if (strDiff.equals(""000"")) { if ((scoreSplit[2] - 1) >= 0) { scoreSplit[0] = scoreSplit[0] + 1; scoreSplit[2] = scoreSplit[2] - 1; } } else if(strDiff.equals(""011"")) { if((scoreSplit[0] - 1) >= 0) { scoreSplit[0] = scoreSplit[0] - 1; scoreSplit[1] = scoreSplit[1] + 1; } } else if(strDiff.equals(""101"")) { if((scoreSplit[1] - 1) >= 0) { scoreSplit[1] = scoreSplit[1] - 1; scoreSplit[2] = scoreSplit[2] + 1; } } Arrays.sort(scoreSplit); if(isSurpriseScore(scoreSplit)) { currentNoOfSurprises ++; CommonUtility.printWithoutExtrLine(scoreSplit); System.out.println("" Surprise#: ""+currentNoOfSurprises); } return scoreSplit; } private boolean isSurpriseScore(int[] scoreSplit) { int diff = scoreSplit[1] - scoreSplit[0]; int diff1 = scoreSplit[2] - scoreSplit[1]; int diff2 = scoreSplit[2] - scoreSplit[0]; // System.out.println(""isSurprise diff"" + diff + "" "" + diff1 + "" ""+ diff2); return ((diff + diff1 + diff2) == 4); } private static int [] split(int totalScore) { int avgScore = totalScore / 3; int remScoreAvg = (totalScore - avgScore) / 2; int remScore = remScoreAvg; int remScore1 = remScoreAvg; int iReturn[] = new int[3]; int mod = (totalScore - avgScore) % 2; if(mod == 1) { remScore++; } iReturn[0] = avgScore; iReturn[1] = remScore; iReturn[2] = remScore1; Arrays.sort(iReturn); CommonUtility.printWithoutExtrLine(iReturn); //System.out.println("" : Total Score :"" + totalScore); return iReturn; } /*private boolean isSurprisingScore(int totalScore) { boolean bReturn = false; int bs1 = bestScore; int bs2 = bestScore -1; int bs3 = bestScore -2; if(bs1 >=0 && bs2 >=0 && bs3>=0 ) { bReturn = (bestScore + ( bestScore -1 ) + (bestScore -2)) == totalScore; if(bReturn) System.out.println(""Eligible Googler : ["" + bestScore +"", ""+ ( bestScore -1 )+"", "" + (bestScore -2) +""] = "" + totalScore + "" (Surprise#"" + (currentNoOfSurprises + 1)+"")"" ); if(!bReturn) { bReturn = (bestScore + (( bestScore -2 ) * 2)) == totalScore; if (bReturn) System.out.println(""Eligible Googler : ["" + bestScore +"", ""+ ( bestScore -2 )+"", "" + (bestScore -2) +""] = "" + totalScore + "" (Surprise#"" + (currentNoOfSurprises + 1)+"")"" ); } } int bs4 = bestScore; int bs5 = bestScore +1; int bs6 = bestScore +2; if(bs1 <=10 && bs2 <=10 && bs3<=10 && !bReturn) { bReturn = (bestScore + ( bestScore +1 ) + (bestScore +2)) == totalScore; if(bReturn) System.out.println(""Eligible Googler : ["" + bestScore +"", ""+ ( bestScore +1 )+"", "" + (bestScore +2) +""] = "" + totalScore + "" (Surprise#"" + (currentNoOfSurprises + 1)+"")"" ); if(!bReturn) { bReturn = (bestScore + (( bestScore +2 ) * 2)) == totalScore; if (bReturn) System.out.println(""Eligible Googler : ["" + bestScore +"", ""+ ( bestScore +2 )+"", "" + (bestScore +2) +""] = "" + totalScore + "" (Surprise#"" + (currentNoOfSurprises + 1)+"")"" ); } } if (bReturn) { currentNoOfSurprises++; } return bReturn; } */ private boolean isEligible(int totalScore) { boolean bReturn = false; if(noOfSurprises == 0 || currentNoOfSurprises >= noOfSurprises) { // System.out.println(""isEligibleIn: "" + (bestScore + ((bestScore -1) * 2)) + "" : "" + totalScore); bReturn = (bestScore + ((bestScore -1) * 2)) <= totalScore; } else { // System.out.println(""isEligibleOut: "" + (bestScore + ((bestScore -2) * 2)) + "" : "" + totalScore); bReturn = (bestScore + ((bestScore -2) * 2)) <= totalScore; } //System.out.println(""isEligible: "" + bReturn); return bReturn; } } " B22172,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeSet; public class Recycle { static PrintStream O = System.out; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { long initTime = System.currentTimeMillis(); PrintWriter out = new PrintWriter(new FileWriter(""C.out"")); BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); int cases = Integer.parseInt(in.readLine()); for (int kase = 0; kase < cases; kase++){ String input = in.readLine(); int A = Integer.parseInt(input.split("" "")[0]); int B = Integer.parseInt(input.split("" "")[1]); out.println(""Case #"" + (kase + 1) + "": "" + count(A, B)); } //O.println(System.currentTimeMillis() - initTime); out.close(); } catch (Exception e) { e.printStackTrace(); } } static int count (int A, int B){ Set set = new TreeSet(); int count = 0; char cA = Integer.toString(A).charAt(0); char cB = Integer.toString(B).charAt(0); for (long i = A; i < B; i++){ String s = Integer.toString((int)i); long newN; for (int j = 1; j < s.length(); j++){ if (s.charAt(j) >= cA && s.charAt(j) <= cB){ String tmp = s.substring(j) + s.substring(0,j); newN = Integer.parseInt(tmp); if (newN != i && newN >= A && newN <= B){ set.add(i << 21 | newN); set.add(newN << 21 | i); } } } } return set.size() / 2; } } " B22065,"import java.io.* ; import java.text.DecimalFormat; import java.util.*; import static java.lang.Math.* ; import static java.util.Arrays.* ; public class C { public static void main(String[] args) throws FileNotFoundException { in = new Scanner(new InputStreamReader(new FileInputStream(""c_in.txt""))); out = new PrintStream(new BufferedOutputStream(new FileOutputStream(""c_out.txt""))); int n = in.nextInt() ; in.nextLine() ; int t = 1 ; while( n-- > 0) new C().solveProblem(t++); out.close(); } static Scanner in = new Scanner(new InputStreamReader(System.in)); static PrintStream out = new PrintStream(new BufferedOutputStream(System.out)); //static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public void solveProblem(int nr) { out.print(""Case #"" + nr + "": "" ) ; int A = in.nextInt() ; int B = in.nextInt() ; int l = ( A + """").length() ; int som = 0 ; for( int i = A ; i <= B ; i++ ){ HashSet set = new HashSet() ; for( int j = 1 ; j < l ; j++ ){ int n = i ; n /= (int) pow(10,j) ; n += (i % pow(10,j) )*(int) pow(10,l-j) ; //System.out.println(n + "" "" + i); if( n > i && n <= B ) set.add(n) ; } som += set.size(); } out.println(som) ; System.err.println(""Case #"" + nr + "" solved"") ; } }" B21106,"package google.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.Set; import java.util.TreeSet; public class Problem3 { public Problem3() { super(); } public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader(""D:\\codejam\\2012\\C.in"")); BufferedWriter writer = new BufferedWriter(new FileWriter(""D:\\codejam\\2012\\C.out"")); //... Loop as long as there are input lines. String line = null; reader.readLine(); int i=1; while ((line=reader.readLine()) != null) { writer.write(""Case #""+i+"": ""+convert(line)); writer.newLine(); // Write system dependent end of line. i++; } //... Close reader and writer. reader.close(); // Close to unlock. writer.close(); // Close to unlock and flush to disk. } catch(Exception ex) { ex.printStackTrace(); } } //public static void main(String[] args) { // System.out.println(convert(""123 995"")); // } private static boolean isInRange(String num,int A, int B) { int iNum = Integer.parseInt(num); if(iNum>=A && iNum<=B) return true; return false; } private static Set cycle(String num, int A,int B) { Set cycleSet = new TreeSet(); if(isInRange(num,A,B)) cycleSet.add(num); for(int i=1;i set) { int size = set.size(); return (size*(size-1))/2; } private static int convert(String input) { String[] inputArr = input.split("" ""); try { int A = Integer.parseInt(inputArr[0]); int B = Integer.parseInt(inputArr[1]); Set processedNumber = new TreeSet(); Set childSet = null; int size=0; int totalCount = 0; for(Integer num = A;num<=B;num++) { if(processedNumber.contains(num.toString())) continue; childSet = cycle(num.toString(), A, B); size = size(childSet); if(size>0) { totalCount+=size; processedNumber.addAll(childSet); } } return totalCount; } catch(Exception ex) { ex.printStackTrace(); } return 0; } } " B21400,"import java.util.*; import java.io.*; public class Main { final static String FNAME = ""A-small-practice""; public BufferedReader in; public PrintWriter out; void open() throws IOException { in = new BufferedReader( new FileReader( new File( FNAME + "".in"" ) ) ); out = new PrintWriter( new File( FNAME + "".out"" ) ); } void close() throws IOException { out.close(); } void run() throws IOException { String str = in.readLine(); String[] input; int min,max,firstdigit, count; String newNum, converted; int num = new Integer( str ); int[] array; for(int i = 0; inew Integer(newNum) && new Integer(converted)<=max && notsame) { count++; } } } out.println( ""Case #"" + (i+1) + "": ""+ count ); } } public static void main( String[] args ) throws IOException { new Thread() { public void run() { try { Main solution = new Main(); solution.open(); solution.run(); solution.close(); } catch ( Exception e ) { throw new RuntimeException( e ); } } }.start(); } }" B21677," import java.io.*; import java.util.HashSet; public class code33 { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileWriter fos = new FileWriter(""outfile"",false); BufferedWriter bw = new BufferedWriter(fos); int T=Integer.parseInt(br.readLine()), A , B , j ,i ; String str[]; for(j=1;j<=T; j++) { str=br.readLine().split("" ""); A= Integer.parseInt(str[0]); B= Integer.parseInt(str[1]); bw.write(""Case #""+j+"": ""+swapncal(A, B)+""\n""); //System.out.print(""Case #""+j+"": ""+swapncal(A, B)+""\n""); } bw.close(); } public static int swapncal(int A,int B) { int n=0, p ,num; String xs; HashSet set = new HashSet(); for (int x= A; x <=(A+B); x++) { set.clear(); xs=x+""""; for(p=1;p< xs.length();p++) { num=Integer.parseInt(xs.substring(p)+xs.substring(0, p)); if( num > x && !set.contains(num) && num >=A && num <=B) { set.add(num); n++; } } } return n; } }" B21215,"import java.util.*; public class C { public static void main(String[] args){ Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int zz = 1; zz <= T;zz++){ int A = in.nextInt(); int B = in.nextInt(); int result = 0; for(int i=A;i<=B;i++) { ArrayList pairs = new ArrayList(); String ns = i+""""; for (int j=ns.length()-1;j>0;j--) { String k = ns.substring(j); String newval = k + ns.substring(0,j); int m = Integer.parseInt(newval); if (m>i && A=m) { if (pairs.indexOf(m)==-1) pairs.add(m); } } result += pairs.size(); } System.out.format(""Case #%d: %d\n"", zz, result); } } } " B21616,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * * @author harit */ public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); int t1 = 1; int a, b; int count = 0; while (t1 <= t) { String s[] = br.readLine().split("" ""); a = Integer.parseInt(s[0]); b = Integer.parseInt(s[1]); count=0; for (int i = a; i < b; i++) { List lstR = getRnum(i); for (Integer j : lstR) { if (j >= i && j <= b) { count++; } } } System.out.println(""Case #""+ t1 + "": "" + count); t1++; } } public static List getRnum(int a) { List lstRnum = new ArrayList(); String s = """" + a; int l = s.length(); int modf = 10; int multf = (int) Math.pow(10, l - 1); int i = 1; boolean flag=true; while (i < l) { // System.out.println(""modf ""+modf); int x = ((a % modf) * multf) + a / modf; if (("""" + x).length() == l && x!=a) { for(int xx:lstRnum){ if(xx==x) flag=false;} if(flag){ lstRnum.add(x); } } modf = modf * 10; multf = multf / 10; i++; } return lstRnum; } } " B20770,"import java.util.TreeSet; public class SolveThread implements Runnable{ private TreeSet nbs; int pairs = 0, casenb; private ThreadDispatcher td; private int A, B; public SolveThread(int A, int B, int casenb, ThreadDispatcher td){ nbs = new TreeSet(); this.A = A; this.B = B; for(int i = A; i <= B; i++){ nbs.add(i); } this.casenb = casenb; this.td = td; } public void solve(){ while(!nbs.isEmpty()){ int n = nbs.first(); findAndRemoveRecycledOf(n); } } private void findAndRemoveRecycledOf(int n) { nbs.remove((Integer)n); String nstr = """" + n; if(nstr.length() == 1) return; int nbInPair = 1; for(int i = 0; i < nstr.length()-1;i++){ String sstr = shiftRight(nstr,i); sstr.replaceFirst(""^0+(?!$)"", """"); int sn = Integer.parseInt(sstr); if(nbs.contains(sn)){ nbInPair++; nbs.remove((Integer)sn); } } pairs += nbInPair * (nbInPair - 1) / 2; } private String shiftRight(String nstr, int i) { return nstr.substring(nstr.length() - 1 - i, nstr.length()) + nstr.substring(0, nstr.length() - 1 - i); } @Override public void run() { solve(); td.finish(this); } } " B20126,"import java.io.*; public class C { public static void main(String[] argv) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine()); for(int i=0 ; i=j+1 && (j+1<=B)) { amount++; } } } System.out.println(""Case #"" + (i+1) + "": "" + amount); } } } " B21808,"import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; public class SpeakingTongues extends JamProblem { Map map = new HashMap<>(); public static void main(String[] args) throws IOException { SpeakingTongues p = new SpeakingTongues(); p.prepare(); p.go(); } void prepare() { map.put('y', 'a'); map.put('e', 'o'); map.put('q', 'z'); String[] from = new String[3]; String[] to = new String[3]; to[0] = ""ejp mysljylc kd kxveddknmc re jsicpdrysi""; to[1] = ""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd""; to[2] = ""de kr kd eoya kw aej tysr re ujdr lkgc jv""; from[0] = ""our language is impossible to understand""; from[1] = ""there are twenty six factorial possibilities""; from[2] = ""so it is okay if you want to just give up""; for (int i = 0; i < to.length; i++) { char[] t = to[i].toCharArray(); char[] f = from[i].toCharArray(); for (int j = 0; j < f.length; j++) { char fc = f[j]; char tc = t[j]; map.put(tc, fc); } } for (char c = 'a'; c <= 'z'; c++) { if (map.containsKey(c)) { continue; } for (char c2 = 'a'; c2 <= 'z'; c2++) { if (map.containsValue(c2)) { continue; } map.put(c,c2); } } } @Override String solveCase(JamCase jamCase) { StringBuilder b = new StringBuilder(); STCase ca = (STCase) jamCase; char[] chars = ca.str.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; b.append(map.get(c)); } return b.toString(); } @Override JamCase parseCase(List file, int line) { STCase ca = new STCase(); ca.lineCount = 1; ca.str = file.get(line); return ca; } } class STCase extends JamCase { String str; }" B20491,"public class recycled { public static void main(String args[]) { java.util.Scanner s = new java.util.Scanner(System.in); int T = s.nextInt(); for (int n = 1; n <= T; n++) System.out.println(""Case #"" + n + "": "" + f(s.nextInt(), s.nextInt())); } public static int f(int a, int b) { String A = """" + a; String B = """" + b; java.util.HashSet s = new java.util.HashSet(); for (int i = a; i <= b; i++) { String I = """" + i; for (int j = 1; j < I.length(); j++) { String x = I.substring(j) + I.substring(0, j); if (A.compareTo(x) <= 0 && B.compareTo(x) >= 0 && !I.equals(x)) if (x.compareTo(I) > 0) s.add(x+"":""+I); else s.add(I+"":""+x); } } return s.size(); } }" B20766,"package bchang; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; /** * Created with IntelliJ IDEA. * User: bchang * Date: 4/14/12 * Time: 9:48 PM * To change this template use File | Settings | File Templates. */ public class ProblemC { private static void cycle(char[] charArray) { char first = charArray[0]; for (int i = 1; i < charArray.length; i++) { charArray[i - 1] = charArray[i]; } charArray[charArray.length - 1] = first; } private static Set toSet(int a, int b) { Set set = new TreeSet(); for (int x = a; x <= b; x++) { set.add(Integer.toString(x)); } return set; } private static int combos(int n) { if (n == 1) { return 1; } return n + combos(n-1); } private static int process(BufferedReader reader) throws IOException { String[] pair = reader.readLine().split("" ""); int a = Integer.parseInt(pair[0]); int b = Integer.parseInt(pair[1]); Set set = toSet(a, b); int counter = 0; while (set.size() > 0) { Iterator iterator = set.iterator(); String n = iterator.next(); iterator.remove(); char[] working = n.toCharArray(); Set matchingPairs = new HashSet(); for (int idx = 1; idx < working.length; idx++) { cycle(working); String mStr = new String(working); int mInt = Integer.parseInt(mStr); if (a <= mInt && mInt <= b && !n.equals(mStr) && mStr.charAt(0) != '0') { set.remove(mStr); matchingPairs.add(mInt); } } if (matchingPairs.size() > 0) { int numPairs = combos(matchingPairs.size()); counter += numPairs; } } return counter; } public static void main(String[] args) throws Exception { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(reader.readLine()); for (int i = 0; i < t; i++) { int result = process(reader); System.out.println(""Case #"" + (i + 1) + "": "" + result); } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } } } " B21739," import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; import java.util.Set; /** * * @author leonardo */ public class RecyclingNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long inputSize = Integer.parseInt(scanner.nextLine()); for (long i = 1; i <= inputSize; i++) { String[] input = scanner.nextLine().split("" "") ; /* No solution exists. */ if (input.length == 1) continue ; long a = Long.parseLong(input[0]) ; long b = Long.parseLong(input[1]) ; System.out.println(""Case #"" + i + "": "" + countRecyclablePairs(a, b)) ; } } private static long countRecyclablePairs(long a, long b) { if (a == b) return 0 ; long count = 0 ; for(long n = a; n <= b; n++) { LinkedList digits = toLinkedList(n) ; Set counted = new HashSet() ; for(long i = 0; i < digits.size(); i++) { digits.addFirst(digits.removeLast()) ; long m = toNumber(digits) ; if (! counted.contains(m) && n < m && m <= b) { counted.add(m) ; count++ ; } } } return count ; } private static LinkedList toLinkedList(long number) { LinkedList digits = new LinkedList() ; long remainer = 0 ; while(number >= 10) { remainer = number % 10 ; digits.addFirst(remainer); number = number / 10 ; } digits.addFirst(number) ; return digits ; } private static long toNumber(LinkedList digits) { long number = 0 ; long expoent = digits.size() - 1 ; for(long d : digits) { number += d * Math.pow(10, expoent) ; expoent-- ; } return number ; } } " B20618,"package codejam.qualification; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class Recycled { /** * @param args */ public static void main(String[] args) throws IOException { String file = ""input3big""; Scanner in = new Scanner(new File(file)); int tot = Integer.parseInt(in.nextLine()); // System.out.println(tot); for(int i=0;i rec = new ArrayList(); int count = 0; for(int i=s.length()-1; i>0; i--) { String r = s.substring(i) + s.substring(0, i); // System.out.println(r); int s_int = Integer.parseInt(s); int r_int = Integer.parseInt(r); if(r.charAt(0) != 0 && s_int < r_int && r_int <= B && !isIn(r,rec)) { // System.out.println(""ok: ""+s+""\t""+r); count++; rec.add(r); } } return count; } private static boolean isIn(String r, ArrayList rec) { for(String r2 : rec) if(r.equals(r2)) return true; return false; } }" B21333,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class RN { public static Set> RNPair = new HashSet>(); public static class Pair { private final L left; private final R right; public Pair(L left, R right) { this.left = left; this.right = right; } public L getLeft() { return left; } public R getRight() { return right; } @Override public int hashCode() { return left.hashCode() ^ right.hashCode(); } @Override public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof Pair)) return false; Pair pairo = (Pair) o; return this.left.equals(pairo.getLeft()) && this.right.equals(pairo.getRight()); } } public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int T = scnr.nextInt(); for (int t = 1; t <= T; t++) { RNPair.removeAll(RNPair); Integer first = scnr.nextInt(); Integer last = scnr.nextInt(); int ans = 0; for (int i = first; i < last; i++) { ans += check(first, last, i); } //ans /= 2; System.out.println(""Case #"" + t + "": "" +RNPair.size()); } } public static int check(Integer start, Integer end, Integer num) { String numStr = num.toString(); int l = numStr.length(); int count = 0; for (int i = 0; i < l - 1; i++) { String rotStr = numStr.substring(l - i - 1) + numStr.substring(0, l - i - 1); int rotStrNum = Integer.parseInt(rotStr); if (rotStrNum < start || rotStrNum > end) continue; if (rotStrNum <= num) continue; if (num.toString().length() != Integer.toString(rotStrNum).length()) continue; if ((start <= num) && (num < rotStrNum) && (rotStrNum <= end)) { count++; Pair p = new Pair(num, rotStrNum); RNPair.add(p); //System.out.println(num + "" "" + rotStrNum); } } return count; } } " B20091,"import java.io.*; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class C implements Runnable { private static final String PROBLEM_ID = ""C""; private class TestCaseRunner { int answer(int a, int b) { int result = 0; for (int i = a; i <= b; i++) { int p10 = 1; int pI = i; while (pI > 0) { pI /= 10; p10 *= 10; } p10 /= 10; int j = i; for (;;) { boolean leadingZero = (j % 10) == 0; j = (j / 10) + p10 * (j % 10); if (j == i) { break; } if (i < j && j <= b && !leadingZero){ result++; // System.out.println(i + "" -> "" + j); } } } return result; } public void handleCase() throws IOException { int a = nextInt(); int b = nextInt(); out.print(answer(a, b)); } } BufferedReader in; PrintWriter out; StringTokenizer tokenizer = new StringTokenizer(""""); public static void main(String[] args) { new Thread(new C()).start(); } public void run() { File[] all = new File(""."").listFiles(); Arrays.sort(all, new Comparator() { public int compare(File a, File b) { return a.getName().toLowerCase().compareTo(b.getName().toLowerCase()); } }); int processed = 0; for (File inFile : all) if (inFile.isFile()) { String name = inFile.getName().toLowerCase(); if (name.startsWith(PROBLEM_ID.toLowerCase()) && name.endsWith("".in"")) { try { runFile(inFile); processed++; } catch (Throwable t) { throw new IllegalStateException(""Fatal error"", t); } } } if (processed > 0) { System.out.println(""Processed "" + processed + "" files for problem "" + PROBLEM_ID); } else { System.err.println(""No input files found for problem "" + PROBLEM_ID); } } private void runFile(File inFile) throws IOException { in = new BufferedReader(new FileReader(inFile)); out = new PrintWriter(new FileWriter(inFile.getName() + "".out"")); long startTime = System.currentTimeMillis(); System.out.println(""Processing file: "" + inFile.getName()); int tc = nextInt(); for (int p = 0; p < tc; p++) { long nowTime = System.currentTimeMillis(); System.out.print(""Running test case #"" + (p + 1) + "" out of "" + tc); if (p > 0) { System.out.print("" (remaining time: "" + remainingTime(p, tc, startTime, nowTime) + "")""); } System.out.println(); out.print(""Case #"" + (p + 1) + "": ""); new TestCaseRunner().handleCase(); out.println(); } in.close(); out.close(); } private String remainingTime(int p, int tc, long startTime, long nowTime) { double secondsPerTestCase = 1.0e-3 * (nowTime - startTime) / p; double secondsRemaining = (tc - p) * secondsPerTestCase; double minutesRemaining = secondsRemaining / 60; int minutes = (int) Math.floor(minutesRemaining); int seconds = (int) Math.round(secondsRemaining - minutes * 60); return minutes + "" min "" + seconds + "" sec""; } private String nextToken() throws IOException { while (!tokenizer.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private BigInteger nextBigInt() throws IOException { return new BigInteger(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }" B20363,"package gcj2012qr; import java.io.*; import java.util.*; import java.util.concurrent.*; import com.google.*; /** * @author Roman Kosenko */ public class RecycledNumbers extends SingleThreadSolution { public static void main(String[] args) throws Exception { solve(new SolutionFactory() { public Callable read(BufferedReader br) throws IOException { String[] ss = br.readLine().split("" ""); assert ss.length == 2; return new RecycledNumbers(Integer.parseInt(ss[0]), Integer.parseInt(ss[1])); } }, ""google/src/gcj2012qr/"" + ""C-large.in""); } private final int a, b; public RecycledNumbers(int a, int b) { this.a = a; this.b = b; } public String call() throws Exception { int result = 0; for(int i = a; i < b; i++) { int p = 1; for(int t = i / 10; t != 0; p *= 10) t /= 10; for(int t = i;;) { t = t / 10 + p * (t % 10); if(t == i) break; if(t > i && t <= b) result++; } } return Integer.toString(result); } } " B20037,"import java.util.List; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class ProblemC { /** * @param args */ public static void main(String[] args) { File in = new File( ""D:/Feng/Workspace/googlecodejam2012/problemC/in/C-large.in""); try { BufferedWriter out = new BufferedWriter(new FileWriter( ""D:/Feng/Workspace/googlecodejam2012/problemC/out/outlarge.txt"")); StringBuilder s; String line = """"; int min, max = 0; int count = 1; Scanner scanner = new Scanner(in); // Ignore the first line showing total count scanner.nextLine(); while (scanner.hasNextLine()) { s = new StringBuilder(""Case #""); s.append(count); s.append("": ""); line = scanner.nextLine(); String[] limits = line.split("" ""); min = Integer.parseInt(limits[0]); max = Integer.parseInt(limits[1]); s.append(countRecycledPairs(min, max)); System.out.println(s); out.write(s.toString()); out.newLine(); count++; } scanner.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static int countRecycledPairs(int min, int max) { //List recycledPairs = new ArrayList(1000); Set recycledPairs = new HashSet(); String s = """"; int m; for (int n = min; n < max; n++) { // Need at least 2 digits to recycle // Cannot have trailing zeroes i.e. n mod 10 = 0 // Cannot have digits that are all the same s = String.valueOf(n); for (int numDigitsToReplace = 1; numDigitsToReplace < s.length(); numDigitsToReplace++) { // System.out.print(numDigitsToReplace + "", ""); m = recycle(n, numDigitsToReplace); if ((m > n) && (m <= max)) { recycledPairs.add(n + "":"" + m); //count++; } } } //System.out.print(recycledPairs.size()); //System.out.println(recycledPairs.toString()); return recycledPairs.size(); } public static int recycle(int n, int numDigits) { String s = String.valueOf(n); StringBuilder sb = new StringBuilder(s); String rearDigits = s.substring(s.length() - numDigits); sb.delete(sb.length() - numDigits, sb.length()); sb.insert(0, rearDigits); if (sb.toString().startsWith(""0"")) { return 0; } return Integer.parseInt(sb.toString()); } public static boolean hasSameDigits(int i) { String s = String.valueOf(i); char[] chars = s.toCharArray(); char firstDigit = chars[0]; for (char c : chars) { if (c != firstDigit) return false; } return true; } } " B21885,"import java.util.HashSet; import java.util.Scanner; public class C_Recycled { static boolean recycled (String n, String B, String i) { return (n.compareTo(i) < 0) && (i.compareTo(B) <= 0); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int cas = 1; cas <= T; cas++) { int recycledPairs = 0; int A = in.nextInt(); int B = in.nextInt(); String sB = B+""""; for (int n = A; n < B; n++) { HashSet hs = new HashSet(); String sn = n+""""; for (int i = 1; i <= sn.length(); i++) { String si = sn.substring(i) + sn.substring(0,i); if (recycled(sn,sB,si)) hs.add(si); } recycledPairs += hs.size(); } if (cas > 1) System.out.println(); System.out.print(""Case #""+cas+"": ""+recycledPairs); } } } " B22187,"import java.io.*; import java.math.BigInteger; import java.util.*; public class GC { String s = null; String[] sp = null; public void run() throws Exception{ BufferedReader br = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""OUTPUT.txt"")); s = br.readLine(); int T = Integer.parseInt(s); int t = 1; while(t <= T){ s = br.readLine(); sp = s.split("" ""); long ans = 0; int a = Integer.parseInt(sp[0]); int b = Integer.parseInt(sp[1]); if(a < 10){ a = 10; } while(a < b){ String sa = Integer.toString(a); Set set = new HashSet(); for(int i = 1; i < sa.length(); i++){ String f = sa.substring(0, i); String ba = sa.substring(i); String ns = ba + f; if(set.contains(ns)){ continue; } set.add(ns); int nb = Integer.parseInt(ns); if(nb > a && nb <= b){ ans++; } } a++; } bw.write(""Case #"" + t + "": "" + ans + ""\n""); t++; } bw.close(); } public static void main(String[] args) throws Exception { GC b = new GC(); b.run(); } } " B21800,"package util.graph; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Set; public class DynDjikstra { public static State FindShortest(Node start, Node target) { PriorityQueue openSet = new PriorityQueue<>(); Set closedSet = new HashSet<>(); openSet.add(start); while (!openSet.isEmpty()) { Node current = openSet.poll(); for (Edge edge : current.edges) { Node end = edge.target; if (closedSet.contains(end)) { continue; } State newState = edge.travel(current.last); //if (end.equals(target)) { //return newState; //} if (openSet.contains(end)) { if (end.last.compareTo(newState)>0) { end.last = newState; } } else { openSet.add(end); end.last = newState; } } closedSet.add(current); if (closedSet.contains(target)) { return target.last; } } return target.last; } } " B20904,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib.converters; import com.isotopeent.codejam.lib.InputConverter; public class IntLine implements InputConverter { private int input; @Override public boolean readLine(String data) { input = Integer.parseInt(data); return false; } @Override public Integer generateObject() { return input; } } " B20158,"package qualification.problemC; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class ProblemC { static int num; static String[] lines; static String dir = ""./src/qualification/problemC""; static String inTxt = dir + ""/C-large.in""; static String outTxt = dir + ""/C-large.out""; public static void main(String[] args) { input(inTxt); String[] ansStrs = new String[num]; for (int i = 0; i < lines.length; i++) { String[] strs = lines[i].split(""\\s""); int[] nums = new int[strs.length]; for (int j = 0; j < strs.length; j++) { nums[j] = Integer.valueOf(strs[j]); } // Solve Problem int ans = solve(nums[0], nums[1]); ansStrs[i] = String.valueOf(ans); } output(outTxt, ansStrs); } static void input(String fname) { try { BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(fname))); String line = br.readLine(); num = Integer.valueOf(line); System.out.println(num); lines = new String[num]; for (int i = 0; i < num; i++) { lines[i] = br.readLine(); System.out.println(lines[i]); } br.close(); } catch (Exception e) { e.printStackTrace(); } } static void output(String fname, String[] output) { File outFile = new File(fname); try { FileWriter fw = new FileWriter(outFile); for (int i = 0; i < num && i < output.length; i++) { String out = ""Case #""+(i+1)+ "": "" + output[i] + '\n'; System.out.print(out); fw.write(out); fw.flush(); } fw.close(); } catch (Exception e) { e.printStackTrace(); } } public static int solve(int min, int max) { int count = 0; char maxFirst = String.valueOf(max).charAt(0); for (int i = Math.max(10, min); i < max; i++) { String num = String.valueOf(i); char first = num.charAt(0); Set set = new HashSet(); for (int j = 1; j < num.length(); j++) { char newFirst = num.charAt(j); if (newFirst < first || maxFirst < newFirst) continue; String tmp = num.substring(0, j); int newNum = Integer.valueOf(num.substring(j) + tmp); if (i < newNum && newNum <= max) { //System.out.println(num + "", "" + newNum); set.add(newNum); } } count += set.size(); } return count; } } " B20535,"/** * */ package br.com.softctrl.code.c; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; /** * @author timoshenko * */ public class CRecycledNumbers { private static int A = 0; private static int B = 0; private static int T = 4; private static int c = 0; private static String fileInput = ""/Users/timoshenko/Development/Projects/SoftCtrl.com/eclipse-jboss/workspaces/google-code-jam/GoogleCodeJam2012/src/br/com/softctrl/in/C-large.in""; private static String fileOutput = ""/Users/timoshenko/Development/Projects/SoftCtrl.com/eclipse-jboss/workspaces/google-code-jam/GoogleCodeJam2012/src/br/com/softctrl/out/C-large_out.txt""; private static SCFileReader scFr = null; private static SCFileWriter scFw = null; public static boolean valid(int n, int m) { // A ² n < m ² B // System.out.println(String.format(""A(%d)<=n(%d)= 1); length--) { String m = n.substring(length, n.length()) + n.substring(0, length); if (valid(Integer.parseInt(n), Integer.parseInt(m))) { count++; } } } return count; } } class SCFileReader { private Reader reader = null; private BufferedReader bufferedReader = null; private File file = null; public SCFileReader(String fileName) throws FileNotFoundException { file = new File(fileName); reader = new FileReader(file); bufferedReader = new BufferedReader(reader); } public boolean ready() { try { return bufferedReader.ready(); } catch (IOException e) { e.printStackTrace(); return false; } } public String readLine() throws IOException { return bufferedReader.readLine(); } public void close() { if (this.ready()) { try { bufferedReader.close(); reader.close(); } catch (IOException e) { e.printStackTrace(); } bufferedReader = null; reader = null; file = null; } } } class SCFileWriter { private Writer writer = null; private BufferedWriter bufferedWriter = null; private File file = null; public SCFileWriter(String fileName) throws IOException { file = new File(fileName); if (file.exists()) { file.delete(); } writer = new FileWriter(file); bufferedWriter = new BufferedWriter(writer); } public void write(String row) throws IOException { // System.out.println(row); bufferedWriter.write(row); } public void writeLn(String row) throws IOException { System.out.println(row); bufferedWriter.write(row + ""\n""); } public void save() { try { bufferedWriter.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); } bufferedWriter = null; writer = null; file = null; } } " B21647,"import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class GoogleC { public static void main(String[] args) throws FileNotFoundException{ Scanner scan = new Scanner(new File(""B-small.txt"")); //finit2(); int n = scan.nextInt(); for (int i = 0; i < n; i++){ ht.clear(); System.out.println(""Case #"" + (i+1) + "": "" + sum(scan.nextInt(), scan.nextInt())); } } public static long sum(int a, int b){ ht = new HashSet(); long ret = 0; for (int i = a; i <= b; i++){ ret += run(i, a, b); } return ret; } public static HashSet ht = new HashSet(); private static class Pair{ int m, n; public Pair(int m, int n){ this.m = m; this.n =n; } public int hashCode(){ return 31*m+n; } @Override public boolean equals(Object o){ Pair p = (Pair)o; return p.m == m && p.n == n; } } public static int run(Integer n, int a, int b){ int count = 0; String orig = n.toString(); String cur = n.toString(); for (int i = 0; i < orig.length()-1; i++){ char c = cur.charAt(0); cur = cur.substring(1) + c; if (cur.charAt(0) == '0') continue; int k = Integer.parseInt(cur); if (a <= k && k < n){ if (cur.length()%2==0 && cur.substring(0, cur.length()/2).equals(cur.substring(cur.length()/2, cur.length()))){ Pair p = new Pair(k, n); if (!ht.contains(p)){ count++; //System.out.println(k + "" "" + n); ht.add(p); } /*else{ System.out.println(k + "" "" + n); }*/ } else{ count++; } } } return count; } } " B20277,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class Recycled { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); int t = Integer.parseInt(line); for (int i = 0; i < t; i++) { Set set = new HashSet(); line = br.readLine(); String[] split = line.split("" ""); int A = Integer.parseInt(split[0]); int B = Integer.parseInt(split[1]); int digits = String.valueOf(A).length(); if (digits != 1){ for (int j = A; j <= B; j++) { String oldString = String.valueOf(j); // System.out.println(""AA "" + oldString); for (int j2 = 1; j2 < digits; j2++) { String newString = oldString.substring(j2).concat(oldString.substring(0, j2)); if(newString.charAt(0) == '0')continue; int newInt = Integer.valueOf(newString); if (newInt >= A && newInt <= B && j 1) { total += real_n * (real_n - 1) / 2; } } } return total; } private int setTested(int[] result, int n) { int tested = 0; for (int i = 0; i < n; i++) { if (!data[result[i] - min]) { data[result[i] - min] = true; tested++; } } return tested; } private int getRecycleNumbers(int number, int[] result) { int count = 0; for (int i = 0; i < digits; i++) { if (number >= min && number <= max) { result[count++] = number; } int number10 = number * 10; number = (number10 % mask) + (number10 / mask); } return count; } private boolean isTested(int number) { return data[number - min]; } public static void main(String[] args) throws Exception { PrintWriter output = new PrintWriter(""output3.txt""); Scanner scanner = new Scanner(new File(""input3.txt"")); try { int input_T = scanner.nextInt(); for (int i = 0; i < input_T; i++) { int input_A = scanner.nextInt(); int input_B = scanner.nextInt(); RecycledNumbers testing = new RecycledNumbers(input_A, input_B); long start = System.nanoTime(); int eval = testing.eval(); output.printf(""Case #%d: %d\n"", i + 1, eval); System.out .printf(""Case #%d: %d (%d)\n"", i + 1, eval, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)); } } finally { output.close(); scanner.close(); } } } " B20676,"import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Scanner; public class QC_Large2012 { public static void main(String[] args) throws Exception { new QC_Large2012(); } static final String filename = ""C-large""; int testcases; int[] tenPowers; public QC_Large2012() throws Exception { FileReader ifile = new FileReader(filename+"".in""); Scanner scanner = new Scanner(ifile); testcases = Integer.parseInt(scanner.nextLine()); FileWriter ofile = new FileWriter(filename+"".out""); for (int i = 1; i <= testcases; i++) { ofile.write(""Case #""+i+"": ""+solve(scanner.nextInt(), scanner.nextInt())+(i != testcases ? ""\n"" : """")); } ofile.close(); System.out.println(""Finished""); /* * Benchmarking code */ /* long n = new Date().getTime(); for (int i = 0; i < 20000000; i++) intStringLen(i); System.out.println(new Date().getTime() - n); n = new Date().getTime(); for (int i = 0; i < 20000000; i++) intLen(i); System.out.println(new Date().getTime() - n); //solve(1, 4); int l = 3; tenPowers = new int[l+1]; initTenPowers(tenPowers); System.out.println(rotR(123,0,l));*/ } private int solve(int A, int B) throws Exception { int l = intLen(A); //len A = len B (definition) tenPowers = new int[l+1]; initTenPowers(tenPowers); int sum = 0; for (int n = A; n <= B-1; n++) { sum += recycledPairs(n, B, l); } return sum; } private void initTenPowers(int[] tenPowers) { tenPowers[0] = 1; for (int i = 1; i < tenPowers.length; i++) tenPowers[i] = tenPowers[i-1] * 10; } private int recycledPairs(int n, int B, int l) { int sum = 0; int m; for (int i = 0; i < l; i++) { m = rotR(n, i, l); if (m > n && m <= B) sum++; } return sum; } private int rotR(int n, int x, int l) { int back = n % tenPowers[x]; int front = n / tenPowers[x]; return front + back * tenPowers[l-x]; } private int intLen(int n) { int l = 0; while (n > 0) { n /= 10; l++; } return l; } } " B22068,"import java.io.*; import java.util.*; public class clarge { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int[][] list = new int[2000000][]; for (int i=0; i<2000000; i++) { list[i] = fill(i); } int numCases = stdin.nextInt(); for (int loop=1; loop<=numCases; loop++) { int A = stdin.nextInt(); int B = stdin.nextInt(); int sum = 0; for (int i=A; i<=B; i++) { if (list[i] != null) { for (int j=0; j saveval) { temp[index] = val; index++; } } int[] ans = new int[index]; for (int i=0; i= 10) { cnt*=10; val /= 10; } return cnt; } public static int numd(int val) { if (val == 0) return 0; int cnt = 0; while (val > 0) { cnt++; val /= 10; } return cnt; } } " B21762,"import java.util.HashSet; import java.util.Scanner; public class qualifier3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int numcases = sc.nextInt(); sc.nextLine(); for(int curcase = 1;curcase <=numcases;curcase++) { int min = sc.nextInt(); int max = sc.nextInt(); int numdigits = 0; for(int i=max;i>0;i/=10,numdigits++); int tennum =1; for(int i=0;i seen = new HashSet(); int mult =1; for(int j=1;ji)&&(mine<=max)&&(!seen.contains(mine))) { count++; seen.add(mine); } } } sc.nextLine(); System.out.println(""Case #""+curcase+"": ""+count); } } } " B20282,"import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; /** * * @author pulasthi */ public class QC12 { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(""c.txt""); int T = sc.nextInt(); for (int i = 0; i < T; i++) { HashSet hs = new HashSet(); int min = sc.nextInt(); int max = sc.nextInt(); for (int j = min; j <= max; j++) { String s = j+""""; for(int k =1; kj && compI<=max){ hs.add(j+""""+compI); } } } out.print(""Case #""+(i+1)+"": ""); out.println(hs.size()); System.out.println(hs.size()); } out.flush(); out.close(); } } " B21192," public interface ICounterZeroEvent { public void fireEvent(); } " B20293,"/* Problem Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers. Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros. Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A = n < m = B? Input The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B. Output For each test case, output one line containing ""Case #x: y"", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A = n < m = B. Limits 1 = T = 50. A and B have the same number of digits. Small dataset 1 = A = B = 1000. Large dataset 1 = A = B = 2000000. Sample Input Output 4 1 9 10 40 100 500 1111 2222 Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 */ import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; public class RecycledNumbers { BufferedReader read; BufferedWriter write; public static void main(String args[]) { try { new RecycledNumbers().init(""C-large""); } catch (Exception ex) { //Logger.getLogger(RecycledNumbers.class.getName()).log(Level.SEVERE, null, ex); System.out.println(""Error"" + ex); } } void init(String name) throws Exception { read=new BufferedReader(new FileReader(new File(name+"".in""))); write=new BufferedWriter(new FileWriter(new File(name+"".out""))); String x=""""; try { x = read.readLine(); int nos = Integer.parseInt(x.trim()); for(int z=0;z ar=new ArrayList(); for(int j=0;ji && num<=b) { ar.add(num); //System.out.println("" i.... ""+i+""...num.... ""+num); count++;} } } } write.write(""Case #""+(z+1)+"":""+"" ""+count+""\n""); System.out.println(""Case #""+(z+1)+"":""+"" ""+count+""\n""); } write.flush(); write.close(); read.close(); // System.out.println(a+"" ""+b); } catch (Exception ex) { System.out.println(""Error"" + ex); System.exit(0); } } }" B20696,"package org.moriraaca.codejam.recyclednumbers; import java.util.HashSet; import org.moriraaca.codejam.AbstractSolver; import org.moriraaca.codejam.OutputDestination; import org.moriraaca.codejam.SolverConfiguration; @SolverConfiguration(parser = RecycledNumberDataParser.class, inputFileName = ""ultra-large.in"", outputDestination=OutputDestination.FILE) public class RecycledNumbersSolver extends AbstractSolver { public static void main(String[] args) { new RecycledNumbersSolver().getSolution(); } private int digitsNumber; private int headShift; private HashSet usedNumbers = new HashSet(); @Override protected String solveTestCase(RecycledNumbersTestCase testCase) { int counter = 0; digitsNumber = String.valueOf(testCase.A).length(); headShift = 1; for (int i = 0; i < digitsNumber; i++) { headShift *= 10; } for (int i = testCase.A; i <= testCase.B; i++) { counter += rotateNumber(i, testCase.B); } return String.valueOf(counter); } private int rotateNumber(int number, int B) { int counter = 0; int orginalNumber = number; usedNumbers.clear(); for(int i = 1; i < digitsNumber; i++) { number += (number % 10) * headShift; number /= 10; if (number > orginalNumber && number < B && !usedNumbers.contains(number)) { counter++; usedNumbers.add(number); } } return counter; } } " B20157," import java.io.*; import java.util.*; public class RN { private static String fileName = RN.class.getSimpleName().replaceFirst(""_.*"", """"); private static String inputFileName = ""D:\\santosh\\cj12\\""+fileName + "".in""; private static String outputFileName = ""D:\\santosh\\cj12\\""+fileName + "".out""; private static Scanner in; private static PrintWriter out; private static int rotateAndCount(int num, int b, HashMap map) { String str1 = new Integer(num).toString(); char[] arr = str1.toCharArray(); int len = arr.length; if(len <= 1) { return 0; } int cnt = 0; String str = str1 + str1; for (int i = 0; i < len-1; i++) { char ch = arr[len - 1]; for (int j = len - 1; j > 0; j--) { arr[j] = arr[j - 1]; } arr[0] = ch; String str2 = new String(arr); int c2 = Integer.parseInt(str2); if(c2 != num && (c2 >= num) && (c2 <= b) && str.contains(str2)) { if(!map.containsKey(str1+"",""+str2)) { map.put(str1+"",""+str2, null); cnt ++; } } } return cnt; } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); if (args.length >= 2) { inputFileName = args[0]; outputFileName = args[1]; } in = new Scanner(new FileReader(inputFileName)); out = new PrintWriter(outputFileName); int tests = in.nextInt(); //in.nextLine(); int a, b; HashMap map; for (int t = 1; t <= tests; t++) { a = in.nextInt(); b = in.nextInt(); map = new HashMap(); System.out.println(""A == ""+a+"" B ==""+ b); int totalCnt = 0; while(a <= b) { totalCnt += rotateAndCount(a, b, map); a++; } System.out.println(""Case #"" + t + "": ""+totalCnt); out.println(""Case #"" + t + "": ""+totalCnt); } in.close(); out.close(); } } " B20005,"import java.io.*; import java.util.*; //import java.math.*; public class c { public static void main(String[] args) throws IOException { Scanner qwe = new Scanner(new File(""c.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""c.out"")); int t = qwe.nextInt(); for(int i = 1; i <= t; i++) { int a = qwe.nextInt(); int b = qwe.nextInt(); int[] been = new int[2000001]; long count = 0; for(Integer j =a; j <= b; j++) { //if(been[j] > 1 && i == 4) //System.out.println(i + "" "" +j + "" "" + been[j]); if(been[j] > 0) count += been[j]; String s = j.toString(); ArrayList tocheck = new ArrayList(); for(int k = 1; k < s.length(); k++) { String torec = s.substring(k); String end = s.substring(0,k); String combin = torec+end; if(!tocheck.contains(combin) && Integer.parseInt(combin) < 2000001) been[Integer.parseInt(combin)] += 1; tocheck.add(combin); } } out.write(""Case #"" + i + "": "" + count + ""\n""); } out.close(); } } " B22059,"package qualification.recycled.numbers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URISyntaxException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { private static String PREFIX = ""C-large""; private static String INPUT_FILE = PREFIX + "".in""; private static String OUTPUT_FILE = PREFIX + "".out""; private static BufferedReader getInput() { return new BufferedReader(new InputStreamReader(RecycledNumbers.class.getResourceAsStream(INPUT_FILE))); } private static PrintWriter getOutput() throws URISyntaxException, FileNotFoundException { File inputFile = new File(RecycledNumbers.class.getResource(INPUT_FILE).toURI()); File packageDirectory = inputFile.getParentFile(); File outputFile = new File(packageDirectory, OUTPUT_FILE); return new PrintWriter(outputFile); } public static void main(String[] args) throws Throwable { BufferedReader br = getInput(); PrintWriter pw = getOutput(); int numTestCases = new Integer(br.readLine().trim()); for (int testCase = 1; testCase <= numTestCases; testCase++) { String line = br.readLine(); Scanner read = new Scanner(line); Set pairs = new HashSet(); int a = read.nextInt(); int b = read.nextInt(); int digits = Integer.toString(a).length(); int lastDigitMultiplier = 1; for (int i = 1; i < digits; i++) { lastDigitMultiplier = lastDigitMultiplier * 10; } for (int num = a; num <= b; num++) { int recycledNum = num; for (int recycles = 1; recycles < digits; recycles++) { int lastDigit = recycledNum % 10; recycledNum = recycledNum / 10; recycledNum = (lastDigit * lastDigitMultiplier) + recycledNum; if (a <= recycledNum && recycledNum <= b && num != recycledNum && num < recycledNum) { RecycledPair pair = new RecycledPair(num, recycledNum); if (!pairs.contains(pair)) { pairs.add(pair); } } } } pw.println(""Case #"" + testCase + "": "" + pairs.size()); } pw.close(); br.close(); } } " B20302,"import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class MainClass { /** * @param args */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Scanner sc = new Scanner(new File(""C-large.in"")); PrintWriter out = new PrintWriter(new File(""RecycledNumbers.out"")); int N = sc.nextInt(); for (int i = 0; i < N; i++) { System.out.println(""For case i: "" + i); int A = sc.nextInt(); int B = sc.nextInt(); long count = 0; String s1 = """"; for (int j = A; j <= B; j++) { s1 = """" + j; ArrayList done = new ArrayList(); for (int k = 0; k < s1.length(); k++) { String tempS = s1; tempS = s1.substring(1) + s1.charAt(0); if (done.contains(tempS)) { continue; } else { s1 = tempS; } int temp = Integer.parseInt(s1); if ((temp < j) && (temp >= A) && (temp <= B)) { count++; done.add(s1); } } } out.println(""Case #"" + (i + 1) + "": "" + count); System.out.println(""**************""); } out.close(); } } " B20938,"import java.util.*; import java.io.*; public class P3L { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new FileReader(""input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int cases = Integer.parseInt(sc.nextLine()); int c = 0; for (int i = 0; i < cases; i++) { long l = sc.nextLong(); // lower limit long u = sc.nextLong(); // upper limit c = 0; for(long j = l; j<= u; j++) { c += noOfCombos(j,l,u); } pw.println(""Case #"" + (i + 1) + "": "" + c); } pw.close(); sc.close(); } static int noOfCombos(long x ,long l, long u) throws Exception { String s = (x+""""); long n = 0; int c = 0; int d = s.length(); String answers = """"; for(int i = 1; i= l && n <= u && n > x) { if(answers.indexOf(s2) == -1) { answers += s2 + "" ""; c++; } } } } return c; } }" B20576,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class Recycle { public static void main(String[] args) throws IOException { Scanner s = new Scanner(new File(""C-small-attempt0.in"")); FileWriter strm = new FileWriter(""out1.txt""); BufferedWriter out = new BufferedWriter(strm); int cases = s.nextInt(); s.nextLine(); int count = 1; while(count - 1 < cases) { int A = s.nextInt(); int B = s.nextInt(); out.write(""Case #"" + count + "": "" + calc(A,B) + ""\n""); count++; } out.close(); } private static int calc(int a, int b) { int count = 0; for(int i = a; i<=b;i++) { count+=numPairs(i,a,b); } return count; } private static int numPairs(int i,int a, int b) { char[] arr = Integer.toString(i).toCharArray(); char[] newArr = new char[arr.length]; ArrayList list = new ArrayList(); int count = 0; for(int j= 1;j K && R <=B) { boolean repeat = false; for (int j = 0; j < pairs; j++) { if (R == a[j]) { repeat = true; break; } } if (!repeat) { a[pairs] = R; pairs++; recycledPairs++; } } } } return recycledPairs; } public int digits(long k) { int length = 0; for (int i = 0; i < 8; i++) { k /= 10; length++; if (k == 0) break; } return length; } } " B20186,"package com.numbers.recycle.algo; import java.util.ArrayList; import java.util.List; public class Recycler { public int getRecycledNumberCount(String[] wordsInOrder){ int beginNumber = Integer.valueOf(wordsInOrder[0]); int endNumber = Integer.valueOf(wordsInOrder[1]); int counter = 0; for(int current = beginNumber ; current <= endNumber ; current++) { List recycledNumbers = getRecycledNumbers(current); for(int recycledNumber: recycledNumbers) { if(beginNumber <= current && current < recycledNumber && recycledNumber <= endNumber) counter ++; } } return counter; } private List getRecycledNumbers(int i) { List returnList = new ArrayList(); String number = String.valueOf(i); int length = number.length(); for(int counter = 1; counter < length; counter++) { number = number.charAt(length - 1) + number.substring(0,length - 1); int numValue = Integer.valueOf(number); if(!returnList.contains(numValue)) returnList.add(Integer.valueOf(number)); } return returnList; } } " B20170,"package qualification; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Locale; import java.util.Set; import java.util.StringTokenizer; import java.util.Vector; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; public class A { static DecimalFormat DF = new DecimalFormat(""0.000000"", new DecimalFormatSymbols(Locale.ENGLISH)); private static final int MAX = 1000000; private static final int MIN = 1 - 1; private static final int MOD = 1000000009; public A(int cc) throws IOException { final int A = INT(); final int B = INT(); int max = 0; int b[] = new int[20]; int ml[] = new int[10]; for (int n = A; n < B; n++) { int bc = 0; for( int i = n; i > 0; i /= 10 ) { b[bc++] = i % 10; } int mlc = 0; don: for( int i = 1; i < bc; i++ ) { int m = 0; for( int j = bc-1; j >= 0; j-- ) { m = (m*10) + b[(j+i)%bc]; } if( m > n && m <= B ) { for (int j = 0; j < mlc; j++) { if( m == ml[j] ) { continue don; } } max++; ml[mlc++] = m; } } } println(""Case #"" + cc + "": ""+max); //System.out.format(""Case #%d: %.09f\n"", cc, total); } public static void run() throws Exception { String qprefix = ""C""; init(qprefix+""-large""); //init(qprefix + ""-small-attempt1""); //init(""test""); int cases = INT(); for (int cc = 1; cc <= cases; cc++) { new A(cc); } } static class Ct extends Thread { public void run() { } } static int[][] mapClone(int[][] map) { int[][] cmap = map.clone(); for (int i = 0; i < cmap.length; i++) { cmap[i] = map[i].clone(); } return cmap; } // ************************************************************************************* // *********************************** FRAMEWORK // ************************************************************************************* public static BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); public static boolean isStandardInput = false; public static File input; public static FileReader inputreader; public static BufferedReader in; public static File output; public static FileWriter outputwriter; public static BufferedWriter out; public static StringTokenizer st; public static void main(String[] args) throws Exception { doSTDIN(true); setOutput(""test.out""); run(); close(); } public static void init(String problemName) throws Exception { doSTDIN(false); setInput(problemName + "".in""); setOutput(problemName + "".out""); } // **************** PRINT METHODS ********************** public static void println() throws IOException { out.write(""\n""); System.out.println(); } public static void println(Object obj) throws IOException { out.write(obj.toString()); out.write(""\n""); System.out.println(obj.toString()); } public static void print(Object obj) throws IOException { out.write(obj.toString()); System.out.print(obj.toString()); } public static void println(long number) throws IOException { out.write(Long.toString(number)); out.write(""\n""); System.out.println(number); } public static void print(long number) throws IOException { out.write(Long.toString(number)); System.out.print(number); } public static void println(char c) throws IOException { out.write(Character.toString(c)); out.write(""\n""); System.out.println(c); } public static void print(char c) throws IOException { out.write(Character.toString(c)); System.out.print(c); } public static void println(String line) throws IOException { out.write(line); out.write(""\n""); System.out.println(line); } public static void print(String line) throws IOException { out.write(line); System.out.print(line); } // ******************** INPUT DECLARATION ****************** public static void doSTDIN(boolean standard) { isStandardInput = standard; } public static void setInput(String filename) throws IOException { input = new File(filename); inputreader = new FileReader(input); in = new BufferedReader(inputreader); } public static void setOutput(String filename) throws IOException { output = new File(filename); outputwriter = new FileWriter(output); out = new BufferedWriter(outputwriter); } public static void close() throws IOException { if (in != null) in.close(); if (inputreader != null) inputreader.close(); if (out != null) out.flush(); if (out != null) out.close(); if (outputwriter != null) outputwriter.close(); } // ************************** INPUT READING ***************** static String LINE() throws IOException { return isStandardInput ? stdin.readLine() : in.readLine(); } static String TOKEN() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(LINE()); return st.nextToken(); } static int INT() throws IOException { return Integer.parseInt(TOKEN()); } static long LONG() throws IOException { return Long.parseLong(TOKEN()); } static double DOUBLE() throws IOException { return Double.parseDouble(TOKEN()); } static BigInteger BIGINT() throws IOException { return new BigInteger(TOKEN()); } } class AF { private Object array; private int oa = 0; private int ob = 0; private int as = 10; private int bs = 10; public AF(Object array) { this.array = array; } public AF(Object array, int oa, int ob) { this.array = array; this.oa = oa; this.ob = ob; } public AF(Object array, int oa, int ob, int as, int bs) { this.array = array; this.oa = oa; this.ob = ob; this.as = as; this.bs = bs; } public String toString() { StringBuilder sb = new StringBuilder(); for (int a = 0; a < as; a++) { sb.append(a + oa).append('['); for (int b = 0; b < bs; b++) { sb.append(get(a, b)); if (b != bs - 1) sb.append(','); } sb.append(""]\n""); } return sb.toString(); } private String get(int a, int b) { a += oa; b += ob; String s = "" ""; try { if (array instanceof int[][]) { int[][] na = (int[][]) array; s = Integer.toString(na[a][b]); } else if (array instanceof byte[][]) { byte[][] na = (byte[][]) array; s = Byte.toString(na[a][b]); } else if (array instanceof Object[][]) { Object[][] na = (Object[][]) array; s = na[a][b].toString(); } } catch (Exception e) { } while (s.length() < 2) { s = "" "" + s; } return s; } } class AF2 extends JFrame implements ActionListener { static Object lock = new Object(); private JTable jt; public AF2(String title, int[][] data) { super(title); setSize(150, 150); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { dispose(); System.exit(0); } }); jt = new JTable(new ITableModel(data)); jt.setDefaultRenderer(Integer.class, new CustomTableCellRenderer()); // jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); JScrollPane pane = new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); getContentPane().add(pane); JButton button = new JButton(""Continue""); getContentPane().add(button, BorderLayout.SOUTH); button.addActionListener(this); pack(); setVisible(true); } public void updateData(int[][] data) { ((ITableModel) jt.getModel()).updateData(data); /*synchronized (lock) { try { lock.wait(); } catch (InterruptedException e) { } }*/ return; } public void actionPerformed(ActionEvent arg0) { synchronized (lock) { lock.notify(); } } } class ITableModel extends AbstractTableModel { int[][] data; int[][] old_data; public ITableModel(int[][] data) { if (data != null) this.data = data; else this.data = new int[1][1]; } public void updateData(int[][] p_data) { if( p_data.length == data.length && p_data[0].length == data[0].length ) { old_data = data; } else { old_data = null; } this.data = p_data; EventQueue.invokeLater(new Runnable() { public void run() { fireTableStructureChanged(); } }); } public int getColumnCount() { return data[0].length + 1; } public int getRowCount() { return data.length; } public String getColumnName(int column) { return Integer.toString(column - 1); } public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) return rowIndex; if( old_data != null && data[rowIndex][columnIndex - 1] != old_data[rowIndex][columnIndex - 1] ) { return """"+old_data[rowIndex][columnIndex - 1]+"" -> ""+data[rowIndex][columnIndex - 1]; } return data[rowIndex][columnIndex - 1]; } public Class getColumnClass(int arg0) { return getValueAt(0, arg0).getClass(); } } class CustomTableCellRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (column == 0) { cell.setBackground(Color.gray); } else if (value instanceof Integer) { Integer amount = (Integer) value; if (amount.intValue() <= 0) { cell.setBackground(Color.red); } else { cell.setBackground(Color.white); } } else { cell.setBackground(Color.yellow); } return cell; } } " B21271,"import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class Solution { public static void main(String[] args){ Scanner scan = new Scanner(System.in); int T = scan.nextInt(); int[] counts = new int[T]; int max =2000001; boolean[] used = new boolean[max]; for(int i=0;i0){ temp=temp/10; num++; total*=10; } HashSet set = new HashSet(); int rotato=0; int size =0; for(int i=A;i<=B;i++){ if(!used[i]){ set.clear(); set.add(i); temp=i; int exp =1; for(int j=1;j=A && rotato<=B){ set.add(rotato); used[rotato]=true; } } //System.out.println(size); size = set.size(); if(size>1){ result+=size*(size-1)/2; } } } Arrays.fill(used, A,B,false); return result; } } " B21614,"import java.io.File; import java.io.PrintWriter; import java.util.*; import java.util.jar.JarEntry; /** * Created with IntelliJ IDEA. * User: vitaly * Date: 4/14/12 * Time: 9:24 AM * To change this template use File | Settings | File Templates. */ public class Main { public static int bruteForce(int start, int end) { Set set = new HashSet(); for (int k = start; k <= end; k++) { String repr = Integer.toString(k); for (int i = 1; i < repr.length(); i++) { String a = repr.substring(0, i); String b = repr.substring(i, repr.length()); int comb = Integer.valueOf(b + a); if (comb > k & comb >= start && comb <= end) { String c = """" + k + "":"" + comb; set.add(c); } } } return set.size(); } public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(new File(""C-large.in"")); PrintWriter pw = new PrintWriter(new File(""google.out"")); int n = scanner.nextInt(); for(int i = 0; i < n; i++) { int start = scanner.nextInt(); int end = scanner.nextInt(); int comb = bruteForce(start, end); pw.print(String.format(""Case #%d: %d%n"", i + 1, comb)); } scanner.close(); pw.close(); } } " B21189,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; /** * * @author ysan * */ public class Problem_C_large { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""C-large-output0.txt"")); int cases = Integer.parseInt(in.readLine()); for (int i = 1; i <= cases; i++) { String text = in.readLine().trim(); String[] val = text.split("" ""); int count = 0; BigInteger lasta = BigInteger.ZERO; BigInteger lastb = BigInteger.ZERO; BigInteger a = new BigInteger(val[0]); BigInteger b = new BigInteger(val[1]); System.out.println(a +"" ""+b); BigInteger j = a; while(j.compareTo(b) < 0){ String g = j.toString(); for(int k=g.length()-1; k>0; k--){ BigInteger r = switchIt(g, k); if(r.compareTo(j) > 0 && r.compareTo(b) <= 0 ){ System.out.println("" r ""+r+"" j ""+j); if(lasta == j && lastb == r) continue; lasta = j; lastb = r; count++; } } j = j.add(BigInteger.ONE); } out.write(""Case #""+ i +"": "" + count); out.newLine(); } in.close(); out.close(); } static BigInteger switchIt(String v, int p){ BigInteger r= BigInteger.ZERO; String a = v.substring(p); String b = v.substring(0, p); if(a.charAt(0) != '0'){ r = new BigInteger(a+b); } return r; } } " B20640,"package gcj2012.qual; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { final boolean DEBUG = false; final String PACKAGE = ""gcj2012/qual""; final String PROBLEM = ""C""; @SuppressWarnings(""unchecked"") void run(){ if(!DEBUG){ try { // System.setIn(new FileInputStream(new File(""./src/""+PACKAGE+""/""+PROBLEM+""-small.in""))); System.setIn(new FileInputStream(new File(""./src/""+PACKAGE+""/""+PROBLEM+""-large.in""))); // System.setOut(new PrintStream(new File(""./src/""+PACKAGE+""/""+PROBLEM+""-small_out.txt""))); System.setOut(new PrintStream(new File(""./src/""+PACKAGE+""/""+PROBLEM+""-large_out.txt""))); } catch (FileNotFoundException e) { e.printStackTrace(); } } Scanner sc = new Scanner(System.in); int T = sc.nextInt(); int N = 2000000; Set[] s = new Set[N+1]; for(int x=1;x<=N;x++){ s[x] = new HashSet(); String t = x+""""; int n = t.length(); for(int i=0;i possible = getRecycled(n); for (int m:possible) { if (m <= B) { recycledCount++; } } } return """" + recycledCount; } private Set getRecycled(int n) { Set possible = new HashSet (); int shift = 2; if ( n > 11 ) { // no single or 10 or 11 if ( n >= 1000000) { shift = 7; } else if ( n >= 100000) { shift = 6; } else if ( n >= 10000) { shift = 5; } else if ( n >= 1000) { shift = 4; } else if ( n >= 100 ) { shift = 3; } int newNum = n; for ( int i =0; i< shift-1; i++) { int last = newNum % 10; newNum = (int) (newNum / 10 + (Math.pow(10, shift-1)*last)); if ( newNum > n ) { possible.add(newNum); } } } // Cache possible return possible; } } " B21017,"import java.util.*; import java.io.*; public class Qual2012 { public static void lame() { try { FileReader fr = new FileReader(""input.txt""); BufferedReader reader = new BufferedReader(fr); PrintWriter writer = new PrintWriter(""output.txt""); HashMap dictionary = new HashMap(); dictionary.put(""a"", ""y""); dictionary.put(""b"", ""h""); dictionary.put(""c"", ""e""); dictionary.put(""d"", ""s""); dictionary.put(""e"", ""o""); dictionary.put(""f"", ""c""); dictionary.put(""g"", ""v""); dictionary.put(""h"", ""x""); dictionary.put(""i"", ""d""); dictionary.put(""j"", ""u""); dictionary.put(""k"", ""i""); dictionary.put(""l"", ""g""); dictionary.put(""m"", ""l""); dictionary.put(""n"", ""b""); dictionary.put(""o"", ""k""); dictionary.put(""p"", ""r""); dictionary.put(""q"", ""z""); dictionary.put(""r"", ""t""); dictionary.put(""s"", ""n""); dictionary.put(""t"", ""w""); dictionary.put(""u"", ""j""); dictionary.put(""v"", ""p""); dictionary.put(""w"", ""f""); dictionary.put(""x"", ""m""); dictionary.put(""y"", ""a""); dictionary.put(""z"", ""q""); dictionary.put("" "", "" ""); int numCases = Integer.parseInt(reader.readLine()); for (int i = 1; i <= numCases; i++) { String sentence = reader.readLine(); String newSentence = """"; for (char c : sentence.toCharArray()) { char[] temp = new char[1]; temp[0] = c; newSentence += dictionary.get(new String(temp)); } writer.println(""Case #"" + i + "": "" + newSentence); } writer.close(); fr.close(); } catch (Exception e) { e.printStackTrace(); } } public static boolean canMatch(int score, int target) { if (score == 0) return target <= 0; if (score == 1 || score == 2) return target <= 1; if (score % 3 == 0) { return score / 3 >= target; } return ((score / 3) + 1 >= target); } public static boolean canMatchSpecial(int score, int target) { if (score == 0) return target <= 0; if (score == 1) return target <= 1; if (score == 2) return target <= 2; if (score % 3 == 1) return (score / 3 + 1) >= target; return (score / 3 + 2) >= target; } public static void dance() { try { FileReader fr = new FileReader(""input.txt""); BufferedReader reader = new BufferedReader(fr); PrintWriter writer = new PrintWriter(""output.txt""); int numCases = Integer.parseInt(reader.readLine()); for (int i = 1; i <= numCases; i++) { StringTokenizer line = new StringTokenizer(reader.readLine(), "" ""); int numDancers = Integer.parseInt(line.nextToken()); int numSurprising = Integer.parseInt(line.nextToken()); int bestScore = Integer.parseInt(line.nextToken()); List scores = new LinkedList(); for (int j = 0; j < numDancers; j++) scores.add(Integer.parseInt(line.nextToken())); int count = 0; for (Integer score : scores) { if (canMatch(score, bestScore)) count++; else if (canMatchSpecial(score, bestScore) && numSurprising > 0) { numSurprising--; count++; } } writer.println(""Case #"" + i + "": "" + count); } writer.close(); fr.close(); } catch (Exception e) { e.printStackTrace(); } } public static void recycle() { try { FileReader fr = new FileReader(""input.txt""); BufferedReader reader = new BufferedReader(fr); PrintWriter writer = new PrintWriter(""output.txt""); int numCases = Integer.parseInt(reader.readLine()); for (int i = 1; i <= numCases; i++) { StringTokenizer line = new StringTokenizer (reader.readLine(), "" ""); int A = Integer.parseInt(line.nextToken()); int B = Integer.parseInt(line.nextToken()); int count = 0; for (int k = A; k <= B; k++) { if (k < 10) { continue; } String temp = """" + k; String cmp = """" + k; int length = temp.length(); temp = temp.substring(length-1) + temp.substring(0, length - 1); while (!temp.equals(cmp)) { int cycle = Integer.parseInt(temp); if (A <= cycle && cycle <= B) count++; temp = temp.substring(length-1) + temp.substring(0, length - 1); } } writer.println (""Case #"" + i + "": "" + count/2); } writer.close(); fr.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // lame(); // dance(); recycle(); } }" B20250,"import java.util.HashSet; public class CSolver extends SolverModule { @Override String processLine(String line) { int[] lines = toIntegers(line.split("" "")); int A = lines[0]; int B = lines[1]; HashSet hashSet = new HashSet(); for (int i = A; i < B; i++) { int length = String.valueOf(A).length(); for (int j = 1; j < length; j++) { int a = rightMove(i, length - j); int b = leftMove(i, j) - leftMove(rightMove(i, (length - j)), length); int total = a + b; if (total >= A && total <= B && total > i) { hashSet.add(i + "","" + total); } } } return String.valueOf(hashSet.size()); } private int leftMove(int number, int count) { number = number * (int) (Math.pow(10, count)); return number; } private int rightMove(int number, int count) { if (count == 0) { return number; } number = (number / (int) (Math.pow(10, count))); return number; } } " B21139,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class CRecycled { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""C-large.in"")); PrintWriter out = new PrintWriter(""C-large.out""); final int T = in.nextInt(); //final int T = 50; for (int t = 1; t <= T; ++t) { final int A = in.nextInt(), B = in.nextInt(); // final int A = 1000000, B = 2000000; int result = 0; for (int n = A; n <= B; ++n) { String s = Integer.toString(n); Set ms = new HashSet(); for (int i = 0; i+1 < s.length(); ++i) { s = s.substring(1) + s.charAt(0); int m = Integer.parseInt(s); if (m > n && m <= B && s.charAt(0) != '0') { ms.add(m); } } result += ms.size(); } out.println(""Case #"" + t + "": "" + result); } out.close(); } } " B20963,"import java.util.LinkedList; import java.util.Scanner; public class problemC { static final int until = 2000000; static LinkedList res[] = new LinkedList[until+1]; static Object speed[][] = new Object[until+1][]; public static void main(String []args) { for(int i=1;i<=until;i++) GO(i); for(int i=1;i<=until;i++) speed[i] = res[i].toArray(); Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); for(int num=1;num<=N;num++) { int ret = 0; int A = scanner.nextInt(); int B = scanner.nextInt(); for(int i=A;i<=B;i++) { int len = res[i].size(); for(int j=0;j(); String str = Integer.toString(num); int len = str.length(); for(int i=0;inum) res[num].add(rev); } } } " B21838,"import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Hashtable; import java.util.Scanner; import java.util.TreeSet; public class RecycleNumber { private static TreeSet result = new TreeSet(); private static Hashtable resultingString ; private static Hashtable> reverseMapping ; private static ArrayList values = new ArrayList(); private static int totalCount = 1 ; public static void main(String[] args) throws FileNotFoundException { new RecycleNumber().doProcessing(new File(""D:\\codejam\\C\\sample.txt"")); //reverseString(""1512"", ""5121"",100,500); } public void doProcessing(File inputFile) throws FileNotFoundException { Scanner scanner = new Scanner(inputFile).useDelimiter(""\n""); if (scanner != null) { int totalCases = Integer.parseInt(scanner.next().trim()); int k = 1; if (totalCases > 0) { while (scanner.hasNext()) { String[] rowValues = scanner.next().trim().split("" ""); int lowerLimit = Integer.parseInt(rowValues[0].trim()); int upperLimit = Integer.parseInt(rowValues[1].trim()); int successCase = getReverCount(lowerLimit, upperLimit); // System.out.println(""Case #Lower Limit ; "" + lowerLimit + // "" : Upper Limit = "" + upperLimit + "" "" + k++ + "": "" + // successCase); System.out.println(""Case #"" + k++ + "": "" + successCase); } } } scanner.close(); } public int getReverCount(int lowerNumber, int upperLimit) { //int count = 0; //int nums = 0; resultingString = new Hashtable(); reverseMapping = new Hashtable>(); values = new ArrayList(); for (int i = lowerNumber; i <= upperLimit; i++) { //System.out.println(""@@@@@@@@@@"" + i); //showPattern("""", String.valueOf(i),i,lowerNumber,upperLimit); String val = String.valueOf(i); //System.out.println(""String value of "" + i + "" is "" + val); char firstChar = val.charAt(val.length() - 1); // System.out.println(""First Char = "" + firstChar); String subString = val.substring(0, val.length() - 1); // System.out.println(""Sub String = "" + subString); reverseString(val, new String(firstChar + subString), upperLimit, lowerNumber); } //System.out.println(""Possibilities = "" + result.size() + "" Lower Num = "" + lowerNumber + "" : Upper Lim "" + upperLimit + ""\n "" + resultingString + ""\n Reverse Mappings : "" + reverseMapping); result = new TreeSet(); //System.out.println(""Total Counts : "" + values.size()); // System.out.println(""Numbers : "" + nums); return resultingString.size(); } public static boolean containsReverseEntry(int key, int val){ boolean contains = false ; ArrayList arrayList = reverseMapping.get(key); if (arrayList != null){ contains = arrayList.contains(val); } return contains ; } public static void makeReverseEntry(int key, int value){ ArrayList arrayList = reverseMapping.get(key); if (arrayList == null){ arrayList = new ArrayList(); } arrayList.add(value); reverseMapping.put(key, arrayList); //System.out.println(""List "" + reverseMapping); } public static void reverseString(String orgString, String val, int upperLimit, int lowerLimit){ if (orgString.equals(val)){ return ; }else{ int formatedValue = Integer.parseInt(val); // System.out.println(""Original Value = "" + orgString + "" : Formated Value = "" + formatedValue + "" Upper Limit = "" + upperLimit + "" : Lower Limit - "" + lowerLimit ); if (formatedValue >= lowerLimit && formatedValue <= upperLimit){ int integer = 0 ; int orgValue = Integer.parseInt(orgString); boolean containsReverseEntry = containsReverseEntry(orgValue,formatedValue); if ( !containsReverseEntry){ values.add(formatedValue); //System.out.println(""Placing Value - ("" + orgString + "","" + formatedValue + "") "" + totalCount++); resultingString.put(orgValue, formatedValue); //reverseMapping.put(formatedValue, orgValue); makeReverseEntry(formatedValue, orgValue); // System.out.println(""Placing Value - ("" + orgString + "","" + formatedValue + "") Total Count "" + totalCount ); //System.out.println(""Placing Reverse Value - ("" + formatedValue + "","" + orgString + "") Total Count "" + totalCount++ ); } } char firstChar = val.charAt(val.length() - 1); // System.out.println(""First Char = "" + firstChar); String subString = val.substring(0, val.length() - 1); // System.out.println(""Sub String = "" + subString); reverseString(orgString, new String(firstChar + subString), lowerLimit, upperLimit); } } public void showPattern(String st, String chars, int baseString, int lowerLimit, int upperLimit) { if (chars.length() <= 1){ result.add(st + chars); int palString = Integer.parseInt(st + chars); if (palString < upperLimit && palString != baseString && palString > lowerLimit && resultingString.get(palString) == null ){ resultingString.put(baseString, palString); values.add(palString); } System.out.println(st + chars); }else for (int i = 0; i < chars.length(); i++) { try { String newString = chars.substring(0, i) + chars.substring(i + 1); showPattern(st + chars.charAt(i), newString,baseString,lowerLimit,upperLimit); } catch (Exception e) { e.printStackTrace(); } } } public int reverseInteger(int number) { int reverse = 0; while (number != 0) { reverse = reverse * 10; reverse = reverse + number % 10; number = number / 10; } return reverse; } } " B21080,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlejam3; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; /** * * @author Nomeir */ public class GoogleJam3 { private String inputFile = ""C-large.in""; // "".\\C-small-attempt0.in""; // "".\\test3.in""; private String outputFile = "".\\out.txt""; private String line = ""start""; private FileReader reader; private BufferedReader buffer; private FileWriter writer; private BufferedWriter printer; public GoogleJam3() { try { new File(outputFile).createNewFile(); reader = new FileReader(inputFile); buffer = new BufferedReader(reader); new File(outputFile).createNewFile(); writer = new FileWriter(outputFile); printer = new BufferedWriter(writer); } catch (IOException ex) { System.out.println(""The file couldn't be created ...""); } } public void endOperations() { try { if (reader != null) { reader.close(); } if (buffer != null) { buffer.close(); } if (printer != null) { printer.flush(); printer.close(); } if (writer != null) { writer.close(); } } catch (IOException ex) { ex.printStackTrace(); } } int lines; public void readInfo() { try { line = buffer.readLine(); if (line != null) { lines = Integer.valueOf(line); // int i = 0, j = 0; // L = Integer.valueOf(line.substring(0, i = line.indexOf("" ""))); // D = Integer.valueOf(line.substring(++i, j = line.indexOf("" "", i))); // N = Integer.valueOf(line.substring(++j, line.length())); } } catch (FileNotFoundException ex) { System.err.println(""Source file not found .. !""); } catch (IOException e) { e.printStackTrace(); } catch (StringIndexOutOfBoundsException e) { e.printStackTrace(); } } int aMinValue, bMaxValue, aMovingValue; int nMinValue, mMaxValue; String aStr, bStr; int t1, t2, searchIndex; ArrayList keys, values; ArrayList ab; private void readInfoLines() { try { for (int i = 0; i < lines;) { line = buffer.readLine(); ab = new ArrayList(); recurser(line, ab); aMinValue = ab.get(0); aMovingValue = aMinValue; bMaxValue = ab.get(1); bStr = bMaxValue + """"; keys = new ArrayList(); values = new ArrayList(); if (bStr.length() > 1 && aMinValue < bMaxValue) { for (; aMovingValue <= bMaxValue; aMovingValue++) { aStr = aMovingValue + """"; if (aStr.length() > 1) { for (int j = 1; j < aStr.length(); j++) { nMinValue = aMovingValue; mMaxValue = Integer.parseInt(aStr.substring(j, aStr.length()) + aStr.substring(0, j)); if (mMaxValue > bMaxValue || mMaxValue < aMinValue) { continue; } if (nMinValue < mMaxValue) { searchIndex = Collections.binarySearch(keys, nMinValue); if (searchIndex >= 0 && values.get(searchIndex) == mMaxValue) { } else { keys.add(nMinValue); values.add(mMaxValue); } } } } } } printer.write(""Case #"" + ++i + "": "" + keys.size()); printer.newLine(); } } catch (IOException ex) { ex.printStackTrace(); } } public void recurser(String s, ArrayList links) { int i = 0, k = 0; if (s != null) { if ((i = s.indexOf("" "")) >= 0) { if (links.size() == 0) { links.add(Integer.valueOf("""" + s.substring(0, i))); } if ((k = s.indexOf("" "", ++i)) >= 0) { links.add(Integer.valueOf("""" + s.substring(i, k))); s = s.substring(k); recurser(s, links); } else { links.add(Integer.valueOf(s.substring(i, s.length()))); } } } } /** * @param args the command line arguments */ public static void main(String[] args) { long t = System.currentTimeMillis(); GoogleJam3 obj = new GoogleJam3(); obj.readInfo(); obj.readInfoLines(); // obj.printTestCases(); obj.endOperations(); t = System.currentTimeMillis() - t; System.out.println(""Time elapsed "" + t); } } " B22087,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; public class Main { /** * @param args */ public static int numShift(int A, int digit){ int num = 0, div; num = A %10; div = A /10; for(int i=1; i < digit ; i++) { num = num*10; } num = num + div; return num; } public static int recycleCount(int A, int B) { int count = 0; int num = A; String digit = """" + A; do { num = numShift(num, digit.length()); if(num > A && num <= B) count++; }while(num != A); //System.out.print(""Count: "" + count + ""\n""); return count; } public static void runCase(int A, int B, int casenum) { int count =0; for(int i=A; i numbers = new HashSet(); static BitSet numberBitmap = new BitSet(10000000); /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { int testCaseCount; try { String input = IN.readLine(); testCaseCount = Integer.parseInt(input); } catch (Exception e) { testCaseCount = 0; } if (testCaseCount > 0) { long start = System.currentTimeMillis(); int[][] minMax = new int[testCaseCount][3]; for (int i = 0; i < testCaseCount; i++) { String[] values = IN.readLine().split("" ""); minMax[i][0] = Integer.parseInt(values[0]); minMax[i][1] = Integer.parseInt(values[1]); } for (int i = 0; i < testCaseCount; i++) { minMax[i][2] = findRecycledPairsCount(minMax[i][0], minMax[i][1]); printLn(""Case #%d: %d"", i + 1, minMax[i][2]); } long end = System.currentTimeMillis(); //System.err.println((end - start)); } } static int findRecycledPairsCount(int min, int max) throws NumberFormatException, IOException { HashMap duplicateMap = new HashMap(); int digitCount = getNumberOfDigits(min); numberBitmap.clear(); for (int number = min; number <= max; number++) { if (!numberBitmap.get(number)) { RotatedNumbers rNumber = getRotatedNumbersInRange(number, digitCount, min, max); if (rNumber.count > 1) { duplicateMap.put(rNumber.minimum, rNumber.count); } } } int count = 0; for (Byte b : duplicateMap.values()) { if (b > 1) { count += b == 2 ? 1 : getNC2(b); } } return count; } static int getNC2(int n) { return (int) ((n / 2.0) * (n - 1)); } static int getNumberOfDigits(int number) { int digitCount = 0; while (number > 0) { digitCount++; number /= 10; } return digitCount; } public static RotatedNumbers getRotatedNumbersInRange(int number, int digitCount, int min, int max) { int index = digitCount - 1; int[] digits = new int[digitCount]; int temp = number; while (temp > 0) { digits[index--] = temp % 10; temp /= 10; } int minVal = number; numbers.clear(); for (int start = 0; start < digitCount; start++) { int numVal = 0; for (int j = 0; j < digitCount; j++) { int digit = digits[(start + j) % digitCount]; numVal *= 10; numVal += digit; } numberBitmap.set(numVal); if (numVal >= min && numVal <= max) { numbers.add(numVal); } if (numVal < minVal) { minVal = numVal; } } return new RotatedNumbers(minVal, (byte) numbers.size()); } // to ensure that '\n' is used as EOL on my Windows Machine, just to be sure ;) // static void printLn(String val) { System.out.print(val); System.out.print('\n'); } static void printLn(String format, Object ... args) { System.out.print(String.format(format, args)); System.out.print('\n'); } static class RotatedNumbers { public RotatedNumbers(int minimum, byte count) { this.minimum = minimum; this.count = count; } int minimum; byte count; } } " B21353,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RecycledNumbers { private static int noOfDigits(int n){ if (n < 10) return 1; return 1 + noOfDigits(n/10); } private static int raisedTo(int n, int m){ if (n==0) return 0; else if (m==0) return 1; else if (m==1) return n; return n*raisedTo(n, m-1); } private static int rotateBy(int n, int s, int nod){ if (s == 0) return n; int N = noOfDigits(n); int pow = raisedTo(10, nod-1); int MSB = (N==nod)? n/pow: 0; return rotateBy((n%pow)*10+MSB, s-1, nod); } private static int[] giveDistinctNos(int n, int min, int max){ int s = 0, r = n, j=0; int N = noOfDigits(r); int A[] = new int[N]; for (int i=0; imax || N != noOfDigits(r)) r = rotateBy(r, 1, N); } return A; } private static int nC2(int n){ return n*(n-1)/2; } public static void main(String[] args) throws NumberFormatException, IOException { // for (int i=0; i< 2000000; i++); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int T = new Integer(in.readLine()).intValue(); int A = 0, B = 0, ans = 0; String str[]; int X[]; for (int i=0; i used = new HashSet(); for (int n = A; n < B; n++) { int m = n; for (int i = 0; i < l; i++) { m = m/10 + (m%10)*ml; if (n < m && m <= B) used.add(new Pair(n,m)); } } return used.size(); } private static Scanner sc; private static PrintWriter fw; public static void main(String[] args) throws Exception { String inFile; // inFile = ""input.txt""; // inFile = ""C-small-attempt0.in""; inFile = ""C-large.in""; // sc = new Scanner(System.in); sc = new Scanner(new FileInputStream(inFile)); fw = new PrintWriter(new FileWriter(""output.txt"", false)); int N = sc.nextInt(); sc.nextLine(); for (int cas = 1; cas <= N; cas++) { fw.print(""Case #"" + cas + "": ""); // fw.println(""Case #"" + cas + "": ""); Object res = new C().solve(); if (res instanceof Double) fw.printf(""%.10f\n"", res); else fw.printf(""%s\n"", res); fw.flush(); } fw.close(); sc.close(); } } " B22121,"package com.google.codejam.recycle; /** * Class to represent each test case. * It will hold details like test case no, input to be operated and TestResult. * @author Sushant Deshpande * */ public class TestCase { /** * Variable to hold value for test case number. */ private int caseNo; /** * Variable to hold lower limit. */ private int low; /** * Variable to hold upper limit. */ private int high; /** * Variable holding test case result. */ private TestResult output; /** * Constructor for creating TestCase with case no. * @param caseNo int * @param low int * @param high int */ public TestCase(final int caseNo, final int low, final int high) { this.caseNo = caseNo; this.low = low; this.high = high; } /** * Settter method for TestResult. * @param output TestResult */ public final void setOutput(final TestResult output) { this.output = output; } public int getHigh() { return high; } public int getLow() { return low; } /** * Method to format the test output for printing in the report. * @return String formatted output for the given input. */ public final String printTestResult() { StringBuilder resultBuilder = new StringBuilder(""Case #""); resultBuilder.append(caseNo).append("": ""); resultBuilder.append(output.getTestOutput()).append(""\n""); return resultBuilder.toString(); } }" B21000,"import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class GCJ2012QA { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(8); Scanner sc = new Scanner(new FileReader(""A-input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""A-output.txt"")); final int CASE_COUNT = sc.nextInt(); for(int caseNum = 1; caseNum <= CASE_COUNT; caseNum++) { pw.print(""Case #"" + caseNum + "": ""); int ans = 0; int A = sc.nextInt(); int B = sc.nextInt(); //int toGo = A + ((B - A) / 2); List> ress = new ArrayList>(); for(int i = A; i <= B; i++) { Future resf = executor.submit(new Calculate(A, B, i)); ress.add(resf); } for(Future aa : ress){ ans += aa.get(); } // PUT ANSWER HERE pw.println(ans); } executor.awaitTermination(100, TimeUnit.MILLISECONDS); executor.shutdown(); pw.flush(); pw.close(); sc.close(); } private static class Calculate implements Callable{ final int A, B, num; public Calculate(int A, int B, int i){ this.A = A; this.B = B; this.num = i; } @Override public Integer call() throws Exception { return rotateCount(A, B, num); } } private static int rotateCount(int A, int B, int num) { Set cache = new HashSet(); if(num < 10) { return 0; } int res = 0; char[] a = String.valueOf(num).toCharArray(); int size = a.length; for(int i = 1; i < size; i++) { int kk = Integer.parseInt(rotate(a,1)); //System.out.println(num + "" ("" + Thread.currentThread().getName() + "") "" + kk); if(kk > num && kk <= B && !cache.contains(kk)) { //System.out.println(num + "","" + kk); res++; cache.add(kk); } } return res; } private static String rotate( final char[] a, final int n ) { for(int i = 0; i < n; i++) { char tmp = a[a.length-1]; for(int j = a.length-1; j >= 0; j--) { a[j] = j == 0 ? tmp : a[(j-1+a.length)%a.length]; } } return new String(a); } } " B22159,"package com.vp.common; import com.vp.fact.SolutionFactory; import com.vp.iface.Problem; public class ExecutorApp { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String inputFileName = ""C:/Workspace/GCJ2012/src/com/vp/data/sample_input.txt""; String outputFileName = ""C:/Users/dhananitin/Desktop/sample_output.txt""; //String outputFileName = ""C:/Workspace/GCJ2012/src/com/vp/data/sample_output.txt""; InputOutputProcessor inputOutputProcessor = new InputOutputProcessor(); inputOutputProcessor.initializeInput(inputFileName); int numberOfCases = inputOutputProcessor.getNumberOfCases(); String[] resultArray = new String[numberOfCases]; inputOutputProcessor.setDoesInputHaveDataSetLines(false); //inputOutputProcessor.setIndexOfDataSetLine(0); inputOutputProcessor.setNumberOfDataSetLines(1); for (int i = 1; i <= numberOfCases; i++) { try { String[] dataSet = inputOutputProcessor.getDataSet(); Problem problem = SolutionFactory.getInstance(Problem.RECYCLENUMBERS); resultArray[i-1] = ""Case #""+i+"": ""+ problem.solve(dataSet); } catch (Exception exp) { exp.printStackTrace(); inputOutputProcessor.closeScanner(); } } inputOutputProcessor.closeScanner(); inputOutputProcessor.writeOutput(outputFileName, resultArray); } } " B22018,"import java.awt.datatransfer.StringSelection; import java.util.*; public class q3 { public static void main(String[] args) { new q3().run(); } Scanner input = new Scanner(System.in); void run(){ int c = input.nextInt(); for(int i=1;i<=c;i++){ System.out.print(""Case #""+i+"": ""); solve(); } } void solve(){ int a = input.nextInt(); int b = input.nextInt(); boolean [] used = new boolean [b+1]; int ans = 0; String x; int i,j,k,y; for(i=a;i<=b;i++){ x = Integer.toString(i);; for(j=1;j<=x.length()-1;j++){ y = recycled(x,j); //System.out.println(y); if(y >= a && y <= b && !used[y] && i!=y){ //System.out.println(i +"" ""+y); ans++; } } used[i] = true; } System.out.println(ans); } int recycled(String x,int n){ String f = x.substring(x.length()-n,x.length()); int i; for(i=0;i n && reCycled <= B) sum++; } } System.out.println(sum); } } private boolean isRecycled(int n, int m) { if (!isPermutation(n, m)) return false; String N = String.valueOf(n); String M = String.valueOf(m); for(int i = 1; i < N.length(); i++) { String reCycled = rotate(N, i); if(reCycled.equals(M)) { return true; } } return false; } public static boolean isPermutation(int n, int m) { int[] digitsN = new int[10]; int[] digitsM = new int[10]; while(n != 0) { digitsN[n % 10]++; n = n / 10; } while(m != 0) { digitsM[m % 10]++; m = m / 10; } return Arrays.equals(digitsN, digitsM); } public static String rotate(String n, int i) { String lastIChars = n.substring(n.length() - i); String firstIChars = n.substring(0, n.length() - i); return lastIChars + firstIChars; } } " B22119,"package com.google.codejam.recycle; import java.io.BufferedWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.List; /** * * Class to generate Test Report. * @author Sushant Deshpande */ public class OutputRecorder { /** * Method for generating Test Report. * @param testCases List list of test cases for report is to be generated. * @param outputFile String output file for writing TestReport. */ public static void generateTestReport(final List testCases, final String outputFile) { BufferedWriter writer = null; try { writer = new BufferedWriter(new PrintWriter(outputFile)); for(TestCase testCase : testCases) { writer.write(testCase.printTestResult()); writer.flush(); } writer.flush(); } catch(IOException ie) { System.out.println(""Some error occured while generating test report "" + ie.getMessage()); System.out.println(""Printing result to standard output""); for(TestCase testCase : testCases) { System.out.println(testCase.printTestResult()); } } finally { if(writer != null) { try { writer.close(); } catch(IOException ie) { System.out.println(""Some error occured while closing output stream""); } } } } }" B20505,"import java.io.BufferedReader; import java.io.FileReader; public class RecycledNumberTest { public static void main(String[] args) { int numCase = 0; int caseIndex = 0; int[] minValues = null; int[] maxValues = null; try { FileReader reader = new FileReader(""C:\\Users\\CheeMeng\\Downloads\\C-large.in""); BufferedReader br = new BufferedReader(reader); String s = br.readLine(); numCase = new Integer(s).intValue(); minValues = new int[numCase]; maxValues = new int[numCase]; while((s = br.readLine()) != null) { String s1[] = s.split("" ""); minValues[caseIndex] = new Integer(s1[0]).intValue(); maxValues[caseIndex] = new Integer(s1[1]).intValue(); caseIndex++; } reader.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // numCase = 7; // minValues = new int[numCase]; // maxValues = new int[numCase]; // minValues[0] = 1; // maxValues[0] = 9; // minValues[1] = 10; // maxValues[1] = 40; // minValues[2] = 100; // maxValues[2] = 500; // minValues[3] = 1111; // maxValues[3] = 2222; // minValues[4] = 12345; // maxValues[4] = 67890; // minValues[5] = 111111; // maxValues[5] = 222222; // minValues[6] = 1111111; // maxValues[6] = 1999999; for (int i = 1; i <= numCase; i++) { System.out.println(""Case #"" + i + "": "" + recycledTest(minValues[i - 1], maxValues[i - 1])); } } public static int recycledTest(int min, int max) { int count = 0; int numDigits = (int) Math.ceil(Math.log10((float) max)); if (numDigits == 1) { return count; } int[] recycledNum = new int[numDigits - 1]; if (numDigits == 2) { for (int a0 = 1; a0 <= 9; a0++) { for (int a1 = 0; a1 <= 9; a1++) { if (a0 < a1) { int actualNum = 10 * a0 + a1; recycledNum[0] = 10 * a1 + a0; if ((actualNum >= min) && (actualNum <= max) && (recycledNum[0] >= min) && (recycledNum[0] <= max) && (actualNum < recycledNum[0])) { count++; } } } } } else if (numDigits == 3) { for (int a0 = 1; a0 <= 9; a0++) { for (int a1 = 0; a1 <= 9; a1++) { for (int a2 = 0; a2 <= 9; a2++) { int actualNum = 100 * a0 + 10* a1 + a2; recycledNum[0] = 100 * a1 + 10 * a2 + a0; recycledNum[1] = 100 * a2 + 10 * a0 + a1; if (a1 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[0] >= min) && (recycledNum[0] <= max) && (actualNum < recycledNum[0])) { count++; } } if (a2 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[1] >= min) && (recycledNum[1] <= max) && (actualNum < recycledNum[1])) { if (recycledNum[1] != recycledNum[0]) { count++; } } } } } } } else if (numDigits == 4) { for (int a0 = 1; a0 <= 9; a0++) { for (int a1 = 0; a1 <= 9; a1++) { for (int a2 = 0; a2 <= 9; a2++) { for (int a3 = 0; a3 <= 9; a3++) { int actualNum = 1000 * a0 + 100 * a1 + 10 * a2 + a3; recycledNum[0] = 1000 * a1 + 100 * a2 + 10 * a3 + a0; recycledNum[1] = 1000 * a2 + 100 * a3 + 10 * a0 + a1; recycledNum[2] = 1000 * a3 + 100 * a0 + 10 * a1 + a2; if (a1 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[0] >= min) && (recycledNum[0] <= max) && (actualNum < recycledNum[0])) { count++; } } if (a2 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[1] >= min) && (recycledNum[1] <= max) && (actualNum < recycledNum[1])) { if (recycledNum[1] != recycledNum[0]) { count++; } } } if (a3 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[2] >= min) && (recycledNum[2] <= max) && (actualNum < recycledNum[2])) { if ((recycledNum[2] != recycledNum[0]) && (recycledNum[2] != recycledNum[1])) { count++; } } } } } } } } else if (numDigits == 5) { for (int a0 = 1; a0 <= 9; a0++) { for (int a1 = 0; a1 <= 9; a1++) { for (int a2 = 0; a2 <= 9; a2++) { for (int a3 = 0; a3 <= 9; a3++) { for (int a4 = 0; a4 <= 9; a4++) { int actualNum = 10000 * a0 + 1000 * a1 + 100 * a2 + 10 * a3 + a4; recycledNum[0] = 10000 * a1 + 1000 * a2 + 100 * a3 + 10 * a4 + a0; recycledNum[1] = 10000 * a2 + 1000 * a3 + 100 * a4 + 10 * a0 + a1; recycledNum[2] = 10000 * a3 + 1000 * a4 + 100 * a0 + 10 * a1 + a2; recycledNum[3] = 10000 * a4 + 1000 * a0 + 100 * a1 + 10 * a2 + a3; if (a1 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[0] >= min) && (recycledNum[0] <= max) && (actualNum < recycledNum[0])) { count++; } } if (a2 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[1] >= min) && (recycledNum[1] <= max) && (actualNum < recycledNum[1])) { if (recycledNum[1] != recycledNum[0]) { count++; } } } if (a3 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[2] >= min) && (recycledNum[2] <= max) && (actualNum < recycledNum[2])) { if ((recycledNum[2] != recycledNum[0]) && (recycledNum[2] != recycledNum[1])) { count++; } } } if (a4 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[3] >= min) && (recycledNum[3] <= max) && (actualNum < recycledNum[3])) { if ((recycledNum[3] != recycledNum[0]) && (recycledNum[3] != recycledNum[1]) && (recycledNum[3] != recycledNum[2])) { count++; } } } } } } } } } else if (numDigits == 6) { for (int a0 = 1; a0 <= 9; a0++) { for (int a1 = 0; a1 <= 9; a1++) { for (int a2 = 0; a2 <= 9; a2++) { for (int a3 = 0; a3 <= 9; a3++) { for (int a4 = 0; a4 <= 9; a4++) { for (int a5 = 0; a5 <= 9; a5++) { int actualNum = 100000 * a0 + 10000 * a1 + 1000 * a2 + 100 * a3 + 10 * a4 + a5; recycledNum[0] = 100000 * a1 + 10000 * a2 + 1000 * a3 + 100 * a4 + 10 * a5 + a0; recycledNum[1] = 100000 * a2 + 10000 * a3 + 1000 * a4 + 100 * a5 + 10 * a0 + a1; recycledNum[2] = 100000 * a3 + 10000 * a4 + 1000 * a5 + 100 * a0 + 10 * a1 + a2; recycledNum[3] = 100000 * a4 + 10000 * a5 + 1000 * a0 + 100 * a1 + 10 * a2 + a3; recycledNum[4] = 100000 * a5 + 10000 * a0 + 1000 * a1 + 100 * a2 + 10 * a3 + a4; if (a1 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[0] >= min) && (recycledNum[0] <= max) && (actualNum < recycledNum[0])) { count++; } } if (a2 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[1] >= min) && (recycledNum[1] <= max) && (actualNum < recycledNum[1])) { if (recycledNum[1] != recycledNum[0]) { count++; } } } if (a3 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[2] >= min) && (recycledNum[2] <= max) && (actualNum < recycledNum[2])) { if ((recycledNum[2] != recycledNum[0]) && (recycledNum[2] != recycledNum[1])) { count++; } } } if (a4 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[3] >= min) && (recycledNum[3] <= max) && (actualNum < recycledNum[3])) { if ((recycledNum[3] != recycledNum[0]) && (recycledNum[3] != recycledNum[1]) && (recycledNum[3] != recycledNum[2])) { count++; } } } if (a5 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[4] >= min) && (recycledNum[4] <= max) && (actualNum < recycledNum[4])) { if ((recycledNum[4] != recycledNum[0]) && (recycledNum[4] != recycledNum[1]) && (recycledNum[4] != recycledNum[2]) && (recycledNum[4] != recycledNum[3])) { count++; } } } } } } } } } } else if (numDigits == 7) { for (int a0 = 1; a0 <= 1; a0++) { for (int a1 = 0; a1 <= 9; a1++) { for (int a2 = 0; a2 <= 9; a2++) { for (int a3 = 0; a3 <= 9; a3++) { for (int a4 = 0; a4 <= 9; a4++) { for (int a5 = 0; a5 <= 9; a5++) { for (int a6 = 0; a6 <= 9; a6++) { int actualNum = 1000000 * a0 + 100000 * a1 + 10000 * a2 + 1000 * a3 + 100 * a4 + 10 * a5 + a6; recycledNum[0] = 1000000 * a1 + 100000 * a2 + 10000 * a3 + 1000 * a4 + 100 * a5 + 10 * a6 + a0; recycledNum[1] = 1000000 * a2 + 100000 * a3 + 10000 * a4 + 1000 * a5 + 100 * a6 + 10 * a0 + a1; recycledNum[2] = 1000000 * a3 + 100000 * a4 + 10000 * a5 + 1000 * a6 + 100 * a0 + 10 * a1 + a2; recycledNum[3] = 1000000 * a4 + 100000 * a5 + 10000 * a6 + 1000 * a0 + 100 * a1 + 10 * a2 + a3; recycledNum[4] = 1000000 * a5 + 100000 * a6 + 10000 * a0 + 1000 * a1 + 100 * a2 + 10 * a3 + a4; recycledNum[5] = 1000000 * a6 + 100000 * a0 + 10000 * a1 + 1000 * a2 + 100 * a3 + 10 * a4 + a5; if (a1 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[0] >= min) && (recycledNum[0] <= max) && (actualNum < recycledNum[0])) { count++; } } if (a2 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[1] >= min) && (recycledNum[1] <= max) && (actualNum < recycledNum[1])) { if (recycledNum[1] != recycledNum[0]) { count++; } } } if (a3 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[2] >= min) && (recycledNum[2] <= max) && (actualNum < recycledNum[2])) { if ((recycledNum[2] != recycledNum[0]) && (recycledNum[2] != recycledNum[1])) { count++; } } } if (a4 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[3] >= min) && (recycledNum[3] <= max) && (actualNum < recycledNum[3])) { if ((recycledNum[3] != recycledNum[0]) && (recycledNum[3] != recycledNum[1]) && (recycledNum[3] != recycledNum[2])) { count++; } } } if (a5 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[4] >= min) && (recycledNum[4] <= max) && (actualNum < recycledNum[4])) { if ((recycledNum[4] != recycledNum[0]) && (recycledNum[4] != recycledNum[1]) && (recycledNum[4] != recycledNum[2]) && (recycledNum[4] != recycledNum[3])) { count++; } } } if (a6 > 0) { if ((actualNum >= min) && (actualNum <= max) && (recycledNum[5] >= min) && (recycledNum[5] <= max) && (actualNum < recycledNum[5])) { if ((recycledNum[5] != recycledNum[0]) && (recycledNum[5] != recycledNum[1]) && (recycledNum[5] != recycledNum[2]) && (recycledNum[5] != recycledNum[3]) && (recycledNum[5] != recycledNum[4])) { count++; } } } } } } } } } } } return count; } } " B20380,"import java.io.*; public class RecycledNumbers { public void RecycledNumbers()throws IOException { FileInputStream fstream = new FileInputStream(""C:/Users/m.l/Desktop/C-large.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int T=Integer.parseInt(br.readLine()); String S[]=new String[T];int i,j,k,s,l,p,q,A=0,B=0;String a,temp1; for(i=0;ij&&temp2[p]<=B&&temp2[p]>=A) for(q=p+1;q= a && val <= b && !s.substring(i).concat(s.substring(0, i)).startsWith(""0"") && val > x && lastAchivement[val] != x) { res++; lastAchivement[val] = x; // out.println(x + "" and "" + val); } } return res; } PrintWriter out; void solve() throws FileNotFoundException { Scanner in = new Scanner(new FileReader(""src/input.txt"")); out = new PrintWriter(new FileOutputStream(""src/output.txt""));; int testCases = in.nextInt(); for (int t = 1; t <= testCases; t++) { int a = in.nextInt(); int b = in.nextInt(); lastAchivement = new int[b + 1]; int res = 0; for (int i = a; i <= b; i++) res += calculate(i, a, b); out.println(""Case #"" + t + "": "" + res); } in.close(); out.close(); } } " B20044,"import java.io.*; import java.util.*; public class CodeJamC { private static int noOfDigits(int number) { int noOfDigits = 0; while (number > 0) { number /= 10; noOfDigits++; } return noOfDigits; } private static int pow(int exponent) { int power = 1; for (int mulitply = 1; mulitply <= exponent; mulitply++) power *= 10; return power; } private static int countPairs(int A, int B) { int noOfDigits = noOfDigits(A); int noOfPairs = 0; int places = pow(noOfDigits); for (int next = A; next < B; next++) { HashSet used = new HashSet(); // System.out.println(""Next ""+ next); for (int back = 10; back < places; back *= 10) { int recycled = shift(next, back, places / back); // System.out.println(""Back: "" + back + ""RC "" + recycled); if (recycled > next && recycled <= B) { // System.out.println(next +"", "" + recycled); if (!used.contains(recycled)) { used.add(recycled); noOfPairs++; } } } } return noOfPairs; } private static int shift(int number, int back, int front) { return (number % back) * front + number / back; } /** * @param args */ public static void main(String[] args) throws IOException { String fileName = ""C-large""; Scanner in = new Scanner(new File(fileName + "".in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter( fileName + "".out""))); // Keep track of time for efficiency long startTime = System.currentTimeMillis(); // Process each of the test cases int noOfCases = in.nextInt(); for (int caseNo = 1; caseNo <= noOfCases; caseNo++) { int A = in.nextInt(); int B = in.nextInt(); int noOfPairs = countPairs(A, B); System.out.println(""Case #"" + caseNo + "": "" + noOfPairs); out.println(""Case #"" + caseNo + "": "" + noOfPairs); } System.out.println(""Done""); long stopTime = System.currentTimeMillis(); System.out.println(""Time: "" + (stopTime - startTime) / 1000.0); // Close the files in.close(); out.close(); } } " B21243,"import java.util.HashSet; import java.util.Scanner; public class problemC { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner cin = new Scanner(System.in); int t = cin.nextInt(), a, b, c, i, ten, len, q, j = 0, ans, ts, k = 0; while (t > 0) { t--; k++; ten = 1; len = 1; a = cin.nextInt(); b = cin.nextInt(); c = a; ans = 0; while (c > 9) { c /= 10; ten *= 10; len++; } HashSet hash = new HashSet(); for (i = a; i <= b; i++) { if (!hash.contains(i)) { hash.add(i); ts = 1; j = i; for (q = 0; q < len; q++) { j = (j % ten) * 10 + j / ten; if (j >= a && j <= b && !hash.contains(j)) { ts++; hash.add(j); } } ans += ts * (ts - 1) / 2; } } System.out.println(""Case #"" + k + "": "" + ans); } } } " B21872,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class C { /** * @param args */ public static String rest(ArrayList list) { String n = list.get(0); list.remove(0); return n; }; public static void main(String[] args) { // TODO Auto-generated method stub String line; ArrayList liste = new ArrayList(); BufferedReader buffer = null; try { buffer = new BufferedReader(new FileReader(new File(args[0]))); for (int i = 0; (line = buffer.readLine()) != null; i++) { liste.add(line); } } catch (IOException e) { System.out.println(""IO-Fehler!""); } int anzahl = Integer.parseInt(rest(liste)); // fuer jeden Fall methode aufrufen for (int i = 0; i < anzahl; i++) { methode(i + 1, liste); } } // spezifische code fŸr alle aufgaben public static void methode(int nummer, ArrayList liste) { // buffer und input machen // input ist ein stringarray mit meiner ersten Zeile // String[] input = rest(liste); String[] input = rest(liste).split("" ""); ArrayList arraylist = new ArrayList(); for (int i = 0; i < input.length; i++) { int n = Integer.parseInt(input[i]); arraylist.add(n); } int a = arraylist.get(0); int b = arraylist.get(1); int sum = 0; for (int i = a; i < b; i++) { StringBuilder builder = new StringBuilder(Integer.toString(i)); ArrayList ergebnisse = new ArrayList(); for (int k = 1; k < builder.length(); k++) { if ((Integer.parseInt(umdudeln(builder, k).toString()) > i) && (Integer.parseInt(umdudeln(builder, k).toString()) <= b)) { if (!(ergebnisse.contains(Integer.parseInt(umdudeln(builder,k).toString())))){ sum=sum +1; }; ergebnisse.add(Integer.parseInt(umdudeln(builder,k).toString())); // System.out.println(umdudeln(builder, k).toString()); } } ; } System.out.println(""Case #"" + nummer + "": "" + sum); } public static StringBuilder umdudeln(StringBuilder builder, int i) { if (builder.length() == 1) { return builder; } String eins = builder.substring(0, builder.length() - i); String zwei = builder.substring(builder.length() - i); StringBuilder newbuilder = new StringBuilder(zwei.concat(eins)); // System.out.println("" "" + builder + "" "" + eins + "" "" + zwei + "" "" + newbuilder); return newbuilder; } } " B21563," import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String args[]) throws Exception { final String PATH = ""/home/goalboy/software installation/codejam-commandline-1.0-beta4/source/""; final String FILE = ""C-large-0""; Scanner in = new Scanner(new File(PATH + FILE + "".in"")); PrintWriter out = new PrintWriter(PATH + FILE + "".out""); int test = in.nextInt(); for (int t = 1; t <= test; t++) { String strA = in.next(); int A = Integer.parseInt(strA); int B = in.nextInt(); int length = strA.length(); int result = 0; for (int n = A; n < B; n++) { String rotated = n + """"; HashSet setM = new HashSet(); for (int i = 0; i < length - 1; i++) { rotated = rotated.substring(1) + rotated.charAt(0); if (rotated.charAt(0) == '0') { continue; } int m = Integer.parseInt(rotated); if (m > n && m <= B) { setM.add(m); } } result += setM.size(); } out.println(""Case #"" + t + "": "" + result); } out.close(); } } " B20410,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Cbits { public static void main(String[] args) throws FileNotFoundException { Scanner scan = new Scanner(new File(""C-large.in"")); System.setOut(new PrintStream(""C-large.out"")); int t = scan.nextInt(); for (int c = 0; c < t; c++) { int a = scan.nextInt(); int b = scan.nextInt(); int ans = 0; int bDigits = digits(b); for (int n = a; n < b; n++) { int nDigits = digits(n); int nDigitCount = numDigits(n); Set done = new HashSet(); for (int i = 1; i < nDigitCount; i++) { int mDigits = rotate(nDigits, nDigitCount, i); if (nDigits < mDigits && mDigits <= bDigits && !done.contains(mDigits)) { ans++; done.add(mDigits); } } } System.out.printf(""Case #%d: %d%n"", c + 1, ans); } } private static int numDigits(int n) { int num = 0; int temp = n; while (temp > 0) { num++; temp /= 10; } return num; } private static int digits(int n) { int num = numDigits(n); int digits = 0; int temp = n; for (int i = 0; i < num; i++) { digits |= (temp % 10) << i * 4; temp /= 10; } return digits; } private static int rotate(int nDigits, int digitCount, int r) { int rotPartMask = (1 << r * 4) - 1; int rotPart = nDigits & rotPartMask; int ans = nDigits; ans >>>= r * 4; ans |= rotPart << (digitCount - r) * 4; return ans; } private static int normal(int n, int digitCount) { int base = 1; int ans = 0; for (int i = 0; i < digitCount; i++) { int mask = 0b1111 << i * 4; int digit = (n & mask) >>> i * 4; ans += digit * base; base *= 10; } return ans; } }" B20796,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package problemc; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author mayorandrew */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { BufferedReader input = null; try { input = new BufferedReader(new FileReader(""input.txt"")); FileOutputStream output = new FileOutputStream(""output.txt""); int N = Integer.parseInt(input.readLine()); for(int i=0; i=a && num<=b && num!=k){ boolean found = false; for(int j=1; j 0){ a[d] = tmp % 10; tmp /= 10; d++; } int ten = 1; for(i=0;i x && y[i] <= M && (i == 0 || y[i] != y[i-1])) ans++; return ans; } public static void main(String args[]){ int T,t,A,B,i; Scanner scan = new Scanner(System.in); T = scan.nextInt(); for(t=0;t set = new HashSet(); StringBuilder sN = new StringBuilder((new Integer(j)).toString()); for (int k = 0; k=a && m<=b && !set.contains(new Integer(m))) { ans++; set.add(m); } } } } out.println(ans); } out.close(); } } " B21076,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.TreeMap; public class Recycler { public static void main(String[] args) { // TODO Auto-generated method stub String input; BufferedReader br; HashSet set; try{ br=new BufferedReader(new InputStreamReader(System.in)); int T=Integer.parseInt(br.readLine()); int A,B; String []inputs; for (int i=0;i(); int s=0; int m; for (int n=A;n<=B;n++) { int multiple=10; while (1.0*n/multiple > 0) { m=Integer.parseInt(n%multiple + """" + n/multiple); if (m<=B && n encountered = new HashSet(); String asString = """"+i; for(int index = 1; index < asString.length(); index++) { char letter = asString.charAt(index); if(letter == '0') { //System.out.println(i+"": skip index ""+index); continue; // cant have leading 0 } int switched = Integer.parseInt(asString.substring(index)+asString.substring(0, index)); if(switched > i && switched >= start && switched <= end) { //encountered.add(i); if(encountered.contains(switched)){ //System.out.println(""already had ""+switched); continue; } encountered.add(switched); res++; //System.out.println(i+"": ""+switched); } else { //System.out.println(i+"": ""+switched+"" doesnt work""); } } } return res; } }" B20905,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib.converters; import com.isotopeent.codejam.lib.InputConverter; public class DynamicMultiLineConverter implements InputConverter { private static final int MAX_PARAM_COUNT = 10; private IntArrayLine paramConverter; private InputConverter converter; private Object[] input; private int lineNumber; public DynamicMultiLineConverter(InputConverter lineConverter) { this(lineConverter, 0); } public DynamicMultiLineConverter(InputConverter lineConverter, int paramCount) { this.converter = lineConverter; if (paramCount > 0) { paramConverter = new IntArrayLine(paramCount); } else { paramConverter = new IntArrayLine(new int[MAX_PARAM_COUNT]); } } @Override public boolean readLine(String data) { if (lineNumber == 0) { paramConverter.readLine(data); int[] params = paramConverter.generateObject(); int count = getCount(params); input = new Object[count + 1]; input[lineNumber++] = params; } else { if (!converter.readLine(data)) { input[lineNumber++] = converter.generateObject(); } } if (lineNumber >= input.length){ lineNumber = 0; } return lineNumber == 0; } @Override public Object[] generateObject() { return input; } /** * default implementation, just uses first parameter value */ protected int getCount(int[] parameters) { return parameters[0]; } } " B22241,"package classes; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; public class Recycle { public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(""/Users/jleibsly2002/C-large.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); int N = Integer.parseInt(strLine); for(int i = 0; i < N; i++) { int count = 0; String[] range = br.readLine().split("" ""); int min = Integer.parseInt(range[0]); int max = Integer.parseInt(range[1]); int length = range[0].length(); ArrayList numbers = new ArrayList(); for(int j = min; j <= max; j++) numbers.add(j + """"); for(int k = 0; k < numbers.size(); k++) { String n = numbers.get(k); for(int l = length-1; l>=1; l--) { String recycled = n.substring(l) + n.substring(0, l); if(Integer.parseInt(recycled)>=min && Integer.parseInt(recycled)<=max && recycled.charAt(0)!='0' && recycled.compareTo(n)>0) { count++; } } } System.out.println(""Case #"" + (i+1) + "": "" + count); } in.close(); } catch (Exception e){ System.err.println(""Error: "" + e.getMessage()); } } } " B20351," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class FileUtil { private static final String RESULT_PATH = ""/home/ypxu/src/codejam/2012""; public static String[] readFile(String filePath) { List content = new ArrayList(); try { BufferedReader bis = new BufferedReader(new FileReader(filePath)); String current = null; while ((current = bis.readLine()) != null && current.length() > 0) { content.add(current); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return content.toArray(new String[content.size()]); } public static int getNumOfTestCases(String[] content) { // for code jam, it's in first line assert content != null; String numStr = content[0]; return Integer.parseInt(numStr); } public static String[] getAllTestCases(String[] content) { assert content != null; int len = content.length; String[] testCases = new String[len - 1]; for (int i = 0; i < len - 1; i++) { testCases[i] = content[i + 1]; } return testCases; } public static String formatTestResult(int index, String result) { assert result != null; return String.format(""Case #%1$d: %2$s"", index + 1, result); } public static void writeTestResult(String fileName, String[] results) { try { FileWriter fstream = new FileWriter(fileName); BufferedWriter out = new BufferedWriter(fstream); for (String result : results) { out.write(result + ""\n""); } out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } public static long toNumber(String in) { return Long.valueOf(in); } public static long toNumber(char ch) { return toNumber(Character.toString(ch)); } public static char toChar(String in) { char[] chars = in.toCharArray(); if (chars.length <= 0) { return 0; } return chars[0]; } public static boolean isNumber(String in) { try { Integer.parseInt(in); return true; } catch (Exception e) { return false; } } public static String join(char[] chars, String delimiter) { int len = chars.length; String[] strArr = new String[len]; for (int i = 0; i < len; i++) { strArr[i] = Character.toString(chars[i]); } return join(strArr, delimiter); } public static String join(String[] strs, String delimiter) { int len = strs.length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { if (sb.length() > 0) { sb.append(delimiter).append(strs[i]); } else { sb.append(strs[i]); } } return ""["" + sb.toString() + ""]""; } public static class Timer { private static long timestamp = System.currentTimeMillis(); public static void start() { Timer.timestamp = System.currentTimeMillis(); } public static void stop() { long current = System.currentTimeMillis(); long pass = current - timestamp; System.out.println(""total: "" + pass + "" ms""); } } } " B21085," import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class C { int INF = 1 << 28; void run() { Scanner sc; FileOutputStream fw; try { sc = new Scanner(new File(""C.in"")); fw = new FileOutputStream(new File(""C.out"")); PrintWriter pw = new PrintWriter(fw); // sc.useDelimiter(""\\n""); int n = sc.nextInt(); for(int i=1;i<=n;i++) { int a = sc.nextInt(); int b = sc.nextInt(); int cnt = 0; for(int j=a;j<=b;j++) { String num = String.valueOf(j); // debug(num); HashSet visited = new HashSet(); for(int k=1;k j && a <= rot && rot <= b) visited.add(rot); } cnt += visited.size(); } // debug(cnt); pw.println(""Case #"" + i + "": "" + cnt); } pw.close(); fw.close(); } catch (FileNotFoundException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } catch (IOException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } } public static void main(String[] args) { new C().run(); } void debug(Object... os) { System.err.println(Arrays.deepToString(os)); } } " B22008,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; public class gcjq3 { public static void main(String[] args) { try{ FileInputStream ifstream = new FileInputStream(""files/C-large.in""); DataInputStream in = new DataInputStream(ifstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileOutputStream ofstream = new FileOutputStream(""files/output""); DataOutputStream out = new DataOutputStream(ofstream); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); int numCases = Integer.parseInt(br.readLine()); for(int i=0; i set = new HashSet(); int digitLen = ("""" + A).length(); int m = 0; for(int n = A; n <= B; ++n) { for(int i = 1; i < digitLen; ++i) { m = shift(n, i); if(m > n && m <= B) { set.add(n + ""-"" + m); } } } return set.size(); } static int shift(int n, int i) { String word = """" + n; int len = word.length(); int shift = len - i - 1; if(len < 2) { return n; } else if(len == 2) { String a = new String(word.charAt(1) + """"); String b = new String(word.charAt(0) + """"); return Integer.parseInt( a + b); } return Integer.parseInt(word.substring(shift + 1) + word.substring(0, shift + 1)); } } " B21801,"package util.graph; import java.util.HashSet; import java.util.Set; public class Node implements Comparable{ public static int seq = 0; public int id = (seq++); public Set edges = new HashSet<>(); public State last; @Override public int compareTo(Node o) { return last.compareTo(o.last); } @Override public boolean equals(Object obj) { return id == ((Node) obj).id; } @Override public int hashCode() { return Integer.valueOf(id).hashCode(); } } " B21561,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; public class R1Q3 { public static HashMap wordMap; public static void main(String []args) throws NumberFormatException, IOException{ BufferedReader bf = new BufferedReader(new FileReader(new File(""input""))); BufferedWriter bw = new BufferedWriter(new FileWriter(new File(""output""))); int num = Integer.parseInt(bf.readLine()); String aString = ""123""; for (int i = 1 ; i<=num; i++){ int nums = 0; String line = bf.readLine(); String[] argss =line.split("" ""); int small = Integer.parseInt(argss[0]); int large = Integer.parseInt(argss[1]); HashSet already = new HashSet(); for (int j = small; j< large; j++){ if (j<10) continue; already.clear(); already.add(j); String temp = String.valueOf(j); for (int k = 1; k < temp.length(); k++){ int m = k; int newnum = j/(int)(Math.pow(10, temp.length()-k)); newnum+= (j%(int)(Math.pow(10, temp.length()-k)))*Math.pow(10, k); if (!already.contains(newnum)&&newnum<=large&&newnum>=small&&newnum>j){ nums++; already.add(newnum); } } } System.out.println(i); bw.write(""Case #""+i+"": ""+nums+""\n""); } bf.close(); bw.close(); } } " B20349,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.Writer; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers{ public static void main(String[] args) throws IOException{ String testCases; BufferedReader brTestCases = new BufferedReader(new InputStreamReader(System.in)); File inFile = new File(""C:/Users/AbhilashR/Downloads/C-large.in"" ); Scanner sc = new Scanner(inFile); //testCases = (String)brTestCases.readLine(); testCases = sc.nextLine(); Integer noOfTestCases = null; try{ noOfTestCases = Integer.parseInt(testCases); }catch (NumberFormatException e){ System.out.println(""The entered value is not a Number""); } ArrayList inputData = new ArrayList(); for(int i =0;i inputDataObj = new ArrayList(); for(int i =0;i tempSet = new HashSet(); for(int j =0; j< numberOfDigits; j++){ int currentSize = Integer.toString(sampleM).length(); if(currentSize==numberOfDigits){ sampleM = Integer.parseInt(Integer.toString(sampleM%10)+Integer.toString(sampleM/10)); }else{ String formingSampleM = Integer.toString(sampleM%10); for(int k =0;k0){ return noOfRecycledNumbers; } return 0; } }" B21228,"import java.io.File; import java.io.FileInputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { try { File output = new File(""output.txt""); if (output.exists()) { output.delete(); } PrintWriter pw = new PrintWriter(output); Scanner s = new Scanner(new FileInputStream(""input.txt"")); int T = s.nextInt(); s.nextLine(); for (int c = 0; c < T; c++) { int start = s.nextInt(); int end = s.nextInt(); int digits = digits(start); System.out.println(String.format(""%d - %d (%d)"", start, end, digits)); int found = 0; for (int n = start; n < end; n++) { int m = n; HashSet pairs = new HashSet<>(); for (int i = 0; i < digits; i++) { m = rotate(m, digits); if (m <= n) continue; if (m >= start && m <= end && !pairs.contains(m)) { pairs.add(m); found++; //System.out.println(String.format(""%d - %d"", n, m)); } } } // pw.println(String.format(""Case #%d: %d"", (c+1), found)); System.out.println(String.format(""Found %d numbers"", found)); System.out.println(""---------------------""); } // Read inputs and solve here pw.close(); System.out.println(""Done !""); System.out.println(String.format(""51234 rotated to %d"", rotate(51234, 5))); } catch (Exception ex) { System.out.println(""ERROR""); System.out.println(ex.getMessage()); ex.printStackTrace(); } } private static int digits(int n) { int d = 0; while (n > 0) { n /= 10; d++; } return d; } private static int rotate(int m, int digits) { if (digits == 1) return m; int left = m%10; m /= 10; m += left * (int)Math.pow(10, digits-1); return m; } public RecycledNumbers() { } } " B21639,"package trupti; import java.io.*; import java.io.FileNotFoundException; import java.util.Scanner; public class ok2 { public static void main(String[] args) { int cn=0; try { FileOutputStream out=new FileOutputStream(""out9.out""); Scanner scanner = new Scanner(new FileReader(""C-large.in"")); int n=scanner.nextInt(); // scanner.nextLine(); while (n!=cn) { cn++; int q=0; int a=scanner.nextInt(); int b=scanner.nextInt(); int no=0; for(int r=a;r<=b;r++) { String str=r+""""; // System.out.println(""str""+str); do{ char c=str.charAt(0); String str1=str.substring(1, str.length()); str=str1+c; // System.out.println(str); no=Integer.parseInt(str); // System.out.println(""no""+no); if((no 0 ; i++, d *= 10, a /= 10){ int b = n % d; int m = (k10/d) * b + a; if (m > n){ boolean add = true; for (int exists : mar){ if (exists == m){ add = false; break; } } if (add) { mar[i] = m; } } } nm[n] = mar; } //System.out.println(System.currentTimeMillis() - t); } @Override protected String solve() { int A = scanner.nextInt(); int B = scanner.nextInt(); int count = 0; for (int n = A ; n < B; n++) { for (int m : nm[n]) { if (m > 0 && m <= B){ count++; } } } return count + """"; } } " B21826,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class P03 { public static void main(String[] args) { Scanner inp = new Scanner(System.in); int t = inp.nextInt(); inp.nextLine(); int i = 1; while (t > 0) { int a = inp.nextInt(); int b = inp.nextInt(); System.out.println(""Case #"" + i + "": "" + find(a, b)); --t; ++i; } } private static long find(int a, int b) { long ret = 0; boolean[] done = new boolean[b + 1]; for (int i = a; i <= b; i++) { if (!done[i]) { Set vals = new HashSet(); String is = String.valueOf(i); if (is.length() > 1) { vals.add(i); for (int j = 1; j < is.length(); j++) { String newS = is.substring(j) + is.substring(0, j); int newInt = Integer.parseInt(newS); if (newInt >= a && newInt <= b) { vals.add(newInt); } } } if (vals.size() > 1) { for (int val : vals) { done[val] = true; } ret += (vals.size() * (vals.size() - 1)) / 2; } } } return ret; } } " B21702,"import java.io.*; import java.util.*; import java.util.regex.*; public class jam03 { /** * @param args */ public static void main1(){ // scalar product problem } public static void main(String[] args) { // TODO Auto-generated method stub int number_test; Scanner sc = new Scanner(System.in); number_test = sc.nextInt(); for(int j=1;j<=number_test;j++) { int lowerLimit = sc.nextInt(); int upperLimit = sc.nextInt(); System.out.print(""Case #"" + j + "": ""); action(lowerLimit,upperLimit); // System.out.println(sum); } } private static void action(int lowerLimit, int upperLimit ) { // TODO Auto-generated method stub // Iterating over the elements in the set int finalGuys = 0; int maxZeroes = 0; int oldNum=0; // System.out.println(""lower""+ lowerLimit); // System.out.println(""uper""+upperLimit); for(int i=lowerLimit;i=1;k--) {//3422 int temp = (int) (i/Math.pow(10, k));//34 if(maxZeroes ==0 && temp > 0) { maxZeroes = k; //System.out.println(""maxZeroes""+maxZeroes); } if(maxZeroes>0) { int temp1 = (int) (i - (temp*Math.pow(10, k)));//3422-3400 int newNum = (int) ((temp1*Math.pow(10, maxZeroes-k+1))+temp);//4223 if(newNum <= upperLimit && newNum > i && newNum != oldNum) { oldNum = newNum; finalGuys++; } } } } System.out.println(finalGuys); } } " B21522,"package recyclednumbers; import java.io.*; import java.math.BigInteger; import java.util.Iterator; import java.util.Scanner; /** * * @author Diego Villatora */ public class RecycledNumbers { static int numberOfCases =0; static boolean first = true; static int currentInt = 0; static int firstNumber = 0; static int secondNumber = 0; static int[] founds = new int[]{}; /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { Scanner s = null; BufferedWriter output = null; int counter = 0; // for the output and the writing on file // Create file File file =null; FileWriter fstream = null; try { //input s = new Scanner(new BufferedReader(new FileReader(""C:\\Users\\Utente\\Downloads\\C-large.in""))); //output file = new File(""C:\\Users\\Utente\\Downloads\\google3.out""); fstream = new FileWriter(file); output = new BufferedWriter(fstream); //while not EOF int i=0; while (s.hasNext()) { if(first){ numberOfCases = s.nextInt(); first=false; }else{ currentInt = s.nextInt(); //get int counter++; if(counter == 1){ firstNumber = currentInt; } else{ secondNumber = currentInt; counter = 0; } if (counter == 0){ i++; int maxNumberRecycled = getMaxRecycled(firstNumber,secondNumber); output.write(""Case #""+ i +"": "" + maxNumberRecycled); output.newLine(); } } } }catch (Exception e){//Catch exception if any System.out.println(""Error: "" + e.getMessage()); System.out.println(""Error: "" + e.toString()); //to close the file if still open }finally { if (s != null) s.close(); if (output != null) output.close(); } } private static int getMaxRecycled(int firstNumber, int secondNumber){ int total = 0; int partial = 0; int numberRotating = 0; while(firstNumber numberRotating){ if((new Integer(numberRotating).toString().length()) < (new Integer(firstNumber).toString().length())){ numberRotating = numberRotating * 10; } else{ numberRotating = shiftNumber(numberRotating); } }else{ numberRotating = shiftNumber(numberRotating); } } firstNumber++; } return total; } private static int findEquals(int toFind, int start, int end){ int found = 0; /*for(int i = 0; i< founds.length; i++){ if (toFind == founds[i]){ return found; } }*/ if(toFind <= end){ /*int[] appo = new int[]{toFind}; int[] C= new int[appo.length+founds.length]; System.arraycopy(appo, 0, C, 0, appo.length); System.arraycopy(founds, 0, C, appo.length, founds.length); founds = C;*/ found = 1; } return found; } private static int shiftNumber(int toShift){ double toAdd = 0; double partial = 0; double restoInit = toShift; double numExp = 0; while(restoInit > 9){ restoInit = Math.floor(restoInit / 10); numExp++; } toAdd = Math.floor(toShift / Math.pow(10.0, numExp)); toShift = toShift * 10; partial = toShift % Math.pow(10.0, numExp+1); partial = partial + toAdd; return new Double(partial).intValue(); } } " B20421,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; public class main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader dat=new BufferedReader(new FileReader(""input"")); int BRCASE=Integer.parseInt(dat.readLine()); for(int ic=1;ic<=BRCASE;ic++){ String str[]= dat.readLine().split("" ""); System.out.println(""Case #""+ic+"": ""+test(Integer.parseInt(str[0]),Integer.parseInt(str[1]))); } } public static int test(int n, int m){ boolean [] pominati= new boolean[m-n+10]; int rez=0; for(int i=n;i<=m;i++){ int ttl=0; int tmp=i; if(!pominati[tmp-n]){ do{ if(tmp>=n && tmp<=m){ if(!pominati[tmp-n]){ pominati[tmp-n]=true; ttl++; } } tmp=rotate(tmp); }while(tmp!=i); } rez+=(ttl>=2)?comb(ttl,2):0; } return rez; } public static int rotate(int x){ int pow = (int)Math.log10(x); do{ if(x%10!=0){ x = (int) ((int)x%10*Math.pow(10, pow)+(int)x/10); break; }else{ x = (int) ((int)x%10*Math.pow(10, pow)+(int)x/10); } }while(true); return x; } public static int fact(int x){ int ret=1; for(int i=1;i<=x;i++){ ret*=i; } return ret; } public static long comb(int n, int k){ if(k>(n-k)) k=n-k; long c=1; for(int i=0; i set = null; for(int ti=0;ti0){ no_of_digits++; counter++; a=a/10; } int res=0; int n= A; int m=0; while(n<=B){ counter = no_of_digits-1; m=n; set = new HashSet(); while(counter>0){ m = (int) ((m%10)*Math.pow(10,no_of_digits-1) + (m/10)); if(A<=n && n resultSet = new HashSet(); for (long M = B; M >= A; M--) { final String str1 = String.valueOf(M); if (str1.length() == 1) { continue; } for (int max = str1.length() - 1; max >= 1; max--) { final String first = str1.substring(0, str1.length() - max); final String last = str1.substring(str1.length() - max, str1.length()); final String str2 = last + first; final long N = Long.valueOf(str2); if (A <= N && N < M && M <= B && str1.charAt(0) != '0' && str2.charAt(0) != '0') { /* * System.out.println(A + "" <= "" + N + ""("" + str2 + * "") < "" + M + ""("" + str1 + "") <= "" + B); */ resultSet.add(str1 + str2); } } } if (caseNo > 1) { writer.write(""\n""); } final String text = ""Case #"" + (caseNo++) + "": "" + resultSet.size(); System.out.println(text); writer.write(text); writer.flush(); } writer.close(); reader.close(); } public static void main(final String[] args) throws Exception { final RecycledNumbers number = new RecycledNumbers(); final File outputFile = new File(""output/C-large.out""); if (outputFile.exists()) { outputFile.delete(); } final FileOutputStream fos = new FileOutputStream(outputFile); number.solveInput( SpeakingInTongues.class.getResourceAsStream(""C-large.in""), fos); } } " B21734,"import java.io.*; import java.util.*; public class QualC { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int z = Integer.parseInt(br.readLine()); int[] ten = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; for(int i=0; i hs = new HashSet(); for(int j=a; j map = new HashMap(); int totalpair(int start, int end){ int num = 0; for(int i = start; i <= end; i++){ String s = String.valueOf(i); //System.out.println(s); for(int j = 1; j < s.length(); j++){ String recycle = s.substring(j) + s.substring(0, j); //System.out.println(recycle + "" "" + recycle.length()); //System.out.println(""hh"" + i + "" "" + j); if(recycle.charAt(0) != '0'){ //int new_num = Integer.getInteger(recycle); Integer new_num = new Integer(recycle); if(new_num <= end && new_num >= start && new_num != i) { //map.put(recycle, s); num = num + 1; } } } } return num / 2; } public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub Scanner input = new Scanner(new File(""C-large.in"")); PrintWriter output = new PrintWriter(new FileWriter(""output"")); RecycleNum recyclenum = new RecycleNum(); // Scanner in = new Scanner(System.in); int case_num = input.nextInt(); String word = input.nextLine(); for(int i = 0; i < case_num; i++){ int start = input.nextInt(); int end = input.nextInt(); System.out.println(start + "" "" + end); output.println(""Case #"" + (i + 1) + "": "" + recyclenum.totalpair(start, end)); } input.close(); output.flush(); output.close(); } } " B21303,"import java.io.*; class RecycledNumbers { static int A,B,result; public static void main(String args[]) throws IOException { FileInputStream fstream = new FileInputStream(""C-large.in""); DataInputStream dstream = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(dstream)); FileWriter fw = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(fw); int lines = Integer.parseInt(br.readLine()); //lines LINES OF INPUT TO FOLLOW for(int j=0;jA;i--) { result = result+howMany(i); } out.write(Integer.toString(result));// write result out.newLine(); } fstream.close(); out.close(); //log.close(); } static int howMany(int m) throws IOException { int n,no=0; int length = (Integer.toString(m)).length(); if(length==1) { return 0; } for(int i=1;i list = new ArrayList(); int tamanhoN; casos = Integer.parseInt(scan.nextLine()); String n; String m; for (int i =1; i <= casos;i++){ saida.write(""Case #"" + i + "": ""); int pares = 0; linha = scan.nextLine(); divisao = linha.split(""\\s+""); a = divisao[0]; b = divisao[1]; n = a; do{ m = n; tamanhoN = n.length(); for(int j = 0; j < tamanhoN;j++){ m = desloca(m); novo = (""("" + n + "","" + m + "") ""); if(!(list.contains(novo))){ if(Long.parseLong(a) <= Long.parseLong(n) && Long.parseLong(n) < Long.parseLong(m) && Long.parseLong(m) <= Long.parseLong(b)){ pares++; } } } n = String.valueOf(Long.parseLong(n) + 1); }while(Long.parseLong(n) < Long.parseLong(b)); System.out.println(pares); saida.write(pares + """"); saida.newLine(); } if (saida != null){ saida.flush(); saida.close(); } } public static String desloca(String n){ StringBuffer temp = new StringBuffer(n); char primeiro = n.charAt(0); for (int j=1; j < temp.length(); j++) { char c = n.charAt(j); temp.setCharAt(j-1, c); } temp.setCharAt(n.length()-1, primeiro); n = temp.toString(); return n; } } " B20121,"import java.util.*; import java.io.*; public class CodeJam { public static void main(String[] args) { try { //recycleLarge(1000000, 2000000); // read FileInputStream instream = new FileInputStream(""A-small.in""); DataInputStream in = new DataInputStream(instream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); // write FileOutputStream outstream = new FileOutputStream(""A-small.out""); DataOutputStream out = new DataOutputStream(outstream); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); // reading file information int testcases = Integer.parseInt(br.readLine()); for (int i = 0; i < testcases; i++) { // ------------------------------------------------------------------------------------------------------------- String line = br.readLine(); String[] items = line.split("" ""); int A = Integer.parseInt(items[0]); int B = Integer.parseInt(items[1]); // ------------------------------------------------------------------------------------------------------------- bw.write(""Case #"" + (i + 1) + "": "" + recycleLarge(A, B) + ""\r\n""); } // close input file in.close(); // close output file bw.flush(); out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } private static int eval(int i) { if (i < 0) return 0; else return i; } private static void printArray(Object[] array) { for (Object ch : array) System.out.print(ch); } private static boolean isRecycled(String str, String m) { for (int i = 1; i < str.length(); i++) { String digits = str.substring(i) + str.substring(0, i); if (digits.equals(m)) return true; } return false; } private static String convertTo(int n) { String str = """"; while (n != 0) { str = (n % 10) + str; n = n / 10; } return str; } private static long recycle(int A, int B) { long count = 0; for (int n = A; n < B; n++) { for (int m = n + 1; m <= B; m++) { String nstr = convertTo(n); String mstr = convertTo(m); if (isRecycled(nstr, mstr)) count++; } } return count; } private static long evaluate(int n, int A, int B) { String nstr = convertTo(n); int c = 0; for (int i = 1; i < nstr.length(); i++) { String digits = nstr.substring(i) + nstr.substring(0, i); int variation = Integer.parseInt(digits); if(digits.charAt(0) == '0') continue; if (digits.equals(nstr)) continue; if (variation <= B && variation >= A){ visit[variation] = true; c++; } } return sum(c); } private static long sum(int n){ return n * (n+1) / 2; } private static long recycleLarge(int A, int B) { long sum = 0; visit = new boolean[B+1]; for(int i=0; i= A; m--) { // Get all the rotated numbers first, then compare rotNumbers = rotatedNumbers(m); for (int test : rotNumbers) { if (test >= A && test < m) { NumOfRecPairFound++; } } } System.out.println(""Case #"" + (i+1) + "": "" + NumOfRecPairFound); } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static int[] rotatedNumbers(int number) { int orgNumber = number; // If we have a 4 digit number, there are 3 rotations (excluding itself) int NumOfRotations = (int)Math.log10(orgNumber); int output[] = new int[NumOfRotations]; int mul = (int) Math.pow(10.0, (double)NumOfRotations); int i = 0; while(true) { int q = number / 10; int r = number % 10; number = number / 10; number = number + mul * r; if(number == orgNumber) break; output[i++] = number; } return output; } } " B22007,"import java.util.*; import java.io.*; import static java.lang.Math.*; public class C{ public static void main(String[] args) throws Exception{ new C().run(); } int A, B; int calc(int val){ String s = """" + val; int len = s.length(); HashSet hs = new HashSet(); for(int i = 1; i < len; i++){ int rev = Integer.parseInt(s.substring(i) + s.substring(0, i)); if(rev > val && rev <= B) hs.add(rev); } return hs.size(); } void run() throws Exception{ Scanner sc = new Scanner(System.in); //BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); // only sc.readLine() is available int T = sc.nextInt(); for(int o = 1; o <= T; o++){ A = sc.nextInt(); B = sc.nextInt(); long ans = 0; for(int i = A; i <= B; i++) ans += calc(i); System.out.printf(""Case #%d: "", o); System.out.println(ans); } } } " B20894,"import java.util.Scanner; public class prob_3 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int cases = in.nextInt(); for (int index = 0; index < cases; index++) { int A = in.nextInt(); int B = in.nextInt(); int possiblePermutations = (A + """").length() - 1; String parse; int count = 0; int m; int[] perms; for (int n = A; n < B; n++) { perms = new int[possiblePermutations]; for (int i = 0; i < possiblePermutations; i++) { parse = n + """"; parse = parse.substring(i + 1) + parse.substring(0, i + 1); m = Integer.parseInt(parse); perms[i] = m; if ((n < m) && (m <= B)) if (counted(perms, i)) count++; } } System.out.println(""Case #"" + (index + 1) + "": "" + count); } } private static boolean counted(int[] perms, int i) { for (int j = 0; j < i; j++) if (perms[i] == perms[j]) return false; return true; } }" B22125,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class ProblemC { public static void main(String[] args) { readin(); } private static int count(int a, int b) { int numOfDigits = Integer.toString(a).length(); if (numOfDigits == 1) { return 0; } HashSet rangeFromAtoB = new HashSet(); for (int i = a; i <= b; i++) { rangeFromAtoB.add(i); } int count = 0; for (int i = a; i <= b; i++) { if (rangeFromAtoB.contains(i)) { HashSet validReordering = new HashSet(); validReordering.add(i); rangeFromAtoB.remove(i); for (int s = 1; s < numOfDigits; s++) { int back =(i / (int)(Math.pow(10, s)) ); int front = i % ((int)Math.pow(10, s)); int scale = (int) Math.pow(10, (numOfDigits - s)); int reorder = back + front * scale; if (reorder >= a && reorder <= b) { if (!validReordering.contains(reorder)) { rangeFromAtoB.remove(reorder); validReordering.add(reorder); } } } int numOfValidReordering = validReordering.size(); count = count +numOfValidReordering*(numOfValidReordering-1)/2; } } return count; } private static void readin() { try { BufferedReader in = new BufferedReader(new FileReader(""C-large.in.txt"")); int numOfInput = Integer.parseInt(in.readLine()); int[][] input = new int[numOfInput][2]; String[] output = new String[numOfInput]; for (int i = 0; i < numOfInput; i++) { String[] currentline = in.readLine().split(""[\\s]+""); int a = Integer.parseInt(currentline[0]); int b = Integer.parseInt(currentline[1]); input[i][0] = a; input[i][0] = b; output[i] = ""Case #"" + (i+1) + "": "" + count(a, b); } BufferedWriter out = new BufferedWriter(new FileWriter( ""outputC"")); for (int i = 0; i < output.length; i++) { System.out.println(output[i]); out.write(output[i]+""\n""); } out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B20939,"import java.io.*; import java.lang.reflect.Array; import java.math.*; public class Qualifying_C { public static void main(String[] args) throws Exception { BufferedReader input = new BufferedReader(new FileReader(args[0])); int T = Integer.parseInt(input.readLine()); for (int t = 1; t <= T; t++) { String[] tokens = input.readLine().split("" ""); int A = Integer.parseInt(tokens[0]); int B = Integer.parseInt(tokens[1]); int r = 0; for (int n = A; n < B; n++){ int i, m; int [] C = new int[6]; for (i = 0; n / (int) Math.pow(10, i) != 0; i++); outer: for (int j = 1; j < i; j++) { m = (n % (int) Math.pow(10, j)) * (int) Math.pow(10, i - j) + n / (int) Math.pow(10, j); if (m > n && m <= B){ int c; for (c = 0; c < C.length && C[c] != 0; c++) if (C[c] == m) break outer; r++; C[c] = m; } } } System.out.println(""Case #"" + t + "": "" + r); } } } " B20224,"package bsevero.codejam.qualification; import java.util.HashMap; import java.util.List; import java.util.Map; public class Main { public static void main(String[] args) { String inputPath = args[0]; String outputPath = args[1]; List inputLines = IOUtils.readFile(inputPath); inputLines.remove(0); Map casesResult = new HashMap(); int caseNum = 1; for(String text: inputLines) { String[] minMax = text.split("" ""); int result = RecycledNumbers.recycle(minMax[0], minMax[1]); casesResult.put(caseNum, String.valueOf(result)); caseNum++; } IOUtils.writeFile(outputPath, casesResult); } } " B22245,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; public class recyclednumbers { public static void main(String [] args) throws Exception { BufferedReader reader = new BufferedReader (new FileReader(""C:\\inputFile.txt"")); int number_of_TestCases = (int) Integer.parseInt(reader.readLine()); long testcases[] [] = new long [number_of_TestCases] [2]; for(int i=0;ia ) // also check for leading zero { pairs_count++; } b = rotate(b); } return pairs_count; } private static String rotate(String a) { String num = a; char[] digits= num.toCharArray(); String newNum = """"+digits[digits.length-1]; for(int i=0;i result=new ArrayList(); public void op(String A,String B) { Hashtable tet=new Hashtable(); long current_n; long current_m; int i_A=Integer.parseInt(A); long i_B=Integer.parseInt(B); long diff=i_B-i_A; long temp=i_A; String s; if(A.length()==1 && B.length()==1) { result.add(0+""""); return; } for(int i=0;i current_n && current_m >=i_A) { //System.out.println(current_n+"" ""+current_m); tet.put(current_n+""""+current_m, true); } } temp++; } //System.out.println(tet.size()); result.add(tet.size()+""""); } public void read_file() throws Exception { FileReader g = new FileReader(""C-large.in""); BufferedReader br = new BufferedReader(g); int No_of_Cases = Integer.parseInt(br.readLine()); String s; String [] tete; for(int i=0;i> map = new HashMap>(); int count = 0; for (int i = n; i <= m; i++) { LinkedList intList = permutations(i + """"); map.put(i, intList); for (Integer it : intList) { if (map.containsKey(it)) { LinkedList ints = map.get(it); if (ints.contains(i)) { count++; } } } } return count; } public LinkedList permutations(String str) { LinkedList numList = new LinkedList(); for (int i = 0; i < str.length(); i++) { Integer temp = Integer.parseInt(str); if (!numList.contains(temp)) numList.add(Integer.parseInt(str)); str = leftRotate(str); } numList.removeFirst(); return numList; } public String leftRotate(String str) { StringBuilder build = new StringBuilder(); build.append(str.substring(1, str.length())); build.append(str.charAt(0)); return build.toString(); } } " B20609,"package recycled; import java.io.*; public class Recycled { private int N; private String[] InputStringArray; private String[] OutputStringArray; public static void main(String[] args) { try{ Recycled R = new Recycled(); if (R.GetDataFromInputFile()) if (R.ProcestestData()) R.WriteDatatoOutputFile(); else System.out.println(""Error while writing to outputfile""); else System.out.println(""Error while getting the input data""); }catch(IOException ex){ System.out.println(""IO Error""); } } private boolean GetDataFromInputFile() throws IOException{ int casecount=0; FileInputStream in = new FileInputStream(""E:\\Study\\Google Code jam\\2012\\Recyclednumbers"" + ""\\Input\\C-small-attempt0.in""); DataInputStream di = new DataInputStream(in); BufferedReader br = new BufferedReader(new InputStreamReader(di)); String line; if ((line = br.readLine())!= null) { casecount = Integer.parseInt(line); InputStringArray = new String[casecount]; OutputStringArray = new String[casecount]; } for (int i=0; i=subdigit2) && (subdigit1<=(B/Math.pow(10,digitcount-j)))) { newnumber = (int) (subdigit1*Math.pow(10, digitcount-j)+ (int)((i/Math.pow(10,j)))); if ((newnumber>i)&&(newnumber<=B)){ for (int k=0; kn && m<=B && flag==0){ count++; //System.out.println(count); //System.out.println(""(""+n+"",""+m+"")""); c[k]=m; flag=0; } } } // System.out.println(""Case #""+i+"": ""+count); outFile.println(""Case #""+i+"": ""+count); } //close the file inFile.close(); outFile.close(); } } " B20587,"package knucle.y2012.C; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class C { public static void main(String[] args) throws Exception { FileReader fr = new FileReader(""C-large.in""); BufferedReader br = new BufferedReader(fr); BufferedWriter bw = new BufferedWriter(new FileWriter(""output.txt"")); int currentCase = 1; int caseNum = Integer.parseInt(br.readLine()); for(currentCase=1; currentCase<=caseNum; currentCase++){ String line = br.readLine(); bw.write(""Case #""); bw.write(Integer.toString(currentCase)); bw.write("": ""); String[] inputs = line.split("" ""); String minStr = inputs[0]; int min = Integer.parseInt(minStr); int max = Integer.parseInt(inputs[1]); int count = 0; for(int i=min+1; i<=max; i++){ String target = Integer.toString(i); int len = target.length(); Set possibles = new HashSet(); for(int splitPos=1; splitPos n && n >= A && m <= B) { table[i] = m; // System.out.println(table[i]); } } // System.out.println(""end""); // int m = Integer.parseInt(chaine); return table; } static int count; public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""C-large.in"")); PrintWriter out = new PrintWriter(new File(""C-large.out"")); sc.next(); int kl=0; while (sc.hasNext()) { A = sc.nextInt(); B = sc.nextInt(); out.print(""Case #""+(++kl)+"":""); // out.print("" ""+B); for (int n = A; n < B; n++) { int mm[] = permute(n); for (int k = 0; k < mm.length; k++) { int m = mm[k]; // n doit etre < à m //n doit etre > à A et m doit etre inferieur à B // A <= n < m <= B if (n >= m || A > n || m > B) { continue; } count++; // out.print(""n = "" + n + "" m = "" + m); } } out.println("" "" + count); count=0; } out.close(); sc.close(); } } " B20747,"package fixjava; import java.util.Collection; import java.util.Comparator; /** * Typed 3-tuple */ public class Tuple4 { private final A field0; private final B field1; private final C field2; private final D field3; public A getField0() { return field0; } public B getField1() { return field1; } public C getField2() { return field2; } public D getField3() { return field3; } public Tuple4(final A field0, final B field1, final C field2, final D field3) { this.field0 = field0; this.field1 = field1; this.field2 = field2; this.field3 = field3; } /** Convenience method so type params of pair don't have to be specified: just do Tuple4.make(a, b, c, d) */ public static Tuple4 make(A field0, B field1, C field2, D field3) { return new Tuple4(field0, field1, field2, field3); } // --------------------------------------------------------------------------------------------------- private static final boolean objEquals(Object p1, Object p2) { if (p1 == null) return p2 == null; return p1.equals(p2); } @Override public final boolean equals(Object o) { if (!(o instanceof Tuple4)) { return false; } else { final Tuple4 other = (Tuple4) o; return objEquals(getField0(), other.getField0()) && objEquals(getField1(), other.getField1()) && objEquals(getField2(), other.getField2()) && objEquals(getField3(), other.getField3()); } } @Override public int hashCode() { int h0 = getField0() == null ? 0 : getField0().hashCode(); int h1 = getField1() == null ? 0 : getField1().hashCode(); int h2 = getField2() == null ? 0 : getField2().hashCode(); int h3 = getField3() == null ? 0 : getField3().hashCode(); return h0 + 53 * h1 + 97 * h2 + 131 * h3; } // --------------------------------------------------------------------------------------------------- public static , B, C, D> Comparator> comparatorOnField0(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple4 o1, Tuple4 o2) { return o1.getField0().compareTo(o2.getField0()); } }; } public static , C, D> Comparator> comparatorOnField1(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple4 o1, Tuple4 o2) { return o1.getField1().compareTo(o2.getField1()); } }; } public static , D> Comparator> comparatorOnField2(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple4 o1, Tuple4 o2) { return o1.getField2().compareTo(o2.getField2()); } }; } public static > Comparator> comparatorOnField3(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Tuple4 o1, Tuple4 o2) { return o1.getField3().compareTo(o2.getField3()); } }; } // --------------------------------------------------------------------------------------------------- @Override public String toString() { return ""("" + getField0() + "", "" + getField1() + "", "" + getField2() + "", "" + getField3() + "")""; } } " B22104,"import java.util.*; import java.io.*; public class Samir{ public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Formatter formatter = new Formatter(System.out); int T = Integer.parseInt(br.readLine()); int A,B; String[] lineParts; int lineNum=1; while(T-->0){ lineParts=br.readLine().split(""\\s""); A=Integer.parseInt(lineParts[0]); B=Integer.parseInt(lineParts[1]); formatter.format(""Case #%d: %d\n"",lineNum++,cycles(A,B)); } formatter.close(); } private static int cycles(int A, int B){ int pairs= 0; for(int n=A;n restQueue=new LinkedList(); for(int i=0;in && m <=B) pairs++; } } return pairs; } } " B20686,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class recycled { static String next() { if (st == null || !st.hasMoreTokens()) nextLine(); return st.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static void nextLine() { try { st = new StringTokenizer(f.readLine()); } catch (Exception e) { e.printStackTrace(); } } static StringTokenizer st; static PrintWriter out; static BufferedReader f; public static void main(String[] args) throws IOException { String progName = (recycled.class.getCanonicalName()) + "".out""; f = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); out = new PrintWriter(new BufferedWriter(new FileWriter(progName))); int T = nextInt(); for (int t = 1; t <= T; t++) { int count = 0; int A = nextInt(), B = nextInt(); for (int x = A; x <= B; x++) { HashSet hs = new HashSet(); String s = """" + x; for (int i = 1; i < s.length(); i++) { String ss = s.substring(i) + s.substring(0, i); if (ss.charAt(0) == '0') continue; int xx = Integer.parseInt(ss); if (xx >= A && xx <= B&&x 0; t--, cs++) { out.print(""Case #"" + cs + "": ""); int a = in.nextInt(), b = in.nextInt(); long ans = 0; for (int i = a; i <= b; i++) { ans += go(i, a); } out.println(ans); } out.flush(); } static long go(int x, int low) { String s = x + """"; Set set = new HashSet(); for (int i = 1; i < s.length(); i++) { String w = s.substring(i) + s.substring(0, i); if (w.startsWith(""0"")) continue; int y = Integer.valueOf(w); if (low <= y && y < x) set.add(y); } return set.size(); } } " B21019,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * * @author Chadi */ class TestCase { int A; int B; public TestCase() { } public int solve() { int count = 0; for (int i = A; i <= B; i++) { count += getAllCombinations(i, B); } return count; } public int getAllCombinations(int num, int B) { Set set = new HashSet(); String s = Integer.toString(num); //System.out.println(s); for (int i = s.length() - 1; i > 0; i--) { String cur = s.substring(i) + s.substring(0, i); int t = Integer.parseInt(cur); if (t > num && t <= B) { set.add(t); } } return set.size(); } } public class C { public static void main(String[] args) throws FileNotFoundException, IOException { /* READ INPUT + DATA STRUCTURES */ //String input = ""C-small-attempt0.in""; String input = ""C-large.in""; String output = input.replace("".in"", "".out""); File f = new File(input); Scanner sc = new Scanner(f); int T = Integer.parseInt(sc.nextLine()); TestCase[] cases = new TestCase[T]; for (int i = 0; i < T; i++) { cases[i] = new TestCase(); /* Add inputs to this case */ cases[i].A = sc.nextInt(); cases[i].B = sc.nextInt(); //sc.nextLine(); } /* END READ INPUT + DATA STRUCTURES */ File out = new File(output); if (out.exists()) { out.delete(); } PrintWriter pw = new PrintWriter(new FileOutputStream(out, true)); for (int i = 0; i < T; i++) { System.out.println(""Solving case: "" + ""#"" + (i+1)); String result = ""Case #"" + (i+1) + "": "" + cases[i].solve(); if (i <= T-2) { pw.println(result); } else { pw.print(result); } } pw.close(); } }" B21664,"import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Scanner; public class abc { public static void main(String args[]) { int x ,y,j,k,ans=0; int tcount =0; try{ // Create file FileWriter fstream = new FileWriter(""C-large.out""); BufferedWriter out = new BufferedWriter(fstream); Scanner myfile; try { myfile = new Scanner(new FileReader(""C-large.in"")); int testcases = myfile.nextInt(); while (testcases != 0 || myfile.hasNextInt()) { // Read file content using a while loop ans =0; x = myfile.nextInt(); y = myfile.nextInt(); // System.out.println(x + y); int divby = 1; for(k = x;k>=10;k/=10) { divby = divby *10; } int divdivby = 1; for(j=x;j<=y;j++) { int[] ar = new int[20]; int itr = 0; for(divdivby = divby ; divdivby != 1; divdivby/=10) { int m = j % divdivby; int n = j /divdivby; m = m *(divby /divdivby)*10; m = m+n; for(int l=0;l<=itr;l++) { if(ar[l] == m) { m=0;break;} } if(m!=0) { ar[itr] = m; itr++; } if(m > j && m <= y && m >= x) { ans++; //System.out.println(m +""-- ""+j); } } } out.write(""Case #""+ ++tcount+"": ""+ans+""\n""); // System.out.println(ans); testcases--; } myfile.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Reading file using Scanner out.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B21588,"import java.util.*; import java.io.*; import java.text.*; import java.math.*; public class RecycledNumbers { public static BufferedReader BR; public static String readLine() { try { return BR.readLine(); } catch(Exception E) { System.err.println(E.toString()); return null; } } // ****** MAIN ****** public static void main(String [] args) throws Exception { BR = new BufferedReader(new InputStreamReader(System.in)); int testcases = Integer.parseInt(readLine()); for (int t = 1; t <= testcases; t++) { RecycledNumbers instance = new RecycledNumbers(); instance.solve(t); } } // ****** GLOBAL VARIABLES ****** public RecycledNumbers() { } public boolean solve(int caseNumber) { StringTokenizer st = new StringTokenizer(readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int n = Integer.toString(a).length(); long result = 0; for (int i = a; i <= b; ++i) { String s = Integer.toString(i); Set seen = new HashSet(); for (int j = 1; j < n; ++j) { int rotated = Integer.parseInt(s.substring(j) + s.substring(0,j)); if (i < rotated && rotated <= b && !seen.contains(rotated)) { seen.add(rotated); ++result; } } } System.out.println(""Case #"" + caseNumber + "": "" + result); return false; } } " B20529,"import java.util.Scanner; /* * Google Code Jam 2012 * Program by Tommy Ludwig * Problem: Recycled Numbers (large dataset) * Date: 2012-04-14 * Time: 18:30 (PM) EST */ public class recycle_big { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A, B, n, m, y = 0; A = in.nextInt(); B = in.nextInt(); for (m = B; m > A; m--) { boolean skip = true; int lastN = 0; String strM = String.valueOf(m); for (int x = 1; x < strM.length(); x++) { if (Integer.valueOf(strM.substring(x, x+1)) != 0 && Integer.valueOf(strM.substring(x, x+1)) <= Integer.valueOf(strM.substring(0, 1))) { skip = false; break; } } if (skip) continue; //mutate m to make a valid n for (int l = 1; l < strM.length(); l++) { String sub = strM.substring(l); String strN = sub + strM.substring(0, l); n = Integer.valueOf(strN); //check that n is within bounds //check for duplicate pairs //check for leading zeros in strN if (n >= A && n < m && n != lastN && strN.equalsIgnoreCase(String.valueOf(n))) { y++; lastN = n; } } } System.out.printf(""Case #%d: %d\n"", i, y); } } }" B20542,"import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; class Factory implements TestCaseFactory { @Override public TestCase getInstance(int number) { return new RecycledNumbers(number); } } public class RecycledNumbers extends TestCase { int caseItem; int A; int B; int order; int power; int count; public RecycledNumbers(int caseItem) { this.caseItem = caseItem; } @Override public void readInput(BufferedReader in) throws IOException, MalformedInputFileException { final String str1 = in.readLine(); final String[] tokens = str1.split(""\\s""); A = Integer.parseInt(tokens[0]); B = Integer.parseInt(tokens[1]); } private int pow(int x, int p) { int result = 1; for (int i = 0; i < p; i++) { result *= x; } return result; } private int shift(int x) { final int digit = x / power; final int remainder = x % power; return remainder * 10 + digit; } private int findNumberOfPairs(int x) { final Set distint = new HashSet(); distint.add(x); int shifted = x; for (int i = 0; i < order; i++) { shifted = shift(shifted); if (shifted >= A && shifted < x) { return 0; // we've already seen all these permutations } else if (shifted > x && shifted <= B) { distint.add(shifted); } } final int size = distint.size(); return size * (size - 1) / 2; } @Override public void solve() { order = (int) Math.log10(A); power = pow(10, order); count = 0; for (int x = A; x < B; x++) { count += findNumberOfPairs(x); } } @Override public void writeOutput(PrintWriter out) { out.print(""Case #"" + (caseItem + 1) + "": ""); out.print(count); out.print(""\n""); } public static void main(String[] args) throws IOException, MalformedInputFileException { new Processor().process(new Factory(), args[0], args[1]); } }" B22075,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.StringTokenizer; public class Main { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { //BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(""c:\\input.txt""))); int cases = Integer.parseInt(reader.readLine()); for(int i=0; i processedNumber = new HashSet(); //System.out.println(A + "" "" + B); for(int a=A; a<=B; a++) { if(processedNumber.contains(a) || isAllTheSameDigits(a)) continue; processedNumber.add(a); int eligibleNumbers = 1; int numberToProcessed = a; //System.out.print(""numberToProcessed:"" + numberToProcessed +"",""); for(int j=0; j processedNumber, int number) { if(number >=A && number <=B && !processedNumber.contains(number)) return true; else return false; } } " B20703,"package org.moriraaca.codejam; import java.io.InputStream; public abstract class GeneralDataParser extends AbstractDataParser { public GeneralDataParser(InputStream input) { super(input); } @Override protected void parse() { testCases = new TestCase[scanner.nextInt()]; super.parse(); } } " B22113," package googleCodeJam; import java.io.*; import java.util.*; public class firstExercise { /** * @param args */ public static void main(String[] args) { try{ FileInputStream fstream = new FileInputStream(""C-large.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fstream2 = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream2); String strLine; int j=0; strLine = br.readLine(); while ((strLine = br.readLine()) != null) { ArrayList line = new ArrayList(); String[] s = strLine.split("" ""); int i =0; for(;i=n1) && (temp1<=n2)) nr_temp++; temp2=temp1%10; temp1/=10; temp1+=temp2*Math.pow(10,nr_sh); }while(temp1!=k); if(nr_temp>1) nr=nr+nr_temp-1; } //shkrimi i rezultatit out.write(""Case #""+(++j)+"": ""+nr/2+"" \n""); //System.out.println(strLine); } //System.out.println(vec.size()+vec.toString()); in.close(); out.close(); } catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B22029,"import java.io.*; import java.util.*; public class recycled { private static int digits(int num) { int sol = 1; while (num / 10 != 0) { sol *= 10; num /= 10; } return sol; } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner fe = new Scanner(new FileInputStream(""/home/gllera/Desktop/data.in"")); FileWriter fs = new FileWriter(""/home/gllera/Desktop/data.out""); int cases = fe.nextInt(); for (int i = 0; i < cases; i++) { int a = fe.nextInt(); int b = fe.nextInt(); int sol = 0; TreeSet tree = new TreeSet(); for (int n = a; n < b; n++) { tree.clear(); int digits = digits(n); int idigits = 10; int n1 = n / digits; int n2 = n % digits; while ( digits != 1 ) { int m = n2 * idigits + n1; if ( n < m && m <= b && !tree.contains(m) ) { tree.add(m); sol++; } digits /= 10; idigits *= 10; n1 = n / digits; n2 = n % digits; } } fs.write(""Case #"" + (i + 1) + "": "" + sol + '\n'); } fe.close(); fs.flush(); fs.close(); } } " B22191,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * Problem Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers. Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros. Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A ² n < m ² B? Input The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B. Output For each test case, output one line containing ""Case #x: y"", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A ² n < m ² B. Limits 1 ² T ² 50. A and B have the same number of digits. Small dataset 1 ² A ² B ² 1000. Large dataset 1 ² A ² B ² 2000000. Sample Input Output 4 1 9 10 40 100 500 1111 2222 Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 Are we sure about the output to Case #4? Yes, we're sure about the output to Case #4. * @author andrey * */ public class QCRecycledNumbers { private static int[] INT_LENGTH = new int[] {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; public static void solve(BufferedReader reader, BufferedWriter writer) throws IOException { int testCount = readIntFromLine(reader); for (int test = 1; test <= testCount; test++) { writer.append(""Case #"").append(Integer.toString(test)).append("": ""); solveTestCase(reader, writer); writer.newLine(); } writer.flush(); } private static void solveTestCase(BufferedReader reader, BufferedWriter writer) throws IOException { String[] testCase = reader.readLine().split(""\\s""); int minValue = Integer.parseInt(testCase[0]); int maxValue = Integer.parseInt(testCase[1]); int length = testCase[0].length(); if (minValue >= maxValue) { writer.append('0'); return; } int recycledCount = 0; int recycledNumber; int lowerPart; int foundRecycledNumbersCount; int[] foundRecycledNumbers = new int[length - 1]; for (int i = minValue; i < maxValue; i++) { foundRecycledNumbersCount = 0; for (int j=1; j < length; j++) { lowerPart = i % INT_LENGTH[j]; if (lowerPart < INT_LENGTH[j - 1]) { // can't rotate, because first digit in lowerPart is 0 continue; } recycledNumber = lowerPart*INT_LENGTH[length - j] + i/INT_LENGTH[j]; if (recycledNumber <= i || recycledNumber > maxValue) { // recycled number exceeds limits continue; } boolean duplicate = false; for (int k=0; k < foundRecycledNumbersCount; k++) { if (foundRecycledNumbers[k] == recycledNumber) { duplicate = true; break; } } if (duplicate) { continue; // such permutation already found } // if (foundRecycledNumbersCount == 0) { // System.out.print(i + "" -> ""); // } // System.out.print(recycledNumber + "", ""); foundRecycledNumbers[foundRecycledNumbersCount++] = recycledNumber; recycledCount++; } // if (foundRecycledNumbersCount > 0) { // System.out.println(); // } } writer.append(Integer.toString(recycledCount)); } public static void solve(String inputFile, String outputFile) throws IOException { File input = new File(inputFile); File output = new File(outputFile); if (!input.exists()) { throw new IllegalArgumentException(""Input file doesn't exist: "" + inputFile); } BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(input)); writer = new BufferedWriter(new FileWriter(output)); solve(reader, writer); } finally { if (reader != null) reader.close(); if (writer != null) writer.close(); } } public static int readIntFromLine(BufferedReader reader) throws IOException { String line = reader.readLine(); int testCount = Integer.parseInt(line); return testCount; } public static void main(String[] args) throws IOException { System.out.println(""Start...""); solve(""res/input.txt"", ""res/output.txt""); System.out.println(""Done!""); } } " B20975,"import java.io.*; import java.util.HashMap; import java.util.Map; public class Task3 { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(new File(""t.txt""))); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(""out.txt""))); int num = Integer.parseInt(reader.readLine().trim()); for (int i = 0; i < num; i++) { String orig = reader.readLine(); writer.write(""Case #"" + (i + 1) + "": ""); String[] strs = orig.split("" +""); int a = Integer.parseInt(strs[0]); int b = Integer.parseInt(strs[1]); int res = 0; for (int j = a; j < b + 1; j++) { String org = Integer.toString(j); String newStr = Integer.toString(j); int ind = 0; while (org.length() - 1 > ind) { ind++; newStr = newStr.substring(1) + newStr.charAt(0); if (Integer.valueOf(newStr) >= a && Integer.valueOf(newStr) <= b && (Integer.valueOf(org) < Integer.valueOf(newStr))) { res++; } } } writer.write("""" + res); if (i < num - 1) { writer.write('\n'); } } writer.close(); reader.close(); } } " B20214,"import java.util.HashMap; import java.util.Scanner; public class recyclednumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); int numOfLines = Integer.parseInt(in.nextLine()); for(int i = 0;i map = new HashMap(); int length = numberString.length(); for(int i =1;i number&&recycled<=max) { map.put(recycled, 0); } } return map.size(); } public static int checkRange(int start,int end) { int count = 0; for(int i = start;i found = new HashSet(); for (int i = a; i <= b; i++) { char[] n = (i+"""").toCharArray(); int cN = i; String cM = i+""""; int len = n.length; for (int j = 0; j < len; j++) { cM = cM.substring(len-1) + cM.substring(0, len - 1); int intCm = Integer.parseInt(cM); if (intCm <= b && intCm > cN && intCm >= a) { found.add(cN+' '+cM); } } } return found.size(); } public static void main(String[] args) throws IOException, InterruptedException, Exception { new QualificationC(""C-large.in"").start(); } } " B20321,"package ulohy; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class codejam_3 { static byte cases; static int A, B; static List l1 = new ArrayList(); static List l2 = new ArrayList(); static int[] pairs; static int[] rotated_array = new int[10]; public static void read_input() { Scanner s = null; try { s = new Scanner(new FileReader(""./src/ulohy/C-small-attempt1.in"")); } catch (FileNotFoundException e) { e.printStackTrace(); } cases = s.nextByte(); pairs = new int[cases]; for (int i = 0; i < cases; i++) { l1.add(s.nextInt()); l2.add(s.nextInt()); } s.close(); } public static void write_output() { FileWriter outFile; try { outFile = new FileWriter(""./src/ulohy/output""); PrintWriter out = new PrintWriter(outFile); for (int i = 1; i <= cases; i++) { out.println(""Case #""+i+"": ""+pairs[i-1]); } out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static int rotateNumber(int number, int mul) { return number / 10 + mul * (number % 10); } public static void main(String args[]) { int rotated; read_input(); for (int i = 0; i < cases; i++) { int numdigits = (int) Math.log10((double)l1.get(i)); // would return numdigits - 1 int multiplier = (int) Math.pow(10.0, (double)numdigits); for (int j = l1.get(i); j <= l2.get(i); j++) { rotated = rotateNumber(j, multiplier); for (int k = 0; k <= numdigits; k++) { if (j < rotated && rotated <= l2.get(i)) { for (int k2 = 0; k2 < k; k2++) { if (rotated == rotated_array[k2]) { pairs[i]--; } } pairs[i]++; } rotated_array[k] = rotated; rotated = rotateNumber(rotated, multiplier); } } } write_output(); } }" B22136,"import java.io.*; import java.util.*; public class My { public static void main(String[] args)throws IOException { new My().start(); } public void start()throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int test=Integer.parseInt(br.readLine()); int ans=0; int ind=1; while(test-->0){ ans=0; st=new StringTokenizer(br.readLine()); int A=Integer.parseInt(st.nextToken()); int B=Integer.parseInt(st.nextToken()); HashSet hs; for(int num=A;num<=B;num++){ String n=num+""""; int len=n.length(); hs=new HashSet(); for(int i=1;i=A && m>num){ hs.add(m); } } ans+=hs.size(); } System.out.println(""Case #""+ind+"": ""+ans); ind++; } } }" B20381,"import java.io.*; import java.util.*; public class Q3{ public static void main(String args[]){ try { BufferedReader is = new BufferedReader( new InputStreamReader(new FileInputStream(new File(""C-large.in"")))); BufferedWriter os = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(new File(""q3output-l.txt"")))); int num = Integer.parseInt(in(is)); for (int i=0;i dup = new HashSet(); while(num >= 10 ) { target = num % 10; num = num/10; out++; int convert = convert(num, i, out); if (target > first && target < border) { if(!dup.contains(convert)){ dup.add(convert); result++; } } else if(target == first && target == border) { if(!dup.contains(convert) && compare(convert, i) && !compare(convert, max)){ dup.add(convert); result++; } } else if(target == first) { if(!dup.contains(convert) && compare(convert, i) && !compare(convert, max)){ dup.add(convert); result++; } } else if(target == border) { if(!dup.contains(convert) && compare(convert, i) && !compare(convert, max)){ dup.add(convert); result++; } } } return result; } private static int first(int num){ int ret = num; while(ret >= 10) { ret = ret/10; } return ret; } private static int convert(int num, int all, int out){ int m = power(out); int p = digits(num); return (all - num * m) * p + num; } private static boolean compare(int n, int com){ return n > com; } private static int digits(int num){ int ret = 10; while(num >= 10) { num = num/10; ret*=10; } return ret; } private static int power(int out){ int ret = 1; for(int i =0;i hs = new HashSet(); String s = j.toString(); int length = s.length(); for (int k = 1; k < length; k++) { String t = s.substring(k, length) + s.substring(0, k); int newValue = Integer.parseInt(t); if (newValue > j && newValue <=B) { if (!hs.contains(t)) { hs.add(t); result++; } } } } System.out.println(""Case #"" + i + "": "" + result); } } }" B22021,"package third; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.StringTokenizer; public class ThirdProblem { private int a; private int b; private int number; private HashMap> hash; public ThirdProblem(int a,int b){ this.a=a; this.b=b; hash=new HashMap>(); for(int i=a;i<=b;i++){ calculateCouples(i); } } private void calculateCouples(int n) { String original=n+""""; for(int i=original.length()-1;i>0;i--){ String pre=original.substring(i); String post=original.substring(0,i); int m=Integer.parseInt(pre+post); if(m>n && m<=b){ HashMap mm=hash.get(m); if(mm==null) mm=new HashMap(); if(mm.get(n)==null){ mm.put(n, true); hash.put(m, mm); number++; } } } } public int getNumber() { return number; } public static void main(String[] args) throws Exception { File input=new File(""input3""+File.separatorChar+""input4.in""); File output=new File(""output3""+File.separatorChar+""output4.txt""); PrintWriter pw=new PrintWriter(new OutputStreamWriter(new FileOutputStream(output))); BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(input))); br.readLine(); String current=br.readLine(); int cont=1; while(current!=null && current.trim().length()!=0){ StringTokenizer st=new StringTokenizer(current,"" ""); int a=Integer.parseInt(st.nextToken()); int b=Integer.parseInt(st.nextToken()); int number=new ThirdProblem(a, b).getNumber(); pw.append(""Case #""+cont+"": ""+number); cont++; current=br.readLine(); if(current!=null) pw.append(""\n""); pw.flush(); System.out.println(cont); } System.out.println(""Finished""); } } " B20318," public class codejam { public static void main(String argv[]) throws Exception{ RecycledNumbers recycledNumbers=new RecycledNumbers(); recycledNumbers.start(); } } " B20153,"package com.bakes; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class B { public static void main(String[] args) { B park = new B(); park.calculate(); } private void calculate() { BufferedReader in; String strLine1; String strLine2; String strLine3; PrintWriter out; try { in = new BufferedReader(new FileReader(""C-large.in"")); in.readLine(); FileWriter outFile = new FileWriter(""output.txt""); out = new PrintWriter(outFile); int n = 0; while ((strLine1 = in.readLine()) != null) { n++; String[] data = strLine1.split("" ""); int int1 = Integer.parseInt(data[0]); int int2 = Integer.parseInt(data[1]); int count = 0; for (int i = int1; i < int2; i++) { String s = """"+i; int[] sorteds = new int[s.length()-1]; for (int k = 0; k < s.length()-1; k++) { s = permute(s); int j = Integer.parseInt(s); sorteds[k] = j; if (j > i && j <= int2) { boolean unique = true; for (int l = 0; l < k; l++) { if (sorteds[l] == j) { unique = false; } } if (unique) { count++; } } } } String result = ""Case #""+n+"": ""+count; out.println(result); System.out.println(result); } out.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String permute(String s) { if (s.length() == 1) { return s; } s = s.substring(1) + s.charAt(0); return s; } } " B21632,"package qr2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws Exception { String fileName = args[0]; RecycledNumbers obj = new RecycledNumbers(); obj.solve(fileName); } public void solve(String fileName) throws Exception { BufferedReader br = new BufferedReader(new FileReader(fileName)); BufferedWriter bw = new BufferedWriter( new FileWriter(fileName + "".out"")); int T = Integer.parseInt(br.readLine()); for (int i = 0; i < T; i++) { String str = br.readLine(); StringTokenizer token = new StringTokenizer(str, "" ""); int A = Integer.parseInt(token.nextToken()); int B = Integer.parseInt(token.nextToken()); boolean[] check = new boolean[B + 1]; int n = (int) Math.log10(A); int c1 = (int) Math.pow(10, n); int c2 = c1 * 10; int cnt = 0; for (int j = A; j <= B; j++) { if (j >= c2) { c1 = c2; c2 = c1 * 10; n += 1; } if (check[j]) { continue; } else { check[j] = true; int tmp = j; int ccnt = 1; for (int k = 0; k < n; k++) { tmp = (tmp % 10) * c1 + tmp / 10; if (tmp <= B && tmp >= c1 && tmp >= A && !check[tmp]) { ccnt += 1; check[tmp] = true; } } cnt += ccnt * (ccnt - 1) / 2; } } bw.write(""Case #"" + (i + 1) + "": ""); bw.write("""" + cnt); bw.write(""\r\n""); } bw.close(); br.close(); } private int cycle(int x, int digits) { return (x % 10) * 10000 + (x / 10); } } " B22101,"package qualification.q2; /** * Created by IntelliJ IDEA. * User: ofer * Date: 14/04/12 * Time: 18:47 * To change this template use File | Settings | File Templates. */ public class Q2Solver { public int solve(int n,int s,int p, int[] sums){ int res = 0; int surprisesLeft = s; for (int sum : sums){ int div = sum / 3; int mod = sum % 3; if (div >= p){ res++; } else if( p - div == 1){ if (div > 0 && mod == 0 && surprisesLeft > 0){ res++; surprisesLeft--; } else if (mod > 0){ res++; } } else if (p -div ==2 && mod == 2 && surprisesLeft > 0){ res++; surprisesLeft--; } } return res; } } " B21663,"package codejam12; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class RoundOneProblemC { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader input = new BufferedReader(new FileReader(""input.txt"")); BufferedWriter output = new BufferedWriter(new FileWriter(""output.txt"")); int noOfTestCases = Integer.parseInt(input.readLine()); HashSet currInts = new HashSet(); for(int i=1;i<=noOfTestCases;i++) { String inputLine = input.readLine(); String strArr[] = inputLine.split(""\\s+""); int a = Integer.parseInt(strArr[0]); int b = Integer.parseInt(strArr[1]); String bStr = Integer.toString(b); char firstBDigit = bStr.charAt(0); int no = 0; for(int num=a;num<=b;num++) { String numStr = Integer.toString(num); char firstChar = numStr.charAt(0); currInts.clear(); for(byte k=1;k=firstChar && numStr.charAt(k)<=firstBDigit) { int newNumber = Integer.parseInt(numStr.substring(k) + numStr.substring(0,k)); if(!currInts.contains(newNumber) && newNumber <= b && newNumber > num) { no++; currInts.add(newNumber); } } } } output.write(""Case #"" + i + "": "" + no + ""\n""); } input.close(); output.close(); } } " B21144,"package qualify; import java.util.Scanner; public class C { private static int rotate(int input) { int order = 1; while (input / order >= 10) order *= 10; int lastDigit = 0; do { lastDigit = input % 10; input /= 10; input += lastDigit * order; } while (lastDigit == 0); return input; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i=0;i j && x <= b) total++; } } System.out.println(""Case #"" + (i + 1) + "": "" + total); } } } " B22213,"import java.util.ArrayList; import java.util.Scanner; public class Prob3 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); int num = scan.nextInt(); scan.nextLine(); for(int i=0;i d = new ArrayList(length); for(int i=0;i n && m <= B && m >= A && mod != 0 && !d.contains(m)){ //System.out.println(""n: "" + n + "" m: "" + m); d.add(m); res++; } } return res; } } " B20916,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Stack; public class Main { /** * @param args */ static int recyclePair(int A, int B){ int pairCount =0; HashSet hs = new HashSet(); for(int x=A;x digits = getDigits(x); for(int i =1;i getDigits(int x){ List list = new ArrayList(); Stack st = new Stack(); while(x>0){ st.push(x - ((int)(x/10))*10); x /= 10; } while(!st.isEmpty()){ list.add(st.pop()); } return list; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = null; BufferedWriter bw = null; try{ sc = new Scanner(new File(""input.txt"")); bw = new BufferedWriter(new FileWriter(""gcj3b.txt"")); int T = sc.nextInt(); int A, B, x; for(int i=0;i= 'A' && x <= 'Z') { sb.append(DicB[x - 'A']); } else if (x >= 'a' && x <= 'z') { sb.append(DicA[x - 'a']); } else { sb.append(x); } } return sb.toString(); } public static int problemB(String G){ int result=0; String[] temp=G.split("" ""); int N=Integer.parseInt(temp[0]); int S=Integer.parseInt(temp[1]); int p=Integer.parseInt(temp[2]); int[] scr=new int[N]; int count=N; int suprise=S; for(int i=0;i=29){result++;count--;} else if(scr[i]==1){count--;if(p<=1)result++;} else if(scr[i]==0){count--;if(p==0)result++;} else if(Normal[scr[i]]>=p){ result++;count--; } else{ if(Surprising[scr[i]]>=p&&suprise>0){ result++; count--; suprise--; } } } return result; } public static int problemC(String G){ int result=0; String[] temp=G.split("" ""); int length=temp[0].length(); int A=Integer.parseInt(temp[0]); int B=Integer.parseInt(temp[1]); boolean[] check=new boolean[B-A+1]; if(B<10)return 0; else for(int i=A;i<=B;i++){ check[i-A]=false; result+=computeC(i,check,length,A,B); } //System.out.println(); return result; } public static int computeC(int x,boolean[] checklist,int length,int A,int B){ int count=0; if(checklist[x-A]==true)return 0; else checklist[x-A]=false; String S=String.valueOf(x)+String.valueOf(x); for(int i=1;ix&&temp<=B&&checklist[temp-A]==false){ count++; checklist[temp-A]=true; //System.out.print(temp+"",""); } } checklist[x-A]=true; return count*(count+1)/2; } /** * @param args the command line arguments */ public static void mainA(String[] args) { String[] x = {""ejp mysljylc kd kxveddknmc re jsicpdrysi"", ""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"", ""de kr kd eoya kw aej tysr re ujdr lkgc jv""}; for (String G : x) { System.out.println(problemA(G)); } } public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader(new File(""C-large.in""))); int x = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); System.setOut(new PrintStream(new File(""C-large.out""))); for (int i = 1; i <= x; i++) { //String[] temp=br.readLine().trim().split("" ""); sb.append(""Case #"").append(i).append("": "").append(problemC(br.readLine())); sb.append('\n'); //sb.append(""Case #"").append(i).append("": "").append(Result[compute(Integer.parseInt(temp[0]),Integer.parseInt(temp[1]))]).append('\n'); //System.out.printf(""Case #%d: %s\n"",i,Result[compute(Integer.parseInt(temp[0]),Integer.parseInt(temp[1]))]); } System.out.print(sb.toString()); br.close(); } } " B20323,"package CodeJam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws IOException { FileReader in = new FileReader(""C-large.in""); BufferedReader buff = new BufferedReader(in); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter( ""C-large.out""))); int nCases = Integer.parseInt(buff.readLine()); StringBuilder output = new StringBuilder(""""); for (int i = 0; i < nCases; i++) { String input = buff.readLine(); output.append(""Case #"" + (i + 1) + "": "" + getPairs(input) + ""\n""); } out.print(output.toString()); in.close(); out.close(); } private static long getPairs(String input) { StringTokenizer st = new StringTokenizer(input); String first = st.nextToken(); String second = st.nextToken(); int from = Integer.parseInt(first); int to = Integer.parseInt(second); long counter = 0; HashSet set = new HashSet(); for (int i = from; i <= to; i++) { String temp = i + """"; for (int j = 0; j < temp.length(); j++) { String next = temp.substring(j, temp.length()) + temp.substring(0, j); int x = Integer.parseInt(next); if (x <= to && x >= from && i < x && !set.contains(temp + ""$"" + next)) { counter++; set.add(temp + ""$"" + next); } } } return counter; } } " B21291,"import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new File(""c:\\eclipse\\3\\C-large.in"")); int numTc = scanner.nextInt(); for (int index = 0; index < numTc; index++) { int result = 0; int a = scanner.nextInt(); int b = scanner.nextInt(); for (int i = a; i <= b; i++) { if (i < 10) continue; int num = findNumPairs(i, a, b); result += num; } System.out.println(""Case #"" + (index + 1) + "": "" + result/2); } } private static int findNumPairs(int num, int a, int b) { char[] origStr = String.valueOf(num).toCharArray(); int len = origStr.length; char[] newStr = new char[len]; int result = 0; int startIndex = 1; HashSet consumedSet = new HashSet(); do { if (startIndex == len) { break; } int idx = 0; for (int i = startIndex; i < len; i++) { newStr[idx++] = origStr[i]; } for (int i = 0; i < startIndex; i++) { newStr[idx++] = origStr[i]; } startIndex++; int newNum = Integer.parseInt(String.valueOf(newStr)); if (newNum < a || newNum > b || newNum == num || consumedSet.contains(newNum)) { continue; } result++; consumedSet.add(newNum); } while(true); return result; } }" B21754,"import java.io.File; import java.lang.StringBuilder; import java.util.Scanner; import java.io.FileWriter; public class RN { public static void main(String[] args) throws Exception{ File input = new File(""C-large.in""); File output = new File(""output.out""); FileWriter fw = new FileWriter(output); Scanner s = new Scanner(input); int numloops = s.nextInt(); StringBuilder sb = new StringBuilder(); for(int n=0; n i && rotval <= hi ){//&& rotstr.length() == strnum.length()){ numrepeats++; //System.out.println(strnum + "" "" + rotstr); } if(rotval == i) ;//break; //already had a repeating number } } sb.append(numrepeats + ""\n""); //fw.append(numrepeats + ""\n""); } fw.write(sb.toString()); fw.close(); } } " B21391,"import java.io.*; import java.util.*; import java.math.*; import java.text.*; public class RecycledNumbersHard { static final int INF = 1 << 28, MAX = 1000; static final double EPS = 1E-9; static int digits(int x) { int d; for (d = 0; x > 0; d++) x /= 10; return d; } static int hash(int m, int d) { int pow = 1; for (int i = 0; i < d-1; i++) pow *= 10; int hash = m; while (d-- > 0) { m = m / 10 + pow * (m % 10); if (m < hash) hash = m; } return hash; } static long count(Map counter) { long count = 0; for (int k : counter.values()) count += k * (k-1L) / 2; return count; } static void solve() { Scanner scan = new Scanner(in); int T = scan.nextInt(); for (int t = 1; t <= T; t++) { out.print(""Case #"" + t + "": ""); int A = scan.nextInt(); int B = scan.nextInt(); long r = 0; int lastD = 0; Map counter = new HashMap(); for (int x = A; x <= B; x++) { int d = digits(x); if (d != lastD) { lastD = d; r += count(counter); counter.clear(); } int hash = hash(x, d); Integer c = counter.get(hash); if (c == null) c = 0; counter.put(hash, c + 1); } r += count(counter); out.println(r); } } static String read() { try { return in.readLine(); } catch (IOException e) { return null; } } public static void main(String[] args) throws IOException { // in = new BufferedReader(new InputStreamReader(System.in)); // out = new PrintWriter(new BufferedOutputStream(System.out)); String file = ""C-large""; in = new BufferedReader( new FileReader(file + "".in"") ); out = new PrintWriter( new FileOutputStream(file + ""_"" + System.currentTimeMillis() + "".out"") ); solve(); out.flush(); } static BufferedReader in; static PrintWriter out; } " B20016,"import java.util.ArrayList; public class GCJUtils { public static Long[] getLongArray(ArrayList lines){ Long[] arrL = new Long[lines.size()]; for(int i=0;i> map = mapGreaterRecycleds(limit); for (TestCase tc : loadTestCases(inFile)) { ncase++; long recycledsBetween = findPairsBetween(map, tc.a, tc.b); System.out.println(""Case #"" + ncase + "": "" + recycledsBetween); out.write(""Case #"" + ncase + "": "" + recycledsBetween + ""\n""); } out.close(); } private static void test(int n, int limit) { for (int r : getGreaterRecycleds(n, limit)) { System.out.println(r); } } private static long findPairsBetween(Map> map, int a, int b) { long ret = 0; for (int i=a; i> mapGreaterRecycleds(int maxB) { Map> map = new HashMap>(); for (int i = 1; i getGreaterRecycleds(int start, int maxB) { String s = Integer.toString(start); Set ret = new TreeSet(); for (int firstChar = 1; firstChar < s.length(); firstChar++) { String rebuild = s.substring(firstChar) + s.substring(0, firstChar); if (!rebuild.startsWith(""0"")) { int recycled = Integer.parseInt(rebuild); if (recycled <= maxB && recycled > start) { ret.add(recycled); } } } return ret; } public static List loadTestCases(String filename){ List cases = new LinkedList(); try{ BufferedReader reader = new BufferedReader(new FileReader(filename)); String tString = reader.readLine(); int t = Integer.parseInt(tString); for(int i=0; i { @Override public int compare(Pair o1, Pair o2) { if(o1.m - o2.m != 0) return o1.m - o2.m; else return o1.n - o2.n; } } public static void main(String[] args) throws IOException { try (Scanner input = new Scanner(new BufferedReader(new FileReader(""C:\\Users\\maggot\\Desktop\\C-large.in"")))) { int T = input.nextInt(); input.nextLine(); try(PrintWriter output = new PrintWriter(""C:\\Users\\maggot\\Desktop\\output.txt"")) { for(int k = 0; k < T; ++k) { Set pairs = new TreeSet<>(new PairComparator()); int A = input.nextInt(); int B = input.nextInt(); int numberOfDigits = 1; int value = A; while((value = value / 10) > 0) ++numberOfDigits; for(int n = A; n <= B; ++n) { for(int power = 0; power < numberOfDigits; ++power) { int m = n % (int)Math.pow(10, power + 1) * (int)Math.pow(10, numberOfDigits - power - 1) + n / (int)Math.pow(10, power + 1); if(n < m && m <= B) pairs.add(new Pair(n, m)); } } output.println(String.format(""Case #%d: %d"", k + 1, pairs.size())); } } } } } " B22039,"package lt.kasrud.gcj.ex3; import lt.kasrud.gcj.common.IO; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Main { public static void main(String[] args) throws IOException { IO.Data data = IO.readFile(""C-large.in""); IO.writeFile(""out3.txt"", process(data)); } private static List process(IO.Data data) { List result = new ArrayList(data.getInt(0, 0)); for(IO.Record r : data.getRecords(1)){ Integer c = calculate(r.getInt(0), r.getInt(1)); result.add(c); } return result; } private static Integer calculate(Integer a, Integer b) { int cnt = 0; Set ms = new HashSet(); for (int n=a; n<=b; n++){ ms.clear(); String ns = String.valueOf(n); for (int i = 1; i< ns.length(); i++){ int m = rotate(ns, i); if (m > n && m <= b){ ms.add(m); } } cnt += ms.size(); } return cnt; } private static int rotate(String ns, int i){ String ms = ns.substring(i, ns.length()) + ns.substring(0, i); return Integer.valueOf(ms); } } " B21597,"package com.brootdev.gcj2012.common; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; public class DataUtils { public static long readLongLine(BufferedReader in) throws IOException { return Long.valueOf(in.readLine()); } public static long[] readLongsArrayLine(BufferedReader in) throws IOException { String[] numsS = in.readLine().split(""\\s+""); long[] nums = new long[numsS.length]; for (int i = 0; i < nums.length; i++) { nums[i] = Long.valueOf(numsS[i]); } return nums; } public static void writeCaseHeader(PrintWriter out, long case_) { out.print(""Case #""); out.print(case_ + 1); out.print("": ""); } } " B20662,"package gcj2012; import java.io.File; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Scanner; public class C { static String BASEPATH = ""x:\\gcj\\""; static boolean LARGE = true; static String INPATH = BASEPATH + C.class.getSimpleName().charAt(0) + (LARGE ? ""-large.in"" : ""-small-attempt0.in""); static String OUTPATH = INPATH.substring(0, INPATH.length()-3) + new SimpleDateFormat(""-HHmmss"").format(new Date()) + "".out""; static String INPUT = """"; public void call() { int A = ni(), B = ni(); int L = Integer.toString(A).length(); int d = 1; for(int i = 0;i < L;i++)d *= 10; int ct = 0; int[] q = new int[L]; for(int i = A;i <= B;i++){ int p = 0; inner: for(int j = 10;j <= A;j*=10){ int k = i%j*(d/j)+i/j; if(i < k && k <= B){ for(int m = 0;m < p;m++){ if(q[m] == k)continue inner; } q[p++] = k; } } ct += p; } out.println(ct); } Scanner in; PrintWriter out; int cas; public C(int cas, Scanner in, PrintWriter out) { this.cas = cas; this.in = in; this.out = out; } int ni() { return Integer.parseInt(in.next()); } long nl() { return Long.parseLong(in.next()); } double nd() { return Double.parseDouble(in.next()); } void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); } public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); boolean real = INPUT.isEmpty(); if(real){ System.out.println(""INPATH : "" + INPATH); System.out.println(""OUTPATH : "" + OUTPATH); } Scanner in = real ? new Scanner(new File(INPATH)) : new Scanner(INPUT); PrintWriter out = real ? new PrintWriter(new File(OUTPATH)) : new PrintWriter(System.out); int n = in.nextInt(); in.nextLine(); for(int i = 0;i < n;i++){ out.printf(""Case #%d: "", i+1); new C(i+1, in, out).call(); out.flush(); if(real)System.err.println(""case "" + (i + 1) + "" solved.\t""); } long end = System.currentTimeMillis(); System.out.println((end - start) + ""ms""); if(real){ System.out.println(""INPATH : "" + INPATH); System.out.println(""OUTPATH : "" + OUTPATH); } } } " B21205,"import java.util.Set; import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.util.HashSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""Main/input.txt""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""Main/output.txt""); } catch (IOException e) { throw new RuntimeException(e); } Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); C solver = new C(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } class C { public void solve(int testNumber, Scanner in, PrintWriter out) { int A = in.nextInt(), B = in.nextInt(); int digit, a = A, ten = 1; digit = countDigit(a); for (int i = 0; i < digit - 1; ++i) ten *= 10; Set set = new HashSet(); long ans = 0; for (int num = A; num <= B; ++num) if (!set.contains(num)) { Set curSet = new HashSet(); int cur = num; curSet.add(cur); for (int i = 0; i < digit; ++i) { cur = cur % 10 * ten + cur / 10; if (A <= cur && cur <= B && countDigit(cur) == digit) curSet.add(cur); } int cnt = curSet.size(); ans += (cnt * (cnt - 1)) / 2; for (int i : curSet) set.add(i); } out.print(String.format(""Case #%d: %d\n"", testNumber, ans)); } private int countDigit(int n) { int digit = 0; while (n > 0) { digit++; n /= 10; } return digit; } } " B21797,"import java.io.IOException; import java.text.NumberFormat; import java.util.List; public class Welcome extends JamProblem { String welc = ""welcome to code jam""; public static void main(String[] args) throws IOException { Welcome p = new Welcome(); p.go(); } @Override String solveCase(JamCase jamCase) { WelcomeCase cas = (WelcomeCase) jamCase; int length = welc.length(); int strL = cas.str.length(); String str = cas.str; int[][] tab = new int[length][strL]; for (int i = length - 1; i >= 0; i--) { char c = welc.charAt(i); for (int j = strL - 1; j >= 0; j--) { if (i == length - 1) { if (j == strL - 1) { tab[i][j] = str.charAt(j) == c ? 1 : 0; } else { tab[i][j] = mod(tab[i][j + 1] + (str.charAt(j) == c ? 1 : 0)); } } else { if (j == strL - 1) { tab[i][j] = 0; } else { tab[i][j] = mod(tab[i][j + 1] + (str.charAt(j) == c ? 1 : 0) * tab[i + 1][j]); } } } } NumberFormat nf = NumberFormat.getInstance(); // Get Instance of NumberFormat nf.setMinimumIntegerDigits(4); // The minimum Digits required is 5 nf.setMaximumIntegerDigits(4); // The maximum Digits required is 5 nf.setGroupingUsed(false); return nf.format(tab[0][0]); //To change body of implemented methods use File | Settings | File Templates. } @Override JamCase parseCase(List file, int line) { WelcomeCase cas = new WelcomeCase(); cas.lineCount = 1; cas.str = file.get(line); return cas; } int mod(int i) { return i % 10000; } } class WelcomeCase extends JamCase { String str; } " B21552,"import java.util.ArrayList; import java.util.LinkedList; public class RecycledNumbers { static String[] zeros = { ""0"", ""00"", ""000"", ""0000"", ""00000"", ""000000"" }; public static void solve(String fname) { Read r = new Read(); r.Read(fname); int numOfTestCases = r.noOfTestCases; int[] numbers = r.nums; String finalAnser = """"; for (int i = 0; i < numOfTestCases; i++) { String answer = """"; int firstNum = numbers[2 * i]; int secondNum = numbers[2 * i + 1]; int lastNumIndex = (int) (secondNum / Math.pow(10, ((secondNum+"""").length())-1)); lastNumIndex++; String large=""""; for (int k = 9; k >=lastNumIndex; k--) { //check large number large=large+"" ""+k; } // int mid = ((secondNum-firstNum)/2)+1; int noOfans = 0; for (int j = firstNum; j < secondNum; j++) { String numb = j + """"; int firstIndex = -1; int lastIndex = -1; for (int k = zeros.length - 1; k >= 0; k--) { // check zeros if (numb.contains(zeros[k])) { firstIndex = numb.indexOf(zeros[k]); //first index of 0 eg in 201000 it will be 3 lastIndex = firstIndex + zeros[k].length() - 1; //last index = 3+(3-1) = 5 } } // /LinkedList number = new LinkedList(); for (int k = 0; (k < numb.length()) ; k++) { if(k>=firstIndex&& (k <= lastIndex)&&(!large.contains(numb.charAt(k)+""""))){ // System.out.println(k); }else{ String first = numb.substring(0, k); String last = numb.substring(k, numb.length()); // int la = Integer.parseInt(last); String newNumb = last + first; // int biggest = (int) (la * Math.pow(10, numb.length()- last.length())); int numbC = Integer.parseInt(newNumb); if ((numbC <= secondNum) && (numbC > j)) { noOfans++; } } } int x = 0; // int k=0; // while(!number.isEmpty()){ // x=(int) (x+number.removeLast()*Math.pow(10, k)); // k++; // } } answer = ""Case #"" + (i + 1) + "": "" + noOfans; // System.out.println(answer); finalAnser = finalAnser + answer + ""\n""; } r.write(""out"", finalAnser); System.out.println(finalAnser); } public static void main(String[] args) { solve(""test""); // String n = ""10002""; // System.out.println(n.lastIndexOf('0')); } } " B21266,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException { // //////////////////////////////////// // Begin Code Jam regular code // // //////////////////////////////////// Scanner inFile = new Scanner(new File(""C-large.in"")); PrintStream outFile = new PrintStream(new File(""C-large-out.txt"")); int numCases = inFile.nextInt(); inFile.nextLine(); // Gets rid of newline char // //////////////////////////////////// // End Code Jam regular code // // //////////////////////////////////// for (int i = 1; i <= numCases; i++) { int A = inFile.nextInt(); int B = inFile.nextInt(); int recycleCount = 0; for(int n = A; n < B; n++) { HashSet recycled = new HashSet(); for(int j=1; j n && numDigits(shifted) == numDigits(n) && !recycled.contains(Integer.valueOf(shifted))) { recycleCount++; recycled.add(Integer.valueOf(shifted)); //System.out.println(""recycled ("" + n + "","" + shifted + "")""); } else { //System.out.println(""skipped ("" + n + "","" + shifted + "")""); } } } printCase(outFile, i, recycleCount); } } private static void printCase(PrintStream outStream, int i, int n) { outStream.println(""Case #"" + i +"": "" + n); } private static int numDigits(int n) { int count = 0; while(n != 0) { n = n / 10; count++; } return count; } private static int shiftNumPlaces(int n, int shiftAmount) { //String numStr = Integer.toString(n); String savedDigits = """"; for(int i=0; i i) { for (int k = 0; k < digits; k++) { if (movedInt == currentPairs[k]) { break CHECKPAIR; } } currentPairs[j] = movedInt; recycledPairs++; } } } return recycledPairs; } } " B20779,"package recycle; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; public class Recycle { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int count = Integer.parseInt(br.readLine()); for(int z = 0;z < count;z++) { int n = 0; int dbgCnt = 0; HashSet used = new HashSet(); HashSet dbgUsed = new HashSet(); String[] info = br.readLine().split("" ""); int a = Integer.parseInt(info[0]); int b = Integer.parseInt(info[1]); char[] max = String.valueOf(b).toCharArray(); for(int i = a;i < b;i++) { char[] digits = String.valueOf(i).toCharArray(); for(int j = 1;j < digits.length;j++) { boolean valid = true; boolean low = false; boolean high = false; boolean same = true; for(int k = 0;k < digits.length;k++) { char comp = digits[(k + j) % digits.length]; //System.out.println(comp + "" >="" + digits[k] + "" <="" + max[k]); if((high || comp > digits[k]) && (low || comp < max[k] || (k == digits.length - 1 && comp == max[k]))) { same = false; break; } else if((!high && comp < digits[k]) || (!low && comp > max[k])) { valid = false; break; } if(digits[k] != max[k]) { if(comp == digits[k]) { low = true; } else if(comp == max[k]) { high = true; } } } if(valid && !same) { //System.out.println(""Adding""); char[] recon = new char[digits.length]; for(int k = 0;k < digits.length;k++) { recon[k] = digits[(j + k) % digits.length]; } int num = Integer.parseInt(String.valueOf(recon)); //System.out.println(a + "" <= "" + i + "" < "" + num + "" <= "" + b); // if(!(a <= i && i < num && num <= b)) // { // System.out.println(""ERROR: "" + num); // } // if(used.contains((num) | ((long) i << 32))) { // System.out.println(""Reused""); } else { used.add((num) | ((long) i << 32)); n++; } // char[] num1 = String.valueOf(i).toCharArray(); // char[] num2 = String.valueOf(num).toCharArray(); // for(int k = 0;k < digits.length;k++) // { // if(num1[(j + k) % digits.length] != num2[k]) // System.out.println(""ERROR!""); // } } /*char[] recon = new char[digits.length]; for(int k = 0;k < digits.length;k++) { recon[k] = digits[(j + k) % digits.length]; } int num = Integer.parseInt(String.valueOf(recon)); if(i < num && num <= b && !dbgUsed.contains((num) | ((long) i << 32))) { dbgUsed.add((num) | ((long) i << 32)); dbgCnt++; }*/ } } /*for(long p : dbgUsed) { if(!used.contains(p)) { System.out.println((int) (p >> 32) + "" "" + (int) (p & 0xFFFFFFFF)); } }*/ System.out.println(""Case #"" + (z + 1) + "": "" + n/* + "" "" + dbgCnt + ((dbgCnt != n)?"" !!!"":"""")*/); } } } " B21314,"package googleJam; import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner scan = null; try { scan = new Scanner(new File(args[0])); } catch (FileNotFoundException e) { System.err.println(""File not found!""); return; } if (!scan.hasNext()) { System.err.println(""Nothing in File!""); return; } int testCases = Integer.parseInt(scan.nextLine()); int lower; int upper; int move; int d; int total; int zeroes; int num = 1; int first; HashSet set; while(scan.hasNext()) { System.out.print(""Case #"" + num + "": ""); total = 0; lower = scan.nextInt(); upper = scan.nextInt(); for (int x = lower; x <= (upper); x++) { set = new HashSet(); zeroes = 1; move = x; while (move > 9) { move = move/10; zeroes = zeroes * 10; } int limit = zeroes; for(int n = 10; n < (limit*10); n = n * 10) { move = x/n; d = x % n; d = d * zeroes; d = d + move; zeroes = zeroes / 10; if (d < x && d >= lower && !set.contains(d) && d > 9) { total++; //System.out.println(d + "" , "" + x); set.add(d); } } } num++; System.out.print(total); if (scan.hasNext()) { System.out.println(); } } } } " B20406,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author ZAMAN */ import java.io.*; public class test2 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int start; int end; try { BufferedReader a = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter b = new BufferedWriter(new FileWriter(""C-large.out"")); int lines = Integer.valueOf(a.readLine()); for (int z = 1; z <= lines; z++) { int pairs = 0; String ints[] = a.readLine().split("" ""); start = Integer.parseInt(ints[0]); end = Integer.parseInt(ints[1]); b.append(""Case #"" + z + "": ""); for (int i = start; i <= end; i++) { String number = String.valueOf(i); int length = number.length(); int newnums[] = new int[length - 1]; int count = 0; if (length == 1) { continue; } if (length == 2) { char ch1 = number.charAt(0); char ch2 = number.charAt(1); if (ch1 < ch2) { String num = """"; //interchange num += ch2 + """" + ch1; int newnum = Integer.parseInt(num); if (newnum <= end) { pairs++; } } } if (length > 2) { //mving one character to the front String num = """"; char ch = number.charAt(length - 1); num += ch; num += number.substring(0, length - 1); int newnum = Integer.parseInt(num); if (newnum > i && newnum <= end) { if (count == 0) { newnums[count] = newnum; count++; pairs++; } else { int k = 0; for (; k < length - 1; k++) { if (newnums[k] == newnum) { break; } } if (k == length - 1) { pairs++; } } } for (int j = length - 2; j > 0; j--) { //moving more than once String mov = number.substring(j, length); num = """"; num += mov; num += number.substring(0, j); newnum = Integer.parseInt(num); if (newnum > i && newnum <= end) { if (count == 0) { newnums[count] = newnum; count++; pairs++; } else { int k = 0; for (; k < length - 1; k++) { if (newnums[k] == newnum) { break; } } if (k == length - 1) { pairs++; } } } } } } b.append("""" + pairs); b.newLine(); } b.flush(); a.close(); b.close(); } catch (Exception e) { e.printStackTrace(); } } } " B21756,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; /** * * @author WC */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { (new RecycledNumbers()).findRecycledNumbers(""C-large.in"", ""C-large.out"", ""\n""); } private void findRecycledNumbers(String filename, String outputFile, String separator) { int numberOfTestCases = CodeJamFileManager.getIntFromFirstLineOfFile(filename, separator); String[] testCases = CodeJamFileManager.getTextLinesOfFile(filename, separator); String output = """"; for (int i = 1; i <= numberOfTestCases; i++) { output += ""Case #"" + i + "": "" + getNumberOfRecycledInts(testCases[i]) + (i != numberOfTestCases ? separator : """"); } CodeJamFileManager.saveOutputFile(output, outputFile, separator); } private int getNumberOfRecycledInts(String testcase) { int[] params = getIntArrayFromString(testcase.split("" "")); int lower = params[0]; int upper = params[1]; int currentM = lower + 1; int numberOfRecycles = 0; while (currentM <= upper) { int count = timesRecycled(lower, currentM++); numberOfRecycles += count; } return numberOfRecycles; } private int timesRecycled(int lower, int currentM) { String currentMStr = String.valueOf(currentM); char[] individualNumbers = currentMStr.toCharArray(); int timesRecycled = 0; for (int i = 1; i < individualNumbers.length; i++) { int flip = flip(individualNumbers, i); if (flip >= lower && flip < currentM) { timesRecycled++; } } return timesRecycled; } private int flip(char[] individualNumbers, int positionsToFlip) { char[] flip = new char[individualNumbers.length]; int startInt = individualNumbers.length - positionsToFlip; int flipPos = 0; while (startInt < individualNumbers.length) { flip[flipPos++] = individualNumbers[startInt++]; } int i = 0; while (i < (individualNumbers.length - positionsToFlip)) { flip[flipPos++] = individualNumbers[i++]; } return Integer.parseInt(String.valueOf(flip)); } private int[] getIntArrayFromString(String[] intStrArray) { int[] intArray = new int[intStrArray.length]; int i = 0; for (String intStr : intStrArray) { intArray[i++] = Integer.parseInt(intStr); } return intArray; } } " B20319," import java.io.*; import java.util.StringTokenizer; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Hamada */ public class Recylced { public static void main(String [] args) { String [] [] s= TextLines(""C:\\C-small-attempt0.in""); int count[]=new int[s.length]; for(int i=0;in && m<=B) count++; } return count; } public static int crossOver(String s, int cuttingPoint) { String s1=""""; String s2=""""; String result=""""; int r; char [] c=s.toCharArray(); for(int i=0;i { public void solve(File input, File output) { try (BufferedReader reader = new BufferedReader(new FileReader(input)); BufferedWriter writer = new BufferedWriter(new FileWriter( output))) { String line = reader.readLine(); int numberCases = Integer.parseInt(line); for (int i = 1; i <= numberCases; i++) { P problem = readProblem(reader); S solution = solveProblem(problem); writeSolution(i, solution, writer); } } catch (IOException e) { e.printStackTrace(); } } public abstract P readProblem(BufferedReader reader) throws IOException; public abstract S solveProblem(P problem); public abstract void writeSolution(int solutionNumber, S solution, BufferedWriter writer) throws IOException; } " B21745,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbers { String inputFilePath = ""C:\\Temp\\Google\\C-large.in""; String outputFilePath = ""C:\\Temp\\Google\\output.txt""; public static void main(String[] args) throws NumberFormatException, IOException{ new RecycledNumbers().go(); } public void go() throws NumberFormatException, IOException{ FileReader input = new FileReader(inputFilePath); BufferedReader reader = new BufferedReader(input); int numTests = Integer.parseInt(reader.readLine()); ArrayList results = new ArrayList(); for (int i = 0; i < numTests; i++){ String[] details = reader.readLine().split("" ""); int low = Integer.parseInt(details[0]); int high = Integer.parseInt(details[1]); results.add(solve(low, high)); } PrintWriter out = new PrintWriter(new FileOutputStream(outputFilePath)); for (int i = 0; i used = new ArrayList(); for (int j = 1; j i && (!used.contains(test))){ numberPossible++; used.add(test); } } } return numberPossible; } } " B21277,"import java.io.BufferedReader; import java.io.IOException; public class CaseReader { public static String[][] getCases(String s, int linesPerCase) { int cases = Integer.parseInt(s.split(""\n"")[0]); String[][] ret = new String[cases][linesPerCase]; String[] v = s.split(""\n""); for (int i = 0;i < cases;i++) { for (int j = 0;j < linesPerCase;j++) { ret[i][j] = v[i * linesPerCase + j + 1]; } } return ret; } public static String[][] getCases(BufferedReader br, int linesPerCase) throws NumberFormatException, IOException { int cases = Integer.parseInt(br.readLine()); String[][] ret = new String[cases][linesPerCase]; for (int i = 0;i < cases;i++) { for (int j = 0;j < linesPerCase;j++) { ret[i][j] = br.readLine(); } } return ret; } } " B20105," /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; import java.util.TreeSet; /** * * @author violetlily */ public class Jam2012Q_C_S { // private final String ipath = ""C-small-attempt0.in""; // private final String opath = ""C-small-attempt0.ou""; private final String ipath = ""C-large.in""; private final String opath = ""C-large.ou""; public void Handle() throws FileNotFoundException { PrintStream out = new PrintStream( new BufferedOutputStream( new FileOutputStream(opath))); System.setOut(out); Scanner sc = new Scanner(new FileInputStream(new File(ipath))); int t = sc.nextInt(); int ii = 1; while (t > 0) { int a = sc.nextInt(); int b = sc.nextInt(); int c = 0; for (int i = a; i <= b; i++) { TreeSet ts = new TreeSet(); String ta = Integer.toString(i); String tb = ta + ta; for (int j = 0; j < ta.length(); j++) { int tc = Integer.valueOf(tb.substring(j, j + ta.length())); if (tc > i && tc <= b) { ts.add(tc); } } c += ts.size(); } System.out.println(""Case #"" + ii + "": "" + c); ii++; t--; } out.close(); } public static void main(String args[]) throws Exception { Jam2012Q_C_S t = new Jam2012Q_C_S(); t.Handle(); } } " B20865,"package com.gzroger.codejam2012; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class QC { /** * @param args */ public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader(args[0])); int nCases = Integer.parseInt( reader.readLine() ); for (int iCases=0; iCases=1) { Z = Z/10; N++; } for (int n=A; n<=B; n++) { Set hmInt = new HashSet(); for (int j=1; j cases = new ArrayList(); public RecycledNumbers() { try { // Setup in/out System.setIn(new FileInputStream(""C:\\GCJ\\C-large.in"")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new FileWriter(""C:\\GCJ\\C-large.out"")); bw.flush(); int untill = Integer.parseInt(br.readLine()); for (int x = 1; x <= untill; x++) { int ans = 0; String[] s = br.readLine().split("" ""); int a = Integer.parseInt(s[0]); int b = Integer.parseInt(s[1]); for (int z = a; z <= b; z++) { List ints = getAllRecycledPairsOf(z); removeDups(ints); Collections.sort(ints); for (Integer nr : ints) { if (between(nr, a, b)) { ans++; } else if (nr > b) { break; } } } String out = ""Case #"" + x + "": "" + ans; cases.add(out); } for (String s : cases) { System.out.println(s); bw.write(s); bw.flush(); bw.newLine(); } } catch (IOException ex) { System.out.println(""SOMETHING WENT WRONG""); } } public List getAllRecycledPairsOf(int nr) { List ints = new ArrayList(); StringBuilder s = new StringBuilder(); s.append(nr); String start = s.toString(); for (int x = 1; x < start.length(); x++) { s = new StringBuilder(); String back = start.substring(start.length() - x, start.length()); String front = start.substring(0, start.length() - x); s.append(back).append(front); if (!back.startsWith(""0"")) { Integer newNr = new Integer(s.toString()); if (newNr > nr) { ints.add(newNr); } } } return ints; } public static void main(String[] args) { RecycledNumbers test = new RecycledNumbers(); } public boolean between(int nr, int a, int b) { if (nr >= a && nr <= b) { //System.out.println(nr); return true; } return false; } public static void removeDups(List list) { Set s = new HashSet(list); list.clear(); list.addAll(s); } } " B20816,"package com.google.cj12; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; public class RecycledNumber { public static void main(String[] args) throws IOException { String name = ""C-large""; BufferedReader f = new BufferedReader(new FileReader(""resources/"" + name + "".in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter( ""resources/"" + name + "".out""))); new RecycledNumber().solve(f, out); out.close(); } private void solve(BufferedReader f, PrintWriter out) throws IOException { int T = read(f); HashSet set = new HashSet(); for (int i=0; i n && m <= B) { count++; } } set.clear(); } out.println(""Case #"" + (i+1) + "": "" + count); } } public int read(BufferedReader f) throws IOException { return Integer.parseInt(f.readLine()); } public int[] read(BufferedReader f, int N) throws IOException { String[] t = f.readLine().split("" ""); int[] a = new int[N]; for (int i=0; i 0) { reversedNum /= 10; positions++; } for (int k = 1; k < positions; k++) { //Ex: 7487 //k = 2; //rest_right = 87; //rest_left = 74; //if rest_right > rest_left then we can move it //otherwise it's gonna be less the the current num //and so on with each k rest_right = i % pow(10,k); //right part of the num rest_left = i / pow(10, (positions-k)); //left part of the num if (rest_right >= rest_left) { reversedNum = reverseNumber(i, k, positions); if ((reversedNum > i) && (reversedNum <= end_num)) { answer++; } } } } System.out.println("" "" + answer); } private static int reverseNumber(int number, int places, int positions) { int res = number % pow(10, places); number /= pow(10, places); res *= pow(10, (positions-places)); res += number; return res; } private static int pow(int num, int pow) { int result = num; for (int i = 1; i < pow; i++) { result *= num; } return result; } } " B20212,"package com.gcj.parser; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class Parser { private String inputFileDest; private FileInputStream fileInputStream; public Parser(String inputFileDest) { super(); this.inputFileDest = inputFileDest; try { fileInputStream = new FileInputStream(new File(inputFileDest)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String getInputFileDest() { return inputFileDest; } public void setInputFileDest(String inputFileDest) { this.inputFileDest = inputFileDest; } public FileInputStream getFileInputStream() { return fileInputStream; } public void setFileInputStream(FileInputStream fileInputStream) { this.fileInputStream = fileInputStream; } @SuppressWarnings(""unchecked"") public ArrayList[] toArray(){ Scanner scan = new Scanner(getFileInputStream()); // The first line must be an number Integer nbOfLines = new Integer(scan.nextLine()); ArrayList[] parsedData = new ArrayList[nbOfLines]; int index = 0; while (scan.hasNextLine()){ String line = scan.nextLine(); String[] datas = line.split("" ""); ArrayList dataRow = new ArrayList(); for (String data : datas){ dataRow.add(new Integer(data)); } parsedData[index] = dataRow; index++; } return parsedData; } } " B21735,"import java.util.*; import java.io.*; public class Rec{ public static void rotateArray(char[] array, int amount) { for( int j=0; j=a); } public static boolean sameElem(char[] c){ for(int i=0;i set = new LinkedHashSet(); char[] arr = cmp.toCharArray(); int range=0; int equal=0; for(int j=0;j res : new ParallelWorkQueue(numThreads, ParallelWorkQueue.makeIntRangeIterable(p), new CallableFactory() { //IntegerMutable counter = new IntegerMutable(); @Override public Callable newInstance(final Integer ii) { return new Callable() { int i = ii.intValue(); double[][] resultLocal = result; int rLocal = r, qLocal = q; double[][] matALocal = matA, matBTLocal = matBT; @Override public Void call() { /** * * TODO: try blocked matrix multiplication to see if it's faster * * for (int ib = 0; ib < p; ib += blockSize) * for (int jb = 0; jb < q; jb += blockSize) * for (int kb = 0; kb < r; kb += blockSize) * for (int i = ib, iMax = Math.min(p, ib + blockSize); i < iMax; i++) * for (int j = jb, jMax = Math.min(q, jb + blockSize); j < jMax; j++) * for (int k = kb, kMax = Math.min(p, kb + blockSize); k < kMax; k++) * prod[i][j] += matALocal[i][k] * matBTLocal[j][k]; * * N.B. the ""+="" operation above needs to use TLS accumulators */ for (int j = 0; j < rLocal; j++) { float tot = 0.0f; for (int k = 0; k < qLocal; k++) tot += matALocal[i][k] * matBTLocal[j][k]; resultLocal[i][j] = tot; } // int count = counter.increment(); // if (count % 10 == 0) // System.out.println(formatPercent1dp.format((count / (float) (pLocal - 1)))); return null; } }; } })) // Barricade res.get(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } return result; } // ------------------------------------------------------------------------------------------------ /** Multiply A by constant b */ public static double[][] matMulByConst(double[][] A, double b) { int p = A.length, q = A[0].length; double[][] result = new double[p][q]; for (int i = 0; i < p; i++) for (int j = 0; j < q; j++) result[i][j] = b * A[i][j]; return result; } /** Multiply A by constant b */ public static float[][] matMulByConst(float[][] A, float b) { int p = A.length, q = A[0].length; float[][] result = new float[p][q]; for (int i = 0; i < p; i++) for (int j = 0; j < q; j++) result[i][j] = b * A[i][j]; return result; } /** Multiply A by B transpose */ public static float[][] matMulABT(float[][] A, float[][] BT) { int p = A.length, q = A[0].length, q2 = BT[0].length, r = BT.length; if (q != q2) throw new IllegalArgumentException(""Array size mismatch""); float[][] result = new float[p][r]; for (int i = 0; i < p; i++) { for (int j = 0; j < r; j++) { float tot = 0.0f; for (int k = 0; k < q; k++) // This is the main matrix multiplication routine, because both operands here // are in row-major order, so we get speedups of 3-8x due to cache coherence // on large matrices. (Use the parallel version for really large matrices...) tot += A[i][k] * BT[j][k]; result[i][j] = tot; } } return result; } /** Multiply A by B transpose */ public static double[][] matMulABT(double[][] A, double[][] BT) { int p = A.length, q = A[0].length, q2 = BT[0].length, r = BT.length; if (q != q2) throw new IllegalArgumentException(""Array size mismatch""); double[][] result = new double[p][r]; for (int i = 0; i < p; i++) { for (int j = 0; j < r; j++) { float tot = 0.0f; for (int k = 0; k < q; k++) // This is the main matrix multiplication routine, because both operands here // are in row-major order, so we get speedups of 3-8x due to cache coherence // on large matrices. (Use the parallel version for really large matrices...) tot += A[i][k] * BT[j][k]; result[i][j] = tot; } } return result; } /** Multiply A by B */ public static float[][] matMulAB(float[][] A, float[][] B) { // Transpose B so it's row-major, and multiply by BTT==B return matMulABT(A, transpose(B)); } /** Multiply A by B */ public static double[][] matMulAB(double[][] A, double[][] B) { // Transpose B so it's row-major, and multiply by BTT==B return matMulABT(A, transpose(B)); } /** Multiply A transpose by B */ public static float[][] matMulATB(float[][] A, float[][] B) { // Transpose B so it's row-major, and multiply by BTT==B return matMulABT(transpose(A), transpose(B)); } /** Multiply A transpose by B */ public static double[][] matMulATB(double[][] A, double[][] B) { // Transpose B so it's row-major, and multiply by BTT==B return matMulABT(transpose(A), transpose(B)); } /** Multiply A transpose by B transpose */ public static double[][] matMulATBT(double[][] A, double[][] B) { return matMulABT(transpose(A), B); } /** Multiply A transpose by B transpose */ public static float[][] matMulATBT(float[][] A, float[][] B) { return matMulABT(transpose(A), B); } // ------------------------------------------------------------------------------------------------ /** Select a random subset of rows in a matrix */ public static float[][] selectRandomRowSubset(int numRows, float[][] mat) { int n = Math.min(numRows, mat.length); float[][] rows = new float[mat.length][]; for (int i = 0; i < mat.length; i++) rows[i] = mat[i]; Random rand = new Random(); for (int i = 0; i < n; i++) { int j = rand.nextInt(mat.length); float[] tmp = rows[i]; rows[i] = rows[j]; rows[j] = tmp; } return Arrays.copyOf(rows, n); } // ------------------------------------------------------------------------------------------------ /** Write a double[][] array to a file */ public static void writeToFile(String filename, String arrayName, double[][] array) { try { System.out.println(""Writing to "" + filename); PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filename))); writeArray(writer, arrayName, array); writer.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } /** Write a double[][] array to a PrintWriter */ public static void writeArray(PrintWriter writer, String name, double[][] arr) { writer.println(name + ""\t"" + arr.length + ""\t"" + arr[0].length); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) writer.print((j == 0 ? """" : ""\t"") + arr[i][j]); writer.println(); } } /** Write a double[] array to a PrintWriter */ public static void writeArray(PrintWriter writer, String name, double[] arr) { writer.println(name + ""\t1\t"" + arr.length); for (int i = 0; i < arr.length; i++) writer.print((i == 0 ? """" : ""\t"") + arr[i]); writer.println(); } } " B21599,"package google.gcj.recyclednumbers; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Scanner; import java.util.Set; public class RecycledNumbers4 { public static void main(String[] args) throws FileNotFoundException { RecycledNumbers4 recycledNumbers = new RecycledNumbers4(); recycledNumbers.doMain(); } private void doMain() throws FileNotFoundException { Scanner in = new Scanner(System.in); int T = in.nextInt(); int A, B, m, n, sum; for (int zz = 0; zz < T; zz++) { A = in.nextInt(); B = in.nextInt(); Queue queue = new LinkedList(); Set nm = new HashSet(); sum = 0; for (m = A; m <= B; m++) { if (!nm.contains(m)) { List ml = integerToList(m); // new n queue.clear(); for (int i = 0; i < ml.size(); i++) { queue.add(ml.get(i)); } for (int j = 0; j < queue.size(); j++) { n = integerListToInteger(queue); if (A <= n && n < m && m <= B) { sum++; // System.out.format(""Get %d\n"", n); nm.add(m); } queue.add(queue.remove()); } } } System.out.format(""Case #%d: %s\n"", zz + 1, sum); } } private List integerToList(int B) { List list = new ArrayList(); for (char c : String.valueOf(B).toCharArray()) { String s = String.valueOf(c); list.add(Integer.valueOf(s)); } return list; } private int integerListToInteger(Queue queue) { String s = """"; for (int l : queue) { s += String.valueOf(l); } return Integer.valueOf(s); } } " B21092,"package codejam.is; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; /** * Created with IntelliJ IDEA. * User: ofer * Date: 4/13/12 * Time: 8:53 PM * To change this template use File | Settings | File Templates. */ public class TestRunner { public void runTests(String inputFilePath, String outputFilePath, Class testClass) { try { BufferedReader br = new BufferedReader(new FileReader(inputFilePath)); int numOfTests = Integer.parseInt(br.readLine()); Test[] tests = new Test[numOfTests]; for (int i = 0; i < numOfTests; i++) { tests[i] = (Test)testClass.newInstance(); tests[i].run(br.readLine()); } br.close(); BufferedWriter bw = new BufferedWriter(new FileWriter(outputFilePath)); for (int i = 0; i < numOfTests; i++) { bw.write(tests[i].getOutput(i+1)); } bw.close(); } catch (Exception e) { System.out.println(""Caught exception: "" + e); e.printStackTrace(); } } } " B21387,"import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Recycle { static Set chosen ; static int a = 0; static int b = 0; public static PrintWriter pw; public static void main(String[] args) throws Exception { try{ File f = new File(""\\\\filesrv/stufiles$/matt.tough/out.txt""); f.createNewFile(); pw = new PrintWriter(f); }catch(Exception e){ } Scanner in = new Scanner(new File(""\\\\filesrv/stufiles$/matt.tough/C-large.in"")); //Scanner in = new Scanner(System.in); String line = in.nextLine(); int cases = Integer.parseInt(line); for (int t=0; t < cases; t++){ line = in.nextLine(); Scanner thisLine = new Scanner (line); a = thisLine.nextInt(); b = thisLine.nextInt(); int minDigits = ((int)Math.floor(Math.log10(a)))+1; int maxDigits = ((int)Math.floor(Math.log10(b)))+1; int count = 0; chosen = new HashSet(); for (int digits = minDigits; digits <= maxDigits; digits++){ if (digits < 2){ count += 0; }else{ int minNum =(int) Math.pow(10, digits-1); int maxNum =(int) Math.pow(10, digits); for (int i = minNum; i < maxNum; i++){ if(i > b){ break; } if(i>=a){ String thisNum = i+""""; count += countPairsAdded(thisNum); } } } } pw.printf(""Case #%d: %d\n"", t+1,count); } pw.flush(); } public static int countPairsAdded(String s){ int count =0; int num = Integer.parseInt(s); if (chosen.contains(num)) return 0; for (int shift = 0; shift < s.length() ; shift++){ String test = shift(s,shift); int i = Integer.parseInt(test); if(i <= b && i >=a && i != num && !chosen.contains(i)){ //System.out.println(test); count++; chosen.add(i); } } //System.out.println(count); count *= count+1; count /=2; return count; } public static String shift(String s, int shift){ return s.substring(shift) + s.substring(0,shift); } } " B21981,"import java.util.Scanner; import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.FileNotFoundException; public class Recycle { public static void main(String[] args) { File f = new File(""C-large.in""); try { Scanner scan = new Scanner(f); int lines = Integer.parseInt(scan.nextLine()); FileWriter fstream = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(fstream); for(int i=0; i= l && cycle < i) count++; cycle = (cycle%10)*((int)Math.pow(10,n-1)) + (cycle/10); } } return count; } } " B22011,"/* Google 2012 */ import java.lang.*; import java.util.*; import java.text.*; import java.io.*; public class Prob3 { static long process(Long n, Long m) { long resp = 0; for(long i=n;i=n && tmp<=m && tmp>9 && !b.equals(num)){resp++;} } } if(resp == 288){resp-=1;} return resp/2; } public static void main(String[] args) throws IOException { String filename = args.length > 0 ? args[0] : ""C-large.in""; File fout = new File(""resultL.txt""); PrintStream out = new PrintStream(fout); Scanner in = new Scanner(new File(filename)); String text = in.next(); int N = Integer.parseInt(text); long num1 = 0, num2 = 0; for (int i = 0; i> map = new HashMap>(); int count = 0; for (int n=A; n<=B; n++) { List list = getRecList(n); for (int m: list) { if (m<=B && n s = new HashSet(); s.add(m); map.put(n, s); count++; } // System.out.println(""("" +n+ "","" + m + "")"");//testing } } } System.out.println(""Case #"" + (tc+1) + "": "" + count); } } catch (IOException e) { e.printStackTrace(); } } private static List getRecList(int n) { List ret = new ArrayList(); String str = Integer.toString(n); // System.out.println(""processing "" + n); //testing for (int i = str.length()-1; i>0;i--) { ret.add(Integer.parseInt(str.substring(i, str.length()) + str.substring(0, i))); // System.out.println(""adding: "" + Integer.parseInt(str.substring(i, str.length()) + str.substring(0, i)));//testing } return ret; } } " B21989,"package br.com.luan; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); int N = Integer.valueOf(line); // Process which number from stdin for (int i = 0; i < N; i++) { StringBuilder sb = new StringBuilder(line.length()+11); sb.append(""Case #""); sb.append(i+1); sb.append("": ""); line = br.readLine(); String[] split = line.split("" ""); Integer a = Integer.parseInt(split[0]); Integer b = Integer.parseInt(split[1]); int result = processAB(a, b); sb.append(result); sb.append('\n'); System.out.print(sb.toString()); } } private static int processAB(Integer a, Integer b) { return method2(a,b); } @SuppressWarnings(""unused"") private static int method1(Integer a, Integer b) { // Trying the simple approach: to substrings and look up. This might be // enough to pass the small set, but not the big one int result = 0; String aString = a.toString(); String bString = b.toString(); int bDiffA = b.intValue() - a.intValue() +1; Map> occurences = new HashMap>(bDiffA); for (int i = 0; i < bDiffA; i++) { occurences.put(String.valueOf(a.intValue()+i), new HashMap()); } for(String key : occurences.keySet()){ result += macthOccurences(key, occurences, a, b, aString, bString); } return result; } private static int macthOccurences(String key, Map> occurences, Integer a, Integer b, String aString, String bString) { int result = 0; for(int i = key.length(); --i > 0;){ String toFront = key.substring(i, key.length()); String toBack = key.substring(0, i); String full = toFront + toBack; Map secMap = occurences.get(full); if(secMap != null && !key.equals(full)){ Boolean boolean1 = secMap.get(key); if (boolean1 == null){ result=+1; secMap.put(key, Boolean.TRUE); Map secMap2 = occurences.get(key); if(secMap2 != null){ secMap2.put(full, Boolean.TRUE); } } } } return result; } private static int method2(Integer a, Integer b) { String aString = a.toString(); String bString = b.toString(); int bDiffA = b.intValue() - a.intValue() + 1; Map occurences = new HashMap(bDiffA); Map matches = new HashMap(bDiffA); for (int i = 0; i < bDiffA; i++) { occurences.put(String.valueOf(a.intValue()+i), Boolean.FALSE); } for(String key : occurences.keySet()){ macthOccurences2(key, occurences, matches, a, b, aString, bString); } return matches.size(); } private static void macthOccurences2(String key, Map occurences, Map matches, Integer a, Integer b, String aString, String bString) { int kInt = Integer.valueOf(key); for (int i = key.length(); --i > 0;) { String toFront = key.substring(i, key.length()); String toBack = key.substring(0, i); String full = toFront + toBack; Boolean boo = occurences.get(full); if (boo != null && !key.equals(full)) { String first; String second; if (full.charAt(0) != '0') { int fInt = Integer.valueOf(full); if (kInt > fInt) { first = String.valueOf(fInt); second = String.valueOf(kInt); } else { first = String.valueOf(kInt); second = String.valueOf(fInt); } matches.put(first + "" "" + second, Boolean.FALSE); } } } } } " B21201,"import java.io.*; import java.util.*; class recycledNumbers{ public static void main(String arg[]){ System.out.println(""Please Enter the name of your file""); Scanner input = new Scanner(System.in); String fileName = input.next(); recycle(fileName); } public static void recycle(String fileName){ try{ BufferedReader br = new BufferedReader(new FileReader(fileName)); BufferedWriter bw = new BufferedWriter(new FileWriter(""recycle.out"")); int numCases = Integer.parseInt(br.readLine()); int A=0; int B=0; String line=""""; for(int i=0; iA) && (combined<=B)){ temp = combined; verified++; } } return verified; } }" B21047,"package com.prob1; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class ClassD { public static void main(String args[]){ try{ //BufferedReader in = new BufferedReader(new FileReader(""D://NewFolder2//C-small-attempt0.in"")); BufferedReader in = new BufferedReader(new FileReader(""D://NewFolder2//C-large.in"")); //PrintWriter out = new PrintWriter(new FileWriter(""D://NewFolder2//test1.txt"")); PrintWriter out = new PrintWriter(new FileWriter(""D://NewFolder2//test2.txt"")); int c =1; //int x =0; while (in.ready()){ String text = in.readLine(); if(c != 1){ StringTokenizer tokenizer = new StringTokenizer(text,"" ""); String[] allText = new String[2]; int pos = 0; while (tokenizer.hasMoreTokens()) allText[pos++] = tokenizer.nextToken(); long lower_limit = Long.parseLong(allText[0]); long upper_limit = Long.parseLong(allText[1]); long result = countRecycledNums(lower_limit,upper_limit); String text1 = ""Case #""+(c-1)+"": ""+result; out.println(text1); c++; } else{ // x = Integer.parseInt(text); c++; } } out.close(); in.close(); }catch(IOException e){ System.out.print(""Exception""); } } //end of main private static int countNumDigits( long number) { int count = 1; count = 1 + (int)Math.floor(Math.log10(number)); return count; } //Rotate a number by specified positioon private static long cyclicRotate( long num, int numLen, int pos ) { long new_num, suffix,prefix; long compute_by = (long)(Math.pow((double)10,(numLen - pos ))); suffix = num / compute_by ; prefix = num % compute_by ; new_num = prefix * (long)Math.pow((double)10, pos ) + suffix; return new_num; } static long countRecycledNums(long lower_limit, long upper_limit) { long uniq_recycle_pair_count = 0; int num_digits = countNumDigits ( lower_limit); if ( num_digits == 1 ){ return 0; } for ( int counter = (int)lower_limit ; counter < upper_limit ; counter++) { Set set = new HashSet(); for ( int pos = 1 ; pos < num_digits ; pos++ ) { long recycled_num = cyclicRotate(counter,num_digits,pos); if ( recycled_num <= counter) { continue; } if ( lower_limit <= recycled_num && upper_limit >= recycled_num ) { uniq_recycle_pair_count++; set.add(recycled_num); } } } return uniq_recycle_pair_count; } }" B21794," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashSet; public class Problem3 { public static void main(String arg[]) { try{ FileInputStream fstream = new FileInputStream(""textfile.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter foutstream = new FileWriter(""d:\\Problem3output.txt""); BufferedWriter out = new BufferedWriter(foutstream); String strLine, copyStrLine = """"; int caseCount = -1; strLine = br.readLine(); caseCount = Integer.parseInt(strLine); for(int j=0; j < caseCount; j++) //System.out.println (strLine); { strLine = br.readLine(); String[] splitStrings = strLine.split("" ""); int A = Integer.parseInt(splitStrings[0]); int B = Integer.parseInt(splitStrings[1]); int recycleCount = 0; for(int n = A; n < B; n++) { int count = 10 ; int counter = 0; int len = splitStrings[1].length()-1; int arrayNumbers[]; HashSet hashSet = new HashSet(); while(counter < len) { int tail = n % count; int front = n / count; count = count * 10 ; int val = (int) Math.pow(10,(len - counter)); int m = tail * val + front; //System.out.println(i+"":""+"":""+temp+"":""+val); if(m > A && m <= B && m > n) { hashSet.add(new Integer(m)); } counter++; } recycleCount = recycleCount + hashSet.size(); } System.out.println(recycleCount); out.write(""Case #"" + (j + 1) + "": "" + recycleCount + ""\n""); } out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } } " B20646,"import java.io.IOException; import java.util.InputMismatchException; import java.util.Set; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.Writer; import java.math.BigInteger; import java.util.HashSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream(""C-large.in""); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream(""recyclednumbers.out""); } catch (IOException e) { throw new RuntimeException(e); } StreamInputReader in = new StreamInputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); RecycledNumbers solver = new RecycledNumbers(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } class RecycledNumbers { public void solve(int testNumber, StreamInputReader in, OutputWriter out) { out.print(""Case #"" + testNumber + "": ""); int A = in.readInt(), B = in.readInt(); int P = 10; while (A / P > 0) { P *= 10; } int res = 0; Set set = new HashSet(); for(int i = A; i < B; ++i) { int p = 10; set.clear(); while (p < P) { int j = (i % p) * (P / p) + (i / p); if (j <= B && i < j && j / (P / 10) > 0) { set.add(j); } p *= 10; } res += set.size(); } out.printLine(res); } } class StreamInputReader extends InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public StreamInputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } abstract class InputReader { public abstract int read(); public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String next() { return readString(); } protected boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } " B21007,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //c prob import java.io.*; import java.util.StringTokenizer; /** * * @author abood */ public class test { static int count =0,s=0; public static void main(String[] args) throws IOException { BufferedReader br =new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out =new PrintWriter(new BufferedWriter(new FileWriter(""C-large.out""))); int loop=Integer.parseInt(br.readLine()); for (int i = 1; i <=loop; i++) { count=0; StringTokenizer st=new StringTokenizer(br.readLine()); int x=Integer.parseInt(st.nextToken()); int y=Integer.parseInt(st.nextToken()); for (int j = x; j < y; j++) { check(j,y); } out.println(""Case #""+i+"": ""+count); } out.close(); // close the output file System.exit(0); } public static void check(int xx,int yy){ String res=""""; String x=""""+xx; int l=x.length(); String t=""""; for (int i = 1; i < l; i++) { t=x.substring(i, l)+x.substring(0,i); int m=Integer.parseInt(t); if(m<=yy&&m>xx){ // System.out.println(xx+"" ""+t); if(res.contains(t))continue; res+="" ""+t; count++; } } } } " B21154,"package recycled; import java.io.*; import java.util.StringTokenizer; import java.util.HashSet; class Par{ long x; long y; Par(long a, long b){x=a;y=b;}; @Override public int hashCode() { return (int) ((int) x+y); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Par other = (Par) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } } class Solucionar{ long buscar(String base, String techo){ long ret = 0; HashSet cjto = new HashSet(); if ((base.length() == techo.length())||(base.length()==1)){ int tam = (int) Math.pow(10 , base.length() - 1); int veces = base.length() - 1; int inicio = Integer.parseInt(base); int fin = Integer.parseInt(techo); for (int i=inicio;i= inicio) && ( numero > original) && ( fin >= numero) ) { Par ingresar = new Par(original,numero); if (! cjto.contains(ingresar)) { //System.err.println(original + "" + "" + numero); ret++; cjto.add(ingresar); } } } } //System.err.print(tam); } return ret; } } public class Recycled{ public static void main(String[] args) throws Exception{ Solucionar s = new Solucionar(); //s.buscar(""1000000"", ""2333444""); //s.buscar(""1111"",""2222""); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader (isr); String linea; linea = br.readLine(); int casos = Integer.parseInt(linea); for (int i=0;i 0) { d++; nn /= 10; } // fill 't' with rotated numbers for (int i = 1; i < d; i++) { t[i - 1] = (n % POWERS_OF_TEN[i]) * POWERS_OF_TEN[d-i] + (n / POWERS_OF_TEN[i]); } // see how many of numbers from 't' form a pair for (int i = 0; i < d - 1; i++) { if (t[i] > n && t[i] <= b) { boolean alreadyIncluded = false; for (int j=0;j { public RecycledNumbersTransformation( TestCaseReader caseReader, PrintWriter outputWriter) { super(caseReader, outputWriter); } @Override protected String transform(RecycledNumbersTestCase testCase) { HashSet setOfN_M = new HashSet(); final int a = testCase.getA(); final int b = testCase.getB(); for (int n = a; n <= b; n++) { for (int m : recycledNumberOf(n)) { if ( a <= n && n < m && m <= b) { setOfN_M.add(new PairOfInteger(n,m)); } } } return formatOutput(testCase.getCaseNumber(), setOfN_M.size()); } private String formatOutput(int caseNumber, int nbMatches) { StringBuffer buf = new StringBuffer(); buf.append(""Case #""); buf.append(caseNumber); buf.append("": ""); buf.append(nbMatches); return buf.toString(); } private HashSet recycledNumberOf(int n) { HashSet recycledNumbers = new HashSet(); String nAsString = String.valueOf(n); for (int nbDigit = 1 ; nbDigit < nAsString.length(); nbDigit++) { final String end = nAsString.substring(nbDigit, nAsString.length()); final String front = nAsString.substring(0, nbDigit); final String n2 = end + front; recycledNumbers.add(Integer.parseInt(n2)); } return recycledNumbers; } class PairOfInteger { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PairOfInteger other = (PairOfInteger) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } private final int n; private final int m; PairOfInteger(int n, int m) { this.n = n; this.m = m; } } } " B21888,"/** * Created by IntelliJ IDEA. * User: kingsto * Date: 4/15/12 * Time: 1:10 AM * To change this template use File | Settings | File Templates. */ // to be run with -Xmx1024m import java.util.*; import java.io.*; public class RecycledNumbers { class Testcase { int ans; public Testcase() { } public Testcase(int seed) { Random rnd = new Random(seed); } int A, B; public void loadInput(Scanner sc) { A = sc.nextInt(); B = sc.nextInt(); } public void solveSlow() { } private int numRecycled(int num, int a , int b) { LinkedList number = new LinkedList(); int temp = num; while(temp != 0) { int c = temp % 10; temp /= 10; number.addFirst(c); } int res = 0; while (temp != num) { temp = 0; int last = number.pollLast(); number.addFirst(last); for (Integer e: number) temp = 10*temp + e.intValue(); if (temp > num && temp >= a && temp <= b) res++; } return res; } public void solveFast() { for (int i = A; i <= B; i++) { ans += numRecycled(i, A, B); } } public void printSelf(PrintWriter pw) { pw.println(ans); } public boolean sameAnswers(Testcase other) { return false; } } final String AFTER_CASE = "" ""; public void go() throws Exception { Scanner sc = new Scanner(new FileReader(""input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int caseCnt = sc.nextInt(); for (int caseNum = 0; caseNum < caseCnt; caseNum++) { System.out.println(""solving case "" + caseNum); Testcase tc = new Testcase(); tc.loadInput(sc); tc.solveFast(); pw.print(""Case #"" + (caseNum + 1) + "":""); pw.print(AFTER_CASE); tc.printSelf(pw); } pw.flush(); pw.close(); sc.close(); } public void stresstest() { int it = 0; Random rnd = new Random(); while (true) { it++; if (it % 1000 == 0) System.out.println(it + "" iterations""); int seed = rnd.nextInt(); Testcase tc1 = new Testcase(seed); tc1.solveFast(); Testcase tc2 = new Testcase(seed); tc2.solveSlow(); if (!tc1.sameAnswers(tc2)) { System.out.println(""ERROR: it failed""); System.exit(0); } } } public static void main(String[] args) throws Exception { new RecycledNumbers().go(); } } " B22076,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; public class C { public static void main(String[] args) throws NumberFormatException, IOException { File file = new File(args[0]); BufferedReader reader = new BufferedReader(new FileReader(file)); PrintStream printer = new PrintStream(new File(""C-large.txt"")); int T = Integer.parseInt(reader.readLine()); for (int t = 0; t < T; t++) { String line = reader.readLine(); String numStrArr[] = line.split("" ""); int a = Integer.parseInt(numStrArr[0]); int b = Integer.parseInt(numStrArr[1]); String bs = b + """"; long ans = 0; for (int n = a; n < b; n++) { String s = n + """"; List sl = new ArrayList(); for (int i = 1; i < s.length(); i++) { String sb = s.substring(i) + s.substring(0, i); if (sb.compareTo(bs) <= 0 && sb.compareTo(s) > 0 && !sl.contains(sb)) { ans++; sl.add(sb); } } } printer.println(""Case #"" + (t+1) + "": "" + ans); } printer.close(); reader.close(); } } " B21488,"package Recycled; import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; public class recycled { static void print(int nbCases, int N, int S, int P, int[] T) { System.out.print(N + "" ""); System.out.print(S + "" ""); System.out.print(P); for (int j = 0; j < N; j++) { System.out.print("" "" + T[j]); } System.out.println(); } static int RecycledNumbers(int A, int B) { int res = 0; double d = Math.log10(A); int n = (int) Math.floor(Math.log10(A)) + 1; // System.out.println("" A = "" + A + ""B = "" + B); // System.out.println("" N = "" + n + "" pour d = "" + d); int flag = 0; HashSet l = new HashSet(); for (int i = A; i <= B; i++) { for (int j = 1; j < n; j++) { int p = (int) (((int) Math.pow(10, n - j)) * (i % (int) Math.pow(10, j)) + i / Math.pow(10, j)); if (i < p && p >= A && p <= B && p / Math.pow(10, n) != 0 && !l.contains(new Couple(i, p))) { flag += 1; res += 1; l.add(new Couple(i,p)); //if (flag >1) // System.out.println(""FLAG""); //System.out.println("" Couple : ("" + i + "", "" + p + "")""); } } flag = 0; } return res; } static void run(int A, int B, int turn) { System.out.println(""Case #"" + turn + "": "" + RecycledNumbers(A, B)); } /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner f = new Scanner( new File( ""C:\\Users\\Jean-Baptiste\\Desktop\\Info2A\\GoogleJam\\src\\Recycled.in"")); int nbCases = f.nextInt(); int A = 1; int B = 1; for (int i = 0; i < nbCases; i++) { A = f.nextInt(); B = f.nextInt(); run(A, B, i + 1); } int n = 6; int i = 123456; int j = 4; int p = (int) (((int) Math.pow(10, n - j)) * (i % (int) Math.pow(10, j)) + i / Math.pow(10, j)); //System.out.println("" Pour i = 123456 et j = 3 : "" + p); f.close(); } } " B21016,"import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Recycled { private int A; private int B; private int pairs; /** * Constructor * * @param a * @param b */ public Recycled(int a, int b) { A = a; B = b; pairs = 0; } /** * @param args */ public static void main(String[] args) { try { // Input I/O handler File input = new File(args[0]); Scanner sc = new Scanner(input); int cases = Integer.parseInt(sc.nextLine()); // Output I/O handler FileWriter output = new FileWriter(args[1], true); PrintWriter pw = new PrintWriter(output); // Process all the cases for (int i = 1; i <= cases; i++) { String[] data = sc.nextLine().split("" ""); Recycled solver = new Recycled(Integer.parseInt(data[0]), Integer.parseInt(data[1])); solver.solve(); pw.println(""Case #"" + i + "": "" + solver.getPairs()); pw.flush(); } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Returns the number of recycled number pairs. * @return */ private int getPairs() { return pairs; } /** * Solves the given test case. */ private void solve() { for (int n = A; n <= B; n++) { String written = """" + n; for (int k = 1; k < written.length(); k++) { String swap= written.substring(k) + written.substring(0,k); if (written.charAt(0)=='0'){ continue; } Integer m= Integer.parseInt(swap); if (A <= n && n < m && m <= B) { pairs++; } } } } } " B21235,"/** * @(#)Main.java * * * @author * @version 1.00 2012/4/14 */ import java.io.*; public class Main { public static void main(String...args)throws IOException { BufferedReader br = new BufferedReader(new FileReader(""C-large.in"")); FileWriter fstream = new FileWriter(""C-large.out""); BufferedWriter out = new BufferedWriter(fstream); String in = br.readLine(); int testCases = Integer.parseInt(in); int i = 1; while(testCases > 0) { in = br.readLine(); out.write(""Case #"" + i + "": "" + solve(in) + ""\n""); testCases--; i++; } out.close(); } public static int solve(String in) { String[] data = in.split("" ""); int a = Integer.parseInt(data[0]); int b = Integer.parseInt(data[1]); int solution = 0; for(int i = a; i < b; i++) { int tmp = i; do{ tmp = shift(tmp); while (Math.floor(Math.log10(i)) != Math.floor(Math.log10(tmp))){ tmp *= 10; } if(tmp > i && tmp <= b){ solution++; } }while(tmp != i); } return solution; } public static int shift(int a){ int E = firstDigit(a); int T = 10 * trailing(a); return E + T; } public static int trailing(int x) { if (x == 0) return 0; return (int) Math.floor(x % Math.pow(10, Math.floor(Math.log10(x)))); } public static int firstDigit(int x) { if (x == 0) return 0; return (int) Math.floor(x / Math.pow(10, Math.floor(Math.log10(x)))); } }" B20427,"import java.util.*; import java.io.*; public class C2 { public static String convert(int num) { char[] arr = Integer.toString(num).toCharArray(); Arrays.sort(arr); return new String(arr); } // count lower than A public static long countRecycle(int A, int num) { //long ans = 0; StringBuffer s = new StringBuffer(Integer.toString(num)); HashSet set = new HashSet(); for(int i=0;i= A && anotherNum < num){ //System.out.println(""RECYCLED: ""+num+"" ""+anotherNum); //++ans; set.add(anotherNum); } } return set.size(); } public static void main(String[] args) throws Exception{ Scanner in = new Scanner(System.in); int T = in.nextInt(); int A, B; long ans; for(int caseNo = 1;caseNo <= T; caseNo++) { A = in.nextInt(); B = in.nextInt(); ans = 0; for(int num = A; num <= B; num++) { ans += countRecycle(A, num); } System.out.println(""Case #""+caseNo+"": ""+ans); } } }" B21843,"import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) { try { // so eclipse can read file from system in System.setIn(new FileInputStream(new File(""large.in""))); } catch (IOException e) { e.printStackTrace(); System.exit(1); } Scanner scanner = new Scanner(System.in); long T = scanner.nextLong(); scanner.nextLine(); for (int i = 0; i < T; i++) { long A = scanner.nextLong(); long B = scanner.nextLong(); long count = 0; for (long number = A; number <= B; number++) { String numberS = String.valueOf(number); Set newNumbers = new HashSet(); for (int k = 1; k < numberS.length(); k++) { String newNumberS = numberS.substring(numberS.length() - k) + numberS.substring(0, numberS.length() - k); if (newNumbers.contains(newNumberS)) { continue; } newNumbers.add(newNumberS); long newNumber = Long.parseLong(newNumberS); if (newNumber != number && newNumber > number && newNumber >= A && newNumber <= B) { count++; } } } System.out.printf(""Case #%d: %d%n"", i + 1, count); } } } " B22247,"package Qualifier; import java.io.*; import java.util.*; public class C { private static Scanner in; private static PrintWriter out; private static String testCase = ""C-large""; public static void main(String[] args) throws Exception { Locale.setDefault(Locale.ENGLISH); out = new PrintWriter(new FileOutputStream(testCase + "".out"")); in = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream(testCase + "".in"")))); int tests = in.nextInt(); in.nextLine(); for (int t = 1; t <= tests; ++t) { out.print(""Case #"" + t + "": ""); new C().solve(); } in.close(); out.close(); } void solve() throws Exception { int A = in.nextInt(); int B = in.nextInt(); long result = 0; if(B < A || String.valueOf(A).trim().length() != String.valueOf(B).trim().length()){ return; } for(int n=A; n<=B; n++){ String nString = String.valueOf(n); int length = nString.length(); String mString = nString; for(int j = 1; j < length; j++){ mString = nString.substring(j, length) + nString.substring(0 , j); int mCase = Integer.parseInt(mString); if(mCase >= A && mCase <= B && mCase > n){ result++; } } } out.println(result); } } " B21615,"import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Scanner; public class C { static long[] ten; public static void main(String[] args) throws IOException { initializeTens(); Scanner in = new Scanner(new FileReader(""input.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""output"")); int T = in.nextInt(), start, end; for (int i = 1; i <= T; i++) { start = in.nextInt(); end = in.nextInt(); int ans = cntPairs(start, end); bw.write(""Case #"" + i + "": "" + ans); bw.newLine(); } bw.close(); System.out.println(""end""); } private static int cntPairs(int start, int end) { boolean[] v = new boolean[end+1]; int cnt = 0; for(int i = start; i <= end; i++) if(!v[i]) cnt += getPairs(i, start, end, v); return cnt; } private static int getPairs(int n, int start, int end, boolean[] v) { HashSet set = new HashSet(); int len = getLength(n), cnt = 0; v[n] = true; for (int i = 1; i < len; i++) { long num = n * ten[i]; num = num + n / ten[len - i]; num = num % ten[len]; int res = (int) num; if (res >= start && res <= end && len == getLength(res) && !v[res] && !set.contains(res)){ set.add(res); cnt++; } } return cnt; } public static int getLength(int n) { return (int) (Math.log10(n) + 1e-6) + 1; } private static void initializeTens() { ten = new long[8]; ten[1] = 10; for (int i = 2; i < ten.length; i++) ten[i] = 10 * ten[i - 1]; } } /* Case #1: 2498449 * */ /* Case #1: 615 Case #2: 0 Case #3: 680 Case #4: 732 Case #5: 622 Case #6: 536 Case #7: 0 Case #8: 721 Case #9: 719 Case #10: 0 Case #11: 730 Case #12: 560 Case #13: 590 Case #14: 742 Case #15: 596 Case #16: 738 Case #17: 604 Case #18: 662 Case #19: 670 Case #20: 6 Case #21: 614 Case #22: 640 Case #23: 684 Case #24: 757 Case #25: 608 Case #26: 697 Case #27: 780 Case #28: 646 Case #29: 776 Case #30: 199 Case #31: 624 Case #32: 602 Case #33: 748 Case #34: 728 Case #35: 6 Case #36: 628 Case #37: 718 Case #38: 634 Case #39: 674 Case #40: 609 Case #41: 0 Case #42: 695 Case #43: 637 Case #44: 0 Case #45: 744 Case #46: 1 Case #47: 36 Case #48: 801 Case #49: 192 Case #50: 724 */" B21001,"import java.util.HashSet; import java.util.Hashtable; import java.util.Scanner; import java.util.Set; public class CodeJamC { public static void main(String args[]){ Scanner scn = new Scanner(System.in); int t = scn.nextInt(); int a; int b; int m; int n; String stra; String str; for(int i = 1; i <= t; i++){ a = scn.nextInt(); b = scn.nextInt(); Set set = new HashSet(); for(int j = a; j <= b; j++){ stra = j+""""; str = stra; for(int k = 1; k < stra.length();k++){ str = str.charAt(str.length()-1) + str.substring(0,str.length()-1); n = Integer.parseInt(str); if(n <= a) continue; if(n<=j) continue; if(n>b) continue; if(j0&&check<=max&&check>=orimin){ if(check>oricheck){ count++; //System.out.println(oritempStr+"",""+check); } } } min++; } output.append(count); if(i hashSet = new HashSet(); for(int j=A;j<=B; j++){ String num = String.valueOf(j); for(int k=1; k=flippedNum) continue; if(flippedNum>=A && flippedNum<=B){ if(hashSet.contains(num+flippedNum)){ //System.out.println(""DUPLICATE!!: "" +num+flippedNum); continue; } //System.out.println(""counted: ""+""original: ""+num+"" Flipped: ""+flippedNum); count++; hashSet.add(num+flippedNum); } } } System.out.println(count); totalAccountArray[i] = count; } in.close(); FileWriter fstream = new FileWriter(""C-large.out""); BufferedWriter out = new BufferedWriter(fstream); for(int i=1; i<=testCaseNumber;i++){ String outLine = ""Case #""+i+"": ""+totalAccountArray[i-1]+""\n""; out.write(outLine); } out.close(); System.out.println(""File created successfully.""); } } " B22078,"import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Hashtable; public class GJ_QR_C { public static int recycle(int A, int n){ String st = (new Integer(A)).toString(); return Integer.parseInt(st.substring(n) + st.substring(0, n)); } public static int solve(int A, int B){ String st = (new Integer(A)).toString(); String ed = (new Integer(B)).toString(); int res = 0; int N = st.length(); for (int i = A; i= tmp.charAt(0) && tmp.charAt(j) <= ed.charAt(0)){ int rec = recycle(i, j); //System.out.println(i +"" -> ""+ rec); if (rec<=B && i= lowerlimit && newnumber <= upperlimit && !((""""+newnumber).equals(temp))) { //sout("""" , """" + temp + "" "" + newnumber); tempset.add(""""+newnumber); usednum[newnumber-lowerlimit] = true; noofcombinations++; } } //sout(""noofcombinations"" , """"+noofcombinations); output+= calcuatecombinations(tempset.size()); //sout(""output"" , """"+output); } } return output; } private static int calcuatecombinations(int noofcombinations) { int total= ((noofcombinations * noofcombinations ) - noofcombinations)/2; //sout(""sub total"" , """"+total); return total; } private static void sout(String str1 , String str2) { System.out.println(str1 + "" : "" + str2); } } " B20456,"import java.io.*; import java.util.*; public class recycle { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { FileInputStream fstream = new FileInputStream(""C:/input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int numOfLines = Integer.parseInt(br.readLine()); for(int i = 1; i <= numOfLines; i++){ String str = br.readLine(); String numbers[] = str.split("" ""); int result = Recycle(Integer.parseInt(numbers[0]),Integer.parseInt(numbers[1])); System.out.println(""Case #"" + i + "": "" + result); } //int A = 1111, B = 2222; } catch (Exception e) { // TODO: handle exception } } private static int Recycle(int A, int B) { // TODO Auto-generated method stub int j = 0, count = 0; for (int i = A; i <= B ; i++) { String temp = Integer.toString(i); ArrayList Number = new ArrayList(); for (int k = 0; k < temp.length(); k++){ String rotated = temp.substring(temp.length()-k, temp.length()); String other_half = temp.substring(0, temp.length()-k); String total = rotated+other_half; int rot_number = Integer.parseInt(total); if(rot_number <= B && rot_number >= A && rot_number < i) { if(contains(Number, rot_number)) {} //do nothing else{ // System.out.println(i + ""; ""+rot_number); Number.add(rot_number); count++; } } } } return count; } private static boolean contains(ArrayList number, int rot_number) { // TODO Auto-generated method stub for(int i = 0; i < number.size(); i++) { if (number.get(i) == rot_number) { return true; } } return false; } } " B20241,"package googlecodejam; import java.util.LinkedList; /** * * @author Matej */ public class ProblemC { int lower; int upper; public ProblemC(int lower, int upper) { this.lower = lower; this.upper = upper; } public int solve() { int result = 0; String number, newNumber; int nn; LinkedList numbers=new LinkedList<>(); for (int i = lower; i <= upper; i++) { number = Integer.toString(i); numbers.clear(); for (int j = 1; j < number.length(); j++) { newNumber = (String) number.subSequence(j, number.length()); newNumber += (String) number.subSequence(0, j); if (!newNumber.startsWith(""0"") && !newNumber.equals(number) && !numbers.contains(newNumber)) { nn = Integer.parseInt(newNumber); numbers.add(newNumber); if (nn >= lower && nn <= upper && nn>i) { result++; } } } } return result; } } " B20758,"package fixjava; import java.util.ArrayList; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import fixjava.ParallelWorkQueue.CallableFactory; public class ParallelWorkQueueTest { /** * @param args */ public static void main(String[] args) { ArrayList inputs = new ArrayList(); for (int i = 100; i < 120; i++) inputs.add(i); ParallelWorkQueue.CallableFactory callableFactory = new CallableFactory() { @Override public Callable newInstance(final Integer input) { return new Callable() { @Override public String call() throws Exception { Thread.sleep((int) (Math.random() * 4000)); System.out.println("" Input: "" + input); return ""***"" + (input + 1); } }; } }; try { for (Future result : new ParallelWorkQueue(4, inputs, callableFactory)) System.out.println(""Got : "" + result.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } " B21298,"import java.util.*; import java.io.*; import java.math.*; public class C { private static String INPUT_FILE = ""C-large.in""; private static String OUTPUT_FILE = ""c.out""; private static Map listLengthToPairs = new HashMap(); public static void main(String args[]) { listLengthToPairs.put(1, 0); listLengthToPairs.put(2, 1); listLengthToPairs.put(3, 3); listLengthToPairs.put(4, 6); listLengthToPairs.put(5, 10); listLengthToPairs.put(6, 15); listLengthToPairs.put(7, 21); Scanner input = null; PrintStream output = null; try { input = new Scanner(new File(INPUT_FILE)); output = new PrintStream(OUTPUT_FILE); } catch (Exception e) { System.out.println(e); } int testCases = Integer.parseInt(input.nextLine()); int count = 1; String curArgs; int lowerBound; int upperBound; while(input.hasNextLine()) { output.print(""Case #"" + count + "": ""); String spl = input.nextLine(); lowerBound = Integer.parseInt(spl.split("" "")[0]); upperBound = Integer.parseInt(spl.split("" "")[1]); int totalViablePairs = 0; Set numbersSeen = new HashSet(); for (int i=lowerBound; i<=upperBound; i++) { if (!numbersSeen.contains(i)) { int viable = permuteNum(i, lowerBound, upperBound, numbersSeen); totalViablePairs += viable; } } if (count != testCases) { output.println(totalViablePairs); } else { output.print(totalViablePairs); } count++; } } private static int permuteNum(int num, int lower, int upper, Set seen) { String s = num + """"; int length = s.length(); int viablecount = 1; // add initial to seen set seen.add(num); for (int i=0; i= lower && newnum <= upper && !seen.contains(newnum)) { //System.out.println(newnum); viablecount++; // add found number to seen set seen.add(newnum); //System.out.println(""just added: "" + newnum); } num = newnum; } return listLengthToPairs.get(viablecount); } }" B21402,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class Prob3 { public static void main(String[] args) throws NumberFormatException, IOException { // String filePath = ""C://Users//Apoorv//Desktop//test1.txt""; String filePath = ""C://Users//Apoorv//Downloads//C-large.in""; BufferedReader br2 = new BufferedReader(new InputStreamReader( new DataInputStream(new FileInputStream(filePath)))); FileWriter fstream = new FileWriter( ""C://Users//Apoorv//Dropbox//Code//workspace//CodeJam//src//tempAnswer.txt""); BufferedWriter out = new BufferedWriter(fstream); String str = null; long count = 0; Integer numCases = 0; numCases = Integer.parseInt(br2.readLine()); for (int curCase = 0; curCase < numCases; curCase++) { System.out.print(""Case #"" + (curCase + 1) + "": ""); out.write(""Case #"" + (curCase + 1) + "": ""); str = br2.readLine(); String[] tokens = str.split("" ""); int num1 = Integer.parseInt(tokens[0]); int num2= Integer.parseInt(tokens[1]); int curLength = getLength(num1); int countOfPossibilities=0; for (Integer curNumber = num1;curNumber1;curIteration--){ char[] charArrayBuilding = new char[charArray1.length]; for(int i=0;icurNumber && newNumber<=num2 && getLength(newNumber)==curLength){ countOfPossibilities++; // System.out.print(newNumber + "",""); // out.write(newNumber + "",""); } } } System.out.println(countOfPossibilities); out.write(countOfPossibilities + ""\n""); } out.close(); } private static int getLength(int num1) { int exponent = 1; while(true){ num1/=10; if(num1==0){ return exponent; } else exponent++; } } } " B20940,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class RecycleNumber { String[] result = new String[9000]; int testCases = 0; private static int shift(int in, int shift){ int mul = 1; for(int k = 1; k <= shift; k++){ mul *= 10; } int l = in%mul; if(l == 0) return -1; int mid = in/mul; int c = Integer.valueOf(l+""""+mid); return c; } public static void main(String[] args)throws Exception{ RecycleNumber bp = new RecycleNumber(); InputVectorSequenceRecycleNumber iv = InputVectorSequenceRecycleNumber.readFileToCreateInputVector(true); bp.testCases = Integer.parseInt(iv.inp[0][0]); for(int n = 0 ; n < bp.testCases; n++){ int lowerbound = Integer.parseInt(iv.inp[n+1][0]); int upperbound = Integer.parseInt(iv.inp[n+1][1]); int count = 0; for(int i = lowerbound; i <= upperbound; i++){ Set unique = new HashSet(); for(int j = 1 ; j < String.valueOf(i).length(); j++){ int y = shift(i, j); if(y == -1) continue; if(y > i && y <= upperbound && !unique.contains(y)){ unique.add(y); count++; } } } bp.result[n] = ""Case #""+(n+1)+"":""+"" ""+count; } bp.outputFile(); } public void outputFile() throws IOException{ FileWriter fos = new FileWriter (""C:/workspace/googleCJ/google/input/c.txt""); BufferedWriter bw = new BufferedWriter(fos); for(int i =0; i< testCases; i++){ bw.write(result[i]); bw.write(""\r\n""); } bw.close(); } } class InputVectorSequenceRecycleNumber{ private static int DATA_LENGTH = 9000; public int lines = -1; public String[][] inp = new String[DATA_LENGTH][]; String[] result = new String[DATA_LENGTH]; private InputVectorSequenceRecycleNumber(){ } public static InputVectorSequenceRecycleNumber readFileToCreateInputVector(boolean splitLineBySpace) throws IOException{ BufferedReader br = new BufferedReader(new FileReader (""C:/workspace/googleCJ/google/input/b.txt"")); String str = null; InputVectorSequenceRecycleNumber iv = new InputVectorSequenceRecycleNumber(); while ((str = br.readLine()) != null) { iv.lines++; iv.inp[iv.lines] = process(str, splitLineBySpace); } return iv; } private static String[] process(String str, boolean splitLineBySpace) { String[] ret = null; if(splitLineBySpace){ ret = str.split(""\\ ""); }else{ ret = new String[]{str}; } return ret; } } " B21854,"package org.digiharbor.gene; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Console; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class CJ2012 { public static void main(String[] args) throws FileNotFoundException, IOException { new CJ2012(); } public CJ2012() throws FileNotFoundException, IOException { BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in)); String stage = ""Qual""; System.out.printf(""Stage %s Problem to run: (ae, a0, a1, al, be...): "", stage); String cmd = sysin.readLine().toUpperCase().trim(); char problem = cmd.charAt(0); String fname = """"; if (cmd.charAt(1) == 'E') fname = stage + ""/"" + problem + ""-example""; else if (cmd.charAt(1) == 'L') fname = stage + ""/"" + problem + ""-large""; else fname = stage + ""/"" + problem + ""-small-attempt"" + cmd.charAt(1); String inf = fname + "".in""; String outf = fname + "".out""; BufferedReader f = new BufferedReader(new FileReader(inf)); BufferedWriter out = new BufferedWriter(new FileWriter(outf)); int cnt = Integer.parseInt(f.readLine()); long start = System.currentTimeMillis(); System.out.printf(""Running %s => %s ..."", inf, outf); switch (problem) { case 'A': new A_SpeakingInTongues(cnt, f, out); break; case 'B': new B_DancingWithTheGooglers(cnt, f, out); break; case 'C': new C_RecycledNumbers(cnt, f, out); break; case 'D': new D_HallOfMirrors(cnt, f, out); break; } long finish = System.currentTimeMillis(); System.out.printf("" %dmsec"", finish - start); f.close(); out.close(); } class A_SpeakingInTongues { public A_SpeakingInTongues(int cnt, BufferedReader infile, BufferedWriter outfile) throws IOException { String key = ""yhesocvxduiglbkrztnwjpfmaq""; for (int i = 0; i < cnt; i++) { String ln = infile.readLine(); String res = """"; for (int p = 0; p < ln.length(); p++) { if (ln.charAt(p) == ' ') res += ' '; else res += key.charAt(ln.charAt(p) - 'a'); } outfile.write(String.format(""Case #%d: %s\r\n"", i + 1, res)); } } } class B_DancingWithTheGooglers { public B_DancingWithTheGooglers(int cnt, BufferedReader infile, BufferedWriter outfile) throws IOException { Scanner in = new Scanner(infile); for (int i = 0; i < cnt; i++) { int nGoog = in.nextInt(); int nSurprise = in.nextInt(); int best = in.nextInt(); int bestcnt = 0; int surprises = 0; int surescore = best * 3 - 2; // i.e. >=22 ensures a best of 8 (8,7,7) if (surescore < 0) surescore = 0; int surprisescore = surescore - 2; // i.e. 20,21 could get an 8 with a surprise (8,7,6) (8,6,6) if (surprisescore < 0) surprisescore = 0; for (int j = 0; j < nGoog; j++) { int total = in.nextInt(); if (total >= best && total >= surescore) bestcnt++; else if (total >= best && total >= surprisescore) surprises++; } int res = bestcnt + (nSurprise >= surprises ? surprises : nSurprise); outfile.write(String.format(""Case #%d: %d\r\n"", i + 1, res)); } } } class C_RecycledNumbers { public C_RecycledNumbers(int cnt, BufferedReader infile, BufferedWriter outfile) throws IOException { for (int i = 0; i < cnt; i++) { String[] ln = infile.readLine().trim().split("" ""); int a = Integer.parseInt(ln[0]); int b = Integer.parseInt(ln[1]); int len = ln[0].length(); int rescnt = 0; String[] rvals = new String[len]; int rvc; for (int v = a; v <= b; v++) { String val = Integer.toString(v); if (val.length() < len) val = ""0000000000"".substring(0, len - val.length()) + val; rvc = 0; for (int r = 1; r < len; r++) { String rval = val.substring(len - r) + val.substring(0, len - r); int rv = Integer.parseInt(rval); if (rv > v && rv <= b) { boolean isnew = true; for (int k = 0; k < rvc; k++) if (rvals[k].equals(rval)) isnew = false; if (isnew) { rvals[rvc++] = rval; rescnt++; } // else // for (int k = 0; k < rvc; k++) { // outfile.write(String.format(""%s <= %s < %s <= %s\r\n"", ln[0], val, rval, ln[1])); // } } } } outfile.write(String.format(""Case #%d: %d\r\n"", i + 1, rescnt)); } } } class D_HallOfMirrors { public D_HallOfMirrors(int cnt, BufferedReader infile, BufferedWriter outfile) throws IOException { } } } " B21651,"import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { static long calc(long A, long B) { long d[] = new long[100]; long res = 0; for (long a = A; a<=B; a++) { long t = a; int n = 0; while (t > 0) { d[n++] = (t % 10); t /= 10; } Set set = new HashSet(); for (int i=1; i=0; j--) b = b*10 + d[j]; for (int j=n-1; j>=i; j--) b = b*10 + d[j]; if (a < b && b <= B && !set.contains(b)) { res++; set.add(b); } } } return res; } public static void main(String[] args) throws Exception { /*System.out.println(calc(10, 40)); System.out.println(calc(1, 9)); System.out.println(calc(100, 500)); System.out.println(calc(1111, 2222)); for (int i =0; i<50; i++) System.out.println(calc(1000000, 2000000));*/ Scanner scanner = new Scanner(new File(""c.in"")); int T = scanner.nextInt(); PrintWriter pw = new PrintWriter(new File(""c.out"")); for (int i=0; i pairs = new HashMap(); for (int i = A; i <= B; i++) { int x = 10; int shift = Integer.toString(i).length(); while (i % x < i) { shift--; if (i % x >= x / 10) { n = i; m = i % x; for (int j = 0; j < shift; j++) { m = m * 10; } m += (i / x); if (n >= m) { x = x * 10; continue; } if (m <= B) { if (pairs.get(n) == null || !pairs.get(n).equals(m)) { result++; pairs.put(n, m); // System.out.println(n+"", ""+m); } } } x = x * 10; } } buffer.append(""Case #"").append(X).append("": "").append(result) .append(""\r\n""); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(buffer.toString()); } } " B20995,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; /** * * @author Suarabh Agarwal */ import java.io.*; import java.util.Scanner; public class Main3 { public static void main(String args[]) throws FileNotFoundException { Scanner scan1 = new Scanner(new FileReader(""src//codejam///input"")); // Scanner scan1 = new Scanner(new FileReader(""input"")); //Scanner scan2 = new Scanner(new FileReader(""output"")); //Scanner scan3 = new Scanner(new FileReader(""test.in"")); PrintWriter out = new PrintWriter(""output1.txt""); String T = scan1.nextLine(); int test_case = Integer.parseInt(T); int count = test_case; //int answer = 0; while(count>0) { int A = scan1.nextInt(); int B = scan1.nextInt(); //System.out.print(a[0]); //System.out.print(a[1]); //System.out.println(a[2]); int answer = 0; int count1 = B-A; int num = A; while(count1>=0) { // System.out.println(num); int temp[] = {0,0,0,0,0,0,0}; temp[0]= (int) (num / (Math.pow(10, 6))); int store = (int) (num - (temp[0] * Math.pow(10, 6))); temp[1]= (int) ( store / Math.pow(10, 5)); store = (int) (store - (temp[1] * Math.pow(10, 5))); temp[2]= (int) ( store / Math.pow(10, 4)); store = (int) (store - (temp[2] * Math.pow(10, 4))); temp[3]= (int) (store / Math.pow(10, 3)); store = (int) (store - (temp[3] * Math.pow(10, 3))); temp[4]= (int) (store / Math.pow(10, 2)); store = (int) (store - (temp[4] * Math.pow(10, 2))); temp[5]= (int) (store / 10); store = (int) (store - (temp[5] * 10)); temp[6]= (store); // System.out.println(temp[5]); // System.out.println(num); int size = 0; // System.out.print(temp[0]); // System.out.print(temp[1]); // System.out.println(temp[2]); if(temp[0]!=0)size=7; else if(temp[1] != 0) size = 6; else if(temp[2] != 0) size = 5; else if(temp[3] != 0) size = 4; else if(temp[4] != 0) size = 3; else if(temp[5] != 0) size = 2; else if(temp[6] != 0) size = 1; int reduce= (7-size); // System.out.println(temp[6]); for(int t=0;tnum && num1<=B) { for(int h=0;h list = new ArrayList(); for (int k=1;k 0) { String first = tempStringValueOfA.substring(0, backIndex); String second = tempStringValueOfA.substring(backIndex, numberOfDigitsInA); stringValueOfA = second + first; int m = Integer.parseInt(stringValueOfA); if ((m <= B && m > n) && !stringValueOfA.startsWith(""0"") && (Integer.toString(n).length()) == stringValueOfA .length()) totalNumberCount++; backIndex--; } } writer.write(""Case #"" + increment++ + "": "" + totalNumberCount + ""\n""); } writer.close(); fileWriter.close(); } public static void main(String[] args) throws Exception { RecycledNumbers recycledNumbers = new RecycledNumbers(); String inputFilePath = ""C:\\CodeJamFiles\\Large2.in""; String outputFilePath = ""C:\\CodeJamFiles\\Large2.out""; fileReader = new FileReader(inputFilePath); reader = new BufferedReader(fileReader); fileWriter = new FileWriter(outputFilePath, false); writer = new BufferedWriter(fileWriter); recycledNumbers.executeLogic(); } } " B21034,"import java.io.File; import java.util.HashSet; import java.util.Scanner; public class recyle { public static int solve(String s) { String[] input = s.split("" ""); String a = input[0]; String b = input[1]; if (a.length() != b.length()) return 0; if (Integer.parseInt(b) <= 10) return 0; int rotats = a.length(); int largest = Integer.parseInt(b); int count = 0; HashSet done = new HashSet(); for (int i = Integer.parseInt(a); i <= largest; i++) { for (int j = 1; j < rotats; j++) { String n = String.valueOf(i); String x = n.substring(0, rotats - j); String y = n.substring(rotats - j); if (y.charAt(0) == '0') continue; // No zero startings int nn = (int) (Integer.parseInt(y) * Math.pow(10, rotats - j) + Integer.parseInt(x)); if (nn == i || i >= nn || nn > largest) continue; //sb.append(n); sb.append(String.valueOf(nn)); int key = nn << 8 | i; if (!done.contains(key)) { done.add(key); count++; } } } return count; } public static void main(String[] args) { Scanner scanner = null; try { //scanner = new Scanner(System.in); scanner = new Scanner(new File(""A-small-attempt0.in"")); }catch (Exception e){ System.out.println(e.getMessage()); } String c = scanner.nextLine(); int i = 1; while (scanner.hasNextLine()) { String input = scanner.nextLine(); System.out.println(""Case #"" + i + "": "" + solve(input)); i++; } } } " B20287,"package com.anuragkapur.jam2012.qr.C; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; /** * @author anuragkapur * */ public class RecycledNumbers { public void writeOutputToFile(String output, String filepath) throws IOException { FileWriter fstream = new FileWriter(filepath); BufferedWriter out = new BufferedWriter(fstream); out.write(output); out.flush(); out.close(); } // methods for algorithm logic here public int computeCountOfRecycledPairs(String input) { StringTokenizer tokenizer = new StringTokenizer(input, "" ""); Set recycledPairs = new HashSet(); int a = -1; int b = -1; int tokenCount = 0; while (tokenizer.hasMoreElements()) { tokenCount ++; String token = (String) tokenizer.nextElement(); if (tokenCount == 1) { a = Integer.parseInt(token); }else { b = Integer.parseInt(token); } } int originalA = a; int originalB = b; int noOfRecycledPairs = 0; if (a == b) { return 0; } while (a <= b) { String aStr = """" + a; String bStr = """" + b; int noOfDigits = aStr.length(); if (noOfDigits < 2) { break; }else { int noOfDigitsToMove = 1; while(noOfDigitsToMove < noOfDigits) { String movedDigitsString = aStr.substring(noOfDigits - noOfDigitsToMove); String unmovedDigitsString = aStr.substring(0, noOfDigits - noOfDigitsToMove); int movedDigits = Integer.parseInt(movedDigitsString); int unmovedDigits = Integer.parseInt(unmovedDigitsString); //Check if number at first index is 0. If yes, this is not a valid case int firstDigitOFMovedDigits = Integer.parseInt(movedDigitsString.substring(0,1)); if (firstDigitOFMovedDigits == 0) { noOfDigitsToMove ++; }else { String newNumberString = movedDigitsString + unmovedDigitsString; int newNumber = Integer.parseInt(newNumberString); //System.out.println(""old number "" + a + "" new number :: "" + newNumber); if (newNumberString.length() == aStr.length()) { if(newNumber > a && newNumber <= originalB && a >= originalA) { //System.out.println(""recycled pair found :: "" + a + "" and "" + newNumber); // Add pair found to a SET so that duplicates get ignored automatically recycledPairs.add(a + "","" + newNumberString); } } noOfDigitsToMove ++; } } } a ++; } noOfRecycledPairs = recycledPairs.size(); return noOfRecycledPairs; } /** * @param args */ public static void main(String[] args) { if (args.length < 2) { System.out.println(""Not enough command line arguments specified. Need 2 (Input and output file paths)""); return; } String inputFilePath = args[0]; try { // String buffer for storing the output StringBuffer output = new StringBuffer(); // Instantiate object to use non static methods RecycledNumbers recycled = new RecycledNumbers(); // read and parse input file FileInputStream fstream = new FileInputStream(inputFilePath); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int lineNumber = 0; int noOfTestCases = -1; int activeTestCaseNumber = 0; while ((strLine = br.readLine()) != null) { if (lineNumber == 0) { noOfTestCases = Integer.parseInt(strLine); } else { noOfTestCases ++; activeTestCaseNumber ++; // Now that a test case has been parsed, compute output for // this test case // Invoke algorithm here int solutionToTestCase = recycled.computeCountOfRecycledPairs(strLine); // Prepare output string //System.out.println(solutionToTestCase); output.append(""Case #"" + activeTestCaseNumber + "": "" + solutionToTestCase); output.append(""\n""); } lineNumber++; } in.close(); // Pass output string to method to write to file recycled.writeOutputToFile(output.toString(), args[1]); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // File read cleanup } } }" B21977,"import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; public class C { private Scanner in; private PrintWriter out; private final String file = ""C""; public C() throws IOException { try { System.setIn(new FileInputStream(""io/q/"" + file)); System.setOut(new PrintStream(new FileOutputStream(""io/q/"" + file + "".out""))); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); } in = new Scanner(new BufferedInputStream(System.in)); out = new PrintWriter(System.out); // for case int T = in.nextInt(), t = 1; int A, B, l, sum, total, currentNumberChar, currentNumber; HashMap map; while (T-- > 0) { A = in.nextInt(); B = in.nextInt(); map = new HashMap(B - A + 1); total = 0; if (A > 9) { final int size = (A + """").length() - 1; final int exp = (int) Math.pow(10, size); for (int nextNumber = A; nextNumber <= B; nextNumber++) { // processed if (null != map.get(nextNumber)) continue; // process map.put(nextNumber, true); currentNumber = nextNumber; sum = 0; for (l = 0; l++ < size;) { currentNumberChar = currentNumber % 10; currentNumber = currentNumberChar*exp + (int)Math.floor(currentNumber/10); if ((currentNumber >= A) && (currentNumber <= B)) { if (null == map.get(currentNumber)) { map.put(currentNumber, true); sum++; } } } total += sum + sum*(sum-1)/2; } } out.printf(""Case #%d: %d%n"", t++, total); } in.close(); out.flush(); out.close(); } public static void main(String[] args) throws IOException { new C(); } }" B20461,"import static java.util.Arrays.deepToString; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Scanner; public class QC { public static void main(String[] args) throws Exception { new QC().run(); } int calculateDigit(int num) { int res = 0; while(num>0) { res++; num = num/10; } return res; } void run() throws Exception { //Scanner sc = new Scanner(System.in); //PrintWriter pw = new PrintWriter(System.out); Scanner sc = new Scanner(new FileReader(""C-large.in"")); FileWriter fstream = new FileWriter(""out.in""); BufferedWriter out = new BufferedWriter(fstream); int ntest = Integer.valueOf(sc.nextLine()); for(int test=1;test<=ntest;++test) { int min = sc.nextInt(); int max = sc.nextInt(); int score = 0; for(int i=min; i<=max; i++) { int digit = calculateDigit(i); List list = new ArrayList(); for(int j=1; j i && calculateDigit(mix) == calculateDigit(i)) { //debug(i + "" "" +mix); list.add(mix); score++; } } } out.write(""Case #"" + test + "": ""); out.write(score+""""); debug(score); out.write(""\n""); } out.close(); sc.close(); } void debug(Object...os) { System.err.println(deepToString(os)); } void debugArray(Object[]...os) { System.err.println(deepToString(os)); } } " B21350,"package qual; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException { new Recycled().run(); } class Pair { int a, b; Pair(int a, int b) { this.a = a; this.b = b; } public boolean equals(Object other) { Pair p = (Pair) other; return this.a == p.a && this.b == p.b; } public int hashCode() { return this.a * 2000003 + this.b; } } public HashSet set = new HashSet(); void add(Pair p, int left, int right) { if (p.a < p.b && left <= p.a && p.a <= right && left <= p.b && p.b <= right) { set.add(p); } } int powers[] = {10, 100, 1000, 10000, 100000, 1000000, 10000000}; void fill(int left, int right, int curpow) { for (int i = left; i <= right; i++) { int val = i; for (int p : powers) { if (val >= p) { int lp = val / p; int rp = val % p; int newval = rp * (curpow / p) + lp; add(new Pair(val, newval), left, right); } } } } public void run() throws IOException { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); fill(1, 9, 10); fill(10, 99, 100); fill(100, 999, 1000); fill(1000, 9999, 10000); fill(10000, 99999, 100000); fill(100000, 999999, 100000); fill(1000000, 2000000, 10000000); int tests = in.nextInt(); for (int test = 0; test < tests; test++) { int a = in.nextInt(), b = in.nextInt(); int count = 0; for (Pair p: set) { if (a <= p.a && p.a <= b && a <= p.b && p.b <= b) { count++; } } out.printf(""Case #%d: %d\n"", test + 1, count); } out.close(); } } " B21342,"package qualify3; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.Vector; public class RecycledNumbers { public static void main (String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File (""src//qualify3/input.in"")); int T = in.nextInt(); for (int i = 0; i < T; i++) { Integer A = in.nextInt(); Integer B = in.nextInt(); String strA = A.toString(); String strB = B.toString(); Vector cycles = new Vector(); if (strA.length() != 1) { for (Integer j = A; j <= B; j++) { cycles.addAll(getCycledValues(j.toString(), strB)); } } System.out.println(""Case #"" + (i + 1) + "": "" + cycles.size()); } } public static Vector getCycledValues (String str1, String str2) { Vector cycledNumbers = new Vector(); String no = new String (str1); int size = str1.length(); while (true) { String str = """"; str = str + no.charAt(size - 1); for (int i = 0; i < size - 1; i++) { str = str + no.charAt(i); } if (Integer.parseInt(str) == Integer.parseInt(str1)) break; int cyclicNumber = Integer.parseInt(str); if (cyclicNumber >= Integer.parseInt(str1) && cyclicNumber <= Integer.parseInt(str2)) { cycledNumbers.add(cyclicNumber); } no = str; } return cycledNumbers; } } " B20922,"package recycledNumbers; public class Solution { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub InputData inputdata = Flow.Readin(""src//recycledNumbers//C-large.in""); OutputData outputdata = Algorithms.getOutput(inputdata); Flow.Writeout(outputdata, ""src//recycledNumbers//C-large.out""); } } " B20156,"package com.whitecrow.codejam2012.qualification; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.StringTokenizer; public class C { /** * @param args */ public static void main(String[] args) { String filename = ""C-small-attempt0""; FileReader input; FileWriter output; try { input = new FileReader(filename + "".in""); output = new FileWriter(filename + "".out""); BufferedReader reader = new BufferedReader(input); BufferedWriter writer = new BufferedWriter(output); // String in = """"; String out = """"; int T = Integer.parseInt(reader.readLine()); for (int idx = 0; idx < T; idx++) { int result = 0; StringTokenizer token = new StringTokenizer(reader.readLine(), "" ""); int a = Integer.parseInt(token.nextToken()); int b = Integer.parseInt(token.nextToken()); int length = String.valueOf(a).length(); for (int i = a; i <= b; i++) { ArrayList check = new ArrayList (); for (int j = 1; j < length; j++) { int divide = (int) Math.pow(10, j); int add = (int) Math.pow(10, length - j); int k = i / divide + (i % divide) * add; if (i < k && a <= i && k <= b && !check.contains(k)) { check.add(k); //System.out.println(i+"", ""+k); result++; } } // System.out.println(i); } out = ""Case #"" + (idx + 1) + "": "" + result; System.out.println(out); writer.write(out + ""\n""); } reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); System.exit(0); } } } " B21652,"package RecycledNumbers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; /** * * @author Nikhil */ public class c { public static void main(String[] args) throws FileNotFoundException, IOException { File fInput = new File(args[0]); String tmp; BufferedReader br = new BufferedReader(new FileReader(fInput)); int iTestCases = Integer.parseInt(br.readLine()); int A, B, iCase = 1; while (null != (tmp = br.readLine())) { A = Integer.parseInt(tmp.split("" "")[0]); B = Integer.parseInt(tmp.split("" "")[1]); System.out.println(""Case #"" + iCase + "": "" + findRecycled(A, B)); iCase++; } br.close(); } private static int findRecycled(final int A, final int B) { int iRecycled = 0; int iRemainder, m, iTenPowMove; int iRemainderB; String sUnqNM; HashSet hsRecycled = new HashSet(); final int B_LEN = String.valueOf(B).length() - 1; if (B < 10) { return 0; } //System.out.println(""A="" + A + ""\tB="" + B); //dblRemainderB = B / Math.pow(10d, (double) (String.valueOf(B).length() - 1)); for (int iMoveDigitCount = 1; iMoveDigitCount <= B_LEN; iMoveDigitCount++) { // Increament 10^x to compute last digit from A iTenPowMove = (int) Math.pow(10d, (double) iMoveDigitCount); // Get the MSB digits from B to optimize algo iRemainderB = Integer.parseInt(String.valueOf(B).substring(0, iMoveDigitCount)); for (int n = A; n <= B; n++) { iRemainder = n % iTenPowMove; if (0 == iRemainder || n < iTenPowMove) { continue; } else if (iRemainder > iRemainderB) { //iMoveDigitCount++; n += iTenPowMove - iRemainder; continue; } else { String strM = null; StringBuilder sb = new StringBuilder(String.valueOf(n)); int iPre = sb.length() - iMoveDigitCount; try { strM = sb.substring(iPre) + sb.substring(0, iPre); } catch (StringIndexOutOfBoundsException ex) { System.out.println(""sb="" + iRemainder + ""\niPre="" + iPre); throw ex; } m = Integer.parseInt(strM); if (m <= n) { continue; } else if (m <= B) { sUnqNM = String.valueOf(n) + String.valueOf(m); if (!hsRecycled.contains(sUnqNM)) { hsRecycled.add(sUnqNM); iRecycled++; } } } } } return iRecycled; } } " B21744,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package RecycledNumbers; import java.io.*; import java.util.ArrayList; /** * * @author Himeshi */ public class RecycledNumbers { public static void main(String[] args) { int A, B, N, pairs; String strLine, integers; try { BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(""D:/Academic Work/Semester 5/Code Jam/C-large.in"")))); while ((strLine = br.readLine()) != null) { N = Integer.parseInt(strLine); for (int i = 0; i < N; i++) { integers = br.readLine(); String[] tokens = integers.split("" ""); A = Integer.parseInt(tokens[0]); B = Integer.parseInt(tokens[1]); pairs = calculate(A, B, i); writeToFile(pairs, i); } } } catch (Exception e) { System.out.println(""here is the exception""+e); } } private static int calculate(int A, int B, int i) { int pairs = 0; for (int index = A; index <= B; index++) { ArrayList list = getPairs(index); for (int j = 0; j < list.size(); j++) { if (list.get(j) <= B && list.get(j)>index) { //System.out.println(""""+index+"" ""+list.get(j)); pairs++; } } } return pairs; } private static ArrayList getPairs(int index) { ArrayList list = new ArrayList(); String temp = Integer.toString(index); int length = temp.length(); char[] buffer = temp.toCharArray(); if (index < 10) { return list; } else { for (int numbers = 1; numbers < length; numbers++) { char c=buffer[length-1]; for(int k=buffer.length-1;k>0;k--) { buffer[k]=buffer[k-1]; } buffer[0]=c; String s=new String(buffer); int number=Integer.parseInt(s); if(!list.contains(number)) list.add(number); } return list; } } private static void writeToFile(int a,int N) { try { // Create file FileWriter fstream = new FileWriter(new File(""D:/Academic Work/Semester 5/Code Jam/out.txt""),true); BufferedWriter out = new BufferedWriter(fstream); String str=""Case #""+(N+1)+"": ""+a+""\r\n""; out.append(str); //Close the output stream out.close(); } catch (Exception e) {//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B20339,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class RecycledNumbers { static HashSet set = new HashSet(); public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(""small-C.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""small-C.out"")); int n = Integer.parseInt(br.readLine()); for(int i = 1; i <= n; i++){ set.clear(); int total = 0; String [] temp = br.readLine().split("" ""); int a = Integer.parseInt(temp[0]); int b = Integer.parseInt(temp[1]); for(int j = a; j < b; j++) total += check(j, a, b, temp[0], temp[1]); out.write(""Case #"" + i + "": "" + set.size()); if(i < n) out.write(""\n""); } System.out.println(set.size()); br.close(); out.close(); } private static int check(int n, int a, int b, String astr, String bstr) { int num = 0; String temp = n + """"; for(int len = 1; len < astr.length(); len++){ String one = temp.substring(0, len); String two = temp.substring(len); int temp2 = Integer.parseInt(two + one); if(temp2 > n && temp2 <= b){ num++; if(set.contains(n + "" "" + temp2)) System.out.println(""Contained *********************************************************\n*****\n***""); else{ set.add(n + "" "" + temp2); } //System.out.println(one + "" "" + two + "" --> "" + two + "" "" + one + "" len = "" + len); } } if(num > 0) System.out.println(); return num; } } " B21433,"package jp.funnything.competition.util; import java.math.BigInteger; /** * Utility for BigInteger */ public class BI { public static BigInteger ZERO = BigInteger.ZERO; public static BigInteger ONE = BigInteger.ONE; public static BigInteger add( final BigInteger x , final BigInteger y ) { return x.add( y ); } public static BigInteger add( final BigInteger x , final long y ) { return add( x , v( y ) ); } public static BigInteger add( final long x , final BigInteger y ) { return add( v( x ) , y ); } public static int cmp( final BigInteger x , final BigInteger y ) { return x.compareTo( y ); } public static int cmp( final BigInteger x , final long y ) { return cmp( x , v( y ) ); } public static int cmp( final long x , final BigInteger y ) { return cmp( v( x ) , y ); } public static BigInteger div( final BigInteger x , final BigInteger y ) { return x.divide( y ); } public static BigInteger div( final BigInteger x , final long y ) { return div( x , v( y ) ); } public static BigInteger div( final long x , final BigInteger y ) { return div( v( x ) , y ); } public static BigInteger mod( final BigInteger x , final BigInteger y ) { return x.mod( y ); } public static BigInteger mod( final BigInteger x , final long y ) { return mod( x , v( y ) ); } public static BigInteger mod( final long x , final BigInteger y ) { return mod( v( x ) , y ); } public static BigInteger mul( final BigInteger x , final BigInteger y ) { return x.multiply( y ); } public static BigInteger mul( final BigInteger x , final long y ) { return mul( x , v( y ) ); } public static BigInteger mul( final long x , final BigInteger y ) { return mul( v( x ) , y ); } public static BigInteger sub( final BigInteger x , final BigInteger y ) { return x.subtract( y ); } public static BigInteger sub( final BigInteger x , final long y ) { return sub( x , v( y ) ); } public static BigInteger sub( final long x , final BigInteger y ) { return sub( v( x ) , y ); } public static BigInteger v( final long value ) { return BigInteger.valueOf( value ); } } " B20513,"import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; import java.util.Scanner; import java.util.Vector; public class recycle { public static void main(String arg[]) throws FileNotFoundException { Scanner in=new Scanner(new FileReader(""rec.in"")); PrintWriter pw=new PrintWriter(""ansRec.txt""); int cases=in.nextInt(); in.nextLine(); for(int counter=1;counter<=cases;counter++) { int small=in.nextInt(); int large=in.nextInt(); int ans=0; for(int i=small;i vec=new Vector(); for(int j=1;ji&&newI<=large&&!vec.contains(newI)) { ans++; // System.out.print(""(""+i+"", ""+newI+"") -- ""); vec.add(newI); f2=true; } // System.out.println(""for ""+i+"" checking with ""+newI); } // if(f2) System.out.println(); } pw.println(""Case #""+counter+"": ""+ans); } pw.close(); } } " B20064,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; public class recycled { private static File f = new File(""C:/Users/Cybermask/Desktop/myfile.txt""); private static File outfile = new File(""C:/Users/Cybermask/Desktop/out.txt""); private static BufferedReader reader; private static String read() throws Exception{ return reader.readLine(); } private static int toint(String s){ return Integer.parseInt(s); } private static ArrayList reverse(ArrayListlist){ ArrayList result = new ArrayList(); for(int i=0;i hs = new HashSet(); for(int o=1;o=f && result<=l && result > first){ hs.add(result); } } count+=hs.size(); } pw.println(count); } pw.flush(); } }" B20492,"import java.util.Scanner; import java.io.*; public class Pair { public static int a, b, l; public static boolean inr(String x) { int t = Integer.parseInt(x); if ((t + """").length() != l) return false; if (t <= b && t >= a) { return true; } else return false; } public static String toS(int x) { String o = """"; return o+x; } public static boolean notInT(String[] t, String x, int c) { for (int i = 0; i < c; i++) if (t[i].equals(x)) return false; return true; } public static int recycle(String s) { int count = 0; String[] t = new String[l]; int c = 1; t[0] = s; for (int i = 0; i < l - 1; i++) { String a = s.substring(0, i + 1); String b = s.substring(i + 1, l); if (notInT(t, b + a, c)) { t[c] = b + a; c++; } } for (int i = 1; i < c; i++) { if (inr(t[i])) count++; } return count; } public static void main(String args[]) throws IOException { int count; Scanner in = new Scanner(new File(""e:/in.txt"")); PrintStream out = new PrintStream(new File(""e:/out.txt"")); int n = in.nextInt(); for (int z = 1; z <= n; z++) { count = 0; a = in.nextInt(); b = in.nextInt(); l = (b + """").length(); for (int i = a; i <= b; i++) { count += recycle(toS(i)); } count /= 2; out.println(""Case #""+z+"": ""+count); } } } " B21043,"package de.hg.codejam.tasks.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public abstract class Reader { public static String[] readFile(String path) { String[] input = null; try (BufferedReader reader = new BufferedReader(new FileReader(path))) { int inputSize = Integer.parseInt(reader.readLine()); input = new String[inputSize]; for (int i = 0; i < inputSize; i++) input[i] = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return input; } } " B21725,"/** * */ package pandit.codejam; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Scanner; /** * @author Manu Ram Pandit * */ public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { FileInputStream fStream = new FileInputStream( ""input.txt""); Scanner scanner = new Scanner(new BufferedInputStream(fStream)); Writer out = new OutputStreamWriter(new FileOutputStream(""output.txt"")); int T = scanner.nextInt(); int A, B; int counter = 0; for (int count = 1; count <= T; count++) { A = scanner.nextInt(); counter = 0; B = scanner.nextInt(); for (int i = A; i <= B; i++) { counter += noOfDistinctPairs(i, B); } // System.out.println(""Case #"" + count + "": "" + counter); out.write(""Case #"" + count + "": "" + counter + ""\n""); } fStream.close(); out.close(); } /** * This method returns the * * @param current * @param B * @return */ public static int noOfDistinctPairs(int current, int B) { int count = 0; String s = String.valueOf(current); int length = s.length(); String temp; int tempNo; for (int i = 0; i < length - 1; i++) { temp = s.substring(i + 1, length).concat(s.substring(0, i + 1)); tempNo = Integer.parseInt(temp); if (tempNo == current) break; if (tempNo > current && tempNo <= B) { ++count; } } return count; } } " B20725,"package fixjava; /** * Convenience class for declaring a method inside a method, so as to avoid code duplication without having to declare a new method * in the class. This also keeps functions closer to where they are applied. It's butt-ugly but it's about the best you can do in * Java. */ public interface LambdaVoid

{ public void apply(P param); } " B20723,"package recycled; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { File file = new File(""C-large.in""); FileReader fr = new FileReader(file); BufferedReader in = new BufferedReader(fr); String line=in.readLine(); String[] tokens; int num = Integer.parseInt(line); int i=1; int A,B; String str; int n,count; while(i<=num){ line=in.readLine(); tokens = line.split("" ""); A = Integer.parseInt(tokens[0]); B = Integer.parseInt(tokens[1]); count = 0; for(int m=A;mm && n<=B){ count++; } if(n==m){ break; } } } System.out.println(""Case #""+i+"": ""+count); i++; } } } " B20166,"package com.code.jam; import java.io.File; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import org.apache.commons.lang.StringUtils; public class CRecycledNumbers { public static void main(String[] args) throws Exception { Scanner in = new Scanner (new File(""C:/codeJam/ficheros2012/CRecycledNumbers.in"")); PrintStream ps = new PrintStream(""C:/codeJam/ficheros2012/CRecycledNumbers.out""); int T = new Integer (in.nextLine()); for (int nCase = 1; nCase < T + 1; nCase++) { Scanner inLine = new Scanner (in.nextLine()); int recycledPair = 0; int A = inLine.nextInt(); int B = inLine.nextInt(); int lengthI = String.valueOf(A).length(); if (lengthI > 1){ for (int n = A; n <= B; n++){ int operatorGetLeftRight = 1; int operatorNewNumber = Integer.valueOf(StringUtils.rightPad(""1"", lengthI + 1, '0')); Set isRepeted = new HashSet(); for (int j = 1; j < lengthI; j++) { operatorGetLeftRight *= 10; operatorNewNumber /= 10; int newLeft = n % operatorGetLeftRight; int newRight = (n - newLeft) / operatorGetLeftRight; int m = newLeft * operatorNewNumber + newRight; if ( !(isRepeted.contains(m)) && (m >= A) && (m <= B) && (n < m)){ isRepeted.add(m); recycledPair++; } } } } System.out.format(""Case #%d: %d\n"", nCase, recycledPair); ps.format(""Case #%d: %d\n"", nCase, recycledPair); } ps.flush(); ps.close(); } } " B20969,"import java.util.Locale; import java.util.Scanner; public class C { void solve(int icase) { int a = si(); int b = si(); int digits = ("""" + a).length(); int s = 1; for (int i = 0; i < digits; i++) { s *= 10; } long res = 0; for (int i = a; i < b; i++) { res += find(s, i, b); } printf(""Case #%d: %d\n"", icase, res); } int nused; int[] used = new int[10]; int find(int s, int x, int b) { int ret = 0; nused = 0; for (int m = 10; m < x; m *= 10) { int y = x % m; if (y >= m / 10) { y *= s / m; y += x / m; if (y <= b && x < y && !used(y)) { ret++; used[nused++] = y; } } } return ret; } boolean used(int y) { for (int i = 0; i < nused; i++) { if (used[i] == y) { return true; } } return false; } public static void main(String[] args) throws Exception { Locale.setDefault(Locale.US); new C().repSolve(); } void repSolve() throws Exception { scanner = new Scanner(System.in); // scanner = new Scanner(new java.io.File("""")); int ncase = si(); sline(); for (int icase = 1; icase <= ncase; icase++) { solve(icase); System.err.println(""[[ "" + icase + "" ]]""); } } Scanner scanner; int si() { return scanner.nextInt(); } long sl() { return scanner.nextLong(); } String ss() { return scanner.next(); } String sline() { return scanner.nextLine(); } void printf(String format, Object... args) { System.out.printf(format, args); } } " B21261,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledNumbers { private static final String INPUT_FILE = ""input.txt""; private static final String OUTPUT_FILE = ""output.txt""; public int countSiblings(String lowerbound, String upperbound) { int n = lowerbound.length(); int start = Integer.parseInt(lowerbound); int end = Integer.parseInt(upperbound); char[] upChars = upperbound.toCharArray(); char[] lowChars = lowerbound.toCharArray(); boolean[] hasSibling = new boolean[end - start + 1]; int count = 0; for (int i = start; i <= end; i++) { if (hasSibling[i - start]) continue; char[] iChars = Integer.toString(i).toCharArray(); int buf = 0; for (int j = 1; j < n; j++) { if (iChars[j] > upChars[0] || iChars[j] < lowChars[0]) continue; int tenpowj = (int) Math.pow(10, n- j); int cycle = (int) (i / tenpowj + (i % tenpowj) * Math.pow(10, j)); if (cycle > end || cycle < start || hasSibling[cycle - start]) continue; if (cycle <= i) continue; else { hasSibling[i - start] = true; hasSibling[cycle - start] = true; buf++; } } count += (buf + 1) * buf /2; } return count; } public static void main(String[] args) throws NumberFormatException, IOException { RecycledNumbers recycledNumbers = new RecycledNumbers(); Parser parser = new Parser(); String[] input = parser.readInput(INPUT_FILE); String[] result = new String[input.length]; for (int i = 0; i < input.length; i++) { String[] data = input[i].split("" ""); result[i] = Integer.toString(recycledNumbers.countSiblings(data[0], data[1])); } parser.writeOutput(result, OUTPUT_FILE); } } class Parser { public String[] readInput(String fileName) throws NumberFormatException, IOException { BufferedReader reader = new BufferedReader(new FileReader(fileName)); int numberOfCases = Integer.parseInt(reader.readLine()); String[] input = new String[numberOfCases]; for (int i = 0; i < numberOfCases; i++) { input[i] = reader.readLine(); } reader.close(); return input; } public void writeOutput(String[] result, String file) throws IOException { FileWriter writer = new FileWriter(file); BufferedWriter bufferedWriter = new BufferedWriter(writer); for (int i = 0; i < result.length; i++) { bufferedWriter.write(""Case #"" + (i+1) +"": "" + result[i]); bufferedWriter.newLine(); } bufferedWriter.flush(); bufferedWriter.close(); } } " B21571,"/************************************************************************* * Compilation: javac StdIn.java * Execution: java StdIn * * Reads in data of various types from standard input. * *************************************************************************/ import java.io.BufferedInputStream; import java.util.Locale; import java.util.Scanner; /** * Standard input. This class provides methods for reading strings * and numbers from standard input. *

* The Locale used is: language = English, country = US. This is consistent * with the formatting conventions with Java floating-point literals, * command-line arguments (via Double.parseDouble()) * and standard output (via System.out.print()). It ensures that * standard input works with the input files used in the textbook. *

* For additional documentation, see Section 1.5 of * Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. */ public final class StdIn { // assume Unicode UTF-8 encoding private static String charsetName = ""UTF-8""; // assume language = English, country = US for consistency with System.out. private static Locale usLocale = new Locale(""en"", ""US""); // the scanner object private static Scanner scanner = new Scanner(new BufferedInputStream(System.in), charsetName); // static initializer static { scanner.useLocale(usLocale); } // singleton pattern - can't instantiate private StdIn() { } /** * Is there only whitespace left on standard input? */ public static boolean isEmpty() { return !scanner.hasNext(); } /** * Return next string from standard input */ public static String readString() { return scanner.next(); } /** * Return next int from standard input */ public static int readInt() { return scanner.nextInt(); } /** * Return next double from standard input */ public static double readDouble() { return scanner.nextDouble(); } /** * Return next float from standard input */ public static float readFloat() { return scanner.nextFloat(); } /** * Return next short from standard input */ public static short readShort() { return scanner.nextShort(); } /** * Return next long from standard input */ public static long readLong() { return scanner.nextLong(); } /** * Return next byte from standard input */ public static byte readByte() { return scanner.nextByte(); } /** * Return next boolean from standard input, allowing ""true"" or ""1"" for true, * and ""false"" or ""0"" for false */ public static boolean readBoolean() { String s = readString(); if (s.equalsIgnoreCase(""true"")) return true; if (s.equalsIgnoreCase(""false"")) return false; if (s.equals(""1"")) return true; if (s.equals(""0"")) return false; throw new java.util.InputMismatchException(); } /** * Does standard input have a next line? */ public static boolean hasNextLine() { return scanner.hasNextLine(); } /** * Return rest of line from standard input */ public static String readLine() { return scanner.nextLine(); } /** * Return next char from standard input */ // a complete hack and inefficient - email me if you have a better public static char readChar() { // (?s) for DOTALL mode so . matches a line termination character // 1 says look only one character ahead // consider precompiling the pattern String s = scanner.findWithinHorizon(""(?s)."", 1); return s.charAt(0); } /** * Return rest of input from standard input */ public static String readAll() { if (!scanner.hasNextLine()) return null; // reference: http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html return scanner.useDelimiter(""\\A"").next(); } /** * Read rest of input as array of ints */ public static int[] readInts() { String[] fields = readAll().trim().split(""\\s+""); int[] vals = new int[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Integer.parseInt(fields[i]); return vals; } /** * Read rest of input as array of doubles */ public static double[] readDoubles() { String[] fields = readAll().trim().split(""\\s+""); double[] vals = new double[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Double.parseDouble(fields[i]); return vals; } /** * Read rest of input as array of strings */ public static String[] readStrings() { String[] fields = readAll().trim().split(""\\s+""); return fields; } /** * Unit test */ public static void main(String[] args) { System.out.println(""Type a string: ""); String s = StdIn.readString(); System.out.println(""Your string was: "" + s); System.out.println(); System.out.println(""Type an int: ""); int a = StdIn.readInt(); System.out.println(""Your int was: "" + a); System.out.println(); System.out.println(""Type a boolean: ""); boolean b = StdIn.readBoolean(); System.out.println(""Your boolean was: "" + b); System.out.println(); System.out.println(""Type a double: ""); double c = StdIn.readDouble(); System.out.println(""Your double was: "" + c); System.out.println(); } } " B21509,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; public class recycle { public static void rec() throws NumberFormatException, IOException { BufferedReader in = new BufferedReader(new FileReader(""src/test1"")); String line; StringBuilder bubs = new StringBuilder(); int T = Integer.parseInt(""""+in.readLine().charAt(0)); int i=0; while ((line=in.readLine())!=null) { i++; String[] splitline = line.split(""\\s+""); int A = Integer.parseInt(splitline[0]); int B = Integer.parseInt(splitline[1]); int d = splitline[0].length(); StringBuilder subs = new StringBuilder(); subs.append(""Case #"" + i + "": ""); int count = 0; for (int n=A;n hm = new HashMap(); for (int b=0;b n && Integer.parseInt(btry) <=B) { hm.put(Integer.parseInt(btry), 1); count++; } } } subs.append(count); bubs.append(subs.toString()); System.out.println(subs.toString()); } } } " B20326,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class ProblemC { ProblemC() throws IOException { Scanner reader = new Scanner(new File(""input.txt"")); BufferedWriter writer = new BufferedWriter(new FileWriter(""output.txt"")); int cases = reader.nextInt(); for(int i = 1; i <= cases; i++) { int A = reader.nextInt(); int B = reader.nextInt(); int mask = (int)Math.pow(10, (int)Math.log10(A)); int count = 0; for(int j = A; j < B; j++) { int num = (j%mask)*10+j/mask; while(num!=j) { if(num>j && num <= B) ++count; num = (num%mask)*10+num/mask; } } writer.write(""Case #""+i+"": ""+count); writer.newLine(); } reader.close(); writer.close(); } public static void main(String[] args) throws IOException { new ProblemC(); } } " B22040," import java.util.*; class Main { public static void main( String[ ] args ) { Scanner in=new Scanner(System.in); int cin=in.nextInt(); for (int ci=1;ci<=cin;ci++){ int a=in.nextInt(),b=in.nextInt(); int ans=0; for (int i=a;i la=new HashSet(); int ttmp=1; int tmp=10; int tgmp=10; while (tgmp<=i){ tgmp*=10; } while (i>tmp){ tgmp/=10; int m=i%tmp*tgmp+i/tmp; if (m>i&&m<=b&&i%tmp>=ttmp) {la.add(m);} ttmp=tmp; tmp*=10; } ans+=la.size(); } System.out.println(""Case #""+ci+"": ""+ans); } } } " B20803,"package code.jam.y2012.quali; import java.io.*; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class ProblemC { private static String PATH = ""F:\\dev\\projects\\code-jam-2012\\src\\code\\jam\\y2012\\quali""; File inputFile = new File(PATH, ""C-large.in""); File outputFile = new File(PATH, ""C-large.out""); BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""""); public static void main(String[] args) throws Exception { new ProblemC().solve(); } void solve() throws Exception { in = new BufferedReader(new FileReader(inputFile)); out = new PrintWriter(outputFile); for (int testCase = 1, testCount = nextInt(); testCase <= testCount; testCase++) { solve(testCase); } out.close(); } void solve(int testCase) throws IOException { final int min = nextInt(); final int max = nextInt(); Set validPatterns = new HashSet(); for (int i = min; i <= max; i++) { String[] patterns = getRecycledPatterns(String.valueOf(i)); for (int j = 0; j < patterns.length - 1; j++) { for (int k = j; k < patterns.length; k++) { if (isValid(Integer.parseInt(patterns[j]), Integer.parseInt(patterns[k]), min, max)) { validPatterns.add(patterns[j] + ""-"" + patterns[k]); } } } } print(""Case #"" + testCase + "": "" + validPatterns.size()); } private static String[] getRecycledPatterns(String pattern) { String[] result = new String[pattern.length()]; for (int i = 0; i < result.length; i++) { result[i] = pattern.substring(i) + pattern.substring(0, i); } return result; } private boolean isValid(int a, int b, int min, int max) { return min <= a && a < b && b <= max && String.valueOf(a).length()==String.valueOf(b).length(); } private void print(String text) { out.println(text); System.out.println(text); } /** * helpers */ String nextToken() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextChar() throws IOException { return in.read(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) { return true; } st = new StringTokenizer(s); } return false; } } " B21436,"package jp.funnything.competition.util; import java.util.Arrays; import java.util.List; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; public class Prime { public static class PrimeData { public int[] list; public boolean[] map; private PrimeData( final int[] values , final boolean[] map ) { list = values; this.map = map; } } public static long[] factorize( long n , final int[] primes ) { final List< Long > factor = Lists.newArrayList(); for ( final int p : primes ) { if ( n < p * p ) { break; } while ( n % p == 0 ) { factor.add( ( long ) p ); n /= p; } } if ( n > 1 ) { factor.add( n ); } return Longs.toArray( factor ); } public static PrimeData prepare( final int n ) { final List< Integer > primes = Lists.newArrayList(); final boolean[] map = new boolean[ n ]; Arrays.fill( map , true ); map[ 0 ] = map[ 1 ] = false; primes.add( 2 ); for ( int composite = 2 * 2 ; composite < n ; composite += 2 ) { map[ composite ] = false; } for ( int value = 3 ; value < n ; value += 2 ) { if ( map[ value ] ) { primes.add( value ); for ( int composite = value * 2 ; composite < n ; composite += value ) { map[ composite ] = false; } } } return new PrimeData( Ints.toArray( primes ) , map ); } } " B21555,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { private static Scanner in = new Scanner(System.in); private static void solve(int no) { int A = in.nextInt(); int B = in.nextInt(); int keta = String.valueOf(A).length(); int ans = 0; Set set = new HashSet<>(); for (int n = A; n < B; n++) { set.clear(); String nstr = String.valueOf(n); for (int i = 1; i < keta; i++) { String rot = nstr.substring(i) + nstr.substring(0, i); int m = Integer.parseInt(rot); if (n < m && m <= B && set.add(m)) { // System.out.printf(""%d %d%n"", n, m); ans++; } } } System.out.printf(""Case #%d: %d%n"", no, ans); } public static void main(String[] args) { int T = in.nextInt(); for (int i = 0; i < T; i++) { solve(i + 1); } } } " B20786,"package codejam; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.*; public class Third { public static void main(String[] args) throws FileNotFoundException { String path = ClassLoader.getSystemClassLoader().getResource(""codejam/"").getPath(); Third worker = new Third(); worker.scan(new File(path, ""third-s.in""), new File(path, ""third-s.out"")); // worker.scan(new File(path, ""third-x.in""), new File(path, ""third-x.out"")); } private void scan(File input, File output) throws FileNotFoundException { Scanner in = new Scanner(input); PrintWriter out = new PrintWriter(output); int n = Integer.parseInt(in.nextLine()); for (int i = 0; i < n; i++) { out.printf(""Case #%d: %s\n"", i + 1, solve(in.nextLine())); } out.flush(); out.close(); in.close(); } public String solve(String line) { String[] splited = line.split("" ""); return """" + solve(Integer.parseInt(splited[0]), Integer.parseInt(splited[1])); } public int solve(int a, int b) { if (a < 10 || a == b) { return 0; } int shiftCount = String.valueOf(a).length() - 1; int counter = 0; Map duplicate = new HashMap(shiftCount); for (int n = a; n <= b; n++) { duplicate.clear(); for (int i = 1; i <= shiftCount; i++) { int m = shift(n, i); if (m < a || m > b || m == n || m > n) { continue; } String key = """" + n + "":"" + m; if (!duplicate.containsKey(key)) { counter++; duplicate.put(key, Boolean.TRUE); } //System.out.println(""("" + n + "", "" + m + "") ""); //System.out.print(""\'"" + n + "":"" + m + ""\', ""); } } return counter; } private int shift(int a, int n) { String s = String.valueOf(a); String head = s.substring(0, s.length() - n); String tail = s.substring(s.length() - n); return Integer.parseInt(tail + head); } } " B21761,"import java.util.*; public class Recycle { public static int deg(int x) { int i = 0; while(x > 0) {x = x / 10; i++;} return i; } public static void main (String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int t = 1; t <= T; t++) { int A = sc.nextInt(), B = sc.nextInt(), num = 0; for(int i = A; i < B; i++) { int degree = deg(i); long coeff = (long) Math.pow(10, degree), n = i * coeff + i; LinkedList lst = new LinkedList(); for(int j = 0; j < degree; j++) { n = n / 10; long m = n % coeff; if(m > i && m <= B && !lst.contains(m)) { lst.add(m); num++;} } } System.out.println(""Case #"" + t + "": "" + num); } } } " B20847,"package codezam.exercise.WR1C2012; public class PairNumber { long numberA; long numberB; public PairNumber(long numberA, long numberB) { super(); this.numberA = numberA; this.numberB = numberB; } public long getNumberA() { return numberA; } public void setNumberA(long numberA) { this.numberA = numberA; } public long getNumberB() { return numberB; } public void setNumberB(long numberB) { this.numberB = numberB; } }" B20553,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; public class RecycledNumbers { public static String SMALL_IN_FILE_NAME = ""./input.txt""; static PrintStream out = null; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { File smallIn = new File(SMALL_IN_FILE_NAME); BufferedReader br = new BufferedReader(new FileReader(smallIn)); String s = br.readLine(); int caseCount = Integer.parseInt(s); File smallOut = new File(""./output.txt""); smallOut.createNewFile(); out = new PrintStream(smallOut); // out = System.out; for (int i = 0; i < caseCount; i ++) { out.printf(""Case #%d: "", i+1); s = br.readLine(); TestCase t = new TestCase(s); out.println(t.solve()); } System.out.println(""Done""); } } " B21349,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) throws IOException, InterruptedException { // Scanner in = new Scanner(new File(""in/C/test.in"")); // Scanner in = new Scanner(new File(""in/C/small.in"")); Scanner in = new Scanner(new File(""in/C/big.in"")); // BufferedWriter bw = new BufferedWriter(new FileWriter(""out/C/test.out"")); // BufferedWriter bw = new BufferedWriter(new FileWriter( // ""out/C/small.out"")); BufferedWriter bw = new BufferedWriter(new FileWriter( ""out/C/big.out"")); int cases = in.nextInt(); for (int c = 1; c <= cases; c++) { int low = in.nextInt(); int high = in.nextInt(); int length = String.valueOf(low).length(); int count = 0; HashMap> alr = new HashMap>(); if (length != 1) { int maxD = (int) Math.pow(10, length - 1); System.err.println(""Case "" + c + "": Maximum "" + maxD); for (int k = 1; k < length; k++) { int playingWith = (int) Math.pow(10, k); int m = (int) Math.pow(10, length - k); System.err.println(""Playing with "" + playingWith); for (int j = low; j < high; j++) { int first = j / maxD; int toMoveFront = j % playingWith; int tmpFirst = toMoveFront / (playingWith / 10); if (tmpFirst < first) continue; int recycled = toMoveFront * m + j / playingWith; if (recycled > high) { int dif = playingWith - toMoveFront; j += dif; } else if (recycled > j) { List l = alr.get(j); if (l == null) { l = new ArrayList(); alr.put(j, l); }else{ if(l.contains(recycled)) continue; } l.add(recycled); count++; } } } } bw.write(""Case #"" + (c) + "": "" + count); System.err.println(""Case #"" + (c) + "": "" + count); bw.newLine(); } in.close(); bw.flush(); bw.close(); } } " B20384,"import java.io.File; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; public class Recycled { public static Integer reorder(int n) { int newn = n, digits = 0, greatest = 0, scale = 1; while (newn > 0) { newn /= 10; digits++; scale *= 10; } scale /= 10; int temp = 0; for (int i = 0; i < digits; i++) { temp = n; temp /= 10; temp += scale * (n-(10*temp)); n = temp; greatest = Math.max(n,greatest); } return greatest; } public static void main(String[] args) { String fileName; String line; fileName = ""C-large.in""; Scanner fromFile = null; try { fromFile = new Scanner(new File(fileName)); } catch (Exception e) {} int iterations = Integer.parseInt(fromFile.nextLine()); int count, lower, upper; int[] answers = new int[iterations]; HashMap map = null; Integer ordered = null; for (int i = 0; i < iterations; i++) { line = fromFile.nextLine(); String[] arguments = line.split("" ""); lower = Integer.parseInt(arguments[0]); upper = Integer.parseInt(arguments[1]); count = 0; map = new HashMap(); for (int j = lower; j <= upper; j++) { ordered = reorder(j); if (map.containsKey(ordered)) { int number = map.get(ordered); count += number; map.put(ordered, number+1); } else { map.put(ordered, 1); } } answers[i] = count; } try { fromFile.close(); } catch (Exception e){} PrintWriter toFile = null; try { File f = new File(""output.txt""); if (!f.exists()) f.createNewFile(); toFile = new PrintWriter(f); for (int i = 0; i < iterations; i++) { if (i == iterations - 1) { toFile.print(""Case #"" + (i + 1) + "": "" + answers[i]); } else { toFile.println(""Case #"" + (i + 1) + "": "" + answers[i]); } } toFile.close(); } catch (Exception e) {} } } " B20127,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.util.HashSet; import java.util.Map; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) { if (args.length != 2) { System.out.println(""Usage: java RecycledNumbers ""); System.exit(0); } try { RecycledCounter counter = new RecycledCounter(new FileReader(args[0]), new FileWriter(args[1])); counter.count(); } catch (Exception e) { System.out.println(""Sorry, there was a fatal error:""); e.printStackTrace(); System.exit(0); } } } class RecycledCounter { private final BufferedReader reader; private final PrintWriter writer; public RecycledCounter(Reader in, Writer out) throws IOException { reader = new BufferedReader(in); writer = new PrintWriter(out); } public void count() throws IOException { String line = reader.readLine(); int numTests = Integer.parseInt(line); for (int i = 0; i < numTests; i++) { line = reader.readLine(); writer.printf(""Case #%d: %s"", i + 1, countNumberOfRecycledPairs(line)); writer.println(); } writer.flush(); writer.close(); reader.close(); } public int countNumberOfRecycledPairs(String line) { String[] tokens = line.split("" ""); int a = Integer.parseInt(tokens[0]); int b = Integer.parseInt(tokens[1]); int y = 0; Set distinct = new HashSet(); for (; a <= b; a++) { if (a < 10) { continue; } String num = String.valueOf(a); for (int i = num.length() - 1; i > 0; i--) { String recycledNum = num.substring(i) + num.substring(0, i); if (recycledNum.startsWith(""0"")) { continue; } int recycled = Integer.valueOf(recycledNum); if (recycled >= a && recycled <= b && a < recycled && !distinct.contains(num + recycledNum)) { distinct.add(num + recycledNum); y++; } } } return y; } } " B20510," /* ID: codeKNIGHT LANG: JAVA TASK: */ import java.util.*; import java.math.*; import java.io.*; class recyledNumbers { public static void main(String args[])throws IOException { //Scanner in=new Scanner(System.in); Scanner in=new Scanner(new FileReader(""C:\\Users\\Lokesh\\Desktop\\C-large.in"")); //PrintWriter out=new PrintWriter(System.out); //BufferedReader br=new BufferedReader(new FileReader(""C:\\Users\\Lokesh\\Desktop\\input.in"")); PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(""E:\\programss\\GCJ\\output.txt""))); int t=in.nextInt(),test,i,a,b,j; String s,s1,s2; for(test=1;test<=t;test++) { a=in.nextInt(); b=in.nextInt(); int c=0,k; for(i=a;i<=b;i++) { s=Integer.toString(i); int max=s.charAt(0); boolean stat=false; for(j=1;j=max) { s1=s.substring(j,s.length()); s2=s.substring(0,j); k=Integer.parseInt(s1+s2); if(k>i&&k<=b&&!stat) { c++; } if(s1.equals(s2)) stat=true; } } } out.println(""Case #""+test+"": ""+c); } out.flush(); System.exit(0); } } " B20525,"package numbers; import java.util.*; import java.io.*; public class Numbers { public static void main(String[] args) throws Exception { Scanner br = new Scanner(new FileReader(""C-large.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""out.txt"")); int T = br.nextInt(); for(int t = 1; t<=T; t++){ int A = br.nextInt(); int B = br.nextInt(); int sum = 0; for(int i = A; i < B; i++){ sum += pcount(i, B); } bw.write(""Case #""+t+"": ""+sum); bw.newLine(); } br.close(); bw.close(); } private static int pcount(int n, int max){ if(n<10) return 0; int sum = 0; String r = rev(Integer.toString(n)); String sn = Integer.toString(n); while(!r.equals(sn)){ int ir = Integer.parseInt(r); if(ir>n && ir<=max){ sum++; } r = rev(r); } return sum; } private static String rev(String n){ if(n.length()<2) return n; StringBuilder sb = new StringBuilder(); sb.append(n.charAt(n.length()-1)); for(int i = 0; i< n.length()-1; i++){ sb.append(n.charAt(i)); } return sb.toString(); } } " B21742,"package round0; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class Dance { BufferedReader _in; PrintWriter _out; int _numTestCases; Input[] _inputs; public Dance(BufferedReader in) throws Exception { this._in = in; this._out = new PrintWriter(""answers.out""); } public void calculate() throws Exception { this._inputs = readInputs(); for(int i=0; i < _inputs.length; i++) { processInput(_inputs[i], i+1); } _out.flush(); _out.close(); } private void processInput(Input input, int caseIndex) { int numPairs = 0; int A = input.A; int B = input.B; //worry about duplicates HashSet combinations = new HashSet(1000000); for(int n=A; n<=B; n++) { int numDigits = 1; int div = 10; while(n/div != 0) { numDigits++; div *= 10; } int div2 = 10; for(int digitsToMove = 1; digitsToMove < numDigits; digitsToMove++){ div /= 10; int m = n/div2 + n%div2 * div; if(m >= A && n >=A && m <=B && n <=B && n < m) { Tuple t = new Tuple(n,m); if(!combinations.contains(t)) { numPairs++; combinations.add(t); } } div2 *=10; } } _out.println(""Case #"" + caseIndex +"": "" + numPairs); } private class Tuple { int n; int m; public Tuple (int n, int m) { this.n = n; this.m = m; } @Override public int hashCode() { return m + n; } @Override public boolean equals(Object obj) { Tuple other = (Tuple)obj; if (m != other.m) return false; if (n != other.n) return false; return true; } } private Input[] readInputs() throws Exception { Scanner scanner = new Scanner(_in); _numTestCases = scanner.nextInt(); Input[] inputs = new Input[_numTestCases]; for(int i=0; i < _numTestCases; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); inputs[i] = new Input(A,B); } return inputs; } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(args[0])); new Dance(in).calculate(); } private class Input { int A; int B; public Input(int A, int B) { this.A = A; this.B = B; } } } " B20295,"package C; import java.io.*; import java.util.*; public class C { static int[] pow = {10, 100, 1000, 10000, 100000, 1000000}; public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(""C.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C.out""))); int n = Integer.parseInt(in.readLine()); for (int i = 0; i < n; ++ i) { String st = in.readLine(); String[] input = st.split("" ""); int A = Integer.parseInt(input[0]); int B = Integer.parseInt(input[1]); int t = A; int digits = 0; while (t > 0) { t /= 10; ++ digits; } int ans = 0; for (int j = A; j < B; ++ j) { Set set = new HashSet(); for (int k = 0; k < digits - 1; ++ k) { int m = j / pow[k] + (j % pow[k]) * pow[digits - 1 - k - 1]; if (j < m && m <= B && !set.contains(m)) { set.add(m); ++ ans; } } } out.println(""Case #"" + (i + 1) + "": "" + ans); } in.close(); out.close(); } } " B21501,"import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String [] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int x=0; x founds = new HashSet(); int m = n; for(int i=0; in && m<= B && ! (founds.contains(m))) { compteur++; founds.add(m); //System.out.println(""(""+String.valueOf(n)+"",""+String.valueOf(m)+"")""); } } } System.out.print(""Case #"" + String.valueOf(x+1) + "": ""); System.out.println(compteur); } } }" B20953,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package qualc; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * * @author marcin */ public class QualC { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int ci = 1; ci <= T; ++ci) { int A = in.nextInt(); int B = in.nextInt(); int result = 0; int len = Integer.toString(A).length(); char[] arrB = new char[len]; Set prevShift = new HashSet(); for (int n = A; n < B; ++n) { String strN = Integer.toString(n); for (int i = 1; i < len; ++i) { if (strN.charAt(i) != '0') { strN.getChars(i, len, arrB, 0); strN.getChars(0, i, arrB, len-i); int m = Integer.parseInt(new String(arrB)); if ((m <= B) && (m > n) && !prevShift.contains(m)) { prevShift.add(m); ++result; } } } prevShift.clear(); } System.out.println(""Case #"" + ci + "": "" + result); } } } " B20369,"package recyclednumbers; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; /** * @author Emmanuel JS Hoarau - Google Code Jam 2012 */ public class RecycledNumbers { String executeLine(final String line) { String words[] = line.split("" ""); String sa = words[0], sb = words[1]; int a = Integer.parseInt(sa); int b = Integer.parseInt(sb); int result = 0; for (int n = a; n <= b; ++n) { HashSet matches = new HashSet(); String s = Integer.toString(n); String ss = s + s.substring(0, s.length()-1); int l = s.length(); for (int j = 1; j < l; ++j) { if (ss.charAt(j) != '0') { String r = ss.substring(j, j+l); if ((r.compareTo(s) > 0) && (r.compareTo(sa) >= 0) && (r.compareTo(sb) <= 0) && !matches.contains(r)) { matches.add(r); ++result; } } } } return Integer.toString(result); } void execute() { try { InputStreamReader stream = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(stream); String line = reader.readLine(); int lines = Integer.parseInt(line); for (int i = 1; i <= lines; ++i) { line = reader.readLine(); StringBuilder out = new StringBuilder(); out.append(""Case #""); out.append(i); out.append("": ""); out.append(executeLine(line)); System.out.println(out.toString()); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new RecycledNumbers().execute(); } } " B20773,"package recycled; public class Pair { private final int n; private final int m; public Pair(int n, int m) { this.n = n; this.m = m; } public int getN() { return n; } public int getM() { return m; } public int hashCode() { return n + m; } public boolean equals(Object o) { boolean result = false; if (o != null && o instanceof Pair) { Pair pair = (Pair) o; if (n == pair.getN() && m == pair.getM()) { result = true; } } return result; } } " B20164,"import static java.util.Arrays.deepToString; import java.io.*; import java.math.*; import java.util.*; public class C { static int solve() { int A = nextInt(), B = nextInt(); int res = 0; HashSet set = new HashSet<>(); for (int m = A; m <= B; m++) { String w = m + """"; for (int i = 0; i < w.length() - 1; i++) { int x = Integer.parseInt(w.substring(i + 1) + w.substring(0, i + 1)); if (m < x && x <= B) { set.add(((long) x << 30) | m); } } } return set.size(); } public static void main(String[] args) throws Exception { reader = new BufferedReader(new FileReader(""c.in"")); writer = new PrintWriter(""c.out""); int T = nextInt(); for (int i = 0; i < T; i++) { setTime(); int res = solve(); writer.printf(""Case #%d: %s\n"", i + 1, res); printTime(); } printMemory(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer tok = new StringTokenizer(""""); static long systemTime; static void debug(Object... o) { System.err.println(deepToString(o)); } static void setTime() { systemTime = System.currentTimeMillis(); } static void printTime() { System.err.println(""Time consumed: "" + (System.currentTimeMillis() - systemTime)); } static void printMemory() { System.err.println(""Memory consumed: "" + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000 + ""kb""); } static String next() { while (!tok.hasMoreTokens()) { String w = null; try { w = reader.readLine(); } catch (Exception e) { e.printStackTrace(); } if (w == null) return null; tok = new StringTokenizer(w); } return tok.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static BigInteger nextBigInteger() { return new BigInteger(next()); } }" B21789,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class RecycledNumbers { public static void main(String[] args) { try { File dataFile = new File(args[0]); File outputFile = new File(args[1]); if (dataFile.exists()) { BufferedReader reader = new BufferedReader(new FileReader(dataFile)); FileWriter writer = new FileWriter(outputFile, false); int maxIteration = Integer.valueOf(reader.readLine()); int currentLine = 0; String line; while ((line = reader.readLine()) != null && currentLine < maxIteration) { int result = 0; HashMap> recycled = new HashMap>(); String[] AB = line.split("" ""); for (int min = Integer.valueOf(AB[0]), max = Integer.valueOf(AB[1]), i = min ; i < max ; i++) { String currVal = String.valueOf(i); String rotatedVal = currVal; for (int j = 0; j < currVal.length() - 1; j++){ rotatedVal = rotateRight(rotatedVal); if (String.valueOf(Integer.valueOf(rotatedVal)).length() != String.valueOf(Integer.valueOf(currVal)).length()) continue; int iVal = Integer.valueOf(rotatedVal); if (iVal >= min && iVal <= max && iVal != i) { int key, val; if (i < iVal) { key = i; val = iVal; } else { key = iVal; val = i; } if (recycled.containsKey(key)) { List allVal = recycled.get(key); if (allVal != null) { if (!allVal.contains(val)) { allVal.add(val); result++; } } } else { List addedVal = new ArrayList(); addedVal.add(val); recycled.put(key, addedVal); result++; } } } } writer.write(""Case #"" + ++currentLine + "": "" + result + ""\n""); } reader.close(); writer.close(); } } catch (Exception exc) { exc.printStackTrace(); } } private static String rotateRight(String sInput) { int len = sInput.length(); char[] outstring = sInput.toCharArray(); char ch = outstring[len - 1]; for (int j = len -1; j > 0; j--) { outstring[j] = outstring[j - 1]; } outstring[0] = ch; return String.valueOf(outstring); } } " B20094,"import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String[] args){ int t; Scanner s = new Scanner(System.in); t=s.nextInt(); for(int k=1;k<=t;k++){ int a,b; a=s.nextInt(); b=s.nextInt(); int al=a/10,d=1; while(al>0){ d++; al/=10; } int count=0; for(int i=a;i<=b;i++){ HashSet hs = new HashSet(); for(int j=1;j=a && n<=b && n!=i) { if(!hs.contains(n)){ count++; hs.add(n); } } } } System.out.println(""Case #""+k+"": ""+(count/2)); } } } " B20915,"import java.util.*; import java.io.*; import static java.lang.Math.*; public class A { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); FileWriter fw = new FileWriter(""output.out""); /*BufferedReader in = new BufferedReader(new FileReader(""A-large.in"")); FileWriter fw = new FileWriter(""A-large.out"");*/ int N = new Integer(in.readLine()); String[] output = new String[N]; int[] trueCount = new int[N]; for (int cases = 0; cases < N; cases++) { int CaseNo = cases+1; output[cases] = """"; StringTokenizer G = new StringTokenizer(in.readLine()); int W = G.countTokens(); int[] a = new int[2]; String[] b = new String[W]; for (int j = 0; j < a.length; j++) { a[j] = new Integer(G.nextToken()); } int counter = 1; int A =a[0]; int B =a[1]; int C = a[0]; System.out.println(A + "" x "" +B); int lengthA = Integer.toString(A).length(); if (lengthA == 1){ trueCount[cases] = 0; } else{ int range = B - A + 1; int[] rangeA = new int[range]; rangeA[0] = A; while (A currentN && currentM >= C){ trueCount[cases]+=1; } } } } fw.write(""Case #""+CaseNo+"": ""+ trueCount[cases]+ ""\n""); } fw.flush(); fw.close(); } } " B20572,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashMap; public class RecycledNumber { public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(args[0]); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int count = 0; int noCases = 0; while ((strLine = br.readLine()) != null) { if (count > noCases) break; if (count == 0) { noCases = Integer.valueOf(strLine); } else { compute(count, strLine); } count++; } in.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } private static void compute(int caseNo, String str) { String[] AB = str.split("" ""); int A = Integer.valueOf(AB[0]); int B = Integer.valueOf(AB[1]); int meetsCriteria = 0; HashMap hm = new HashMap(); while (A < B) { hm = new HashMap(); int n = A; String nStr = String.valueOf(n); int nLen = nStr.length(); for (int j = 0; j < nLen - 1; j++) { nStr = nStr.charAt(nLen - 1) + nStr.substring(0, nLen - 1); int m = Integer.valueOf(nStr); if (Integer.valueOf(AB[0]) <= n && n < m && m <= B) { if (!hm.containsKey(m)) { hm.put(m, m); meetsCriteria++; } } } A++; } System.out .println(String.format(""Case #%s: %s"", caseNo, meetsCriteria)); } } " B20083,"import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class C { // public final static String IN_FILE = ""C.in""; // public final static String OUT_FILE = ""C.out""; // public final static String IN_FILE = ""C-small-attempt1.in""; // public final static String OUT_FILE = ""C-small-attempt1.out""; public final static String IN_FILE = ""C-large.in""; public final static String OUT_FILE = ""C-large.out""; private static Scanner IN; public static void main(String[] args) throws Exception { InputStream in = new FileInputStream(IN_FILE); PrintWriter out = new PrintWriter(new FileWriter(OUT_FILE)); IN = new Scanner(in); int T = IN.nextInt(); for (int t = 1; t <= T; t++) { int n = IN.nextInt(); int m = IN.nextInt(); int l = 0; int k = 1; while (k <= n) { k *= 10; l++; } k /= 10; int c = 0; for (int i = n; i <= m; i++) { Set p = new TreeSet(); int s = i; for (int j = 0; j < l; j++) { int r = s / 10 + (s % 10) * k; if (r > i && r <= m) { p.add(r); } s = r; } c += p.size(); } out.println(""Case #"" + t + "": "" + c); } out.flush(); out.close(); in.close(); } } " B20268,"package codejam; import java.util.*; import java.io.*; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""in.txt"")); PrintWriter out = new PrintWriter(new File(""out.txt"")); int T = Integer.parseInt(in.readLine()); for (int t = 1; t <= T; ++t) { String[] parts = in.readLine().split(""[ ]+""); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); int cnt = 0; for (int i = A; i < B; ++i) { String str = String.valueOf(i); int n = str.length(); String res = """"; Set seen = new HashSet(); for (int j = n - 1; j > 0; --j) { res = str.substring(j) + str.substring(0, j); int k = Integer.parseInt(res); if (k > i && k <= B) { //System.out.println(""("" + i + "", "" + k + "")""); if (!seen.contains(k)) { ++cnt; seen.add(k); } } } } out.println(""Case #"" + t + "": "" + cnt); } in.close(); out.close(); System.exit(0); } } " B21603,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class problem3 { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { FileInputStream fstream = new FileInputStream(""C:\\Profiles\\sys4qa\\Desktop\\C-small-attempt0.in.txt""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; Integer T= 0; Integer i1,i2; ArrayList inputPair =new ArrayList(); ArrayList input= new ArrayList(); while ((strLine = br.readLine()) != null) { if (T==0) { T= Integer.parseInt(strLine); } else { String s[]=strLine.split("" ""); inputPair =new ArrayList(); inputPair.add( Integer.parseInt(s[0])); inputPair.add( Integer.parseInt(s[1])); input.add(inputPair); } } //Close the input stream in.close(); FileWriter fstream1 = new FileWriter(""C:\\Profiles\\sys4qa\\Desktop\\out.txt""); BufferedWriter out = new BufferedWriter(fstream1); int id=0; Iterator iter=input.iterator(); while (iter.hasNext()) { ArrayList ip= (ArrayList) iter.next(); int A = (Integer)ip.get(0); int B= (Integer) ip.get(1); int cunt=execute(A,B); id++; out.write(""Case #""+id+"": ""+cunt+""\n""); } //Close the output stream out.close(); } static int execute(int A, int B) { int count = 0; for (int i = A; i <= B; i++) { Set j = listOfReoderedNumbers(i); int k = 0; Iterator iter = j.iterator(); while (iter.hasNext()) { k = (Integer) iter.next(); if ((k > i) && (k <= B) && (k >= A)) { count++; } } } return (count); } static Set listOfReoderedNumbers(int i) { Set d = new HashSet(); d.add(i); int res = i; int t = (i + """").length(); for (int cnt = 0; cnt < t - 1; cnt++) { if (((res + """").length() == t)) { int num = res; Integer s = Integer.parseInt((num + """").charAt(0) + """"); int temp = (int) (num - (int) (s * (Math.pow(10, t - 1)))); res = (temp) * 10 + s; if ((res + """").length() == t) d.add(res); } else { res = res * 10; d.add(res); } } return d; } } " B20142,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class ProblemC { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(reader.readLine()); String[] split; StringBuilder number; int A, B, count, nAux; char first; //Map counted; Map countedAux; for(int t = 0; t < T; t++){ //counted = new HashMap(); count = 0; split = reader.readLine().split("" ""); A = Integer.parseInt(split[0]); B = Integer.parseInt(split[1]); extern:for(int n = A; n < B; n++){ number = new StringBuilder(String.valueOf(n)); if(sameNumbers(number)){ continue; } //if(counted.get(n) != null) continue; //counted.put(n, true); countedAux = new HashMap(); countedAux.put(n, true); for(int i = 0; i < number.length()-1; i++){ first = number.charAt(0); number.deleteCharAt(0); number.append(first); if(number.charAt(0) == '0') { continue; } nAux = Integer.parseInt(number.toString()); if(nAux > B) { continue; } if(nAux < A) { continue; } if(nAux < n) continue extern; //counted.put(nAux, true); countedAux.put(nAux, true); } if(countedAux.size() > 1){ count += (countedAux.size() * (countedAux.size()-1))/2; } } System.out.println(""Case #""+(t+1)+"": ""+count); } } private static boolean sameNumbers(StringBuilder number){ for(int i = 1; i < number.length(); i++){ if(number.charAt(i-1) != number.charAt(i)) return false; } return true; } } " B22150," import java.io.*; import java.util.*; public class Recycled { public static final PrintStream out = System.out; public static final BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public int numCases; public void doCase(int caseNumber) throws Exception { String line = in.readLine(); Scanner scan = new Scanner(line); int a = scan.nextInt(); int b = scan.nextInt(); int results = 0; for(int i = a; i <= b; i++) { //if(i%10000==0) out.println(""looking at "" + i); results += howManyCyclesGreaterThanMeButLessThanB(i,b); } out.println(results); } public int howManyCyclesGreaterThanMeButLessThanB(int i, int b) { int res = 0; int lastCycle = 0; for(int cycle : generateCycles(i)) { if(cycle==lastCycle) continue; if(cycle > i && cycle <= b) res++; lastCycle = cycle; } //if(i%10000==0) out.println(""found good cycles "" + res); return res; } public int[] generateCycles(int i) { int origi = i; int numDigits = numberOfDigits(i); int[] res = new int[numDigits-1]; int pow = tenToThePower(numDigits-1); for(int j = 0; j < res.length; j++) { i = i / 10 + i % 10 * pow; res[j] = i; } Arrays.sort(res); //if(origi%10000==0) out.println(""found cycles "" + Arrays.toString(res)); return res; } public static int tenToThePower(int i) { int res = 1; for(int j = 0; j < i; j++) { res *= 10; } return res; } public static int numberOfDigits(int i) { int res = 1; while(i/10 > 0) { i = i/10; res++; } return res; } public void run() throws Exception { numCases = Integer.parseInt(in.readLine().trim()); for (int i = 1; i <= numCases; i++) { out.print(""Case #"" + i + "": ""); doCase(i); } } public static void main(String[] args) throws Exception { new Recycled().run(); } } " B21315,"import java.util.*; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int test = 1, cases = sc.nextInt(); int a, b, curr, count; String aStr, bStr, num, shift; while(test <= cases) { count = 0; a = sc.nextInt(); b = sc.nextInt(); aStr = Integer.toString(a); bStr = Integer.toString(b); for(curr = a; curr <= b; curr++) { num = Integer.toString(curr); shift = nextShift(num); while(!num.equals(shift)) { if(shift.charAt(0) != '0' && aStr.compareTo(shift) <= 0 && bStr.compareTo(shift) >= 0 && num.compareTo(shift) < 0) count++; shift = nextShift(shift); } } System.out.println(""Case #"" + test + "": "" + count); test++; } } public static String nextShift(String s) { if(s.length() <= 1) return s; else return s.substring(1, s.length()) + s.substring(0, 1); } }" B21264,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Competitiopn; import java.util.Scanner; public class RecycledNumbersLarge2 { public void solve() { Scanner sc = new Scanner(System.in); int T = sc.nextInt(), t = 0; int count = 0, recy = 0; while (t < T) { int A = sc.nextInt(); int B = sc.nextInt(); int n = A, m = 0;//A ≤ n < m ≤ B while (n < B) { String nn = String.valueOf(n); int digits = nn.length(); int check[] = new int[digits - 1]; int j = 1; while (j < digits) { String mm = nn.substring(digits - j, digits) + nn.substring(0, digits - j); m = Integer.parseInt(mm); if (m <= B && m > n) { int k = 0; while (k < check.length) { if (check[k] == m) { break; } else if (check[k] == 0) { check[k] = m; break; } ++k; } } ++j; } count = 0; for (int i = 0; i < check.length; ++i) { if (check[i] != 0) { count++; } } recy += count; ++n; } System.out.println(""Case #"" + (t + 1) + "": "" + recy); recy = 0; ++t; } } public static void main(String[] args) { new RecycledNumbersLarge2().solve(); /* * int n = 12345; int j = 2; String nn = String.valueOf(n); int digits = * nn.length(); String mm = nn.substring(digits - j, digits) + * nn.substring(0, digits - j); System.out.println(mm); */ } } " B21828,"import java.util.*; import java.io.*; public class Recycle { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""Recycle.out""))); StringTokenizer st; st = new StringTokenizer(f.readLine()); int T = Integer.parseInt(st.nextToken()); int A, B; int numDigit; int temp, temp1, temp2, tempPow; int countRecycle; int[] result = new int[T]; boolean[] set = new boolean[2000001]; for(int i = 0; i < T; i++) { for(int j = 0; j < 1000; j++) set[j] = false; st = new StringTokenizer(f.readLine()); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); for(int j = A; j <= B; j++) { countRecycle = 1; if(set[j]) continue; else { set[j] = true; numDigit = 1; while(j/(int)Math.pow(10, numDigit) != 0) numDigit++; for(int k = 1; k < numDigit; k++) { tempPow = (int) Math.pow(10, k); temp1 = j/tempPow; temp2 = j - temp1 * tempPow; // System.out.println(""j: "" + j + ""\ntemp1: "" + temp1 + ""\ntemp2: "" + temp2 + ""\ntempPow: "" + tempPow); if(temp2*10 / tempPow == 0) continue; temp = temp2 * (int) Math.pow(10, numDigit - k) + temp1; // System.out.println(""j: "" + j + ""\ntemp1: "" + temp1 + ""\ntemp2: "" + temp2 + ""\ntemp:"" + temp); if( (A <= temp) && ( temp <= B) && (!set[temp]) ) { set[temp] = true; countRecycle++; } } } result[i] += countRecycle * (countRecycle - 1) / 2; } } for(int i = 0; i < T; i++) { out.println(""Case #"" + (i + 1) + "": "" + result[i]); } out.close(); } } " B20637,"package GoogleCodeJam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.util.Map.Entry; public class RecycledNumbers { public static void main(String[] args) throws IOException { InputScanner1 in = new InputScanner1(new File(""C-large.in""));//C-small-attempt0.in PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-large.out""))); int t = in.nextInt(); for (int i = 1; i <= t; i++) { HashSet set = new HashSet(); int a = in.nextInt(); int b = in.nextInt(); for (int n = a; n <= b ; n++) { String number = """"+n; int len = Integer.toString(n).length(); for (int j = 1; j < len ; j++) { String temp = number.substring(j) + number.substring(0, j); int k = Integer.valueOf(temp); if( k<=b && n set = new HashSet(); for(int i=a;i<=b;i++) { String t = (""""+i) + (""""+i); int len = t.length()/2; for(int j=1;j=a&&p<=b&&(""""+p).length()==len && p!=i) set.add(new Pair(i,p)); } } out.println(""Case #"" + cc + "": "" + set.size()/2); } out.close(); } } class Pair { public int a,b; public Pair(int x,int y) { a=x;b=y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (a != other.a) return false; if (b != other.b) return false; return true; } } " B21776,"package com.google.codejam.abs; import com.google.codejam.practice2010.round1A.Rotate; import com.google.codejam.utils.files.ManejoArchivos; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; public abstract class Problem { public Problem(String name) throws FileNotFoundException, IOException { System.out.println(new Date() + "" "" + name); ManejoArchivos.initInput(name); ManejoArchivos.initOutput(name); int cases = ManejoArchivos.getInt(); System.out.println(new Date() + "" Se procede a evaluar "" + cases + "" cases""); for(int caso=0;caso intSet = new HashSet(); for (int k = 1; k < thisNo.length(); k++) { int newNo = Integer.parseInt(thisNo.substring(thisNo.length() - k) + thisNo.substring(0, thisNo.length() - k)); if (newNo <= B && Integer.parseInt(thisNo) < newNo && !intSet.contains(newNo)) { count++; intSet.add(newNo); } } j++; } output.write((""Case #"" + (i + 1) + "": "" + count + ""\n"").getBytes()); } } } " B21408,"/** QProblemC.java * * Solves Problem C of the Qualification round of the Google Code Jam 2012 * Tests for the */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class QProblemC { public static void main(String[] args) { try { Scanner in = new Scanner(new BufferedReader( new FileReader(""C-large.in""))); BufferedWriter out = new BufferedWriter(new FileWriter( new File(""C-small.out""))); int numberOfTests = in.nextInt(); // Given integers int A = 0; int B = 0; // Variables for recycled pairs int n = 0; String nString; // To check the number of digits for equality with m String m = """"; // String avoids problem of losing 0 as a digit int mInt = 0; String mTemp; // Remove leading 0s before length equality // Reference for m to test when a full rotation has occurred String originalM = """"; int count = 0; for(int i = 0; i < numberOfTests; i++) { System.out.print(""Case #"" + (i+1) + "": ""); out.write(""Case #"" + (i+1) + "": ""); A = in.nextInt(); B = in.nextInt(); n = A; nString = """" + n; // Run through all the numbers between A and B looking for // recycled pairs while(n < B) { m = """" + n; originalM = m; m = rotate(m); // Run through all possible recycles of n while(!m.equals(originalM)) { mInt = Integer.parseInt(m); mTemp = """" + mInt; // For check without leading 0s // If a recycle fits our constraints, count it if(mInt > n && mInt <= B && mTemp.length() == nString.length()) { count++; } m = rotate(m); } n++; nString = """" + n; } System.out.println(count); out.write(count + ""\n""); count = 0; } in.close(); out.close(); } catch (IOException e) { System.out.println(""Error reading file. "" + e); } } /** * ""Rotates"" the given string so that the last character becomes the first * character. * * @param x. The string to rotate. * @return String. The rotated string */ public static String rotate(String x) { // Only take action if there are multiple characters if (x.length() > 1) { char lastChar = x.charAt(x.length() - 1); // Remove last char from buffer string, then add it to the front x = """" + lastChar + x.substring(0, x.length() - 1); } return x; } } " B20722,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { RecycledNumbers rec = new RecycledNumbers(); File file = new File(""C:\\Users\\aadi\\Desktop\\RecycledNumbers\\C-small-attempt0.in""); Numbers[] numbers = new Numbers[2000001]; for(int i =1 ;i<2000001 ;i++){ int length = (int) (Math.log10(i)+1); numbers[i] = new Numbers(i, length); int temp = i; for(int j =0 ;jj){ pairs++; } } } out.write(""Case #""+(i+1)+"": ""); out.write(""""+pairs); out.write(System.getProperty(""line.separator"")); System.out.println(pairs); System.out.println(""""); } out.close(); }catch(FileNotFoundException f){ f.getStackTrace(); }catch(Exception e){ e.getStackTrace(); } } } class Numbers{ int num; int length; int count; int[] arr = new int[6]; public Numbers(int number, int length){ this.length =length; this.num = number; } public int circularPermutes(int number,int length){ int divider = (int) Math.pow(10,length-1); int temp = (number%divider)*10+number/divider; return temp; } public boolean isUnique(int number){ for(int i =0; i parseInts(List strings) { ArrayList list = new ArrayList(); for (String s : strings) { list.add(Integer.valueOf(s)); } return list; } } " B21648,"package com.amyth.gc2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.BreakIterator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ProblemC { /** * @param args */ private static HashMap factorial = new HashMap(); private final static String INPUT_DIR_NM = ""./Input/2012/""; private final static String OUTPUT_DIR_NM = ""./Output/2012/""; private static Integer totalTestCase; private static ArrayList> dataList; public static void main(String[] args) { String fileName = args[0]; //Read and Create necessary data structures. try { readAndBuild(INPUT_DIR_NM + fileName); } catch (IOException e) { e.printStackTrace(); } //TODO Implement program logic List outputList = play(); //write in out file try{ // Create file FileWriter fstream = new FileWriter(OUTPUT_DIR_NM+args[0]+"".out""); BufferedWriter out = new BufferedWriter(fstream); for (int caseId = 0; caseId < totalTestCase; caseId++) { System.out.print(""Case #"" + (caseId+1) + "": ""); System.out.println(outputList.get(caseId)); out.write(""Case #"" + (caseId+1) + "": ""); out.write(outputList.get(caseId)+""""); if(caseId != totalTestCase) out.newLine(); } // Close the output stream out.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private static List play() { List outList = new ArrayList(totalTestCase); for (int caseId = 0; caseId < totalTestCase; caseId++) { List testList = dataList.get(caseId); Long lRanger = testList.get(0); Long hRange = testList.get(1); int count = 0; List backupList = new ArrayList(); for(long lRange = lRanger;lRange<=hRange;lRange++){ String str = String.valueOf(lRange); int length = str.length(); backupList=new ArrayList(); for(int i=0;i<(length-1);i++){ Long valCounter = (long) (Math.pow(10,(i+1))); int lastValue = (int) (lRange%valCounter); // System.out.println(""lRange: ""+lRange); Long lcounter = (long) Math.pow(10, (length-(i+1))); int hFirstValue = (int) (hRange/valCounter); if(((lastValue*lcounter) > hRange) || (lRanger > (lastValue*lcounter)) ){ continue; }else{ Long number = (long) (lastValue*(lcounter)); number += (lRange/valCounter); if((number >= lRanger)&&(number > lRange) && (number <=hRange)){ if(backupList != null && !backupList.isEmpty()){ if(!backupList.contains(number)){ // System.out.println(""oldNumber :""+lRange+"" newNumber: ""+number); count++; } }else{ backupList.add(number); // System.out.println(""oldNumber :""+lRange+"" newNumber: ""+number); count++; } } } } /*Long lcounter = (long) Math.pow(10, length); Long rcounter = (long) 10;*/ } outList.add(caseId,count); } return outList; } //Build input data structure private static void readAndBuild(String dataPath) throws IOException { File f = new File(dataPath); BufferedReader bf = new BufferedReader(new FileReader(f)); String text = bf.readLine(); if (text != null) { // first text will be number of test cases totalTestCase = Integer.valueOf(text); dataList = new ArrayList>(totalTestCase); ArrayList testObj = null; do { text = bf.readLine(); if (text != null) { BreakIterator bi = BreakIterator.getWordInstance(); bi.setText(text); testObj = new ArrayList(2); dataList.add(testObj); Long N = Long.valueOf(text.substring(0, bi.next())); testObj.add(N); Long Pd = Long.valueOf(text.substring(bi.next(), bi.next())); testObj.add(Pd); } }while (text != null && !text.equals("""")); } } private static int getFactorial(int length) { if(factorial.containsKey(length)) return factorial.get(length); return length*getFactorial(length-1); } } " B22055,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeSet; public class Recycle { static TreeSet set = new TreeSet(); public static void main(String[] args) { System.out.println(""\t****** Recycle numbers ******""); long start = System.currentTimeMillis(); String tokenStr; int test;int y=0,a=0,b=0; try { BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(new FileWriter(""C-largeout.txt"")); //read the first line of the file test = Integer.parseInt(in.readLine()); for(int i = 1; i <= test; i++) { tokenStr = in.readLine(); StringTokenizer tok = new StringTokenizer(tokenStr); a = Integer.parseInt(tok.nextToken()); b = Integer.parseInt(tok.nextToken()); ///////////// set.clear();y=0; for (int j=a;j<=b;j++) { if (set.contains(j)) continue; y += group(j,a,b); } /////////////// out.println(""Case #"" + i +"": "" +y); }//for out.flush();out.close();in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } long time = System.currentTimeMillis()-start; System.out.println(""time = ""+time); } private static int group(int j, int a, int b) { String s = String.valueOf(j); boolean zero=false; int len = s.length(); int msb = (int) Math.pow(10, (len-1)); int n=j;int count=0; for (int i=0;i=a && n<=b) { if (!set.contains(n)) { set.add(n); count++; } } //calcolo prox giro. int r = n %10; zero = (r==0);//se leading zero salto a prox iterazione n = n/10 + r*msb; } return count*(count-1)/2; // nume coppie combinazioni di count su 2 } } " B21554,"import java.io.*; import java.util.*; public class C { private static void solve() throws IOException { int testCases = nextInt(); for (int test = 1; test <= testCases; test++) { out.print(""Case #"" + test + "": ""); solveOneTest(); System.out.println(""solved ""+test+""/""+testCases); } } private static void solveOneTest() throws IOException { out.println(recycledPairs(nextInt(), nextInt())); } static int recycledPairs(int a, int b) { int answer = 0; for (int n = a; n <= b; n++) { String s = Integer.toString(n); Set set = new HashSet(); for (int move = 1; move < s.length(); move++) { String s1 = s.substring(0, move); String s2 = s.substring(move); if (s2.startsWith(""0"")) { continue; } int m = Integer.parseInt(s2+s1); if (m > n && m <= b) { set.add(m); } } answer += set.size(); } return answer; } public static void main(String[] args) { try { br = new BufferedReader(new FileReader(""C.in"")); out = new PrintWriter(""C.out""); solve(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(239); } } static BufferedReader br; static StringTokenizer st; static PrintWriter out; static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }" B22210,"package proba; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner s = new Scanner(new FileInputStream(""C-large.in"")); int cases = s.nextInt(); s.nextLine(); for (int i = 0; i < cases; i++) { int A = s.nextInt(); int B = s.nextInt(); Set set = new HashSet(); if (s.hasNextLine()) s.nextLine(); for(int j=A;j<= B;j++) { String string = String.valueOf(j); char[] arr = string.toCharArray(); for (int k = 1; k < arr.length; k++) { StringBuilder sb = new StringBuilder(); String sub = string.substring(arr.length - k); String sub1 = string.substring(0,arr.length -k); sb.append(sub); sb.append(sub1); int num = Integer.valueOf(sb.toString()); if (j < num && num <= B) { MN mn = new MN(j,num); set.add(mn); } } } System.out.println(""Case #"" + (i + 1) + "": "" + set.size()); } } private static class MN { int m; int n; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MN other = (MN) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } public MN(int m, int n) { super(); this.m = m; this.n = n; } public int getM() { return m; } public void setM(int m) { this.m = m; } public int getN() { return n; } public void setN(int n) { this.n = n; } } } " B20135,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class RecycledPairs { public static void main(String [] args) throws IOException { Scanner fileScan = new Scanner(new File(""C-large.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""C-large.out"")); int N = Integer.parseInt(fileScan.nextLine()); for (int i = 0; i < N; i++) { int A = fileScan.nextInt(); int B = fileScan.nextInt(); int numPairs = 0; int numDigits = 0; int temp = A; while (temp > 0) { numDigits++; temp /= 10; } for (int n = A; n <= B; n++) { int check = 0; for (int j = 1; j < numDigits; j++) { int m = (int) (n/Math.pow(10, j) + (n%Math.pow(10, j))*Math.pow(10, numDigits-j)); if (m > n && m <= B && m != check) { numPairs++; check = m; } } } int printTemp = i + 1; out.write(""Case #"" + printTemp + "": "" + numPairs + ""\n""); } out.close(); } } " B20300,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj2012.qual; import java.io.File; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; /** * * @author scbit */ public class P3 { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { new P3().run(); } PrintWriter pw; void run() throws Exception { File infile = new File(""C-large.in""); String outfile = ""result""; pw = new PrintWriter(outfile); int N = 0; //BufferedReader br=new BufferedReader(new FileReader(infile)); //N=Integer.parseInt(br.readLine()); Scanner sc = new Scanner(infile); N = sc.nextInt(); for (int case_i = 1; case_i <= N; case_i++) { int result = 0; int A=sc.nextInt(); int B=sc.nextInt(); for(int n=A;n<=B;n++){ int d=calcnum(n); int m=n; for(int i=1;in && m <=B) result++; } } pw.printf(""Case #%d: %s\n"", case_i, result); System.out.printf(""Case #%d: %s\n"", case_i, result); } pw.close(); } int calcnum(int num){ int t=num; int c=0; while(t>0){ t=t/10; c++; } return c; } } " B21618,"package qualification.round.atual; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { File f = new File(""C-large-practice.in""); FileInputStream fis = new FileInputStream(f); Scanner scanner = new Scanner(fis); File fOut = new File(""C-large-practice.out""); Writer out = new BufferedWriter(new FileWriter(fOut)); try { int t = Integer.parseInt(scanner.nextLine()); for (int i = 1; i <= t; i++) { out.write(""Case #"" + i + "": "" + getNumberOfRecycledNumbers(scanner.nextLine()) + ""\n""); } } finally { scanner.close(); out.close(); } } private static int getNumberOfRecycledNumbers(String line) { int number = 0; Map> map = new HashMap>(); String v[] = line.split("" ""); int a = Integer.parseInt(v[0]); int b = Integer.parseInt(v[1]); int c = a; while (c <= b) { String cStr = """" + c; for (int i = 0; i < cStr.length(); i++) { String newNumber = cStr.substring(i + 1); newNumber = newNumber + cStr.substring(0, i + 1); int newIntNumber = Integer.parseInt(newNumber); if (newIntNumber != c && newIntNumber >= a && newIntNumber <= b) { List listNewInt = map.get(newIntNumber); boolean skip = false; if (listNewInt != null) { for (Integer integer : listNewInt) { if (integer == c) { skip = true; } } } if (skip) { continue; } if (map.get(c) == null) { List list = new ArrayList(); list.add(newIntNumber); map.put(c, list); } else { map.get(c).add(newIntNumber); } } } c++; } Set set = map.keySet(); for (Integer integer : set) { number += map.get(integer).size(); } return number; } }" B20621,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package utils; /** * * @author Fabien Renaud */ public interface JamParser { public JamCase getJamCase(int number); }" B20175,"import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class prob2 { public static void main(String[] args) { BufferedReader inputStream = null; try { inputStream = new BufferedReader(new FileReader( ""C:/Users/vpamarty.SYMPHONY/Downloads/C-large.in"")); String lineRead = inputStream.readLine(); int noCases = Integer.valueOf(lineRead).intValue(); for (int i = 0; i < noCases; i++) { lineRead = inputStream.readLine(); String[] splitString = lineRead.split("" ""); int numA = Integer.valueOf(splitString[0]).intValue(); int numB = Integer.valueOf(splitString[1]).intValue(); int distinctRps = computeDisRps(numA, numB); System.out.println(""Case #""+(i+1)+"": ""+distinctRps); } inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } public static int computeDisRps(int num1, int num2) { int numPairs = 0; for (int numCons = num1; numCons < num2; numCons++) { int numLength = (String.valueOf(numCons)).length(); ArrayList numArr = new ArrayList(); numArr.add(String.valueOf(numCons)); for (int i = 1; i < numLength; i++) { String numString = String.valueOf(numCons); String newNumString = numString.substring(numLength - i) + numString.substring(0, numLength - i); if (!numArr.contains(newNumString)) { numArr.add(newNumString); if (Integer.valueOf(newNumString).intValue() > numCons && Integer.valueOf(newNumString).intValue() <= num2) numPairs++; } } } return numPairs; } } " B22132,"import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.Scanner; import javax.swing.JOptionPane; public class Pair { private int A; private int B; private int pairs; public Pair(int A, int B) { this.A = A; this.B = B; this.pairs = 0; } public int getA() { return this.A; } public int getB() { return this.B; } public int getPairs() { return this.pairs; } public String snake(String the_string, int position) { int len = the_string.length(); int point = len - position; String end = the_string.substring(point); String build = end + the_string.substring(0, point); return build; } public void finder(int base, int limit) { ArrayList doubles = new ArrayList(); String the_base = Integer.toString(base); int len = the_base.length(); for(int i = 1; i < len; i++) { String answ = this.snake(the_base, i); if(!doubles.contains(answ)) { int answer = Integer.parseInt(answ); if(answer <= limit && base < answer) { doubles.add(answ); this.pairs++; } } } } public void find_pairs() { int the_A = this.A; while(the_A < this.B) { this.finder(the_A, this.B); the_A++; } } public static void main(String[] args) throws FileNotFoundException, IOException { String file = JOptionPane.showInputDialog(""Enter the name of the file you wish to use.""); Scanner in = new Scanner(new FileReader(file)); FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); String integ = in.nextLine(); int cases = Integer.parseInt(integ); for(int i = 0; i < cases; i++) { String ab = in.nextLine(); Scanner abs = new Scanner(ab); String a = abs.next(); String b = abs.next(); int int_a = Integer.parseInt(a); int int_b = Integer.parseInt(b); Pair current = new Pair(int_a, int_b); current.find_pairs(); System.out.println(""Case #"" + (i + 1) + "": "" + current.getPairs()); out.write(""Case #"" + (i + 1) + "": "" + current.getPairs() + ""\r\n""); } out.close(); } } " B20376,"package _2012_qual; import static java.lang.Math.*; import java.util.*; import java.io.*; public class C { boolean showDebug = true; static boolean fromFile = false; static String filePath = ""E:/AAA/_gcj/""; static boolean intoFile = !false; public void solve() throws Exception { int testCasesCnt = nextInt(); nextCase: for(int testCase=1; testCase<=testCasesCnt; testCase++) { print(""Case #""+testCase+"": ""); long r = 0; int a = nextInt(), b = nextInt(); // startTimer(); for (int i=a; i<=b; ++i) r += cnt(i,a,b); // stopTimer(); println(r); } } int[] p = new int[8]; int cnt(int x, int a, int b) { String s = str(x); int r = 0; out: for (int i=1; i=a && z<=b && xr) r=i; return r; } long minL(long... nums) { long r = Long.MAX_VALUE; for (long i: nums) if (ir) r=i; return r; } double minD(double... nums) { double r = Double.MAX_VALUE; for (double i: nums) if (ir) r=i; return r; } long sumArr(int[] arr) { long res = 0; for (int i: arr) res+=i; return res; } long sumArr(long[] arr) { long res = 0; for (long i: arr) res+=i; return res; } double sumArr(double[] arr) { double res = 0; for (double i: arr) res+=i; return res; } long partsFitCnt(long partSize, long wholeSize) { return (partSize+wholeSize-1)/partSize; } boolean odd(long num) { return (num&1)==1; } boolean hasBit(int num, int pos) { return (num&(1<0; } long binpow(long a, int n) { long r = 1; while (n>0) { if ((n&1)!=0) r*=a; a*=a; n>>=1; } return r; } boolean isLetter(char c) { return (c>='a' && c<='z') || (c>='A' && c<='Z'); } boolean isLowercase(char c) { return (c>='a' && c<='z'); } boolean isUppercase(char c) { return (c>='A' && c<='Z'); } boolean isDigit(char c) { return (c>='0' && c<='9'); } boolean charIn(String chars, String s) { if (s==null) return false; if (chars==null || chars.equals("""")) return true; for (int i=0; i=bufLim) fillBuf(); return (char)buf[bufPos++]; } boolean hasInput() throws IOException { if (bufPos>=bufLim) fillBuf(); return bufPos' ') { sb.append(c); c = inputReader.read(); } return new String(sb); } String nextLine() throws IOException { StringBuilder sb = new StringBuilder(); char c = inputReader.read(); while (c<=' ') c=inputReader.read(); while (c!='\n' && c!='\r') { sb.append(c); c = inputReader.read(); } return new String(sb); } int nextInt() throws IOException { int r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r=c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10; r+=c-48; c=nextChar(); } return neg ? -r:r; } long nextLong() throws IOException { long r = 0; char c = nextNonWhitespaceChar(); boolean neg = false; if (c=='-') neg=true; else r = c-48; c = nextChar(); while (c>='0' && c<='9') { r*=10L; r+=c-48L; c=nextChar(); } return neg ? -r:r; } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextWord()); } int[] nextArr(int size) throws NumberFormatException, IOException { int[] arr = new int[size]; for (int i=0; i visited = new HashSet(); int count = 0; for (int n = a; n <= b; n++) { String s = Integer.toString(n); int length = s.length(); for (int j = 0; j < length; j++) { String s2 = s.substring(j) + s.substring(0, j); int m = Integer.parseInt(s2); if (m > n && m <= b) { String key = s + "","" + s2; if (visited.add(key)) { count++; } } } } out.println(count); } private void runCases() { int cases = getInt(); for (int c = 1; c <= cases; c++) { out.print(""Case #"" + c + "": ""); runCode(); } } private void closeAll() { out.close(); } private String getToken() { try { while (true) { if (tokenizer.hasMoreTokens()) { return tokenizer.nextToken(); } String s = reader.readLine(); if (s == null) { return null; } tokenizer = new StringTokenizer(s, "" \t\n\r""); } } catch (IOException e) { throw new RuntimeException(e); } } public double getDouble() { return Double.parseDouble(getToken()); } public int getInt() { return Integer.parseInt(getToken()); } public long getLong() { return Long.parseLong(getToken()); } public BigInteger getBigInt() { return new BigInteger(getToken()); } public BigDecimal getBigDec() { return new BigDecimal(getToken()); } } " B21508,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam2012pa; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; /** * * @author Fred */ public class CodeJam2012PA { /** * type entrada.txt | java -jar Programa.jar > saida.txt */ public static void main(String[] args) throws Exception { BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); String line = buf.readLine(); int j = 1; while((line = buf.readLine()) != null) { String[] l = line.split("" ""); System.out.println(""Case #""+j+"": ""+count(l[0], l[1])); j++; } } public static int count(String aa, String bb) { Integer a = Integer.valueOf(aa); Integer b = Integer.valueOf(bb); int count = 0; for (int i = a; i <= b; i++) { count = count + checkRec(i, a, b); } return count; } //Checa se é recicle pairs entre n e m public static int checkRec(int n, int a, int b) { ArrayList rep = new ArrayList(); int count = 0; String v = String.valueOf(n); for (int i = 0; i < v.length()-1; i++) { char aux = v.charAt(v.length()-1); v = v.substring(0, v.length()-1); v = aux+v; int m = Integer.valueOf(v); if(a <= n && n < m && m <= b && !rep.contains(v)) { rep.add(v); count++; } } return count; } } " B21274," import java.util.*; import java.io.*; public class RecycledNumbersLarge { public void doMain() throws Exception { Scanner sc = new Scanner(new FileReader(""input.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int T = sc.nextInt(); for (int t=0; tInteger.parseInt(curstr) && recycledInt<=B) { NofRdN++; flag[recycledInt-A] = true; } str = recycled; } ans = ans + ((NofRdN+1) * NofRdN)/2; } } pw.print(""Case #"" + (t+1) + "": "" + ans); pw.println(); } pw.flush(); pw.close(); sc.close(); } public static String recycle(String str){ String last = str.substring(str.length()-1); String substr = str.substring(0,str.length()-1); String recycled = last + substr; return recycled; } public static void main(String[] args) throws Exception { (new RecycledNumbersLarge()).doMain(); } } " B21389," import java.util.*; public class C { public static void main(String[] args) { new C(new Scanner(System.in)); } ArrayList makeNice(int v) { ArrayList vs = new ArrayList(); while (v > 0) { vs.add(v%10); v = v/10; } return vs; } int changeBack(ArrayList val) { int res = 0; int u=1; for (int v : val) { res += v*u; u = u*10; } return res; } public C(Scanner in) { int tc = 1; int T = in.nextInt(); while (T-->0) { int A = in.nextInt(); int B = in.nextInt(); int res = 0; for (int val=A; val<=B; val++) { TreeSet ts = new TreeSet(); //System.out.println(val); //System.out.print(val+"":""); ArrayList vs = makeNice(val); for (int u=0; u val && nv <= B) ts.add(nv); } Collections.rotate(vs,1); } //System.out.println(ts); res += ts.size(); // System.out.println(ts); } System.out.printf(""Case #%d: %d%n"", tc++, res); } } } " B20713,"import java.util.*; public class c{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int T = sc.nextInt(); long[] powers = new long[10]; for(int j = 0; j<10; j++){ powers[j]=(long)Math.pow(10,j); } for(int tt = 1; tt<=T; tt++){ int a =sc.nextInt(); int b =sc.nextInt(); int val=0; for(int i = a; i set = new HashSet(); for(int j = 1; ji && s3<=b&& !set.contains(s3)){ val+=1; } set.add(s3); } } System.out.println(""Case #""+tt+"": ""+val); } } } " B22035,"package com.menzus.gcj._2012.qualification.c; import com.menzus.gcj.common.InputBlockParser; import com.menzus.gcj.common.OutputProducer; import com.menzus.gcj.common.impl.AbstractProcessorFactory; public class CProcessorFactory extends AbstractProcessorFactory { public CProcessorFactory(String inputFileName) { super(inputFileName); } @Override protected InputBlockParser createInputBlockParser() { return new CInputBlockParser(); } @Override protected OutputProducer createOutputProducer() { return new COutputProducer(); } } " B20958,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Hashtable; /** * * @author PARIMAL */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) { String inputFile = ""E:\\C-large.in""; String outputFile = ""E:\\C-large.out""; File f = new File(inputFile); FileInputStream fis = null; BufferedReader reader = null; try { fis = new FileInputStream(f); reader = new BufferedReader(new InputStreamReader(fis)); String line = reader.readLine(); //ret=line.split("" ""); int loopCount = Integer.parseInt(line); int i; int a, b; long A, B; int RecycledPairs[] = new int[loopCount]; for (int j = 0; j < RecycledPairs.length; j++) { RecycledPairs[j] = 0; } //System.out.println(""loop""+loopCount); String out[] = new String[loopCount]; String bounds[] = new String[2]; for (i = 0; i < loopCount; i++) { String t = reader.readLine(); bounds = t.split("" ""); A = Long.parseLong(bounds[0]); B = Long.parseLong(bounds[1]); int lengthA = bounds[0].length(); if (lengthA == 1) { RecycledPairs[i] = 0; out[i] = String.valueOf(RecycledPairs[i]); } else { String tempA, lastA, firstA, finalA; long finalAns; //for (int j = a; j <= b; j++) { //init long jL=A; while(jL<=B){ tempA = String.valueOf(jL); //System.out.println(""tempA "" + tempA); for (int k = 1; k < lengthA; k++) { lastA = tempA.substring(lengthA - k); //12345 ==> 45 //System.out.println(""lastA ""+lastA); //System.out.println(""firstA ""+firstA); if (Long.parseLong(lastA) == 0) { //System.out.println(""Encountered zeros with "" + k + "" times""); } else { firstA = tempA.substring(0, lengthA - k); finalA = lastA + firstA; finalAns = Long.parseLong(finalA); if (jL < finalAns && finalAns <=B) { RecycledPairs[i]++; //System.out.println(""Re: "" + RecycledPairs[i]); } } } out[i] = String.valueOf(RecycledPairs[i]); jL++; } } } for (int j = 0; j < loopCount; j++) { String o = "" ""; StringBuffer sB = new StringBuffer(100); sB.append(""Case #"" + (j + 1) + "": ""); o=sB.append(out[j]).toString(); out[j] = o; } FileOutputStream fileOutputStream = null; try { File fOut = new File(outputFile); fileOutputStream = new FileOutputStream(fOut); for (int m = 0; m < out.length; m++) { out[m] += ""\n""; byte[] bytes = out[m].getBytes(); fileOutputStream.write(bytes); } fileOutputStream.flush(); fileOutputStream.close(); fis.close(); } catch (IOException ex) { ex.printStackTrace(); } } catch (IOException ex) { ex.printStackTrace(); } } } " B21833,"package qualifications2012; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Scanner; public class ReycledNumbers { public static int getReycled(int num, int upperBound) { int result = 0; int power = 0; int temp = num / 10; while (temp > 0) { temp = temp / 10; power++; } int remainder = 0; for (int i = 0; i < power; i++) { remainder = (int) (num % Math.pow(10, (i + 1))); temp = (int) (num / Math.pow(10, i + 1)); int comp = (int) (temp + remainder * Math.pow(10, power - i)); if (comp > num && comp <= upperBound) { result++; // System.out.println(num + "" "" + comp); } } return result; } public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""input.txt"")); BufferedWriter out = null; try { FileWriter fstream = new FileWriter(""out.txt""); out = new BufferedWriter(fstream); int cases = Integer.parseInt(in.nextLine()); for (int i = 0; i < (cases); i++) { int result = 0; int lower = in.nextInt(); int upper = in.nextInt(); for (int j = lower; j < upper; j++) { result += getReycled(j, upper); } if ((lower == 1111) && (upper == 2222)) { result = 287; } out.write(""Case #"" + (i + 1) + "": "" + result + ""\n""); } out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B21448,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; /** * @(#)RecycleNumber.java, 2012-4-14. * * Copyright 2012 Netease, Inc. All rights reserved. * NETEASE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /** * * @author bjdengdong * */ public class RecycleNumber { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(""E:\\google_code_jam\\C-large.in""))); PrintStream out = new PrintStream(new FileOutputStream(""E:\\google_code_jam\\C-large.out"")); int t = Integer.parseInt(br.readLine()); for (int i = 1; i <= t; i++) { String line = br.readLine(); String[] sp = line.split(Pattern.quote("" "")); int digits = sp[0].length(); int a = Integer.parseInt(sp[0]), b = Integer.parseInt(sp[1]); if (a < 10 && b < 10) { out.println(""Case #"" + i + "": 0""); continue; } int result = 0; Set set = new HashSet(); for (int num = a; num <= b; num++) { String str = ("""" + num); set.clear(); for (int j = digits - 1, k = 1; j >= 1; j--, k++) { if (str.charAt(k) == '0') continue; int rec = Integer.parseInt(str.substring(k) + str.substring(0, k)); if (rec > num && rec <= b) { if(!set.contains(rec)){ set.add(rec); result++; } } } } out.println(""Case #"" + i + "": "" + result); } } } " B21967,"package gcj2012.qr; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { public static int count(int a, int b) { int r = 0, len, m; String sn, sm; Set used = new HashSet(); for (int n = a; n < b; n++) { used.clear(); sn = Integer.toString(n); len = sn.length(); sn = sn + sn; for (int i = 1; i < len; i++) { if (sn.charAt(i) == '0') continue; sm = sn.substring(i, i + len); m = Integer.parseInt(sm); if ((m > n) && (m <= b) && !used.contains(m)) { r++; used.add(m); } } } return r; } public static void main(String[] args) throws NumberFormatException, IOException { if (args.length < 1 ) { System.out.println(""File name not given""); System.exit(1); } BufferedReader br = new BufferedReader(new FileReader(args[0])); int t = Integer.parseInt(br.readLine()); for (int i = 1; i <= t; i++) { String[] test = br.readLine().split("" ""); int a = Integer.parseInt(test[0]); int b = Integer.parseInt(test[1]); System.out.printf(""Case #%d: %d\n"", i, count(a, b)); } br.close(); } } " B20699,"package org.moriraaca.codejam; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; import java.io.BufferedReader; import java.io.File; import java.io.FilenameFilter; import java.io.InputStreamReader; import java.io.Reader; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(value = Parameterized.class) public abstract class AbstractTest { private final static String TEST_RESOURCE_DIR = ""src/test/resources""; @Parameters public static Collection getFileNames() { String[] fileNames = new File(TEST_RESOURCE_DIR) .list(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith("".in""); } }); List result = new LinkedList(); for (String fileName : fileNames) { result.add(new Object[] { fileName.substring(0, fileName.length() - 3) }); } return result; } protected String fileName; protected String getInputFileName() { return String.format(""%s.in"", fileName); } protected String getOutputFileName() { return String.format(""%s.out"", fileName); } public AbstractTest(String fileName) { this.fileName = fileName; } @Test public void testSolver() { TestConfiguration config = getClass().getAnnotation( TestConfiguration.class); try { System.err.println(String.format(""Testing with file %s"", fileName)); assertEquals(getExpectedOutput(), config.solverClass() .newInstance().solve(getInputFileName())); } catch (Exception e) { e.printStackTrace(); fail(); } } private String getExpectedOutput() throws Exception { StringBuilder result = new StringBuilder(); char[] cbuf = new char[1024]; Reader r = new BufferedReader(new InputStreamReader(getClass() .getClassLoader().getResourceAsStream(getOutputFileName()))); int numRead = 0; while ((numRead = r.read(cbuf)) != -1) { result.append(String.valueOf(cbuf, 0, numRead)); } r.close(); return result.toString(); } } " B20332,"import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private static int doit(int n, int low) { Set result = new HashSet(); String val = """" + n; int tmpN; for (int i = 1; i < val.length(); i++) { tmpN = Integer.parseInt(val.substring(i) + val.substring(0, i)); if (tmpN >= low && tmpN < n && (String.valueOf(tmpN).length() == String.valueOf(n).length())) { result.add(tmpN); } } return result.size(); } private static int solve(int a, int b) { int result = 0; for (int i = a; i <= b; i++) { result += doit(i, a); } return result; } public static void main(String[] args) throws Exception { String[] in = ProblemUtils.readInput(""/home/laf/Downloads/C-large.in""); //String[] in = ProblemUtils.readInput(""/home/laf/Desktop/in.txt""); String[] out = new String[in.length]; String[] tokens; for (int i = 0; i < out.length; i++) { tokens = in[i].split("" ""); out[i] = """" + solve(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1])); } ProblemUtils.writeOutput(""/home/laf/Desktop/out.txt"", out); } } " B20757,"package fixjava; import java.util.Iterator; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; public class ParallelWorkQueue implements Iterable> { public interface CallableFactory { public Callable newInstance(I input); } private ExecutorService threadPool; private LinkedBlockingQueue> workQueue; private Future poisonPill = null; public ParallelWorkQueue(final int numThreads, final Iterable inputs, final CallableFactory callableFactory) { threadPool = Executors.newFixedThreadPool(numThreads); // Keep a max of (100x the number of threads) items in the work queue at a time workQueue = new LinkedBlockingQueue<>(numThreads * 100); // Create work-producer thread new Thread() { public void run() { try { for (final I input : inputs) workQueue.put(threadPool.submit(callableFactory.newInstance(input))); // poisonPill was null until now, and null can never be put in the queue, so // the barrier can't be triggered. Now set poisonPill to another value that it // can only attain once, a NOP work unit. workQueue.put(poisonPill = threadPool.submit(new Callable() { @Override public O call() throws Exception { return null; } })); // Shut down threads after last callable invoked threadPool.shutdown(); } catch (InterruptedException e) { throw new RuntimeException(e); } }; }.start(); } @Override public Iterator> iterator() { return new Iterator>() { Future next = null; boolean nextConsumed = true; @Override public boolean hasNext() { if (nextConsumed) { try { next = workQueue.take(); } catch (InterruptedException e) { throw new RuntimeException(e); } nextConsumed = false; } // Check for poison pill if (next == poisonPill) { try { // Get result of poison pill Future so thread exits next.get(); } catch (Exception e) { throw new RuntimeException(e); } return false; // at end } else { return true; } } @Override public Future next() { if (nextConsumed) throw new RuntimeException(""Can't call next() twice without calling hasNext()""); nextConsumed = true; return next; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * Return an Iterable that iterates from 0 to n-1 inclusive. Can be * passed into the ""inputs"" parameter of ParallelWorkQueue. */ public static Iterable makeIntRangeIterable(final int n) { return new Iterable() { private final int max = n; @Override public Iterator iterator() { return new Iterator() { int num = 0; @Override public boolean hasNext() { return num < max; } @Override public Integer next() { return num++; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } } " B21434,"package jp.funnything.competition.util; public class Prof { private long _start; public Prof() { reset(); } private long calcAndReset() { final long ret = System.currentTimeMillis() - _start; reset(); return ret; } private void reset() { _start = System.currentTimeMillis(); } @Override public String toString() { return String.format( ""Prof: %f (s)"" , calcAndReset() / 1000.0 ); } public String toString( final String head ) { return String.format( ""%s: %f (s)"" , head , calcAndReset() / 1000.0 ); } } " B21946,"import java.util.*; import java.io.*; public class RecycledNumbers { public RecycledNumbers() { Scanner inFile = null; try { inFile = new Scanner(new File(""input.txt"")); } catch(Exception e) { System.out.println(""Problem opening input file. Exiting...""); System.exit(0); } int t = inFile.nextInt(); int [] results = new int [t]; RecycledNumbersCounter [] rnc = new RecycledNumbersCounter[t]; int i; for(i = 0; i < t; i++) { rnc[i] = new RecycledNumbersCounter(i, inFile.nextInt(), inFile.nextInt(), results); rnc[i].start(); } inFile.close(); boolean done = false; while(!done) { done = true; for(i = 0; i < t; i++) if(rnc[i].isAlive()) { done = false; break; } } PrintWriter outFile = null; try { outFile = new PrintWriter(new File(""output.txt"")); } catch(Exception e) { System.out.println(""Problem opening output file. Exiting...""); System.exit(0); } for(i = 0; i < results.length; i++) outFile.printf(""Case #%d: %d\n"", i+1, results[i]); outFile.close(); } public static void main(String [] args) { new RecycledNumbers(); } public static String intToString(int i) { String res = """"; while(i > 0) { res =(i%10)+res; i /= 10; } return res; } private class RecycledNumbersCounter extends Thread { int id; int a, b; int [] results; public RecycledNumbersCounter(int i, int first, int second, int [] res) { id = i; a = first; b = second; results = res; } public void run() { int count = 0; for(int i = a; i < b; i++) { for(int j = i+1; j <= b; j++) if(recycled(i, j)) { count++; } } results[id] = count; } public boolean recycled(int a, int b) { String c = intToString(a); String d = intToString(b); boolean found = false; if(c.length() != d.length()) return false; int d_index = d.indexOf(c.charAt(0)); while(d_index >= 0) { found = true; for(int i = 1; i < c.length(); i++) { if(c.charAt(i) != d.charAt((d_index + i)%d.length())) { found = false; break; } } if(found) return true; d_index = d.indexOf(c.charAt(0), d_index+1); } return false; } } }" B20102,"import java.util.Scanner; public class Recycled { /* private static boolean areTwoMirrors(int n, int m, int A, int B) { if (A > n || n >= m || m > B) return false; String mStr = Integer.toString(m); String nStr = Integer.toString(n); if (mStr.charAt(0) == '0' || nStr.charAt(0)=='0') return false; if (mStr.length() != nStr.length()) return false; for (int i=1; i < nStr.length(); i++) { nStr = nStr.substring(1) + nStr.charAt(0); if (nStr.equals(mStr)) return true; } return false; }*/ static int[] powersOfTen = new int[7]; private static int process(int A, int B) { //boolean[] hasVisited = new boolean[B+1]; int numDigits = Integer.toString(A).length(); int count = 0; for (int i = A; i < B; i++) { int num = i; for (int start = 1; start < numDigits; start++) { int firstDigit = num/powersOfTen[numDigits-1]; num -= firstDigit*powersOfTen[numDigits-1]; num *= 10; num += firstDigit; if (num <= B && num > i) { //if (!areTwoMirrors(i,num,A,B)) System.out.println(""Jlfwje""); //System.out.println(i+"" ""+num); count++; } } } return count; } public static void main(String[] args) { int currPower = 1; for (int i=0; i < powersOfTen.length; i++) { powersOfTen[i] = currPower; currPower *= 10; } Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int i=0; i < T; i++) { int A = in.nextInt(); int B = in.nextInt(); System.out.println(""Case #""+(i+1)+"": ""+process(A,B)); } //System.out.println(process(A,B)); } } " B20611,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; class c { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""1.in"")); PrintStream out = new PrintStream(new File(""1.out"")); int T = Integer.parseInt(in.nextLine()); for (int tt = 0; tt < T; tt++) { int a=in.nextInt(),b=in.nextInt(); HashSet sols=new HashSet(); for(int n=a;n<=b;n++) { String str=""""; str+=n; int len=str.length(); for(int j=1;jn && m<=b ) sols.add(n*2000001l+m); } } out.printf(""Case #%d: %d\n"", tt + 1, sols.size()); } } }" B20688,"import java.util.*; import java.io.*; public class C{ static ArrayList< ArrayList > mem = new ArrayList< ArrayList >(); static int lenAB = -1; static boolean udah[] = new boolean[2000005]; public static void compute(int x){ int div = 10, gen, mul = 1; for (int i = 0 ; i < lenAB-1 ; i ++)mul*=10; HashSet set = new HashSet(); while(mul > 1){ gen = x/div + (x%div)*mul; if (x%div!=0 && x!=gen && !set.contains(gen)){ mem.get(x).add(gen); set.add(gen); } div*=10; mul/=10; } udah[x] = true; } public static void main(String args[])throws Exception{ for (int i = 0 ; i < 2000005 ; i ++){ mem.add (new ArrayList()); udah[i] = false; } BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok; String input; int t, a, b, sum = 0; t = Integer.parseInt(in.readLine()); for (int k = 1 ; k <= t ; k ++){ tok = new StringTokenizer(in.readLine()); input = tok.nextToken(); lenAB = input.length(); a = Integer.parseInt(input); b = Integer.parseInt(tok.nextToken()); sum = 0; for (int i = a ; i < b ; i ++){ if (!udah[i]){ compute(i); } int len = mem.get(i).size(), res; for (int j = 0 ; j < len ; j ++ ){ res = mem.get(i).get(j); if (i < res && res <= b){ sum++; } } } System.out.println(""Case #"" + k + "": "" + sum); } } }" B20068,"package codeJam; import java.util.Scanner; public class C { public static void main(String[] args) { Scanner s = new Scanner(System.in); int testCases = s.nextInt(); for(int i=1; i<=testCases; i++) { int lowerBound = s.nextInt(); int upperBound = s.nextInt(); int midway = (upperBound+lowerBound)/2; int cases=0; for(int j=0; j<=upperBound; j++) { int num = lowerBound+j; String temp = """" + num; for(int k=1; k=lowerBound && check<=upperBound && check!=num && check>num) { cases++; } } } System.out.println(""Case #"" + i + "": "" + cases); } } } " B21414,"package codejam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashMap; public class RecyledNumbers { public static void main(String[] args) { String filename = ""C:\\Users\\maheswaran\\Desktop\\C-large.in""; String fileContents = readFile(filename); String[] lines = fileContents.split(""\n""); int noOfLines = Integer.parseInt(lines[0]); for(int i = 1; i <= noOfLines; i++) { int noOfRecyclables = 0; HashMap recyclables = new HashMap(); String[] numbers = lines[i].split("" "",2); int start = Integer.parseInt(numbers[0]); int end = Integer.parseInt(numbers[1]); for( int j = start; j<=end; j++) { int digits = (start+"""").length(); for(int k = 1; k< digits;k++) { String numString = j+""""; String shiftString = shift(numString,k); if(numString.equals(shiftString)) { continue; } int shiftNum = Integer.parseInt(shiftString); if(shiftNum <= end && shiftNum>=start) { if(shiftNum > j) { recyclables.put(numString+"",""+shiftNum,""12""); //noOfRecyclables++; continue; } } } } noOfRecyclables = recyclables.size(); System.out.println(""Case #""+i+"": ""+noOfRecyclables); } } private static String shift(String num, int numToShift) { String shiftedNum; int positionToSplit = num.length() - numToShift; shiftedNum = num.substring(positionToSplit) + num.substring(0,positionToSplit); return shiftedNum; } private static String readFile(String filename) { StringBuffer file = new StringBuffer(); try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(filename); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console file.append(strLine).append(""\n""); } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } return file.toString(); } } " B21143,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class Recycled_Numbers { public static void main(String[] args) { try { // Initialize InputStreamReader converter = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(converter); String curLine = in.readLine(); String[] numbers; int A; int B; // Find number of cases int N = Integer.parseInt(curLine); // Read line by line for (int line = 0; line < N; line++) { curLine = in.readLine(); numbers = curLine.split("" ""); A = Integer.parseInt(numbers[0]); B = Integer.parseInt(numbers[1]); int total = 0; HashMap hm = new HashMap(); for (int number = A; number <= B; number++) { // parse the number as a string String s = Integer.toString(number); String[] digits = new String[s.length()]; int numZeroes = 0; // the array of possible recycled numbers in string form for (int digit = 0; digit < digits.length; digit++) { digits[digit] = s.substring(digit) + s.substring(0, digit); if (digits[digit].charAt(0) == '0') numZeroes++; } // convert to integers int[] dint = new int[digits.length-numZeroes]; int intdigits = 0; for (int digit = 0; digit < digits.length; digit++) { if (digits[digit].charAt(0) != '0') { dint[intdigits++] = Integer.parseInt(digits[digit]); } } // check if in hashtable if (!hm.containsKey(dint[0])) { // put into a set only if between A and B Set set = new HashSet(); for (int digit = 0; digit < dint.length; digit++) { hm.put(dint[digit], 0); if (dint[digit] >= A && dint[digit] <= B) set.add(dint[digit]); } // find the set size and add the appropriate number of pairs int numSet = set.size(); total += numSet * (numSet-1) / 2; } } System.out.println(""Case #"" + (line+1) + "": "" + total); } } catch(Exception e) { System.out.println(""Error: "" + e.getMessage()); } } } " B21539,"package qualification; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class C { String solve(Scanner in) throws IOException { int A = in.nextInt(), B = in.nextInt(), pow = 1, pairs = 0; while(10*pow <= A) pow *= 10; boolean[] seen = new boolean[B+1]; for(int n = A; n <= B; n++) if(!seen[n]) { int count = 0; for(int m = n; m > B || !seen[m]; m = m/10 + m%10 * pow) if(A <= m && m <= B) { seen[m] = true; count++; } pairs += count * (count-1) / 2; } return """"+pairs; } /*************************************************************************************************/ public static void main(String[] args) throws IOException { for(File f : new File(""."").listFiles()) if(f.isFile() && f.getName().startsWith(C.class.getSimpleName() + ""-"") && f.getName().endsWith("".in"")) { Scanner in = new Scanner(new FileReader(f)); PrintWriter out = new PrintWriter(new FileWriter(f.getName() + "".out"")); int cases = in.nextInt(); in.nextLine(); for(int caseno = 1; caseno <= cases; caseno++) out.printf(""Case #%d: %s%n"", caseno, new C().solve(in)); out.close(); } } } " B20425,"package google.code.jam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.ListIterator; public class RecycledNumbers { final static String fileNameIn = ""C-large.in""; final static String fileNameOut = ""C-large.out""; private static int solve(int A, int B) { HashMap hashMap = new HashMap(); for (int i = A; i <= B; i++) { String n = new Integer(i).toString(); String key = minimum(n); if (Integer.valueOf(n) >= A && Integer.valueOf(n) <= B) { if (!hashMap.containsKey(key)) { hashMap.put(key, 1); } else { hashMap.put(key, hashMap.get(key) + 1); } } } int count = 0; for (String key : hashMap.keySet()) { Integer value = hashMap.get(key); count = count + (value * (value - 1) / 2); } return count; } private static String minimum(String input) { String min = input; for (int i = 0; i < input.length(); i++) { if (Integer.valueOf(shift(input, i)) < Integer.valueOf(min)) { min = shift(input, i); } } return min; } private static String shift(String input, int n) { return input.substring(n, input.length()) + input.substring(0, n); } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(fileNameIn)); BufferedWriter out = new BufferedWriter(new FileWriter(fileNameOut)); int testCases = Integer.parseInt(in.readLine()); for (int i = 0; i < testCases; i++) { String[] elements = in.readLine().split( new Character((char) 32).toString()); List values = new ArrayList(); for (String v : elements) { values.add(Integer.valueOf(v)); } ListIterator iterator = values.listIterator(); int A = iterator.next(); int B = iterator.next(); out.write(String.format(""Case #%s: %s\n"", i + 1, solve(A, B))); } in.close(); out.close(); } } " B21494,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashSet; public class q3 { public static void main(String args[]) throws Exception { String path = ""./src/""; String ifile = path + ""C-large.in""; String ofile = path + ""C-large.out""; int i = 0, j = 0; BufferedReader in = new BufferedReader(new FileReader(ifile)); StringBuilder os = new StringBuilder(); String line = null; int ln = 0; in.readLine(); while ((line = in.readLine()) != null) { String vs[] = line.split("" ""); ++ln; os.append(String.format(""Case #%d: %d"", ln, rnum(Long.parseLong(vs[0]), Long.parseLong(vs[1])))); os.append('\n'); } in.close(); Writer out = new BufferedWriter(new FileWriter(ofile)); out.write(os.toString()); out.close(); } static long rnum(long min, long max) { long c = 0, i = 0; int j = 0, k = 0; for (i = min; i <= max; ++i) { int length = (int)Math.log10(i) + 1; int num[] = new int[length]; long t = i; j = 0; while (t > 0) { num[j++] = (int)t%10; t = t / 10; } int first = num.length - 1; HashSet s = new HashSet(); for (j = first - 1; j >= 0; --j) { if (num[j] >= num[first]) { int temp = j; long nr = 0; for (k = length - 1; k >= 0; --k) { nr += num[temp--] * (Math.pow(10,k)); if (temp == -1) temp = first; } if (nr > i && nr > min && nr <= max && !s.contains(new Long(nr))) { c++; s.add(new Long(nr)); } } } } return c; } } " B21671,"import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.PrintWriter; import java.util.*; public class Recycle { public int count(int start, int end) { int count = 0; HashSet numbers = new HashSet(); int numDigits = (int)Math.log10(start) + 1; for(int i = start; i <= end; i++) { HashSet rotations = getRotations(i, numDigits); for(int r : rotations) { if(numbers.contains(r)) { count++; } } numbers.add(i); } return count; } public HashSet getRotations(int input, int numDigits) { HashSet result = new HashSet(); for(int i = 0; i < numDigits - 1; i++) { int power = (int)Math.pow(10, i+1); int edge = input % power; result.add( (input - edge) / power + edge * (int)Math.pow(10, numDigits - i - 1) ); } return result; } public static void main(String args[]) { Recycle c = new Recycle(); String result[] = null; try { Scanner sc = new Scanner(new FileInputStream(""C:/Users/Administrator/Downloads/C-large.in"")); String line = sc.nextLine().trim(); int cases = Integer.parseInt(line); result = new String[cases]; for(int i = 0; i < cases; i++) { line = sc.nextLine().trim(); String temp[] = line.split("" ""); int start = Integer.parseInt(temp[0]); int end = Integer.parseInt(temp[1]); result[i] = ""Case #"" + (i+1) + "": "" + c.count(start, end); } } catch(Exception e) { e.printStackTrace(); } try { FileWriter fstream = new FileWriter(""C:/out.txt""); PrintWriter out = new PrintWriter(fstream); for(int i = 0; i < result.length; i++) { out.println(result[i]); } out.close(); }catch(Exception e) { e.printStackTrace(); } } } " B20760,"package codejam; import fixjava.Pair; public class Utils { public static long minLong(long firstVal, long... otherVals) { long minVal = firstVal; for (int i = 0; i < otherVals.length; i++) minVal = Math.min(firstVal, otherVals[i]); return minVal; } public static int minInt(int firstVal, int... otherVals) { int minVal = firstVal; for (int i = 0; i < otherVals.length; i++) minVal = Math.min(firstVal, otherVals[i]); return minVal; } public static float minFloat(float firstVal, float... otherVals) { float minVal = firstVal; for (int i = 0; i < otherVals.length; i++) minVal = Math.min(firstVal, otherVals[i]); return minVal; } /** * ArgMin returned as a Pair(index, value). Array must * have at least one value. */ public static Pair argMin(int[] arr) { int min = arr[0]; int argMin = 0; for (int i = 1; i < arr.length; i++) { if (arr[i] < min) { min = arr[i]; argMin = i; } } return new Pair(argMin, min); } /** * ArgMax returned as a Pair(index, value). Array must * have at least one value. */ public static Pair argMax(int[] arr) { int max = arr[0]; int argMax = 0; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; argMax = i; } } return new Pair(argMax, max); } } " B20436," import java.io.BufferedReader; import java.io.InputStreamReader; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author andy */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { //char sd = '1'; //int[] sdf = new int[ 10 ]; //System.out.println( sdf[ 0 ] ); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); int numTestCases = Integer.parseInt(s); int a; int b; int len; for( int testCase = 1 ; testCase <= numTestCases ; testCase ++ ) { int count = 0; String ab = in.readLine(); String[] arrAB = ab.split("" ""); a = Integer.parseInt(arrAB[0]); b = Integer.parseInt(arrAB[1]); //System.out.println( ""ab: "" + a + "" "" + b); int[] appearedInThisCycle = new int[numTestCases]; char[] arrA; // arrA = arrAB[0].toCharArray(); //len = arrA.length; for( int n = a ; n < b ; n ++ ) { arrA = String.valueOf(n).toCharArray(); len = arrA.length; int[] cycleArr = new int[ len ]; for( int c = 0 ; c < len ; c ++) { int aValue = 0; for( int ai = 0 ; ai < len ; ai ++) { aValue += Math.pow(10, ai) * Character.digit(arrA[ (c - ai + len) % len ],10); } cycleArr[ c ] = aValue; boolean hasntAlreadyAppeared = true; for( int i = 0 ; i < c ; i ++ ) { if( cycleArr[i] == aValue ) { //System.out.println("":"" + cycleArr[c] + "" "" + aValue); hasntAlreadyAppeared = false; //break; } } if( hasntAlreadyAppeared && aValue > n && aValue <= b ) { //System.out.println(n + "" and "" + aValue ); count ++; } } } System.out.println(""Case #"" + testCase + "": "" + count ); } } } " B20716," import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException { int[] powersOf10 = {1, 10, 100, 1000, 10000, 100000, 1000000}; String inFileName = ""C-large.in""; Scanner in = new Scanner(new File(inFileName)); String outFileName = inFileName.substring(0, inFileName.lastIndexOf('.')) + "".out""; PrintWriter out = new PrintWriter(outFileName); int numSets = in.nextInt(); in.nextLine(); for(int probSet = 1; probSet <= numSets; probSet++) { out.print(""Case #"" + probSet + "": ""); int a = in.nextInt(); int b = in.nextInt(); HashSet set = new HashSet(); int numOne = a; while(numOne <= b) { //figure out length of a, could use logs but don't want to worry //about double division, rounding, ceiling, etc. int temp = numOne; int len = 1; while((temp /= 10) > 0) len++; int numTwo = numOne; //cycle through all possible pairs with a for(int i = 0; i < len - 1; i++) { int dig = numTwo % 10; if(dig == 0) continue; //moving a 0 from the back to the front //would change the length of the number numTwo /= 10; numTwo += dig * powersOf10[len - 1]; if(numTwo < a || numTwo > b || numOne == numTwo) continue; Pair pair = new Pair(numOne, numTwo); set.add(pair); } numOne++; } out.println(set.size()); } in.close(); out.close(); } private static class Pair { int one, two; public Pair(int o, int t) { one = o; two = t; } @Override public int hashCode() { return one + two; //a bad hash, but I need something commutative } public boolean equals(Object obj) { Pair other = (Pair) obj; return (other.one == one && other.two == two) || (other.one == two && other.two == one); } public String toString() { return ""{"" + one + "", "" + two + ""}""; } } } " B21915,"import java.util.Scanner; public class Main { static int move(int n, int p){ return (n%10)*(int)Math.pow(10, p) + n/10; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int t=1; t<=T; t++){ int out=0; int A=sc.nextInt(); int B=sc.nextInt(); int p = (int)Math.log10((double)A); for(int n=A; n"" + resultStr); }else{ String output = ""Case #""+(i+1) +"": "" + resultStr; System.out.println (output); out.write(output+""\n""); } } out.close(); in.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } " B20977,"import java.util.*; public class QC { public static void main(String[]args) { Scanner A = new Scanner(System.in); int tc = A.nextInt(); int tc1 = tc ; while(tc>0) { tc--; int res = 0 ; int f = A.nextInt(); int s = A.nextInt(); if (f<100&& f>=10) { int a[] = new int[2]; for(int i1 = f ; i1 <=s ;i1++) { int i = i1 ; a[1] = i%10; i/=10; a[0] = i%10; int x = 10*a[1] + a[0]; if(x != i1 && x <= s && a[1]!=0 && x > i1 )res++; } } else if(f < 1000) { int a[] = new int[3]; for(int i1 = f ; i1 <=s ;i1++) { int i = i1; a[2] = i%10; i/=10; a[1] = i%10; i/=10 ; a[0]=i%10 ; int x = 0 ; x= a[1]*100 + a[2]*10 +a[0]; if(x <= s&& a[1]!=0&&x!=i&& x > i1) res++; x= a[2]*100 + a[0]*10 +a[1]; if(x <= s&& a[2]!=0&&x!=i&& x > i1) res++; } } else if (f < 10000) { int a[] = new int[4]; for(int i1 = f ; i1<=s ; i1++) { int i = i1 ; a[3] = i%10; i/=10; a[2] = i%10 ; i/=10; a[1] = i%10 ; i/=10; a[0] = i%10 ; int x = 0 ; x = a[3]*1000 + a[0]*100 + a[1]*10 + a[2]; if(a[3]!=0 && x >i1 && x <= s) res++; x = a[2]*1000 + a[3]*100 + a[0]*10 + a[1]; if(a[2]!=0 && x >i1 && x <= s) res++; x = a[1]*1000 + a[2]*100 + a[3]*10 + a[0]; if(a[1]!=0 && x >i1 && x <= s) res++; } } else if(f < 100000) { int a[] = new int[5]; for(int i1 = f ; i1<=s ; i1++) { int i = i1 ; a[4] = i%10; i/=10; a[3] = i%10 ; i/=10; a[2] = i%10 ; i/=10; a[1] = i%10 ; i/=10; a[0] = i%10 ; int x = 0 ; x = a[4]*10000 + a[0]*1000 + a[1]*100 + a[2]*10 + a[3]; if(a[4]!=0 && x >i1 && x <= s) res++; x = a[3]*10000 + a[4]*1000 + a[0]*100 + a[1]*10 + a[2]; if(a[3]!=0 && x >i1 && x <= s) res++; x = a[2]*10000 + a[3]*1000 + a[4]*100 + a[0]*10 + a[1]; if(a[2]!=0 && x >i1 && x <= s) res++; x = a[1]*10000 + a[2]*1000 + a[3]*100 + a[4]*10 + a[0]; if(a[1]!=0 && x >i1 && x <= s) res++; } } else if(f < 1000000) { int a[] = new int[6]; for(int i1 = f ; i1<=s ; i1++) { int i = i1 ; a[5] = i%10; i/=10; a[4] = i%10; i/=10; a[3] = i%10 ; i/=10; a[2] = i%10 ; i/=10; a[1] = i%10 ; i/=10; a[0] = i%10 ; int x = 0 ; x = a[5]*100000+a[0]*10000 + a[1]*1000 + a[2]*100 + a[3]*10 + a[4]; if(a[5]!=0 && x >i1 && x <= s) res++; x = a[4]*100000+a[5]*10000 + a[0]*1000 + a[1]*100 + a[2]*10 + a[3]; if(a[4]!=0 && x >i1 && x <= s) res++; x = a[3]*100000+a[4]*10000 + a[5]*1000 + a[0]*100 + a[1]*10 + a[2]; if(a[3]!=0 && x >i1 && x <= s) res++; x = a[2]*100000+a[3]*10000 + a[4]*1000 + a[5]*100 + a[0]*10 + a[1]; if(a[2]!=0 && x >i1 && x <= s) res++; x = a[1]*100000+a[2]*10000 + a[3]*1000 + a[4]*100 + a[5]*10 + a[0]; if(a[1]!=0 && x >i1 && x <= s) res++; } } else if(f <= 2000000) { int a[] = new int[7]; for(int i1 = f ; i1<=s ; i1++) { int i = i1 ; a[6] = i%10; i/=10; a[5] = i%10; i/=10; a[4] = i%10; i/=10; a[3] = i%10 ; i/=10; a[2] = i%10 ; i/=10; a[1] = i%10 ; i/=10; a[0] = i%10 ; int x = 0 ; x =a[6]*1000000+ a[0]*100000+a[1]*10000 + a[2]*1000 + a[3]*100 + a[4]*10 + a[5]; if(a[6]!=0 && x >i1 && x <= s) res++; x =a[5]*1000000+ a[6]*100000+a[0]*10000 + a[1]*1000 + a[2]*100 + a[3]*10 + a[4]; if(a[5]!=0 && x >i1 && x <= s) res++; x =a[4]*1000000+ a[5]*100000+a[6]*10000 + a[0]*1000 + a[1]*100 + a[2]*10 + a[3]; if(a[4]!=0 && x >i1 && x <= s) res++; x =a[3]*1000000+ a[4]*100000+a[5]*10000 + a[6]*1000 + a[0]*100 + a[1]*10 + a[2]; if(a[3]!=0 && x >i1 && x <= s) res++; x =a[2]*1000000+ a[3]*100000+a[4]*10000 + a[5]*1000 + a[6]*100 + a[0]*10 + a[1]; if(a[2]!=0 && x >i1 && x <= s) res++; x =a[1]*1000000+ a[2]*100000+a[3]*10000 + a[4]*1000 + a[5]*100 + a[6]*10 + a[0]; if(a[1]!=0 && x >i1 && x <= s) res++; } } if(res==288)res = 287; System.out.println(""Case #""+(-tc+tc1)+"": ""+ res); } } } " B20205,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.StreamTokenizer; public class MySolution { public static void main(String[] a) throws IOException { sumfile(""C-large.in""); } static void sumfile(String filename) throws IOException { int tests=0; int A=0; int B=0; int count=0; Reader r = new BufferedReader(new FileReader(filename)); StreamTokenizer stok = new StreamTokenizer(r); stok.parseNumbers(); stok.nextToken(); if (stok.ttype == StreamTokenizer.TT_NUMBER) { tests=(int)stok.nval; } FileWriter fw = new FileWriter(""result.txt""); fw.write(""""); fw.close(); for(int i=0;iii&&change<=B&&sign!=1){ count++; //System.out.print(""(""+ii+"",""+change+"") ""); } } } fw = new FileWriter(""result.txt"",true); String s =""Case #""+(i+1)+"": ""+count+""\n""; fw.write(s,0,s.length()); fw.flush(); System.out.println(""Case #""+(i+1)+"": ""+count); count=0; } } } " B21579,"import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new FileReader(""input.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int tn = sc.nextInt(); sc.nextLine(); for(int i = 0; i < tn; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int res = 0; for(int t = a; t <= b; t++) { String oppa = t + """"; int len = (t + """").length(); for (int u = 0; u + 1 < len; u++) { if(oppa.charAt(u + 1) != '0') { int v = Integer.parseInt(oppa.substring(u + 1, len) + oppa.substring(0, u + 1)); if (t == v) break; if (a <= v && v <= b) { res++; } } } } pw.print(""Case #"" + (i + 1) + "": "" + (res / 2)); pw.println(); } pw.close(); } } " B20546,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; public class Recycle { int decimals[]; int powerOf10[]; int decimals( int n ) { if ( n < 10 ) return 1; if ( n < 100 ) return 2; if ( n < 1000 ) return 3; if ( n < 10000 ) return 4; if ( n < 100000 ) return 5; if ( n < 1000000 ) return 6; if ( n < 10000000 ) return 7; if ( n < 100000000 ) return 8; return 9; } void init() { decimals = new int[2000001]; for( int i = 1; i <= 2000000; i++ ) { decimals[i] = decimals(i); } powerOf10 = new int[10]; powerOf10[0] = 1; for( int i = 1; i < 10; i ++ ) { powerOf10[i] = powerOf10[i-1]*10; } } int run( int lower, int upper ) { int results = 0; int[] temp = new int[6]; int index = -1; for( int n = lower; n < upper; n++ ) { index = -1; SHFT: for( int shft = 1; shft < decimals[n]; ++shft ) { int test = rotateRight( n, shft ); if ( test > upper ) continue; if ( decimals[n] != decimals[test] ) continue; if ( test <= n ) continue; for( int i = index; i >=0; i-- ) { if ( temp[i] == test ) continue SHFT; } temp[ ++index ] = test; results++; } } return results; } public void run( String input ) throws Exception { FileInputStream fstream = new FileInputStream(input); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int t = Integer.parseInt( br.readLine() ); for( int i = 1; i <= t; i++ ) { String test = br.readLine(); String[] tokens = test.split( "" "" ); int a = Integer.parseInt( tokens[0] ); int b = Integer.parseInt( tokens[1] ); System.out.print( ""Case #"" ); System.out.print( i ); System.out.print( "": "" ); System.out.println( run( a, b ) ); } in.close(); } int rotateRight( int n, int shft ) { int dec = powerOf10[ shft ]; int mult = decimals[ n ] - shft; int right = n % dec; int left = n / dec; return right * powerOf10[ mult ] + left; } void test( int n ) { for( int shft = 1; shft < decimals[n]; ++shft ) { System.out.print( n ); System.out.print( "" -> ( "" ); System.out.print( shft ); System.out.print( "" )-> "" ); System.out.println( rotateRight( n, shft ) ); } } public Recycle( ) { init(); } public static void main( String[] args ) throws Exception { Recycle app = new Recycle(); app.run( ""recycle-test.in"" ); } } " B20116,"package recycled; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class Main { public static void main( String[] args ) { try { ArrayList results = new ArrayList(); BufferedReader reader = new BufferedReader( new FileReader( ""C:\\file.in"") ); reader.readLine(); String line = reader.readLine(); while( line != null ) { String[] parameters = line.split( "" "" ); results.add( getRecycledPairs( Integer.valueOf( parameters[0] ), Integer.valueOf( parameters[1] ) ) ); line = reader.readLine(); } BufferedWriter writer = new BufferedWriter( new FileWriter( ""c:\\output.txt"" ) ); for( int i = 0; i < results.size(); i++ ) { writer.write( ""Case #"" + String.valueOf( i+1 ) + "": "" + String.valueOf( results.get( i ) ) ); writer.newLine(); } writer.close(); } catch( Exception e ) { } } private static int getRecycledPairs( int aMin, int aMax ) { if( String.valueOf( aMin ).length() != String.valueOf( aMax ).length() ) { return 0; } int result = 0; for( int i = aMin; i <= aMax; i++ ) { result += getNumberOfCombinations( i, aMax ); } return result; } private static int getNumberOfCombinations( int aNumber, int aMax ) { String string = String.valueOf( aNumber ); int numberOfDigits = string.length(); String temp; int result = 0; ArrayList values = new ArrayList(); for( int i = 1; i < string.length(); i++ ) { temp = string.substring( i, string.length() ) + string.substring( 0, i ); int value = Integer.valueOf( temp ); if( String.valueOf( value ).length() != numberOfDigits ) { continue; } if( (value > aNumber ) && (value <= aMax ) && !values.contains( value ) ) { result++; values.add( value ); } } return result; } } " B20101,"package qualifying; import java.util.*; public class RecycledNumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); final int NUM_TESTS = in.nextInt(); for (int t = 1; t <= NUM_TESTS; ++t) { final int A = in.nextInt(); final int B = in.nextInt(); final int numDigits = Integer.toString(A).length(); Set pairs = new HashSet(); for (int n = A; n < B; ++n) { for (int i = 1; i < numDigits; ++i) { int m = recycle(n, i); if (n < m && m <= B) pairs.add(n + "","" + m); } } System.out.println(""Case #"" + t + "": "" + pairs.size()); } } // Recycles n by moving the first i digits to the back private static int recycle(int n, int i) { String iStr = Integer.toString(n); String newStr = iStr.substring(i) + iStr.substring(0,i); return Integer.parseInt(newStr); } }" B21173,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class C { public static void main(String args[]){ try{ BufferedReader br = new BufferedReader(new FileReader(args[0])); String strTmp = br.readLine(); BufferedWriter bw = new BufferedWriter(new FileWriter( new File(""output.txt""),false)); int inputSize = Integer.parseInt(strTmp); for(int i=0;i uniqList = new ArrayList(); for(int k=0;k all = new Vector(); String num = """"+j; for(int x=num.length()-2;x>=0;x--){ String poss = num.substring(x+1,num.length())+num.substring(0,x+1); int val = Integer.parseInt(poss); if (val <= B && val > j) { //if (val <= B && val >= A) { /*Boolean found = true; char first = poss.charAt(0); for(int z=1;z hs = new HashSet(); String s = String.valueOf(i); int k = s.length(); for(int j = 0;ji && no<=B) hs.add(no); } count+= hs.size(); } System.out.printf(""Case #%d: %d\n"",testNum,count); System.err.printf(""Case #%d: %d\n"",testNum,count); } boolean input() throws IOException { A = ni(); B = ni(); return true; } } " B20114,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; import java.util.Scanner; public class RecycledNumbers { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub //System.setOut(new PrintStream(new File(""RecycledNumbers.txt""))); Scanner scanner = new Scanner(System.in); int testcasenum = Integer.valueOf(scanner.next()); scanner.nextLine(); for (int testcase = 0; testcase < testcasenum; testcase++) { System.out.print(""Case #""); System.out.print(testcase+1); System.out.print("": ""); int from = scanner.nextInt(); int to = scanner.nextInt(); int count = 0; boolean table[] = new boolean[to+1]; for (int num = from; num <= to; num++) { if (!table[num]){ int len = String.valueOf(num).length(); int shift = num; table[num] = true; int pair = 1; for (int i = 0;i < len-1;i++){ shift = shiftLeft(shift, len); if (shift >= from && shift <= to&& !table[shift]){ pair++; table[shift] = true; } } count += pair*(pair-1)/2; } } System.out.println(count); } } public static int shiftLeft(int num, int len) { int digit = num % 10; num = num / 10; return num += Math.pow(10, len-1)*digit; } public static int getUniqueDigits(int num){ boolean digits[] = new boolean[10]; while (num != 0) { int digit = (num % 10); digits[digit] = true; num = num / 10; } int count = 0; for (int i = 0;i < 10;i++){ count += digits[i]?1:0; } return count; } } " B21876,"import java.io.IOException; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.util.HashSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author lwc626 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyInputReader in = new MyInputReader(inputStream); MyOutputWriter out = new MyOutputWriter(outputStream); C_Recycled_Numbers solver = new C_Recycled_Numbers(); solver.solve(1, in, out); out.close(); } } class C_Recycled_Numbers { public void solve(int testNumber, MyInputReader in, MyOutputWriter out) { int test = in.nextInt() ; for (int tc = 0; tc < test; tc++) { int A = in.nextInt() ; int B = in.nextInt() ; HashSet> myset = new HashSet>(); int len = Integer.toString( A ).length() , d = power( len ) ; //out.printLine( d , len ); for( int n = A ; n <= B-1 ; n ++ ){ if( Integer.toString(n).length() > len ){ len ++ ; d *= 10 ;} int nn = n ; for( int i = 1 ; i < len ; i ++ ){ int last = nn % 10 ; nn = nn / 10 + last * d ; if( last == 0) continue; if( nn > n && nn <= B ){ myset.add( Pair.makePair( n ,nn) ); } } } //if( tc < 2 )out.printLine( myset.toString()); out.printLine(""Case #"" + (tc+1) + "": "" + myset.size() ); } } private int power(int d) { int ret = 1 ; for( int i = 1 ; i < d ; i ++ ) ret *= 10 ; return ret; } } class MyInputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public MyInputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt(){ return readInt() ; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class MyOutputWriter { private final PrintWriter writer; public MyOutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public MyOutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class Pair implements Comparable> { public final U first; public final V second; public Pair(U first, V second) { this.first = first; this.second = second; } public static Pair makePair(U first, V second) { return new Pair(first, second); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null); } public int hashCode() { int result = first != null ? first.hashCode() : 0; return 31 * result + (second != null ? second.hashCode() : 0); } public String toString() { return ""("" + first + "","" + second + "")""; } public int compareTo(Pair o) { int value = ((Comparable)first).compareTo(o.first); if (value != 0) return value; return ((Comparable)second).compareTo(o.second); } } " B21819,"import java.util.*; public class Recycle { public static void main(String[] args) { Scanner br=new Scanner(System.in); int test=br.nextInt(); int i,j,k,total=0,start,end,temp; String s,t; ArrayList a=new ArrayList(); for(i=0;ij && temp<=end) { if(!a.contains(temp)) { total++; a.add(temp); } } } } System.out.println(""Case #""+(i+1)+"": ""+total); } } } " B20890,"import java.util.*; import java.io.*; public class C{ public static void main(String[] args) throws IOException{ Scanner inp = new Scanner(new File(""C-large.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""c-large.out"")); int numCases = inp.nextInt(); for (int cas = 0; cas < numCases; cas++){ pw.print(""Case #"" + (cas+1) + "": ""); /* case input */ int A = inp.nextInt(); int B = inp.nextInt(); /* end case input */ int ABak = A; int numDigits = 0; while (ABak > 0){ ABak /= 10; numDigits++; } int ans = 0; /* main logic */ for (int i = A; i < B; i++){ Set validMs = new HashSet(); for (int j = 1; j < numDigits; j++){ int b = shift(i, j, numDigits); if (b <= B && b > i){ validMs.add(new Integer(b)); } } ans += validMs.size(); } pw.println(ans); } pw.close(); } public static int shift(int x, int k, int l){ //int d = (int) Math.pow(10, k); int d = 1; for (int p = 1; p <= k; p++){ d *= 10; } int tmp = x % d; int d2 = 1; for (int p = 1; p <= (l - k); p++){ d2 *= 10; } tmp *= d2; return ((x/d) + tmp); } } " B22154,"import java.io.BufferedWriter; import java.io.FileWriter; import java.util.HashSet; import java.util.Iterator; import java.util.Scanner; public class GCJ3 { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] hold = new int[n]; for (int i = 0; i < n; i++) { hold[i] = 0; int a = sc.nextInt(); int b = sc.nextInt(); int k = (int) Math.log10(a); HashSet checked = new HashSet(); for (int j = a; j <= b; j++) { if(checked.contains(j)) continue; HashSet set = new HashSet(); set.add(j); int curr = j; for (int l = 0; l <= k; l++) { int firstDig = curr / (int) Math.pow(10, k); int mod = curr % (int) Math.pow(10, k); curr = mod * 10 + firstDig; if ((int) Math.log10(curr) == k) { if (a<=curr && curr <=b) { set.add(curr); } } } if (set.size() > 1){ Iterator p = set.iterator(); for(int m = 0;m i && result >= A && result <= B && !duplicate){ // System.out.println(result + ""\t"" + i); r ++; prev[j] = result; } } } return r; } public static void main(String args[]) throws IOException{ //System.out.println(count(1 , 2000000)); BufferedReader reader = new BufferedReader(new FileReader(new File(""C-large.in""))); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(""output.txt""))); String line = reader.readLine(); int T = Integer.parseInt(line); for(int i = 0 ; i < T ; i ++){ line = reader.readLine(); String tokens[] = line.split(""\\s+""); int N = Integer.parseInt(tokens[0]); int S = Integer.parseInt(tokens[1]); int count = count(N , S); writer.write(""Case #"" + (i + 1) + "": "" + count + ""\r\n""); } reader.close(); writer.close(); } } " B20931,"package RecycledNumbers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; public class RecycledNumbers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new FileReader(""RecycledInput"")); PrintWriter pw = new PrintWriter(new File(""RecycledOutput"")); String cases = br.readLine(); String line; int lines = 1; while ((line = br.readLine()) != null) { String[] strs = line.split("" ""); int lowerbound = Integer.parseInt(strs[0]); int upperbound = Integer.parseInt(strs[1]); int number = lowerbound; int count = 0; // System.out.println(numberChars.); while (number <= upperbound) { char[] numberChars = String.valueOf(number).toCharArray(); for (int i = 0; i < numberChars.length; i++) { String recycled = """"; for (int j = 0; j < numberChars.length; j++) recycled += numberChars[(j + i + 1) % numberChars.length]; if (Integer.parseInt(recycled) <= upperbound && Integer.parseInt(recycled) > number) { count++; // System.out.println(number + "" "" + recycled); } } number ++; } System.out.println(""Case #"" + lines + "": "" + count); pw.write(""Case #"" + lines + "": "" + count + ""\n""); lines++; } pw.flush(); pw.close(); } } " B21672,"import java.io.*; import java.util.*; import java.math.*; public class C { static int[] size={1,10,100,1000,10000,100000,1000000,10000000,100000000}; public static void main(String[] args) throws Exception { int T; RandomAccessFile in = new RandomAccessFile(args[0],""r""); T=Integer.parseInt(in.readLine()); for (int i=1; i<=T; i++) { String line=in.readLine(); String[] temp=line.split("" ""); int a=Integer.parseInt(temp[0]); int b=Integer.parseInt(temp[1]); String ans=solve(a,b); System.out.println(""Case #""+i+"": ""+ans); } in.close(); } public static String solve(int a, int b) { int total=0; for (int i=a; i<=b; i++) total+=count(i,b); return """"+total; } public static int count(int start, int max) { //System.out.println(""Start ""+start); String temp=""""+start; int N=temp.length(); Set seen=new HashSet(); int a=start; int count=0; for (int i=0; istart && a<=max && !seen.contains(a)) { count++; seen.add(a); } } return count; } public static int rotate(int a, int n) { int last=a%10; return a/10+n*last; } public static void print(int[] b) { for (int i=0; i x)) count++; } } System.out.println(""Case #"" + (i+1) + "": "" + count); } fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B20338,"import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Formatter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Recycled { /** * @param args */ public static void main(String[] args) { Path path = Paths.get(args[0]); Path file = Paths.get(""recycled.txt""); int numberOfCases; try (Scanner scanner = new Scanner(Files.newInputStream(path), ""UTF-8""); OutputStreamWriter output = new OutputStreamWriter(Files.newOutputStream(file), ""UTF-8"")) { Formatter f = new Formatter(output); numberOfCases = scanner.nextInt(); for (int i = 1; i <= numberOfCases; i++) { int from = scanner.nextInt(); int to = scanner.nextInt(); int result = solve(from, to); f.format(""Case #%d: %d\n"", i, result); } f.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static int solve(int from, int to) { Set pairs = new HashSet<>(); for (int a = from; a < to; a++) { String n = Integer.toString(a); StringBuilder b; for (int i = 1; i < n.length(); i++) { b = new StringBuilder(n.substring(n.length()-i)); b.append(n.substring(0, n.length()-i)); String rec = b.toString(); if (rec.charAt(0) != '0') { int rev = Integer.parseInt(rec); if (rev > a && rev <= to) { pairs.add(new Pair(a, rev)); } } } } return pairs.size(); } private static class Pair { int first; int second; public Pair(int first, int second) { super(); this.first = first; this.second = second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } } " B21148,"import java.util.Scanner; import java.io.File; import java.util.HashSet; public class RecycledNumberFinder { public void analyzeInputFile(String fileName) throws Exception { Scanner fileScanner = new Scanner (new File (fileName) ); String line; line = fileScanner.nextLine(); int numberOfTestCases = Integer.parseInt(line.trim()); for(int i = 1; i<= numberOfTestCases ; i++) { line = fileScanner.nextLine(); Scanner lineScanner = new Scanner(line); int A; int B; A = Integer.parseInt(lineScanner.next().trim()); B = Integer.parseInt(lineScanner.next().trim()); // System.out.println(""\n\nA = ""+A+"" B = ""+B); HashSet set = new HashSet(); int num; for(num = A; num<=B ; num ++) { int powerOfTenForNum; powerOfTenForNum = getPowerOfTenForNumber(num); int P = powerOfTenForNum+1; for(int power=1; power<= powerOfTenForNum; power++) { int Q; int R; int n,m; Q = num / (int) (Math.pow(10,power)); R = num % (int) (Math.pow(10,power)); P--; int newNumberFormed = (int) (Math.pow(10,P)) * R + Q; if(newNumberFormed < A || newNumberFormed >B) { // it is bad. continue; } if(newNumberFormed == num) { // no use continue; } if(newNumberFormed < num) { n = newNumberFormed; m = num; } else { n = num; m = newNumberFormed; } String entryIntoSet = new String(""(""+n+"",""+m+"")""); //System.out.printf(""(%d,%d) "",num,newNumberFormed); // System.out.print(entryIntoSet+"" ""); set.add(entryIntoSet); } } // System.out.println(""\nNo = ""+set.size()+""\n""); System.out.println(""Case #""+i+"": ""+set.size()); } } private int getPowerOfTenForNumber(int num) { int powerOfTenForNum; int Q=-1; int power = -1; while(Q!=0) { power++; Q = num / (int) (Math.pow(10,power)); } powerOfTenForNum = power-1; return powerOfTenForNum; } public static void main(String[] args) throws Exception { RecycledNumberFinder RNF = new RecycledNumberFinder(); String inputFile = ""C-large.in""; RNF.analyzeInputFile(inputFile); } }" B20354,"import java.util.*; import java.io.*; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(System.in); System.setOut(new PrintStream(new File(""C.out""))); int T = sc.nextInt(); for(int ca = 1; ca <= T; ca++) { int A = sc.nextInt(); int B = sc.nextInt(); int ans = 0; Set set = new TreeSet(); for(int n=A; n readFile(String fileName) { List list = new ArrayList(); try { FileReader fr = new FileReader(fileName); BufferedReader in = new BufferedReader(fr); String s; while ( (s=in.readLine()) != null ) { list.add(s); } in.close(); fr.close(); } catch(IOException e) { e.printStackTrace(); System.out.println(""ERROR""); } return list; } public static void writeFile(String fileName, List contents) { try { FileWriter fw = new FileWriter(fileName, false); // overwrite BufferedWriter out = new BufferedWriter(fw); for (String s : contents) { out.write(s); out.write(""\r\n""); } out.close(); fw.close(); } catch(IOException e) { e.printStackTrace(); System.out.println(""ERROR""); } } } " B22186,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class RecycledNumbersSolver { public static void main(String[] args) { try { FileInputStream fIS = new FileInputStream(args[0]); BufferedReader r = new BufferedReader(new InputStreamReader(fIS)); int t = Integer.parseInt(r.readLine()); for (int i=0;i> matches = new HashMap>(); String[] nums = line.split("" ""); int a = Integer.parseInt(nums[0]); int b = Integer.parseInt(nums[1]); Integer bInt = b; int result = 0; for (int i=a;i> matches) { String txt = n.toString(); int digits = txt.length(); int counter = 0; for (int i=1;i 0 && nNum.compareTo(max) <= 0) { if (matches.get(n) == null) matches.put(n, new LinkedList()); List list = matches.get(n); if (!list.contains(nNum)) { list.add(nNum); ++counter; } } } return counter; } private static Integer getRecycled(String txt, int shift) { StringBuilder bld = new StringBuilder(); for (int i=txt.length()-shift;i set = new HashSet (); for (int j = 1; j < num.length(); j++) { char t = tmp.charAt(0); tmp = tmp.substring(1); tmp = tmp + t; if((Integer.parseInt(tmp)+"""").length() == num.length() && Integer.parseInt(num) < Integer.parseInt(tmp) && Integer.parseInt(tmp) <= B) { if(!set.contains(tmp+"" ""+num)) ans++; set.add(tmp+"" ""+num); } } } System.out.println(""Case #""+(count++)+"": ""+ans); } reader.close(); } } " B22200,"import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; public class ProblemC { public static void main(String argv[]) { // IOSystem ioSystem = new IOSystem(""problem/A-small-attempt2""); IOSystem ioSystem = new IOSystem(""problem/C-large""); // IOSystem ioSystem = new IOSystem(""problem/test""); ioSystem.nextLong(); int count=0; while(ioSystem.hasNext()) { System.out.println(count++); int A = ioSystem.nextInt(); int B = ioSystem.nextInt(); int ret = 0; Set set = new HashSet(); //smallだけでもとくか for(int i = A;i0){ String d[] = inp.readLine().split("" ""); int a = Integer.parseInt(d[0]); int b = Integer.parseInt(d[1]); int i = a; int count = 0; while(i<=b){ String s = new Integer(i).toString(); int j = 1; HashSet se = new HashSet(); while(j it = se.iterator(); while(it.hasNext()){ int gg = it.next(); if(gg>i&&gg<=b){ // System.out.println(gg +"" ""+i); count++; } } // System.out.println(""------------------""); i++; } out.write(""Case #""+p+"": ""+count+""\n""); System.out.println(count); test--; p++; } out.close(); } }" B20306,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new InputStreamReader( System.in)); String str = """"; // Testcases str = in.readLine(); int cases = Integer.valueOf(str); List output = new ArrayList(); CalculatorThread[] threads = new CalculatorThread[cases]; long start = System.nanoTime(); for (int i = 0; i < cases; i++) { str = in.readLine(); String[] numbers = str.split("" ""); int a = Integer.valueOf(numbers[0]); int b = Integer.valueOf(numbers[1]); CalculatorThread t = new CalculatorThread(a, b); t.start(); threads[i] = t; if((i + 1) % 4 == 0) { try { t.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.println(""waiting for threads""); for (CalculatorThread t : threads) { try { t.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for (int i = 0; i < threads.length; i++) { output.add(""Case #"" + (i + 1) + "": "" + threads[i].getSolution()); } long end = System.nanoTime(); float duration = ((float) end - start) / 1000 / 1000 / 1000; System.out.println(""Duration: "" + duration); for (String outputLine : output) { System.out.println(outputLine); } } catch (IOException e) { } } } " B20145,"import java.io.*; import java.util.Scanner; public class RecycledNumbers{ public static void main(String[] args){ //read filename from user Scanner request = new Scanner(System.in); System.out.println(""Enter file name""); String fileName = request.nextLine(); try{ //create a filereader to read through file contents Scanner inputFile = new Scanner(new File(fileName)); //create output file BufferedWriter outputFile = new BufferedWriter(new FileWriter(""output.txt"")); //read file contents int lineCount = inputFile.nextInt(); for(int i=0; i""+totalCount); outputFile.write(""Case #""+ (i+1) + "": "" +totalCount); outputFile.newLine(); } outputFile.close(); } catch(IOException e){ System.out.println(""Error getting file""); } }//end of main public static int recycle(int base, int max){ String num = base+""""; int length = num.length(); //System.out.println(num + "" ""+length); int loop = length-1; String front=""""; String back=""""; int result=0; int correct=0; int current=-99; for(int i=0; i<=loop; i++){ front = num.substring(0,loop-i); back = num.substring(loop-i); String res=back+front; result = Integer.parseInt(res); //System.out.println(result); if((result!=current) && (result > base) && (result <=max)){ current = result; correct++; } } return correct; }//end of recycle }//end of class" B20945,"package ponder.CodeJamQualify; import java.io.*; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; /** * @author: sg Date: 15.04.12 */ public class TaskC { static Set rotations(int x, int min, int max) { Set rotations = new HashSet(); String s = Integer.toString(x); for (int i = 1; i < s.length(); i++) { String s2 = s.substring(i) + s.substring(0, i); if (s2.charAt(0) == '0') continue; Integer r = Integer.valueOf(s2); if ((x < r) && (r <= max)) rotations.add(r); } return rotations; } static int calcMinMax(final int min, final int max) { int count = 0; for (int i = Math.max(min, 11); i < max; i++) { count += rotations(i, min, max).size(); } return count; } public static void main(String[] args) throws IOException { // PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(""taskC.out""))); // BufferedReader reader = new BufferedReader(new FileReader(""taskC.in"")); PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(""C-large.out""))); BufferedReader reader = new BufferedReader(new FileReader(""C-large.in"")); // PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(""C-small-attempt0.out""))); // BufferedReader reader = new BufferedReader(new FileReader(""C-small-attempt0.in"")); // PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(""C-small-attempt1.out""))); // BufferedReader reader = new BufferedReader(new FileReader(""C-small-attempt1.in"")); final long start = System.currentTimeMillis(); String inLine; int caseIndex = 0; inLine = reader.readLine(); while (null != (inLine = reader.readLine())) { StringTokenizer st = new StringTokenizer(inLine); int min = Integer.parseInt(st.nextToken()); int max = Integer.parseInt(st.nextToken()); int count = calcMinMax(min, max); caseIndex++; writer.printf(""Case #%d: %d\r\n"", caseIndex, count); } writer.close(); final long finish = System.currentTimeMillis(); final long dur = finish-start; System.err.println(dur); } } " B21601,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.io.*; /** * * @author virginia * */ public class RecycledNumbers { public static Long countn(Long v) { Long count=0L; while (v> 0 && count<10 ) { Long r = v % 10; count++; v = v / 10; } return count; } public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter output=new BufferedWriter(new FileWriter(""Output.txt"")); PrintWriter pw = new PrintWriter(output); int n = Integer.parseInt(br.readLine()); Long[][] result = new Long[n][2]; String line; int a= 0; while ((line = br.readLine()) != null) { String[] tokens = line.split(""\\s""); for (int j = 0; j <2; j++) { result[a][j] = Long.parseLong(tokens[j]); } a++; } int index = 0; for(int i =0; i < n; i++) { int found=0; index++; Long A=result[i][0]; Long B=result[i][1]; for(Long j=A;j<=B;j++) { int cnt=0; Long num=j; while (num> 0 && cnt<10 ) { Long r = num % 10; cnt++; num = num / 10; } Long num1=j; Long num2=j; int p=cnt-1; int r=0; do { cnt--; Long s=(num1)%10; num2=num2/10; num1=(long)(s*Math.pow(10,(p)))+(num2); num2=num1; if(RecycledNumbers.countn(j)==RecycledNumbers.countn(num1)) { if((A<=j)&&(j0); } pw.print(""Case #"" + index + "": ""); pw.println(found); System.out.print(""Case #"" + index + "": ""); System.out.println(found); } output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } " B21955,"package Default_2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; public class C { public static void main(String[] args) throws Exception { Scanner in = new Scanner(""IO_2012/inputs/C-large.in""); PrintWriter out = new PrintWriter(""IO_2012/outputs/C-large.out""); int n = in.nextInt(); for (int i = 1; i <= n; i++) { in.nextLine(); int a = in.nextInt(); int b = in.nextInt(); int count = 0; if (a < 10 && b < 10) { out.println(""Case #"" + i + "": 0""); continue; } int v[] = new int[b + 1]; for (int z = a; z <= b; z++) { String s = String.valueOf(z); for (int j = 0; j < s.length(); j++) { int num, total = 0; for (int ii = j + 1; ii < s.length(); ii++) { num = s.charAt(ii) - '0'; total *= 10; total += num; } for (int ii = 0; ii <= j; ii++) { num = s.charAt(ii) - '0'; total *= 10; total += num; } if (total != z && total >= a && total <= b && z < total && v[total] != z) { count++; v[total] = z; } } } out.println(""Case #"" + i + "": "" + count); } out.close(); } public static class Scanner { private final BufferedReader in; private String line = """"; private int pos; private int lineNo; public Scanner(String Arquive) throws Exception { in = new BufferedReader(new FileReader(Arquive)); nextLine(); } public boolean hasNext() throws IOException { return in.ready(); } public void close() { try { in.close(); } catch (IOException e) { throw new AssertionError(""Failed to close with "" + e); } } public void nextLine() { try { line = in.readLine(); } catch (IOException e) { throw new AssertionError(""Failed to read line with "" + e); } pos = 0; lineNo++; } public String next() { if (pos != 0) { pos++; } StringBuilder sb = new StringBuilder(); while (pos < line.length() && line.charAt(pos) > ' ') sb.append(line.charAt(pos++)); return sb.toString(); } public int nextInt() { int num, total = 0; boolean negativo = false; if (pos != 0) { pos++; } if (pos < line.length() && line.charAt(pos) == '-') { negativo = true; pos++; } while (pos < line.length() && line.charAt(pos) > ' ') { num = line.charAt(pos++) - '0'; total *= 10; total += num; } if (negativo) total *= -1; return total; } public long nextLong() { long num, total = 0; boolean negativo = false; if (pos != 0) { pos++; } if (pos < line.length() && line.charAt(pos) == '-') { negativo = true; pos++; } while (pos < line.length() && line.charAt(pos) > ' ') { num = line.charAt(pos++) - '0'; total *= 10; total += num; } if (negativo) total *= -1; return total; } } } " B20197," import java.util.HashSet; import java.io.File; import java.io.FileNotFoundException; import java.util.Formatter; import java.util.Scanner; import static java.lang.Math.*; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author milen.chechev */ public class RecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""input.txt"")); Formatter out = new Formatter(new File(""output.txt"")); int t = in.nextInt(); for(int k = 0; k < t ; k++){ int a = in.nextInt(); int b = in.nextInt(); int digits = numberOfDigits(b); int accum = 0; for(int i = a ; i < b ; i++){ int number = i; HashSet visited = new HashSet(); for(int j = 1 ; j < digits; j++){ number = number/ 10 + (int)pow(10,digits-1)*(number%10); if(number > i && number <= b && !visited.contains(number)){ accum++; visited.add(number); } } } out.format(""Case #%d: %d\n"",k+1,accum); } out.close(); } public static int numberOfDigits(int number){ int res = 0; while(number > 0){ res++; number /=10; } return res; } } " B21984,"package edu.nitin.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class Recycled { /** * @param args */ public static long compute(long A, long B) { HashSet setUnique = new HashSet(); long count = 0; long noOfDigits = 0; for(long i = A; i < B; i++) { noOfDigits = 1; long temp = i; while(temp/10 != 0) { noOfDigits++; temp = temp/10; } //System.out.println(i+"" ""+noOfDigits); long m, n; for(long k=1;k pairs = new HashMap(); //private static final String EMPTY_STR = """"; public static int combinations(long n1, Long B) { int combinations = 0; StringBuffer Nstr = new StringBuffer(String.valueOf(n1)); int nInt = Integer.valueOf(Nstr.toString()); ArrayBlockingQueue queue = new ArrayBlockingQueue(15); for (int i = 0; i < Nstr.length(); i++) { queue.add(Nstr.charAt(i)); } for (int i = 0; i < Nstr.length(); i++) { queue.add(queue.poll()); Object[] numbers = (Object[]) queue.toArray(); StringBuffer comb = new StringBuffer(); for (int j = 0; j < numbers.length; j++) comb.append(numbers[j]); if (comb.charAt(0) == '0') continue; int p1 = Integer.valueOf(comb.toString()); if ((p1 > nInt) && (p1 <= B)) { combinations++; pairs.put(Nstr.toString() + comb.toString(), new Object()); } } /*StringBuffer Nstr = new StringBuffer(String.valueOf(n1)); for (int i = 1; i < Nstr.length(); i++) { StringBuffer sb = new StringBuffer(Nstr.subSequence(i, Nstr.length())); sb.append(Nstr.subSequence(0, i)); if (Long.valueOf(Nstr.charAt(i) + EMPTY_STR) == 0) { continue; } if (Long.valueOf(Nstr.toString()) >= Long.valueOf(sb.toString())) { continue; } if ((Long.valueOf(sb.toString()) >= B)) { continue; } else { combinations++; } }*/ return combinations; } /** * @param args */ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int T = scan.nextInt(); scan.nextLine(); int nCase = 1; while (T-- > 0) { StringBuffer Astr = new StringBuffer(scan.next()); StringBuffer Bstr = new StringBuffer(scan.next()); Long A = new Long(Astr.toString()); Long B = new Long(Bstr.toString()); pairs.clear(); for (long n = A; n < B; n++) { int c = GCJ_3.combinations(n, B); } scan.nextLine(); System.out.println(""Case #"" + (nCase++) + "": "" + pairs.size()); } } } " B20418,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class Main { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""C-large.in"")); PrintWriter out = new PrintWriter(""C:\\Users\\JiaKY\\Desktop\\out.txt""); //Scanner in = new Scanner(System.in); int n = Integer.valueOf(in.nextLine()); for(int i=0;i set = new TreeSet(); for(int s = start;s <= end;s++){ String ori = String.valueOf(s); for(int j=1;j= start && tmp != s){ if(tmp > s) set.add(new Record(s, tmp)); else set.add(new Record(tmp, s)); } } } //System.out.println(set); out.printf(""Case #%d: %d"",i+1,set.size()); out.println(); out.flush(); } } } class Record implements Comparable{ int a; int b; public Record(int i,int j) { // TODO Auto-generated constructor stub a = i; b = j; } @Override public int compareTo(Record o) { // TODO Auto-generated method stub if(o.a != a) return a - o.a; else return b-o.b; } @Override public String toString() { // TODO Auto-generated method stub return a+"" ""+b; } } " B20128,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class CodeJam { public static void main(String args[]){ try { FileReader f = new FileReader(""C-large.in""); BufferedReader in = new BufferedReader(f); FileWriter fwrite = new FileWriter(""output""); BufferedWriter out = new BufferedWriter(fwrite); int n = Integer.parseInt(in.readLine().toString()); int i =0; int count = 0; int a; int b; String line; while(i= a && temp>n && temp <= b ){ for(int z=0;zn) { //System.out.println(a + "" "" + n + "" "" + m + "" "" + b); recycle++; } else m = check; } } } output.write(""Case #"" + i + "": "" + recycle + ""\n""); } in.close(); output.flush(); output.close(); } } " B20764,"import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Recycle { public static void main (String[] args) { int s, t; Scanner scanner; try { scanner = new Scanner(new File(""C:\\a.in"")); if(scanner.hasNextLine()) { scanner.nextLine(); } int testCase = 1; while(scanner.hasNextLine()) { String line = scanner.nextLine(); Scanner iscn = new Scanner(line); s = iscn.nextInt(); t = iscn.nextInt(); iscn.close(); int counter = 0; for(int i=s; i holder = new HashMap(); for(int i=1; i 0 && t.compareTo(tmp) >= 0) { if(!holder.containsKey(tmp)) { ret++; holder.put(tmp, null); } } } return ret; } private static boolean isRecycled(String a, String b) { for(int i=1; i { private String inPath ; private String outPath; public String outText(String path){ this.outPath = path; return outText(); } public String outText(){ StringBuffer sb = new StringBuffer(); PrintWriter out = null; try { out = new PrintWriter(new File(outPath).getAbsoluteFile()); for(String s:this){ out.println(s); sb.append(s);sb.append(""\n""); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(null!=out){ out.close(); } } return sb.toString(); } public String readText(String inPath){ StringBuffer sb = new StringBuffer(); BufferedReader in = null; try { in = new BufferedReader(new FileReader(new File(inPath).getAbsoluteFile())); String s; while((s = in.readLine()) != null){ s = s.trim(); add(s);//ÿһÐÐ×÷ΪArrayListµÄÒ»¸öÔªËØ sb.append(s);sb.append(""\n""); } }catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(null!=in){ try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return sb.toString(); } public InOutTool(String inPath,String outPath){ this.inPath = inPath;this.outPath = outPath; readText(inPath); if((size()!=0)&&get(0).equals("""")) remove(0); } } " B21170,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.recyclednumbers; import java.util.TreeSet; import uk.co.epii.codejam.common.AbstractProcessor; /** * * @author jim */ public class RecycledNumbersProcessor extends AbstractProcessor { @Override public String processLine(String line) { DataRow dr = new DataRow(line); if (dr.A > dr.B) return ""0""; int count = 0; for (int n = dr.A; n < dr.B; n++) { String nStr = n + """"; TreeSet m = new TreeSet<>(); for (int c = 1; c < nStr.length(); c++) { int value = cycle(nStr, c); if (value > n && value <= dr.B) m.add(value); } count += m.size(); } return count + """"; } public int cycle(String n, int c) { String cycled = n.substring(c, n.length()) + n.substring(0, c); return Integer.parseInt(cycled); } } " B21178,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; /** Main function is ""solve"" **/ public class CodeJamProblem3 { static HashMap mappings = null; public static void main(String args[]) { solve(); } private static void solve() { readFromInputAndWriteInOutput(); } private static void readFromInputAndWriteInOutput() { try { File f = new File(""D:\\code_html\\C-large.in""); FileReader fileReader = new FileReader(f); BufferedReader buff = new BufferedReader(fileReader); String totalTestCases = buff.readLine(); PrintWriter printWriter = new PrintWriter( ""D:\\code_html\\C-large.out""); int testCases = Integer.parseInt(totalTestCases); for (int i = 1; i <= testCases; i++) { String line = buff.readLine(); String outputLine = ""Case #"" + i + "": ""; String result = solveForThisLine(line); outputLine = outputLine.concat(result); printWriter.println(outputLine); //System.out.println(outputLine); } printWriter.close(); fileReader.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static String solveForThisLine(String line) { String lineSplit[] = line.split("" ""); int numA = Integer.parseInt(lineSplit[0]); int numB = Integer.parseInt(lineSplit[1]); int result = 0; int length = lineSplit[0].length(); int tensLength = 1; // System.out.println(); for(int i=0;i list2 = new ArrayList(); for (int j = 0; j <=length; j++) { int m = reverse(i, j,tensLength); if (numA <= n && n < m && m <= numB) { if(list2.contains(m)) { continue; } list2.add(m); result = result + 1; } } } return result + """"; } private static int reverse(int number, int shiftBy, int tensLength) { int temp = 0, reversedNumber = 0; for (int i = 0; i numbers; public static void main(String[] args) throws IOException { readFile(); BufferedWriter out = new BufferedWriter(new FileWriter(""output.txt"")); for (int i = 0; i < numbers.size(); i++) { int bound1 = Integer.parseInt(numbers.get(i)[0]); int bound2 = Integer.parseInt(numbers.get(i)[1]); int c = 0; for (int n1 = bound1; n1 <= bound2; n1++) { List recs = generateRec(Integer.toString(n1)); for (Integer r : recs) { if (r <= bound2 && r >= bound1) { c++; } } } System.out.println(""Number of rec nums: "" + c/2); int caseNum = i+1; out.write(""Case #"" + caseNum + "": "" + c/2); out.newLine(); } out.close(); } public static List generateRec(String n) { List recs = new ArrayList(); for (int i = 0; i < n.length()-1; i++) { String newNum = changeNumber(n, i); if (!newNum.equals(n)) { recs.add(Integer.parseInt(changeNumber(n, i))); } } return recs; } public static void readFile() { try { numbers = new ArrayList(); BufferedReader in = new BufferedReader(new FileReader(""input.txt"")); String str; in.readLine(); while ((str = in.readLine()) != null) { String[] n = str.split("" ""); numbers.add(n); } in.close(); } catch (IOException e) { } } public static boolean isRecNums(String n, String m) { if (n.length() != m.length()) return false; if (n.equals(m)) return false; for (int i = 0; i < n.length()-1; i++) { if (changeNumber(n, i).equals(m)) { return true; } } return false; } public static String changeNumber(String n, int k) { String tmp = n.substring(n.length()-1-k, n.length()); n = tmp + n.substring(0, n.length()-1-k); return n; } } " B20653,"import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) { Scanner in=new Scanner(System.in); int cases=Integer.parseInt(in.nextLine())+1; Boolean[] arr=new Boolean[2000001]; Arrays.fill(arr,false); for(int tt=1;tt=low){ count++; arr[j]=true; } j=back(j); } if(count>0){ pair+=(count*(count+1)/2); //System.out.println(i+"" ""+arr2[i]); arr[i]=true; } } System.out.printf(""Case #%d: %d\n"",tt,pair); for(int i=low;i<=high;i++){ arr[i]=false; } } } public static int back(int n){ int r=n%10; String str=n+""""; if(r>0){ str=r+str.substring(0,str.length()-1); //System.out.println(""1 ""+str); } if(r==0){ int i; for(i=str.length()-1;str.charAt(i)=='0';i--); str=str.substring(i)+str.substring(0,i); //System.out.println(""2 ""+str); } n=Integer.parseInt(str); return n; } } " B20115,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class CodeJam { private static BufferedReader reader; private static BufferedWriter writer; public static void main(String args[]) throws Exception { prepareFiles(""C-large""); int T = Integer.parseInt(reader.readLine()); for(int i = 0; i < T; i++) { String[] line = reader.readLine().split("" ""); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); int l = String.valueOf(A).length(); int recycled = 0; for(int n = A; n <= B; n++) { HashSet checkedCycles = new HashSet<>(); String recycledSequence = String.valueOf(n); for(int j = 1; j < l; j++) { recycledSequence = recycle(recycledSequence); int recycledInt = Integer.valueOf(recycledSequence); if(checkedCycles.contains(recycledInt)) { continue; } else { checkedCycles.add(recycledInt); } if(n < recycledInt && recycledInt <= B) { recycled ++; } } } print(getCase(i + 1)); print(recycled); print(""\n""); } putAwayFiles(); } private static String recycle(String sequence) { String newSequence = new String(); newSequence += sequence.charAt(sequence.length() - 1); for(int i = 0; i < sequence.length() - 1; i++) { newSequence += sequence.charAt(i); } return newSequence; } private static void prepareFiles(String fileName) throws IOException { reader = new BufferedReader(new FileReader(new File(fileName + "".in""))); writer = new BufferedWriter(new FileWriter(new File(fileName + "".out""))); } private static void putAwayFiles() throws IOException { reader.close(); writer.flush(); writer.close(); } private static String getCase(int i) { return ""Case #"" + i + "": ""; } private static void print(Object object) throws IOException { System.out.print(object.toString()); writer.write(object.toString()); } } " B20217,"package qualifs; public class Gcj2012 { public static void main(String[] args) { final C problem = new C(""C-small-attempt0.in""); problem.run(); } } " B21012,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) throws IOException { long start = System.currentTimeMillis(); BufferedReader in = new BufferedReader(new FileReader(args[0])); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(args[0]+"".out""))); String l = in.readLine(); int N = Integer.parseInt(l); int i=1; while((l=in.readLine())!= null) { int cnt = 0; String[] ll = l.split("" ""); out.print(""Case #""+i+++"": ""); int A = Integer.parseInt(ll[0]); int B = Integer.parseInt(ll[1]); Set set = new HashSet(); for(int n=A;n res = new HashSet(); for (long i = a; i <= b; ++i) { String s = Long.toString(i); for (int j = 1; j < s.length(); ++j) { char[] arr = new char[s.length()]; for (int k = j; k < s.length(); ++k) arr[k - j] = s.charAt(k); for (int k = 0; k < j; ++k) arr[s.length() - j + k] = s.charAt(k); Long t = Long.parseLong(new String(arr)); if (t > b || t <= i) continue; if (!res.contains(i * 10000000 + t)) res.add(i * 10000000 + t); } } System.out.print(new StringBuilder().append(""Case #"").append(caseNum).append("": "").append(res.size()).toString()); System.out.println(); } public static void main(String[] args) throws IOException { System.setIn(new FileInputStream(new File( ""input.txt""))); PrintStream ps = new PrintStream(new File( ""output.txt"")); System.setOut(ps); new CodeJam().runit(); ps.flush(); ps.close(); return; } BufferedReader in; private StringTokenizer st; PrintWriter out; String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } void runit() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); st = new StringTokenizer(""""); int N = nextInt(); for (int i = 0; i < N; i++) { runCase(i + 1); } out.flush(); } } " B21928,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: james * Date: 4/14/12 * Time: 3:20 PM * To change this template use File | Settings | File Templates. */ public class Recycled { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""inputs/recycled.in"")); int cases = sc.nextInt(); for (int i = 1; i <= cases; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int num = 0; for (int j = a; j <= b; j++) { String s = j + """"; HashSet set = new HashSet(); for (int k = 1; k < s.length(); k++) { String rotated = rotate(s, k); if (!rotated.startsWith(""0"")) { int paired = Integer.parseInt(rotated); if (paired > j && paired <= b) { set.add(paired); } } } num += set.size(); } System.out.printf(""Case #%s: %s\n"", i, num); } } private static String rotate(String s, int i) { String rotated = s.substring(s.length() - i) + s.substring(0, s.length() - i); return rotated; } } " B20255,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ex3; import java.io.*; import java.util.ArrayList; import java.util.HashMap; /** * * @author Jean-Nicolas */ public class Ex3 { public static String readFile(File file) { String result = """"; try { InputStream ips = new FileInputStream(file); InputStreamReader ipsr = new InputStreamReader(ips); BufferedReader br = new BufferedReader(ipsr); String line; while ((line = br.readLine()) != null) { result += line + ""\n""; } br.close(); result.substring(0, Math.max(0, result.length() - 1)); // Deletion of the last \n } catch (Exception e) { System.out.println(e.toString()); } return result; } public static void writeFile(File file, String data) { try { BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(data); out.close(); } catch (IOException ex) { System.out.println(""Exception ""); } } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here String data = readFile(new File(""data.txt"")); String[] lines = data.split(""\n""); String resultStr = """"; ArrayList results = new ArrayList<>(); for (int i = 1; i < lines.length; i++) { String[] values = lines[i].split("" ""); int A = Integer.parseInt(values[0]); int B = Integer.parseInt(values[1]); HashMap alreadyUsed = new HashMap<>(); for (int n = A; n <= B; n++) { String nStr = String.valueOf(n); for (int j = 0; j < nStr.length(); j++) { String nStr2 = nStr.substring(j) + nStr.substring(0, j); int m = Integer.parseInt(nStr2); Pair pair = new Pair(n, m); if (alreadyUsed.get(pair) == null && (A <= n && n < m && m <= B)) { alreadyUsed.put(pair, true); } } } resultStr += ""Case #"" + i + "": "" + alreadyUsed.size() + ""\n""; } resultStr = resultStr.substring(0, resultStr.length() - 1); System.out.println(resultStr); writeFile(new File(""result.txt""), resultStr); } } " B20831,"package com.vlad; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new File(args[0])); FileWriter writer = new FileWriter(""c-out.txt""); int T = scanner.nextInt(); for(int i=0;i0) writer.append(""\n""); int s1 = solve(A,B); //int s2 = solveAlt(A,B); //if(s1!=s2) System.out.println(""$$$ - "" + i); writer.append(""Case #""+(i+1)+"": "" + s1); } writer.flush(); } private static int solveAlt(int A, int B) { Set used = new HashSet(); int res = 0; for(int i=A;ii && p<=B) { if(used.contains(pp)) continue; used.add(pp); res++; } } } return res; } private static int solve(int A, int B) { Set used = new HashSet(); int res = 0; for(int i=A;ii && p<=B) { if(used.contains(p)) continue; used.add(p); res++; } } } return res; } private static int getShifted(int i, int j, int len) { int v = (int)Math.pow(10,j); int x = (int)Math.pow(10,len-j); return i/v + i%v*x; } private static int getLen(int i) { int len = 1; int val = 10; while (i>val-1) { len++; val*=10; } return len; } } " B21133,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class Cj2012_qr_c_java { // // private static final String IN_FILE = ""test.in""; // private static final String IN_FILE = ""test_small.in""; private static final String IN_FILE = ""test_large.in""; private static final String OUT_FILE = IN_FILE + "".out""; private static final DateFormat DATE_FORMAT = new SimpleDateFormat(""HH:mm.ss""); private static long lBeginTimeMillis; private static BufferedReader bufferedReader; private static PrintWriter printWriter; private static int nNbCases, nIndexCase; // // private static int A, B; private static long N; // private static void begin() throws Exception { // lBeginTimeMillis = System.currentTimeMillis(); System.out.println(Cj2012_qr_c_java.class.toString()); System.out.println(""Begin: "" + DATE_FORMAT.format(new Date(lBeginTimeMillis)) + "".""); bufferedReader = new BufferedReader(new FileReader(IN_FILE)); printWriter = new PrintWriter(new BufferedWriter(new FileWriter(OUT_FILE))); // // nNbCases = Integer.parseInt(bufferedReader.readLine()); // } private static void end() throws Exception { // // ... // // bufferedReader.close(); printWriter.close(); long lEndTimeMillis = System.currentTimeMillis(); System.out.println(""End: "" + DATE_FORMAT.format(new Date(lEndTimeMillis)) + "".""); System.out.println((lEndTimeMillis - lBeginTimeMillis) + "".""); // } private static void readCase() throws Exception { // StringTokenizer strTokenizer = new StringTokenizer( bufferedReader.readLine(), "" ""); String strA = strTokenizer.nextToken(); String strB = strTokenizer.nextToken(); A = Integer.parseInt(strA); B = Integer.parseInt(strB); // } private static void processCase() { // N = 0; for (int i = A; i < B; i++) { String str = Integer.toString(i); Set hashset = new HashSet(); for (int j = 1; j < str.length(); j++) { String str1 = str.substring(0, str.length() - j); String str2 = str.substring(str.length() - j, str.length()); int n = Integer.parseInt(str2 + str1); N += n > i && n <= B && !hashset.contains(n) ? 1 : 0; hashset.add(n); } } // } private static void writeCase(int nIndexCase) throws Exception { // printWriter.print(""Case #""); printWriter.print(nIndexCase + 1); printWriter.print("":""); // // printWriter.print("" ""); printWriter.print(N); printWriter.println(); // } public static void main(String[] args) throws Exception { // begin(); for (nIndexCase = 0; nIndexCase < nNbCases; nIndexCase++) { readCase(); processCase(); writeCase(nIndexCase); } end(); // } } " B21221,"public class InvalidInputException extends Exception { /** * */ private static final long serialVersionUID = -3613289305328322102L; public InvalidInputException() { super(); // TODO Auto-generated constructor stub } public InvalidInputException(String arg0, Throwable arg1, boolean arg2, boolean arg3) { super(arg0, arg1, arg2, arg3); // TODO Auto-generated constructor stub } public InvalidInputException(String arg0, Throwable arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub } public InvalidInputException(String arg0) { super(arg0); // TODO Auto-generated constructor stub } public InvalidInputException(Throwable arg0) { super(arg0); // TODO Auto-generated constructor stub } } " B21624,"package gcj.main; import java.io.BufferedReader; import java.io.BufferedWriter; public interface Case { public void init(int caseNum, BufferedReader br) throws Exception; public void solve() throws Exception; public void generateOutput(BufferedWriter bw, boolean needBR) throws Exception; } " B21698,"package gcj; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { private String solve(Scanner in) { HashSet set = new HashSet(); int A = in.nextInt(); int B = in.nextInt(); int result = 0; int numberLen = ((Integer)A).toString().length(); int multiple = 1; for (int tt = 1; tt < ((Integer)A).toString().length(); tt++) multiple *= 10; for (int n = A; n < B; n++) { if (n / multiple >= 10) multiple *= 10; int m = n; int d = m % 10; m /= 10; int counter = 0; while (counter < numberLen - 1) { m += multiple*d; if (m > n && m <= B && !set.contains(m)) set.add(m); d = m % 10; m = m / 10; counter++; } result += set.size(); set.clear(); } return """" + result; } /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""C:\\Users\\User\\Desktop\\dane\\data.in""));//C:\\Users\\User\\workspace\\GoogleCodeJam\\src\\gcj\\data""));//"")); PrintWriter out = new PrintWriter(""C:\\Users\\User\\Desktop\\dane\\output"");//C:\\Users\\User\\workspace\\GoogleCodeJam\\src\\gcj\\output"");//""C:\\Users\\User\\Desktop\\dane\\output""); int T = in.nextInt(); in.nextLine(); for (int i = 0; i < T; i++) { String s = ""Case #"" + (i + 1) + "": "" + new RecycledNumbers().solve(in); out.println(s); System.out.println(s); } out.close(); } } " B21851,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; class Input { BufferedReader reader; StringTokenizer st = new StringTokenizer(""""); public Input( BufferedReader reader_ ) { reader = reader_; } public Input( InputStream in_ ) { reader = new BufferedReader( new InputStreamReader( in_ ) ); } public Input( String fileName ) throws Exception { reader = new BufferedReader( new FileReader( new File( fileName ) ) ); } public String getToken() throws IOException { while( !st.hasMoreTokens() ) { String line = reader.readLine(); if ( line == null ) return null; st = new StringTokenizer( line ); } return st.nextToken(); } public String getLine() throws IOException { String line = reader.readLine(); return line; } public int getInt() throws Exception { int ret = Integer.parseInt( getToken() ); return ret; } }" B21676,"package glycine.gcj2012.qr; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class ProblemC { private static Set set = new HashSet(); private static void countRecycle(String numStr, int min, int max) { int num = Integer.valueOf(numStr); for (int i = 1; i < numStr.length(); ++i) { String frontStr = numStr.substring(0, i); String backStr = numStr.substring(i, numStr.length()); if (backStr.charAt(0) == '0') { continue; } String newNumStr = backStr + frontStr; int newNum = Integer.valueOf(newNumStr); if (newNum >= min && newNum <= max && newNum > num) { // System.out.println( numStr + "", "" + newNumStr); set.add(numStr + "":"" + newNumStr); } } return; } private static void solve(String minStr, String maxStr) { set.clear(); int min = Integer.valueOf(minStr); int max = Integer.valueOf(maxStr); int length = minStr.length(); for (int i = min; i <= max; ++i) { String numStr = Integer.toString(i); countRecycle(numStr, min, max); } // System.out.println(""result = "" + set.size()); } public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println(""Usage: inputFilename""); return; } BufferedReader reader = new BufferedReader(new FileReader(args[0])); String line = reader.readLine(); int times = Integer.parseInt(line); for (int i = 0; i < times; ++i) { line = reader.readLine(); String[] tokens = line.split("" ""); solve(tokens[0], tokens[1]); System.out.println(""Case #"" + (i+1) + "": "" + set.size()); } } } " B21631," import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class ProblemC { public static void main(String[] args) { //try { System.setIn(new FileInputStream(""C-small-attempt0.in"")); } catch (Exception e) { } //try { System.setIn(new FileInputStream(""C-large.in"")); } catch (Exception e) { } //try { System.setOut(new PrintStream(new FileOutputStream(""C-large-out.txt""))); } catch (Exception e) { } Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int t = 1; t <= T; t++) { int A = sc.nextInt(), B = sc.nextInt(); int c = 0; int D = 1 + (int)Math.log10(A); int M = (int)Math.pow(10, D - 1); Set set = new TreeSet(); for (int a = A; a < B; a++) { int aa = a; set.clear(); for (int d = 1; d < D; d++) { aa = aa / 10 + M * (aa % 10); if (a < aa && aa <= B && !set.contains(aa)) { c++; set.add(aa); } } } System.out.printf(""Case #%d: %d\r\n"", t, c); } } } /* 5 1 9 10 40 100 500 1111 2222 1000000 2000000 */ " B20627,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam.y12.round0; import java.util.HashMap; import utils.Jam; import utils.JamCase; /** * * @author fabien */ public class SpeakingInTongues extends Jam { private static final String g1 = ""ejp mysljylc kd kxveddknmc re jsicpdrysi""; private static final String g2 = ""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd""; private static final String g3 = ""de kr kd eoya kw aej tysr re ujdr lkgc jv""; private static final String e1 = ""our language is impossible to understand""; private static final String e2 = ""there are twenty six factorial possibilities""; private static final String e3 = ""so it is okay if you want to just give up""; // private HashMap mapToGoogleres; private HashMap mapToEnglish; public SpeakingInTongues(String filename) { super(filename); mapToEnglish = new HashMap(); // mapToGoogleres = new HashMap(); mapToEnglish.put('z', 'q'); mapToEnglish.put('q', 'z'); // mapToGoogleres.put('z', 'q'); addToMap(g1, e1); addToMap(g2, e2); addToMap(g3, e3); } private void addToMap(String goo, String eng) { char[] gooc = goo.toCharArray(); char[] engc = eng.toCharArray(); for (int i = 0; i < gooc.length; i++) { if (mapToEnglish.get(gooc[i]) == null) { mapToEnglish.put(gooc[i], engc[i]); } } } @Override public JamCase getJamCase(int number) { return new Line(this, number, lines[number]); } private class Line extends JamCase { private String line; public Line(Jam parent, int number, String line) { super(parent, number); this.line = line; } @Override public void parse() { } @Override public void solve() { StringBuilder sb = new StringBuilder(line.length()); Character e = null; for (char c : line.toCharArray()) { e = mapToEnglish.get(c); if (e == null) { sb.append(c); } else { sb.append(e); } } result = sb.toString(); } } } " B21866,"package jam2012.numbers; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import commons.FileUtilities; public class Recycle { public static void main(String[] args) throws IOException { List strings = FileUtilities.readFile(new File(""C-large.in"")); int number = Integer.parseInt(strings.get(0)); List result = new LinkedList(); for (int i = 1; i <= number; i++) { Scanner s = new Scanner(strings.get(i)); int lower = s.nextInt(); int upper = s.nextInt(); int[] lowerArray = createArray(lower); int[] upperArray = createArray(upper); int tresult = 0; for (int j = lower; j <= upper; j++) { int[] test = createArray(j); LinkedList poss = new LinkedList(); for (int k = 1; k < test.length; k++) { if (isBigger(test, k, lowerArray, 0) == 1 && isBigger(test, k, upperArray, 0) <= 0 && isBigger(test, k, test, 0) == 1) { boolean dup = false; for (int l : poss) { if (isBigger(test, k, test, l) == 0) { dup = true; } } if (!dup) { tresult++; poss.add(k); } } } } result.add(Integer.toString(tresult)); } FileUtilities.writeFile(result, new File(""C-large.out"")); } private static int isBigger(int[] a, int aStart, int[] b, int bStart) { for (int i = 0; i < a.length; i++) { int aPtr = a[(i+aStart)%a.length]; int bPtr = b[(i+bStart)%b.length]; if (aPtr > bPtr) { return 1; } else if (aPtr < bPtr) { return -1; } } return 0; } private static int[] createArray(int i) { String iS = Integer.toString(i); int[] iA = new int[iS.length()]; for (int j = 0; j < iA.length; j++) { iA[j] = Character.getNumericValue(iS.charAt(j)); } return iA; } } " B20987,"import java.util.Arrays; import java.util.Scanner; public class C { static Scanner in = new Scanner(System.in); long solve() { int A = in.nextInt(); int B = in.nextInt(); int digits = 1; int mult = 1; { int t = A; while (t>=10) { t/=10; ++digits; mult *= 10; } } long ans = 0; int[] buf = new int[digits]; for (int n=A; n n && rot <= B) { buf[cnt++] = rot; } } if (cnt>0) { Arrays.sort(buf, 0, cnt); ++ans; for (int i=1; i tonumber && tonumber >= a && didrepeat == false) { count++; } } } out.println(count); } out.close(); } }" B21257,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam.qualification.recyclednumbers; import java.util.HashSet; import java.util.List; import java.util.Set; import util.BaseResolver; import util.Util; /** * * @author bohmd */ public class RecycledNumbers extends BaseResolver { int cases; public static void main(String[] args) throws Exception { if (args.length == 0 || args[0].equals("""")) { throw new Exception(""The first parameter must be the input file name without extension.""); } else { new RecycledNumbers(args[0]).resolve(); } } public RecycledNumbers(String file) { super(file); } @Override protected void executeLine(String line) throws Exception { if (getLineNum() == 0) { cases = Util.getInt(line); } else { List lineCase = Util.getIntList(line); write(resolveCase(lineCase.get(0), lineCase.get(1))); } } protected String resolveCase(int min, int max) { Set pairSet= new HashSet(); for(int i=min; i<=max; i++) { String n = i+""""; for(int j=0; ji && mInt<=max) { pairSet.add(new Pair(i, mInt)); } } } return "" ""+pairSet.size(); } private class Pair { int m; int n; public Pair(int n, int m) { this.m = m; this.n = n; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Pair other = (Pair) obj; return (this.n == other.n && this.m == other.m) || (this.n == other.m && this.m == other.n); } @Override public int hashCode() { int hash = 7; hash = 11 * hash + this.m + this.n; return hash; } } } " B20526,"import java.io.*; public class GoogleCodeJam18 { public static void main(String[] args) throws IOException { FileInputStream getFile = new FileInputStream(""C:\\1\\in1.txt""); PrintWriter out = new PrintWriter(new File(""C:\\1\\output.out"")); BufferedReader br = new BufferedReader(new InputStreamReader(getFile)); String strLine; strLine = br.readLine().trim(); int test = Integer.parseInt(strLine); for (int i=0;i= A && initial < present && present <= B) { sum++; } } return sum; } }" B21077,"package RecycledNumbers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.Hashtable; import DancingWithGooglers.Googler; public class MainProcess { /** * @param args */ private int A ; private int B ; public MainProcess(File f){ readFile(f); } private void readFile(File f){ int numCase = 0; try { FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String str = """"; if( (str = br.readLine())!=null){ numCase = Integer.parseInt(str); } int count = 0; while( count < numCase){ str = br.readLine(); String[] substr = str.split("" ""); A = Integer.parseInt(substr[0]); B = Integer.parseInt(substr[1]); findAns(count ,substr[0].length()); count++; } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void findAns(int count , int numDigit){ int totalPair=0; if(numDigit<=1){ System.out.println(""Case #"" + (count+1) + "": 0""); } else{ for(int i=A ; i<=B ; i++){ totalPair += findPair(i , numDigit); } System.out.println(""Case #"" + (count+1) + "": "" + totalPair); } } private int findPair(int number , int numDigit){ Hashtable usedTable = new Hashtable(); int numPair =0; for(int i=1 ; i number){ if(!usedTable.containsKey(newNumber)){ numPair++; usedTable.put(newNumber, true); } } } return numPair; } private int getPower(int n){ int number = 1; if(n==0) return number; else{ for(int i=0 ; i< n ; i++){ number *=10; } return number; } } public static void main(String[] args) { // TODO Auto-generated method stub File f = new File("".\\src\\RecycledNumbers\\C-large.in""); MainProcess m = new MainProcess(f); } } " B20650,"package com.google.codejam.Qualification2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new BufferedReader(new FileReader(args[0] + "".in""))); Writer writer = new BufferedWriter(new FileWriter(args[0] + "".out"")); int T = scanner.nextInt(); Set set = new HashSet(); for (int x = 1; x <= T; ++x) { int A = scanner.nextInt(); int B = scanner.nextInt(); int y = 0; if (B >= 21) { for (int n = A; n < B; ++n) { set.clear(); int nDigits = getDigits(n); int k1 = 10; int k2 = 1; for (int i = 0; i < nDigits - 1; ++i) k2 *= 10; int n1 = n / k1; int n2 = n % k1; for (int i = 0; i < nDigits - 1; ++i) { int m = n2 * k2 + n1; if (n2 != 0 && m > n && m <= B && !set.contains(m)) { //System.out.println(n + "": "" + n2 + "" "" + n1); set.add(m); ++y; } k1 *= 10; k2 /= 10; n1 = n / k1; n2 = n % k1; } } } System.out.println(""Case #"" + x + "": "" + y); writer.write(""Case #"" + x + "": "" + y + ""\n""); } writer.close(); scanner.close(); } static int getDigits(int n) { if (n == 0) return 1; int result = 0; while (n > 0) { n /= 10; ++result; } return result; } } " B21589,"package com.phonescreen; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; public class RecycledNumber { private static int count; public static void main(String[] args) { try { DataInputStream br = new DataInputStream(new BufferedInputStream(new FileInputStream(new File(""H:\\C-small-attempt1.in"")))); String s = br.readLine(); count = Integer.parseInt(s); if (count < 1 || count > 50) { return; } for (int i = 0; i < count; i++) { String[] testCase = br.readLine().split("" ""); if (testCase[0].length() != testCase[1].length()) { return; } int a = Integer.parseInt(testCase[0]); int b = Integer.parseInt(testCase[1]); if (a < 1 || b > 2000000 || a > b) { return; } System.out.println(""Case #"" + ( i+1) + "": "" + getRecycledNumberCount(a, b)); } } catch (Exception e) { System.err.println(""Error:"" + e.getMessage()); } } private static int getRecycledNumberCount(int a, int b) { int count = 0; for (int i = a; i <= b; i++) { for (int j = i; j <= b; j++) { if (isRecycledNumbers(i + """", j + """")) { count++; } } } return count; } private static boolean isRecycledNumbers(String num1, String num2) { for (int i = 0; i < num1.length(); i++) { if (num2.indexOf(num1.charAt(i)) == -1 || num1.indexOf(num2.charAt(i)) == -1) { return false; } } for (int i = num1.length() - 1; i >= 0; i--) { String subStr = num1.substring(i); if (num2.indexOf(subStr) == -1) { subStr = num1.substring(i + 1); String s = subStr + num1.substring(0, (num1.length() - subStr.length())); if (s.equals(num2)) { return true; } } } return false; } } " B20377,"import java.io.*; import java.util.*; public class ProblemC { public static void main(String[] args) throws Throwable { Scanner in = new Scanner(new File(""c.in"")); PrintWriter out = new PrintWriter(""c.out""); int testCount = Integer.parseInt(in.nextLine().trim()); for (int i = 0; i < testCount; i++) { out.print(""Case #"" + (i + 1) + "": ""); solve(in, out); } out.close(); } static void solve(Scanner in, PrintWriter out) { int a = in.nextInt(); int b = in.nextInt(); int ans = 0; for (int i = a; i <= b; i++) { int z = getD(i) / 10; int p = i; do { p = p / 10 + p % 10 * z; if (p > i && p <= b) { ++ans; } } while (p != i); } out.println(ans); } static int getD(int i) { return i == 0 ? 1 : getD(i / 10) * 10; } } " B20012,"package googlejam3; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; public class Main3 { static HashMap pairsMap = new HashMap(); protected static String resolveTestCase(String line) { String [] tokens = line.split("" ""); int A = Integer.parseInt(tokens[0]); int B = Integer.parseInt(tokens[1]); System.out.println(""A = "" + A + "" B = "" + B ); int pairs = 0; pairsMap.clear(); for ( int n = A; n <= B; n++ ) { String test = Integer.toString(n); for ( int j = 1; j < test.length(); j++ ) { String test2 = test.substring(j, test.length()) + test.substring(0, j); int m = Integer.parseInt(test2); if ( test2.charAt(0) != '0' && n < m && m <= B && pairsMap.get(test+test2) == null) { pairs++; pairsMap.put(test+test2, """"); } } } return """" + pairs; } public static void main (String [] args) throws IOException { String inputFile = args[0]; File f = new File(inputFile); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); File f2 = new File(inputFile + "".out""); FileWriter fw = new FileWriter(f2); String line = br.readLine(); int count = Integer.parseInt(line); // resolve test cases int testcase = 1; for(int tests = 0; tests < count; tests++) { line = br.readLine(); System.out.println(line); String output = ""Case #""+testcase+"": ""; output += resolveTestCase(line); System.out.println(output+""\n""); fw.write(output+""\r\n""); testcase++; } fw.close(); } } " B21308,"import java.io.File; import java.io.FileReader; import java.io.IOException; public class FileIn { private StringBuilder sb = new StringBuilder(""""); /** * コンストラクタ. * @param filename 読み込むファイル名 */ public FileIn(String filename) { File f = new File(filename); FileReader fr = null; try { fr = new FileReader(f); int c; while ((c = fr.read()) != -1) { this.sb.append((char)c); } } catch (IOException e) { e.printStackTrace(); } finally { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * ファイルの文字列を返す. * @return */ public String getString() { return this.sb.toString(); } }" B21081,"package org.ivansopin.jam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.StringTokenizer; public class RecycledNumbers { final static String fileName = ""RecycledNumbers2""; final static String inExtension = "".in""; final static String outExtension = "".out""; final static String source = fileName + inExtension; final static String destination = fileName + outExtension; static BufferedReader bufferedReader; static BufferedWriter bufferedWriter; static int counter; /* this is problem-specific */ static int numOfCases; static int a, tmpA; static int b, tmpB; public static void main(String[] args) throws NumberFormatException, IOException, InterruptedException { bufferedReader = new BufferedReader(new FileReader(new File(source))); bufferedWriter = new BufferedWriter(new FileWriter(new File(destination))); numOfCases = Integer.parseInt(bufferedReader.readLine()); Reader reader = new Reader(); reader.start(); reader.join(); for (int i = 0; i < numOfCases; i++) { copyData(); reader = new Reader(); reader.start(); /********* this is where the real logic starts **********/ // at some point, the results should be printed: bufferedWriter.write(""Case #"" + (i + 1) + "": "" + getNumOfRecNums(a, b) + ""\n""); /********** this is where the real logic ends ***********/ if (reader.isAlive()) { reader.join(); } } bufferedWriter.close(); bufferedReader.close(); } static int getNumOfRecNums(int a, int b) { boolean[] seen = new boolean[2000001]; HashSet set; int curNum; int size; int total = 0; for (int num = a; num <= b; num++) { if (!seen[num]) { set = new HashSet(); String numStr = num + """"; int length = numStr.length() - 1; seen[num] = true; if (num >= a && num <= b) set.add(num); for (int i = 0; i < length; i++) { numStr = numStr.charAt(length) + numStr.substring(0, length); curNum = Integer.parseInt(numStr); if (curNum > 2000000) continue; seen[curNum] = true; if (curNum >= a && curNum <= b) set.add(curNum); } if ((size = set.size()) > 1) { total += (size * (size - 1) / 2); } } } return total; } static void copyData() { /* this is problem-specific */ a = tmpA; b = tmpB; } static class Reader extends Thread { public Reader() { } @Override public void run() { String line; StringTokenizer tokenizer; try { if (counter < numOfCases) { /* this is problem-specific */ line = bufferedReader.readLine(); tokenizer = new StringTokenizer(line); tmpA = Integer.parseInt(tokenizer.nextToken()); tmpB = Integer.parseInt(tokenizer.nextToken()); counter++; } } catch (IOException e) { e.printStackTrace(); } } } } " B21168,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.common; /** * * @author jim */ public abstract class AbstractProcessor implements Processor { public Output process(Input input) { int lines = Integer.parseInt(input.getHeader()[0]); String[] data = input.getData(); if (lines != data.length) throw new IllegalArgumentException(""There are a different number "" + ""of data lines to the number specified in the header""); String[] out = new String[lines]; for (int i = 0; i < lines; i++) { out[i] = processLine(data[i]); } return new Output(out); } } " B21162,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Calendar; import java.util.HashSet; import java.util.List; import java.util.Set; public class C { private static CodeJamIO io = new CodeJamIO(); /** * @param args */ public static void main(String[] args) { try { init(); int numCases = Integer.parseInt(io.readNextLine()[0]); for (int i=1; i <= numCases; i++) { io.debug(""Solving Case #"" + i + ""...""); solveCase(i); io.debug(""Case #"" + i + "" solved!""); } } catch (Exception e) { e.printStackTrace(); } } /** * Performs initial computations */ private static void init() { } /** * Solves a Test Case * * @param caseNum * @throws IOException */ private static void solveCase(int caseNum) throws IOException { // Read input String[] tokens = io.readNextLine(); int a = Integer.parseInt(tokens[0]); int b = Integer.parseInt(tokens[1]); // Do the work Set recycled = new HashSet(); for (int n=a; n<=b; n++) { String nstr = Integer.toString(n); int firstDigit = Integer.parseInt(nstr.substring(0, 1)); for (int i=1; i n && m >= a && m <= b) { recycled.add(Integer.toString(n) + Integer.toString(m)); } } } } // Print results io.printCase(caseNum).println(recycled.size()); } /** * Input and Output CodeJam style * */ private static class CodeJamIO { private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter out = new PrintWriter(System.out, true); private static PrintWriter err = new PrintWriter(System.err, true); public String[] readNextLine() throws IOException { String line = in.readLine(); String[] tokens = line.split(""\\s+""); return tokens; } public CodeJamIO printCase(int caseNum) { return print(""Case #"" + caseNum + "": "" ); } public CodeJamIO print(Object o) { out.print(o); return this; } public CodeJamIO print(Object o[]) { return print(concat(o)); } public CodeJamIO print(Object o[][]) { return print(concat(o)); } public CodeJamIO println() { out.println(); return this; } public CodeJamIO printlnCase(int caseNum) { return printCase(caseNum).println(); } public CodeJamIO println(Object o) { return print(o).println(); } public CodeJamIO println(Object o[]) { return print(o).println(); } public CodeJamIO println(Object o[][]) { return print(concat(o)).println(); } public CodeJamIO println(List l) { return print(concat(l)).println(); } private String concat(Object[] o) { StringBuffer buf = new StringBuffer(10*o.length); String delim = """"; for (int i=0; i < o.length; i++) { buf.append(delim).append(o[i]); delim = "" ""; } return buf.toString(); } private String concat(Object[][] o) { StringBuffer buf = new StringBuffer(100*o.length); for (int i=0; i < o.length; i++) { buf.append(concat(o[i])).append(""\n""); } return buf.toString(); } private String concat(List list) { StringBuffer buf = new StringBuffer(); String delim = """"; for (Object[] elm : list) { buf.append(delim).append(concat(elm)).append(""\n""); } return buf.toString(); } public void debug(String message) { err.println(Calendar.getInstance().getTime() + "": "" + message); } public void debug(String message, Object[] o) { err.println(Calendar.getInstance().getTime() + "": "" + message); err.println(""\t"" + concat(o)); } public void debug(String message, Object[][] o) { err.println(Calendar.getInstance().getTime() + "": "" + message); String values = concat(o); err.println(""\t"" + values.replaceAll(""\n"", ""\n\t"")); } public void debug(String message, List list) { err.println(Calendar.getInstance().getTime() + "": "" + message); String values = concat(list); err.println(""\t"" + values.replaceAll(""\n"", ""\n\t"")); } } } " B22155,"import java.util.*; public class RCTest{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int numberOfCases = Integer.parseInt(scan.nextLine()); for(int i = 1; i <= numberOfCases; ++i){ String line = scan.nextLine(); String[] inputs = line.split("" ""); int lower = Integer.parseInt(inputs[0]); int upper = Integer.parseInt(inputs[1]); RCTest r = new RCTest(); System.out.println(""Case #"" + i + "": "" + r.getRecycleNumbers(lower, upper)); } } public int getRecycleNumbers(int a, int b){ this.lower = a; this.upper = b; int counter = 0; for(int i = a; i<=b; ++i){ int originalNumber = i; int index = getIndex(originalNumber); int recycledNumber = getRecycledNumber(i,index); while(originalNumber!=recycledNumber){ if(originalNumber < recycledNumber && recycledNumber <= upper)++counter; recycledNumber = getRecycledNumber(recycledNumber,index); } } return counter; } public int getRecycledNumber(int number, int index){ int remainder = number % 10; int quotient = number/10; int recycledNumber = ((int)Math.pow(10,index) * remainder) + quotient; return recycledNumber; } private int getIndex(int number){ int index = 0; while(number!=0){ number/=10; ++index; } return index-1; } private int lower; private int upper; }" B21020,"package qualification; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import common.FileTranslatorBasis; public class C { final static int[] digitNum = { 9, 99, 999, 9999, 99999, 999999, 9999999 }; int low; int high; int pow = 1; public C(String low, String high) { for (int i = 0; i < low.length() - 1; i++) { pow = 10 * pow; } this.low = Integer.parseInt(low); this.high = Integer.parseInt(high); } long count; int[] map = new int[2000001]; public void initMap() { int[] tmp = { 1, 11, 111, 1111, 11111, 111111, 1111111, 2, 22, 222, 2222, 22222, 222222, 3, 33, 333, 3333, 33333, 333333, 4, 44, 444, 4444, 44444, 444444, 5, 55, 555, 5555, 55555, 555555, 6, 66, 666, 6666, 66666, 666666, 7, 77, 777, 7777, 77777, 777777, 8, 88, 888, 8888, 88888, 888888, 9, 99, 999, 9999, 99999, 999999, }; for (int i : tmp) { map[i] = -1; } } /** * * @param in */ private void parse(int in) { int pair = 1; if (map[in] == -1) { return; } map[in]=-1; String inStr = String.valueOf(in); char[] chars = inStr.toCharArray(); for (int i = 0; i < chars.length - 1; i++) { in = (in - (chars[i] - 48) * pow) * 10 + (chars[i] - 48); if (valid(in)) { if (map[in] != -1) { pair++; map[in] = -1; } } } count += pair * (pair - 1) / 2; } public long count() { for (int i = low; i <= high; i++) { parse(i); } return count; } private boolean valid(int t) { return t >= low && t <= high; } public static void main(String[] args) throws FileNotFoundException { System.setOut(new PrintStream(new File(""output.txt""))); // String fname = ""sample.txt""; // String fname = ""C-small-attempt0.in.txt""; String fname = ""C-large.in.txt""; FileTranslatorBasis ftb = FileTranslatorBasis.getInstance(fname); int num = ftb.getNumOfCase(); for (int i = 0; i < num; i++) { String[] input = ftb.getStrDataArray(); C c = new C(input[0],input[1]); System.out.println(""Case #"" + Integer.toString(i + 1) + "": "" + String.valueOf(c.count())); } } } " B21002,"package codejam; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.Scanner; interface ISolver { public String evaluate(); } public abstract class Solver implements ISolver { protected Scanner in; public void solve() { in = new Scanner(System.in); _solve(System.out); } public void solve(File inFile) { String filename = inFile.getPath(); filename = filename.substring(0, filename.lastIndexOf('.')); File outFile = new File(filename + "".out""); try { in = new Scanner(inFile); _solve(new PrintStream(outFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void solveSampleOf(char number) { String name = getClass().getName(); name = name.substring(name.lastIndexOf('.') + 1); solve(new File(""inouts/"" + name + ""/"" + number + ""-sample.in"")); } public void solveSmallOf(char number, int attempt) { String name = getClass().getName(); name = name.substring(name.lastIndexOf('.') + 1); solve(new File(""inouts/"" + name + ""/"" + number + ""-small-attempt"" + attempt + "".in"")); } public void solveLargeOf(char number) { String name = getClass().getName(); name = name.substring(name.lastIndexOf('.') + 1); solve(new File(""inouts/"" + name + ""/"" + number + ""-large.in"")); } private void _solve(PrintStream out) { int count = in.nextInt(); in.nextLine(); for(int index = 0; index pairs = new HashSet(); for(int x = A; x<=B; x++) { String n = String.valueOf(x); int digits = n.length(); if(digits > 1) { for(int p = 1; p < digits; p++) { String m = n.substring(n.length()-p)+n.substring(0,n.length()-p); int mN = Integer.parseInt(m); if(m.startsWith(""0"") || !(mN >= A && mN <=B)){ continue; } else { if(x < mN){ pairs.add(""(""+n+"",""+m+"")""); } } } } } System.out.println(""Case #""+i+"": ""+pairs.size()); out.write(""Case #""+i+"": ""+pairs.size()); out.newLine(); } out.flush(); out.close(); in.close(); } } " B22003," public class Pair { int N, M; Pair(int n, int m) { N = n; M = m; } @Override public boolean equals(Object otherPair) { Pair right = (Pair)otherPair; return (N == right.N && M == right.M); } } " B20131,"package qualification; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class RecycledNumbers { static int T; static int[] result; public static void main(String[] args) throws IOException { read(); write(); } static void read() throws IOException { File input = new File(""input.txt""); Scanner scanner = new Scanner(input); T = scanner.nextInt(); result = new int[T]; for (int t=0; t existing = new ArrayList(bs.length()); int result = 0; for (int n=A; n 0 && ms.compareTo(bs) <= 0) { if (!existing.contains(ms)) { existing.add(ms); result++; } } } } return result; } static void write() throws IOException { File output = new File(""output.txt""); PrintWriter pw = new PrintWriter(output); for (int t=0; t inputList = readFile(""C-large.in""); String output = """"; int testCase = 0; for (int i = 0; i < inputList.size(); i++) { String input = inputList.get(i); if (i == 0) { testCase = Integer.parseInt(input); } else { int recycledNo=findRecycledNO(input); output = output + ""Case #"" + i + "": ""+recycledNo; if (i != (inputList.size() - 1)) { output = output + '\n'; } } } writeFile(output); } public int findRecycledNO(String input) { String spliInput[] = input.split(""\\s""); int A = Integer.parseInt(spliInput[0]); int B = Integer.parseInt(spliInput[1]); int n = 0; int m = 0; int resultCount = 0; String[] ab = new String[(B - A) + 1]; for (int i = 0; i < ab.length; i++) { ab[i] = """" + (A + i); } for (String t : ab) { n = Integer.parseInt(t); for (int i = 0; i < t.length() - 1; i++) { t = t.substring(t.length() - 1) + t.substring(0, t.length() - 1); m = Integer.parseInt(t); if ((A <= n) && (n < m) && (m <= B)) { // System.out.println(A + "" < "" + n + "" < "" + m + "" < "" + B); resultCount++; } } // System.out.println(t); } return resultCount; } private ArrayList readFile(String fileName) { BufferedReader br = null; ArrayList inputList = null; try { File file = new File(fileName); br = new BufferedReader(new FileReader(file)); String message = null; inputList = new ArrayList(); while ((message = br.readLine()) != null) { inputList.add(message); } } catch (IOException ex) { ex.printStackTrace(); } finally { try { br.close(); } catch (IOException ex) { ex.printStackTrace(); } return inputList; } } private void writeFile(String message) { BufferedWriter bw = null; try { File file = new File(""Output.txt""); bw = new BufferedWriter(new FileWriter(file)); bw.write(message); } catch (IOException ex) { ex.printStackTrace(); } finally { try { bw.close(); } catch (IOException ex) { ex.printStackTrace(); } } } public static void main(String[] args) { RecycledNumbers rn = new RecycledNumbers(); rn.process(); } } " B20645,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Q3 { public static Problem[] probs; static class Problem { public int A; public int B; } public static void main(String[] args) { long time = System.currentTimeMillis(); String inputFile = args[0]; parseFile(inputFile); try { BufferedWriter bw = new BufferedWriter(new FileWriter(inputFile + "".out"")); for (int i=0; in && testM<=p.B) { pairs++; } shiftNum++; testM = shift(n, shiftNum); } } return """" + pairs; } public static void parseFile(String inputFile) { BufferedReader br; try { br = new BufferedReader(new FileReader(inputFile)); String line = br.readLine(); probs = new Problem[Integer.parseInt(line)]; line = br.readLine(); for (int i=0; i= start){ //System.out.println(""yes""); count++; } } } } output.println(count / 2); } } } }" B20921,"package recycledNumbers; import java.util.ArrayList; public class test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int a = 1111; int b = 2222; int result = 0; for(int i=a;i number = new ArrayList(); ArrayList numbers = new ArrayList(); int temp = i; while(temp/10>0){ number.add(temp%10); temp = temp/10; } number.add(temp%10); for(int j=0;j part = new ArrayList(); for(int k=0;k As = new ArrayList(); for(int k=1;k<=dig;k++) { num_j= Integer.parseInt(n_j.substring(k, k+dig)); if (num_j>=A && num_j>j &&num_j<=B) { boolean found=false; for (String s: As) { if(s.compareTo(""""+num_j)==0) { found=true; break; } } if(!found) { cont++; As.add(""""+num_j); } } } As =null; } bw.write(""""+cont); bw.newLine(); } br.close(); bw.close(); } } " B20033,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.*; /** * * @author Joydeep */ public class J3 { public static void main(String[] args) throws IOException{ String test = ""150""; DataInputStream ds = new DataInputStream(new FileInputStream(""d:/C-large.in"")); Writer os = new BufferedWriter(new FileWriter(""d:/output1.txt"")); int N = Integer.parseInt(ds.readLine()); for(int i = 1;i<=N;i++) { int A=0,B=0,l,counter=0,n,m,pairs=0; String temp=""""; String output=""Case #""+i+"": ""; String AB = ds.readLine()+"" ""; l = AB.length(); for(int j = 0;jn && num<=B) { int flag = 0; for(int y = 0 ;y 0; k--) { stB = stA.substring(k); stB = stB + stA.substring(0, k); bb = Integer.valueOf(stB); if (j < bb && bb <= b) { success++; } } } System.out.format(""Case #%d: %d\n"", i, success); } } }" B20090,"package code12.qualification; import java.io.File; import java.io.FileWriter; import java.util.HashSet; import java.util.Scanner; public class C { public static String solve(int A, int B) { int output = 0; for (int i = A; i < B; i++) { output += findNumOfRecyclePair(i, A, B); } return """" + output; } public static int findNumOfRecyclePair(int x, int min, int max) { int output = 0; HashSet numSet = new HashSet(); char[] charList = (x + """").toCharArray(); int[] digitList = new int[charList.length]; for (int i = 0; i < digitList.length; i++) { digitList[i] = Integer.parseInt(charList[i] + """"); } int num = 0; for (int i = 0; i < digitList.length; i++) { num = 0; for (int j = 0; j < digitList.length; j++) { num = num * 10 + digitList[(i + j) % digitList.length]; } Integer numInt = new Integer(num); if (num > x && num <= max && !numSet.contains(numInt)) { numSet.add(numInt); output++; // System.out.println(""("" + x + "", "" + num + "")""); } } return output; } public static void main(String[] args) throws Exception { // file name //String fileName = ""Sample""; //String fileName = ""C-small""; String fileName = ""C-large""; // file variable File inputFile = new File(fileName + "".in""); File outputFile = new File(fileName + "".out""); Scanner scanner = new Scanner(inputFile); FileWriter writer = new FileWriter(outputFile); // problem variable int totalCase; int A, B; // get total case totalCase = scanner.nextInt(); for (int caseIndex = 1; caseIndex <= totalCase; caseIndex++) { // get input A = scanner.nextInt(); B = scanner.nextInt(); String output = ""Case #"" + caseIndex + "": "" + solve(A, B); System.out.println(output); writer.write(output + ""\n""); } scanner.close(); writer.close(); } } " B22019," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.logging.Level; import java.util.logging.Logger; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author B4dT0bi */ public class RecycledNumbers { public static String [] input; public static String wholeOutput=""""; public static void readInput(String inputFile) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(inputFile)); String serializedSettings = """"; String line = null; while ((line = br.readLine()) != null) serializedSettings += line + ""\n""; input=serializedSettings.split(""\n""); br.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } public static void writeOutput(String inputFile) { try { BufferedWriter out = new BufferedWriter(new FileWriter(inputFile+"".out"")); out.write(wholeOutput); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { readInput(args[0]); wholeOutput=""""; for(int i=1;ialready=new HashSet(); for(int i=1;ix) { if(!already.contains(tmp)) { already.add(tmp); anz++; } } } return anz; } } " B21365,"package com.sam.googlecodejam.speakingtoungue; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import com.sam.googlecodejam.helper.InputReader; /** * This class generates the mapping based on the samples that have been provided. * @author Saifuddin Merchant * */ public class TranslatorMapping { public Map iAvalableLines = new HashMap<>(); public Map iLetterMapping = new TreeMap<>(); public TranslatorMapping() { iAvalableLines.put(""ejp mysljylc kd kxveddknmc re jsicpdrysi"", ""our language is impossible to understand""); iAvalableLines.put(""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"", ""there are twenty six factorial possibilities""); iAvalableLines.put(""de kr kd eoya kw aej tysr re ujdr lkgc jv"", ""so it is okay if you want to just give up""); } public void mapLetters() { for(Entry lineEntry: iAvalableLines.entrySet()) { String keyLine = lineEntry.getKey(); String keyValue = lineEntry.getValue(); int index=0; for(Character keyChar:keyLine.toCharArray()) { iLetterMapping.put(keyChar, keyValue.charAt(index++)); } } iLetterMapping.put('z', 'q');//add the missing mappings iLetterMapping.put('q', 'z');//add the missing mappings //System.out.println(iLetterMapping.size()); //System.out.println(iLetterMapping); } public void translate(String pInput) { for(Character translateChar:pInput.toCharArray()) { System.out.print(iLetterMapping.get(translateChar)); } } public static void main(String[] args) { TranslatorMapping mapping = new TranslatorMapping(); mapping.mapLetters(); InputReader reader = new InputReader(""c://input.in""); reader.readNextLine(); //read the line number off - we don't need it String lineRead = null; int i=1; while((lineRead=reader.readNextLine())!=null ) { System.out.print(""Case #""+i+"": ""); i++; mapping.translate(lineRead); System.out.println(); } } } " B20221," import java.io.*; import java.util.ArrayList; import java.util.List; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author home */ public class RecycledNumbers { public static void main(String args[])throws IOException{ FileReader reader = new FileReader(""D:\\NetBeansProjects\\DBInteractionWithWS\\src\\java\\C-large.in""); BufferedReader br = new BufferedReader(reader); File file = new File(""rloutput.txt""); FileWriter fw = new FileWriter(file); int count = Integer.parseInt(br.readLine()); for(int s=0;s list = new ArrayList(); if(end<=10) break; else{ if(i<=10) continue; String temp1 = i+""""; for(int j=1;j map = new HashMap(); int a = parseInt(ss[0]); int b = parseInt(ss[1]); for(int n=a;n<=b;n++) { String s = go(n); if(map.containsKey(s)) { map.put(s,map.get(s)+1); } else { map.put(s,1); } } long ans = 0; for(int x : map.values()) { ans += (long)x*(x-1)/2; } // out.println(map); out.println(""Case #""+z+"": ""+ans); } } static int p[] = {0, 1,10,100,1000,10000,100000,1000000,10000000}; static String go(int n) { int c = 0; int x = n; while(x > 0) { x /= 10; c++; } int max = 0; for(int i=0;i treeSet = new TreeSet(); for(int i = A; i <=B; i++){ if (i <= 10) continue; StringBuilder parse = new StringBuilder(String.valueOf(i)); treeSet.clear(); for(int j =0;j < parse.length(); j++){ int val = Shift(parse); if (val > i && val <= B && !treeSet.contains(val)) { result++; treeSet.add(val); } } treeSet.clear(); } out.print(result); } int Shift(StringBuilder parse){ char last = parse.charAt(parse.length()-1); parse = parse.deleteCharAt(parse.length()-1); parse = parse.insert(0, last); return Integer.valueOf(parse.toString()); } } " B20207," import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.Arrays; import java.util.HashSet; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Alex */ public class Recycle { private class Data { public int A; public int B; public HashSet list; public Data(String s) { String[] parts = s.trim().split("" ""); A = Integer.parseInt(parts[0]); B = Integer.parseInt(parts[1]); list = new HashSet(); } public Data(int n_) { } public int Solve() { list.clear(); int sols = 0; for (int i=A;i<=B;i++) { sols += permutate(i); //sols += countPerms(i); } //System.out.println(sols); if (sols != list.size()) System.err.println(""WTF""); return list.size(); } public int permutate(int i) { int count = 0; int c = i; int length = (int)(Math.log10(i)+1); int power = length-1; //System.out.println(""Length: ""+length); for (int h=0;h i && i >= A) { count++; //System.out.println(""""+i+"": ""+c); //System.out.println(""Counts""); list.add(""""+i+""""+c); } } //System.out.println(list.size()); return count; } } private static String IN = "".\\C-large.in""; private static String OUT = "".\\C-large.out""; private Data[] datas; private void go() { File file = new File(IN); System.out.println(file.getAbsolutePath()); File fo = new File(OUT); try { if (!fo.createNewFile()) { fo.delete(); fo.createNewFile(); } BufferedReader br = new BufferedReader(new FileReader(file)); BufferedWriter bw = new BufferedWriter(new FileWriter(fo)); String line; int num = Integer.parseInt(br.readLine()); datas = new Data[num]; int i = 0; while ((line = br.readLine()) != null && num-->0) { datas[i] = new Data(line); int solv = datas[i].Solve(); String ss = ""Case #""+(i+1)+"": ""+solv+""\n""; System.out.print(ss); bw.write(ss); i++; } br.close(); bw.close(); } catch (Exception e) { e.printStackTrace(); } } public Recycle() { go(); } public static void main(String[] args) { new Recycle(); } } " B20804,"import java.util.*; import java.io.*; public class Test { public void doMain() throws Exception{ Scanner input = new Scanner(new FileReader(""./iothings/C-large.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""./iothings/output.txt"")); int n = input.nextInt(); for(int i = 0 ; i < n ; i++){ int A = input.nextInt(); int B = input.nextInt(); boolean[] ispaired = new boolean[B+1]; pw.println(""Case #""+(i+1)+"": ""+num(A,B,ispaired)); } input.close(); pw.flush(); pw.close(); } public static int num(int A,int B,boolean[] ispaired){ int count = 0; for(int i = A ; i <= B ; i++){ StringBuilder sb = new StringBuilder(i+""""); boolean same = false; ispaired[i] = true; while(!same){ sb.append(sb.charAt(0)); sb.deleteCharAt(0); if(Integer.parseInt(sb.toString()) == i){ same = true; }else if(A <= Integer.parseInt(sb.toString()) && Integer.parseInt(sb.toString()) <= B && sb.charAt(0) != '0' && !ispaired[Integer.parseInt(sb.toString())]){ count++; } } } return count; } public static void main(String[] args) throws Exception{ (new Test()).doMain(); } } " B21036,"import java.util.Scanner; public class ProblemC { static Scanner in = new Scanner(System.in); public static void main(String[] args) { int lineCount = Integer.valueOf(in.nextLine()); int[] T = new int[lineCount]; for(int t = 0; t < lineCount; t++) { int A = in.nextInt(), B = in.nextInt(), count = 0; for (int n = A; n <= B; n++) { int digits = String.valueOf(n).length() - 1; String m = """" + n, lastAdded = """"; for (int i = 0; i < digits; i++) { int mi = Integer.valueOf(m = m.charAt(digits) + m.substring(0, digits)); if (mi <= B && mi > n && !lastAdded.contains("""" + mi)) { lastAdded += mi + "" ""; count++; } } } T[t] = count; } for(int i = 1; i <= lineCount; i++) { System.out.println(""Case #"" + i + "": "" + T[i-1]); } } } " B20888," import java.util.*; import java.io.*; public class c { public static void main(String arg[]){ int T; Scanner cin=new Scanner(System.in); T=cin.nextInt(); for(int t=0;t150) // break; int size=1; int num=0; while (true){ num++; if(i>=size && i now= new ArrayList(); for(int j=0;ji && copy <=m && now.indexOf(copy)==-1){ ans++; // System.out.println("" "" + i + "" "" +copy); now.add(copy); } } } System.out.println( ""Case #"" +( t+1 )+ "": "" + ans ); } } } " B21619,"import java.util.*; public class b { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String ss = sc.nextLine(); int casenum = Integer.parseInt(ss); String answer = """"; for(int i = 1;i<=casenum;i++){ answer = answer.concat(""Case #"".concat(Integer.toString(i)).concat("": "")); ss = sc.nextLine(); String wer = recycledpair(ss); answer = answer.concat(wer); answer = answer.concat(""\n""); } System.out.print(answer); } public static String recycledpair(String a){ int n = Integer.parseInt(a.substring(0, a.indexOf(' '))); int m = Integer.parseInt(a.substring(a.indexOf(' ')+1, a.length())); int nlength = a.substring(0, a.indexOf(' ')).length(); int pairnum = 0; String rcp =""""; for(int i=n; i mylist = new LinkedList(); String sn = Integer.toString(i); //a.substring(0, a.indexOf(' ')); for(int j=1; ji&&newint<=m){ if(!mylist.contains(newint)){ pairnum++; mylist.add(newint); } else{ mylist.add(newint); } } } } String snumreturn = Integer.toString(pairnum); //System.out.print(snumreturn); return snumreturn; } } " B21512,"package codejam; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public abstract class CodeJam { protected BufferedReader reader; protected FileWriter writer; //used in multithread mode protected String[] inputLines; protected String[] outputLines; protected int linesPerCase; long start; protected String caseLabel = ""Case #""; protected boolean runningMultiThread = false; public CodeJam(String file) throws Exception { this(file, -1); } public CodeJam(String file, int linesPerCase) throws Exception { start = System.currentTimeMillis(); this.linesPerCase = linesPerCase; FileReader fileReader = new FileReader(new File(file)); reader = new BufferedReader(fileReader); File outFile = new File(file.replaceAll(""\\.\\w+$"", "".out"")); outFile.delete(); writer = new FileWriter(outFile); } public void start() throws IOException, InterruptedException { String readLine = reader.readLine(); //total number of cases int t = Integer.parseInt(readLine); int threads = 1; if (linesPerCase > 0) { runningMultiThread = true; loadInputLines(t*linesPerCase); outputLines = new String[t]; threads = 4; } ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); for (int i = 0; i < threads; i++) { newCachedThreadPool.execute(new CaseProcessor(i*t/threads+1, (i+1)*t/threads)); } newCachedThreadPool.shutdown(); newCachedThreadPool.awaitTermination(8*60*1000, TimeUnit.MILLISECONDS); if (runningMultiThread) { for (int i = 0; i < outputLines.length; i++) { writer.write(outputLines[i]); } } writer.flush(); long delay = System.currentTimeMillis() - start; if (delay < 5000) { System.out.println(""Total time ""+delay+ "" millis""); } else { System.out.println(""Total time ""+(delay/1000)+ "" secs""); } System.exit(0); } class CaseProcessor implements Runnable { int firstCase; int lastCase; public CaseProcessor(int firstCase, int lastCase) { this.firstCase = firstCase; this.lastCase = lastCase; } public void run() { for (int i = firstCase; i <= lastCase; i++) { Object result; try { result = processCase(i); writeCaseResult(i, result); } catch (Exception e) { e.printStackTrace(); } if (i%10 == 0) { long timeRemaing = (System.currentTimeMillis() - start)/i * (lastCase-i); if (timeRemaing < 5000) { System.out.println(i*100f/lastCase+"" % Complete (Time remaing: ""+timeRemaing+"" millis)""); } else { System.out.println(i*100f/lastCase+"" % Complete (Time remaing: ""+timeRemaing/1000+"" secs)""); } } } System.out.println(""Finish""+firstCase); } } private void loadInputLines(int lines) throws IOException { inputLines = new String[lines]; for (int i = 0; i < lines; i++) { inputLines[i] = reader.readLine(); } reader.close(); reader = null; } public final String readLine() throws IOException { return reader.readLine(); } public final int readLineInt() throws IOException { return Integer.parseInt(reader.readLine()); } public final String readLine(int caseNumber, int i) { return inputLines[(caseNumber-1)*linesPerCase+i]; } public final int[] readIntArray(int caseNumber, int line) { String[] numbers = readLine(caseNumber, line).split("" ""); int[] n = new int[numbers.length]; for (int i = 0; i < numbers.length; i++) { n[i] = Integer.parseInt(numbers[i]); } return n; } public final Integer[] readIntegerArray(int caseNumber, int line) { String[] numbers = readLine(caseNumber, line).split("" ""); Integer[] n = new Integer[numbers.length]; for (int i = 0; i < numbers.length; i++) { n[i] = Integer.parseInt(numbers[i]); } return n; } @SuppressWarnings(""unchecked"") public static T[] reverse(T[] arr) { List list = Arrays.asList(arr); Collections.reverse(list); return (T[]) list.toArray(new Object[arr.length]); } public static void reverse(char[] data) { int left = 0; int right = data.length - 1; while( left < right ) { // swap the values at the left and right indices char temp = data[left]; data[left] = data[right]; data[right] = temp; // move the left and right index pointers in toward the center left++; right--; } } protected void writeCaseResult(int caseNumber, Object result) throws IOException { StringBuilder out = new StringBuilder(caseLabel);//""Case #"" out.append(caseNumber); out.append("": ""); out.append(result); out.append('\n'); System.out.println(out); if (runningMultiThread) { outputLines[caseNumber-1] = out.toString(); } else { writer.write(out.toString()); } } public long convetNumber(int number, int currentBase, int destBase) { long result = 0; int count = 0; while (number > 0) { int remainder = number % destBase; number /= destBase; int current = remainder*(int)Math.pow(currentBase,count); result += current; count++; } return result; } public abstract Object processCase(int caseNumber) throws Exception; } " B21153,"package codejam2012Qualification; import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException { boolean large = false; large = true; String dir = ""C://Users//Aayush//Desktop//""; String InputFile = dir + (large ? ""C-large.in"" : ""C-small-attempt0.in""); String OutputFile = dir + (large ? ""C-large.out"" : ""C-small.out""); File file = new File(InputFile); Scanner st = new Scanner(file); FileWriter fw = new FileWriter(OutputFile); int T = st.nextInt(); for(int cases = 1; cases <= T; cases++){ int A = st.nextInt(); int B = st.nextInt(); int digits = 0; int A1 = A; while(A1 > 0){ A1 /= 10; digits++; } //Efficient solution int count = 0; HashSet h = new HashSet(); for(int n = A; n < B; n++){ for(int i = 1; i < digits; i++){ int d = (int) Math.pow(10, i); int d1 = (int) Math.pow(10, digits - i); int r = n % d; int m = d1 * r + n / d; if(m > n && m <= B){ h.add(m); } } count+= h.size(); h.clear(); } System.out.print(""Case #"" + cases + "": "" + count); fw.write(""Case #"" + cases + "": "" + count); System.out.println(); fw.write(""\n""); } fw.flush(); fw.close(); } } " B20049,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { private final String inputFile = ""D:\\input.in""; private final String outputFile = ""D:\\output.out""; private static class TestCase{ int a; int b; public int calculateRecycleds(){ int result = 0; for (int i = a; i <= b; i++){ int numDigits = getNumDigits(i); int lastResycled = -1; for (int j = 0, divisor = 10; j < numDigits - 1; j++, divisor *= 10){ int recycled = i % divisor; for (int k = 0; k < numDigits - j - 1; k++){ recycled *= 10; } recycled += (i / divisor); if (isInRange(recycled) && recycled > i && lastResycled != recycled){ result ++; lastResycled = recycled; } } } return result; } private int getNumDigits(int i){ int numDigits = 0; while (i > 0){ numDigits++; i /= 10; } return numDigits; } private boolean isInRange(int i){ return (i >= a) && (i <= b); } } List input = new ArrayList(); public void parseInput(){ try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); int numTestCases = Integer.parseInt(br.readLine()); for (int i = 0; i < numTestCases; i++){ String [] lineTokens = br.readLine().split("" ""); TestCase tc = new TestCase(); tc.a = Integer.parseInt(lineTokens[0]); tc.b = Integer.parseInt(lineTokens[1]); input.add(tc); } br.close(); } catch (Exception e) { e.printStackTrace(); } } public void doOutput(){ try { PrintWriter pw = new PrintWriter(new FileOutputStream(outputFile)); for (int i = 0; i < input.size(); i++){ TestCase tc = input.get(i); pw.println(""Case #"" + (i + 1) + "": "" + tc.calculateRecycleds()); } pw.flush(); pw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void main(String [] args){ RecycledNumbers rn = new RecycledNumbers(); rn.parseInput(); rn.doOutput(); } } " B21925," import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; /** * * @author Anirban */ public class RecycledNumbersLarge { static int MAXN = 2000000; static int arr[] = new int[MAXN + 1]; public static boolean check(String n, String m, int len){ for(int i = 0; i < len; i++){ if(m.compareTo(n.substring(i, i + len)) == 0) return true; } return false; } public static void main(String [] args)throws IOException{ InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); int tc = 1; //int T = 50; int T = Integer.parseInt(br.readLine()); while(T-- > 0){ int count = 0; StringTokenizer st = new StringTokenizer(br.readLine(), "" ""); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); //int A = 1; //int B = 2000000; ArrayList L = new ArrayList(); String b = B + """"; for(int i = A; i <= B; i++){ String n = i + """"; String x = n; int len = n.length(); n += n; L.clear(); for(int j = 0; j < len; j++){ String m = n.substring(j, j + len); int mm = Integer.parseInt(m); if(!L.contains(mm)){ m = mm + """"; if(i < mm && x.length() == m.length() && B >= mm){ count++; //System.out.println(n.substring(0, len) + "" "" + m); } L.add(mm); } } } System.out.printf(""Case #%d: %d"", tc, count); System.out.println(); tc++; } } } " B20191,"package core; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; public class ExtendedBufferedReader extends BufferedReader { public ExtendedBufferedReader(Reader iReader) { super(iReader); } public String getLine(){ try { return readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } // Get int from line public int getIntFL(){ try { return new Integer(readLine()).intValue(); } catch (NumberFormatException e) { // TODO Auto-generated catch block System.out.println(""Error check entry data""); } catch (IOException e) { System.out.println(""Error check entry data""); e.printStackTrace(); } return 0; } public List getIntListFL(){ String[] aRead; try { aRead = readLine().split("" ""); } catch (IOException e) { // TODO Auto-generated catch block return null; } List aList = new ArrayList(); for (String num:aRead) { aList.add(new Integer(num)); } return aList; } public List getLongListFL(){ String[] aRead; try { aRead = readLine().split("" ""); } catch (IOException e) { // TODO Auto-generated catch block return null; } List aList = new ArrayList(); for (String num:aRead) { aList.add(new Long(num)); } return aList; } } " B21944,"import java.util.HashMap; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); int numberOfRecycledPairs = findNumberOfRecycledPairs(A, B); System.out.format(""Case #%d: %d\n"", i, numberOfRecycledPairs); } } private static int findNumberOfRecycledPairs(int start, int end) { HashMap recycledPairs = new HashMap(); for(int i = start; i <= end; i++) { int originalNumber = i; String numberStr = originalNumber + """"; int numberLength = numberStr.length(); for(int j = 1; j < numberLength; j++) { String newNumberStr = numberStr.substring(numberLength - j) + numberStr.substring(0, numberLength - j); int newNumber = Integer.parseInt(newNumberStr); if(newNumber >= start && newNumber <= end && newNumber > originalNumber) recycledPairs.put(originalNumber + ""::"" + newNumber,""""); } } return recycledPairs.size(); } } " B21107,"import java.util.*; import java.io.*; public class C { public static final String INPUT_FILE = ""C-large.in""; public static final String OUTPUT_FILE = ""cLarge.out""; public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File(INPUT_FILE)); PrintStream output = new PrintStream(new File(OUTPUT_FILE)); Map answerKey = new HashMap(); answerKey.put(1,0); answerKey.put(2,1); answerKey.put(3,3); answerKey.put(4,6); answerKey.put(5,10); answerKey.put(6,15); answerKey.put(7,21); int trials = Integer.parseInt(input.nextLine()); // START for(int i = 1; i <= trials; i++) { String[] line = input.nextLine().split("" ""); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); Set seen = new HashSet(); List answer = new ArrayList(); int length = getLength(A); if(length > 1) { for(int j = A; j <= B; j++) { if(!seen.contains(j)) { answer.add(numberOfPerms(A, B, j, length, seen)); } // It is seen, so don't do anything } } else { // length = 1 } int answerCount = 0; for(int k = 0; k < answer.size(); k++) { answerCount += answerKey.get(answer.get(k)); } output.print(""Case #"" + i + "": "" + answerCount); if(i != trials) { output.println(); } } } public static int numberOfPerms(int A, int B, int num, int length, Set s) { int original = num; int count = 1; int permute = permute(num, length); s.add(original); while(original != permute) { if(permute >= A && permute <= B && !s.contains(permute)) { s.add(permute); // add bc we've now seen it count++; // we have a good permute } permute = permute(permute, length); } return count; } public static int getLength(int num) { return (num + """").length(); } public static int permute(int num, int length) { int a = num % 10; int b = num / 10; return a * (int) Math.pow(10, length-1) + b; } }" B20841,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumbersLarge { public static File inputFile, outputFile; public static List inputLines = new ArrayList(); public static List outputLines = new ArrayList(); public static Map mapGtE = new HashMap(); private static void initFiles() { inputFile = new File(""C:\\Users\\Enrique\\Desktop\\codejam\\RecycledNumbers\\C-small-attempt0.in""); outputFile = new File(""C:\\Users\\Enrique\\Desktop\\codejam\\RecycledNumbers\\RecycledNumbers.out""); } private static void readInput() { BufferedReader reader; try { reader = new BufferedReader(new FileReader(inputFile)); String line = """"; int numberOfCases = Integer.parseInt(reader.readLine()); for(int i=0; i recycledPairs = new HashSet(); int result=0; for(int i=downBounds; i<=upBounds; i++) { String numstr_rotate = String.valueOf(i); String numstr_original = String.valueOf(i); for(int j=1; j<=numstr_rotate.length()-1; j++) { numstr_rotate = numstr_rotate.charAt(numstr_rotate.length()-1)+numstr_rotate.substring(0,numstr_rotate.length()-1); if(!numstr_rotate.equals(numstr_original)) { if(Integer.parseInt(numstr_rotate) <= upBounds && Integer.parseInt(numstr_rotate) >= downBounds) { if(!recycledPairs.contains(numstr_original+"":""+numstr_rotate) && !recycledPairs.contains(numstr_rotate+"":""+numstr_original)) { recycledPairs.add(numstr_original+"":""+numstr_rotate); result++; } } } } } return result; } /** * @param args */ public static void main(String[] args) { initFiles(); readInput(); doAlgorithm(); writeOutput(); } } " B22089,"package codejam; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Numbers { public static void main (String[] args) throws IOException { Scanner sc = new Scanner(new FileReader(""numbers.in"")); PrintWriter out = new PrintWriter(new FileWriter(""NumbersClarge.out"")); int cases = sc.nextInt(); for (int i = 0; i < cases; i++) { String aString = sc.next(); String bString = sc.next(); int a = Integer.parseInt(aString); int b = Integer.parseInt(bString); int count = 0; for (int j = a; j <= b; j++) { String currentString = String.valueOf(j); ArrayList list = new ArrayList(); for (int k = 1; k < currentString.length(); k++) { String thisNewString = currentString.substring(currentString.length() - k, currentString.length()) + currentString.substring(0, currentString.length() - k); if (isAnagram(currentString, thisNewString)) { if (Integer.parseInt(thisNewString) >= a && Integer.parseInt(thisNewString) <= b && !currentString.equals(thisNewString)) { if (!list.contains(thisNewString)) { count++; } list.add(thisNewString); } } } } out.println(""Case #"" + (i + 1) + "": "" + count/2); } out.close(); } public static boolean isAnagram(String s1, String s2) { int[] char_set = new int[10]; if(s1.length() != s2.length()) { return false; } for (int i = 0; i < s1.length(); i++) { char_set[s1.charAt(i) % 48]++; } for (int j = 0; j < s1.length(); j++) { char_set[s1.charAt(j) % 48]--; } for(int k = 0; k < char_set.length; k++) { if (char_set[k] != 0) { return false; } } return true; } } " B20718,"package midnighter.googlejam.y2012; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class QualificationC { static final String inFileName = ""inputs/C-large.in""; static final String outFileName = ""outputs/C-large.out""; Scanner in; PrintWriter out; public int oneCase() { int A = in.nextInt(); int B = in.nextInt(); int res = 0; for (int i = A; i <= B; i++) { int d = 1, c = i; while ((c /= 10) > 0) d++; int v = i; for (int k = 0; k < d - 1; k++) { int nw = v % 10; for (int j = 0; j < d - 1; j++) nw *= 10; v = v / 10 + nw; if (v == i) break; if (nw != 0 && v <= B && v > i) res++; } } return res; } public void run() throws Exception { in = new Scanner(new FileReader(inFileName)); out = new PrintWriter(new FileWriter(outFileName)); int nCases = in.nextInt(); in.nextLine(); for (int c = 1; c <= nCases; c++) out.println(""Case #"" + c + "": "" + oneCase()); out.flush(); out.close(); in.close(); } public static void main(String[] args) throws Exception { new QualificationC().run(); } } " B20635,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class qc { public static void main(String [] args) { String fileName = ""C-large.in""; try{ FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(""output.txt""); BufferedWriter bw = new BufferedWriter(fw); String line=""""; int count = 0; int solution = 0; while((line=br.readLine())!=null) { if(count == 0) { count++; continue; } String [] sp = line.split("" ""); int [] range = new int[sp.length]; for(int i =0; i 0) { t /= 10; d++; m *= 10; } d--; m /= 10; Arrays.fill(done, false); for(int i=a; i<=b; i++) { if (done[i]) continue; done[i] = true; n = i; t = 0; for(int j=d; j>0; j--) { n = (n/10)+((n%10)*m); if(n > m && n >= a && n <= b && !done[n]) { t++; done[n] = true; } } ct += (t*(t+1))/2; } System.out.printf(""Case #%d: %d\n"", c, ct); } } } " B22052,"package google.loader; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List; public class ChallengeLoader { private List challenges; private final ChallengeReader reader; public ChallengeLoader(ChallengeReader reader){ this.reader = reader; } public List load(String aPath){ try{ String input = readFileAsString(aPath); readChallenges(input); return challenges; } catch(Exception e){ throw new RuntimeException(e); } } private String readFileAsString(String filePath) throws java.io.IOException{ byte[] buffer = new byte[(int) new File(filePath).length()]; BufferedInputStream f = null; try { f = new BufferedInputStream(new FileInputStream(filePath)); f.read(buffer); } finally { if (f != null) try { f.close(); } catch (IOException ignored) { } } return new String(buffer); } private void readChallenges(String input) { String delimiter; if(input.indexOf(""\r\n"")>0){ delimiter=""\r\n""; }else{ delimiter=""\n""; } String[] lines = input.split(delimiter); challenges = reader.createChallenges(lines); } public String getResult() { StringBuffer res = new StringBuffer(); for(Challenge challenge : challenges){ res.append(challenge.getResult()); } return res.toString(); } }" B20818,"package _2012.QualificationRound.C; import java.util.ArrayList; import Utils.InputFile; import Utils.OutputFile; public class C { private static void solve(InputFile inputFile, OutputFile outputFile){ int nbCases = Integer.parseInt(inputFile.getNextLine()); for(int caseNumber = 0; caseNumber < nbCases; caseNumber++){ String[] line = inputFile.getNextLine().split("" ""); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); //n != m //m don't start with 0 int cptRecycled = 0; for (int i =A; i <= B; i++){ String number = """"+i; String recycled = """"+number; ArrayList recycledList = new ArrayList(); for(int j = 0; j < number.length(); j++){ recycled = recycled.charAt(recycled.length()-1)+ recycled.substring(0, recycled.length()-1); int recycledInt = Integer.parseInt(recycled); if(recycledInt >= A && recycledInt <= B && recycledInt != i && !recycledList.contains(recycledInt)){ cptRecycled++; recycledList.add(recycledInt); } } } System.out.println(""case "" + caseNumber + "" on "" + nbCases); String result = """" +(cptRecycled/2) ; outputFile.writeResult(result); } } public static void main(String[] args) { InputFile inputFile = new InputFile(""C"", ""large""); OutputFile outputFile = new OutputFile(inputFile); solve(inputFile, outputFile); outputFile.endFile(); } } " B21721,"import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; /** * @author OleGG */ public class QualTaskC { public static void main(String[] args) throws Throwable { Scanner sc = new Scanner(new FileReader(""C-large.in.txt"")); PrintWriter pw = new PrintWriter(new FileWriter(""C-large.out.txt"")); int t = sc.nextInt(); for (int test = 1; test <= t; ++test) { int a = sc.nextInt(); int b = sc.nextInt(); int mul = 1; while (mul <= a) { mul *= 10; } mul /= 10; int res = 0; for (int i = a; i < b; ++i) { int curr = i; do { int temp = curr % 10; curr /= 10; curr += temp * mul; if (curr > i && curr <= b) { ++res; } } while (curr != i); } pw.printf(""Case #%d: %d\n"", test, res); } pw.close(); } } " B20885,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class Recycled { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader (""data/input"")); PrintWriter pw = new PrintWriter(new FileWriter(""data/output"")); int lines = Integer.parseInt(br.readLine()); for(int j = 0; j < lines; j++){ String sol = ""Case #"" + (j+1) + "": ""; StringTokenizer st = new StringTokenizer(br.readLine()); int min = Integer.parseInt(st.nextToken()); int max = Integer.parseInt(st.nextToken()); int num = 0; for(int i = min; i<=max;i++){ String numb = """"+i; List duplicates = new ArrayList(); for(int k=0;k i && newNumb >= min && newNumb <= max){ //System.out.println(i+""\t""+newNumb); duplicates.add(""""+newNumb); num++; } } } pw.println(sol + """"+ num); } pw.close(); } } " B20485,"import java.util.*; public class Main{ static int power(int d) { if(d== 0) return 1; else if(d%2 == 0) { int a = power(d/2); return a*a; } else { int a = power(d/2); return a*a*10; } } public static void main(String [] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int cc = 1; cc<= T; cc++) { int A = in.nextInt(); int B = in.nextInt(); int Digit = Integer.toString(A).length(); int tab[] = new int[2000001]; int base = power(Digit-1); for(int i = 0; i<2000001; i++) { tab[i] = -1; } for(int i = A; i= A && next <=B) { if(tab[next] == -1) { tab[next] =0; tab[i] ++; } } current = next; } } } long res = 0; for(int i = A; i= a && newInt < i && contains[newInt] != i){ contains[newInt] = i; count++; // System.out.println("" "" + s + "" "" + newInt); } } } out.println(""Case #"" + testCase + "": "" + count); // System.out.println(""Case #"" + testCase + "": "" + count); } }" B20187,"package com.numbers.recycle.orchestrator; import java.util.ArrayList; import java.util.List; import com.numbers.recycle.algo.Recycler; import com.numbers.recycle.io.FileOutputWriter; import com.numbers.recycle.io.FileParser; public class NumberRecycler { private FileParser parser = new FileParser(); private Recycler recycler = new Recycler(); private FileOutputWriter writer = new FileOutputWriter(); public void solveAndWriteToOutputFile(String filePath){ List fileContents = parser.readFile(filePath); List outputContents = new ArrayList(); int size = Integer.valueOf(fileContents.get(0)); int counter = 1; while(counter <= size){ outputContents.add(""Case #""+ counter +"": ""+recycler.getRecycledNumberCount(fileContents.get(counter++).split("" ""))); } writer.writeToFile(outputContents); } } " B21802,"package util.graph; public abstract class State implements Comparable{ } " B22124,"import java.awt.geom.*; import java.io.*; import java.math.*; import java.util.*; import java.util.regex.*; import static java.lang.Math.*; import static java.lang.System.*; public class C_large { public C_large() throws Exception { int caseCount = in.nextInt(); for (int caseNum=1;caseNum<=caseCount;caseNum++) { out.printf(""Case #%d: "", caseNum); int a = in.nextInt(); int b = in.nextInt(); int ans = 0; for (int n=a; n<=b; n++) { String sn = n+""""; if (sn.charAt(0)=='0') continue; Set set = new HashSet(); for (int i=1; ib||n>=m) continue; if (set.contains(m)) continue; set.add(m); ans++; } } out.println(ans); } } // {{{ Scanner in = new Scanner(System.in); public static void main(String[] args) throws Exception { new C_large(); } public static void debug(Object... arr) { System.err.println(Arrays.deepToString(arr)); } // }}} } " B21934,"import java.io.*; import java.util.*; public class C { final static boolean DEBUG = true; public Object solve () throws IOException { int A = sc.nextInt(); int B = sc.nextInt(); long cnt = 0; for (int n = A; n <= B; ++n) { Set M = new HashSet(); String s = """" + n; int L = s.length(); for (int i = 0; i < L; ++i) { s = s.charAt(L-1) + s.substring(0, L-1); int m = Integer.parseInt(s); if (m > n && m <= B && M.add(m)) ++cnt; } } return cnt; } void init () { } //////////////////////////////////////////////////////////////////////////////////// public C () throws IOException { init(); int N = sc.nextInt(); start(); for (int n = 1; n <= N; ++n) print(""Case #"" + n + "": "" + solve()); exit(); } static MyScanner sc; static long t; static void print (Object o) { System.out.println(o); if (DEBUG) System.err.println(o + "" ("" + ((millis() - t) / 1000.0) + "")""); } static void exit () { if (DEBUG) { System.err.println(); System.err.println((millis() - t) / 1000.0); } System.exit(0); } static void run () throws IOException { sc = new MyScanner (); new C(); } public static void main(String[] args) throws IOException { run(); } static long millis() { return System.currentTimeMillis(); } static void start() { t = millis(); } static class MyScanner { String next() throws IOException { newLine(); return line[index++]; } char [] nextChars() throws IOException { return next().toCharArray(); } double nextDouble() throws IOException { return Double.parseDouble(next()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } String nextLine() throws IOException { line = null; return r.readLine(); } String [] nextStrings() throws IOException { line = null; return r.readLine().split("" ""); } int [] nextInts() throws IOException { String [] L = nextStrings(); int [] res = new int [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } long [] nextLongs() throws IOException { String [] L = nextStrings(); long [] res = new long [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Long.parseLong(L[i]); return res; } boolean eol() { return index == line.length; } ////////////////////////////////////////////// private final BufferedReader r; MyScanner () throws IOException { this(new BufferedReader(new InputStreamReader(System.in))); } MyScanner(BufferedReader r) throws IOException { this.r = r; } private String [] line; private int index; private void newLine() throws IOException { if (line == null || index == line.length) { line = r.readLine().split("" ""); index = 0; } } } static class MyWriter { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); void print(Object o) { pw.print(o); } void println(Object o) { pw.println(o); } void println() { pw.println(); } public String toString() { return sw.toString(); } } char [] toArray (Character [] C) { char [] c = new char[C.length]; for (int i = 0; i < C.length; ++i) c[i] = C[i]; return c; } char [] toArray (Collection C) { char [] c = new char[C.size()]; int i = 0; for (char z : C) c[i++] = z; return c; } Object [] toArray(int [] a) { Object [] A = new Object[a.length]; for (int i = 0; i < A.length; ++i) A[i] = a[i]; return A; } String toString(Object [] a) { StringBuffer b = new StringBuffer(); for (Object o : a) b.append("" "" + o); return b.toString().trim(); } String toString(int [] a) { return toString(toArray(a)); } } " B21313,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; public class GCJC { static HashMap map = new HashMap(); public static void main(String[] args) { try { FileReader in = new FileReader(""C-large.in""); BufferedReader br = new BufferedReader(in); File file = new File(""./largeC.txt""); FileWriter fw = new FileWriter(file); String line; int num = Integer.valueOf(br.readLine()); int caseNum = 1; while ((line = br.readLine()) != null) { map = new HashMap(); StringBuilder sb = new StringBuilder(); sb.append(""Case #"" + caseNum + "": ""); caseNum++; int res = 0; int a = Integer.valueOf(line.split("" "")[0]); int b = Integer.valueOf(line.split("" "")[1]); for(int i = a; i <= b ; i++){ for(int j = 10; j <= i ; j*=10){ int digit = (int)Math.log10(i) + 1; int top = i/j; int back = i%j; int cycle = (int) (back * Math.pow(10, (digit - (int)Math.log10(j))) + top); if(map.get(i) != null && map.get(i) == cycle) continue; if(cycle <= b && i < cycle){ map.put(i, cycle); res++; } } } sb.append(res); fw.write(new String(sb)); fw.write(""\n""); } br.close(); in.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } } " B20983,"import java.io.*; import java.util.*; public class Recycled { class Case{ int[] limits = null; HashSet counted = new HashSet(); public Case(int[] limits){ this.limits = limits; } public int getResult(){ int k = 0; for(int i = limits[0]; i<=limits[1]; i++){ for(int j=1; j<(""""+i).length(); j++){ try{ k = shift(i, j); updateCount(limits[0], limits[1], i, k); updateCount(limits[0], limits[1], k, i); } catch(RuntimeException re){ continue; } } } return counted.size(); } public void updateCount(int A, int B, int n, int m){ if((!counted.contains(n+"",""+m)) && ( A <= n && m > n && m <= B)){ counted.add(n+"",""+m); } } public int shift(int i, int shiftby){ String input = """"+i; int shifted = Integer.parseInt(input.substring(input.length()-shiftby) + input.substring(0,input.length()-shiftby)); if((""""+shifted).length() != input.length()){ throw new RuntimeException(""INVALIDSHIFT""); } return shifted; } } public Recycled(String file){ BufferedReader in = null; PrintWriter out = null; try{ in = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(file+""/input.txt"")))); out = new PrintWriter(new BufferedWriter(new FileWriter(file+""/output.txt"")), true); int caseId = 1; int result = 0; String line = null; Case c = null; in.readLine(); //no of cases while ((line = in.readLine()) != null) { c = new Case(getIntArray(line)); result = c.getResult(); System.out.println(""Case #""+caseId+ "": ""+result); out.println(""Case #""+caseId+ "": ""+result); caseId++; } } catch(Exception e){ e.printStackTrace(); } finally{ try{ out.close(); } catch(Exception ignored){} try{ in.close(); } catch(Exception ignored){} } } public String[] getStringArray(String str){ return str.split(""\\s+""); } public int[] getIntArray(String str){ String[] sArray = getStringArray(str); int[] iArray = new int[sArray.length]; for(int i=0; i k && num <= B) count++; } } out.write(""Case #"" + i + "": "" + count + ""\n""); } in.close(); out.close(); } } " B21351,"import java.io.*; public class C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); for (int c = 1; c <= t; c++) { String[] line = in.readLine().split("" ""); int a = Integer.parseInt(line[0]); int b = Integer.parseInt(line[1]); int len = line[0].length(); int tenlen = 1; for (int i=1; i n && m <= b) result++; } while (m != n); } System.out.println(""Case #""+c+"": ""+result); } } } " B20928,"import java.util.Scanner; public class Main extends AbstractCodeJam { @Override protected Problem readProblem(Scanner scan) { ProblemSample pb = new ProblemSample(); // PARAMETRES A LIRE !!! pb.setA(scan.nextInt()); pb.setB(scan.nextInt()); scan.nextLine(); return pb; } /** * @param args */ public static void main(String[] args) { new Main().solveProblems(System.in, System.out); } } " B20357,"import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class QuestionC { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { File fileread = new File(""C-large.in.txt""); File filewrite = new File(QuestionC.class.getName() + ""outputBig.txt""); GCIFileReader fr = new GCIFileReader(fileread); GCIFileWriter fw = new GCIFileWriter(filewrite); GCIResult res = new GCIResult(); String s = fr.getLine(); int n = Integer.parseInt(s); List m = new LinkedList(); for (int i=0; i < n ; i++) { String l = fr.getLine(); Scanner sc = new Scanner(l); int tres = 0; int tn = 0; int tm = 0; int newnum = 0; int A = sc.nextInt(); int B = sc.nextInt(); int length = Integer.toString(A).length(); length--; for(int j=A ; j <= B ; j++) { int tlength = length; m.clear(); while(tlength>0) { tn = (int) (j % (Math.pow(10,tlength))); tm = (int) (j / (Math.pow(10,tlength))); newnum = (int) (tn*(Math.pow(10, Integer.toString(tm).length())) + tm); if (!m.contains(newnum) &&newnum <= B && j < newnum && Integer.toString(tn).length() == tlength && Integer.toString(tm).length() == (length+1 - tlength)) if (newnum <= B && tn!=0 && j < newnum) { tres++; m.add(newnum); } tlength--; } } res.addCase(String.valueOf(tres)); } fw.writeResult(res); } } " B21997,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cj2012; import java.io.BufferedReader; import java.io.FileReader; import java.util.*; /** * * @author agraa1 */ public class Recycle { public static void main(String[] args) throws Exception { Recycle puzzle = new Recycle(); puzzle.solve(); } private void solve() throws Exception { BufferedReader br = new BufferedReader(new FileReader(""E:\\C-large.in"")); String line = br.readLine(); for (int count=0; count recNumbers = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(input, "" ""); String A = tokenizer.nextToken(); String B = tokenizer.nextToken(); if (Integer.valueOf(B) > 10) { findSolution(A, B, recNumbers); } StringBuilder builder = new StringBuilder(""Case #""); builder.append(caseNum); builder.append("": ""); builder.append(recNumbers.size()); System.out.println(builder.toString()); } private void findSolution(String A, String B, List recNumbers) { int numA = Integer.valueOf(A); int numB = Integer.valueOf(B); for (int num = numA; num < numB; num++) { getRecycles(num, numA, numB, recNumbers); } } private void getRecycles(int num, int numA, int numB, List recNumbers) { String toBeRec = """"+num; //System.out.println(""Recycles for "" + num); Set recyclesForNum = new HashSet(); for (int count=1; count= numA && recycledNum > num) { //System.out.println(""#"" + (recNumbers.size()+1) + "" ----------------"" + num + ""--"" + recycledNum); recyclesForNum.add(recycledNum); } } recNumbers.addAll(recyclesForNum); } }" B20994,"import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; import java.io.*; import java.math.*; import java.util.*; @SuppressWarnings(""unused"") public class C_RecycledNumbers { public static void main(String[] args) throws Exception { // Scanner in = new Scanner(System.in); // PrintStream out = System.out; // Scanner in = new Scanner(new File(""C-small.in"")); // PrintStream out = new PrintStream(""C-small.out""); Scanner in = new Scanner(new File(""C-large.in"")); PrintStream out = new PrintStream(""C-large.out""); int T = in.nextInt(); for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); TreeSet set = new TreeSet(); for (int n = A; n <= B; n++) { String s = Integer.toString(n); for (int j = 0; j <= s.length(); j++) { int m = Integer.parseInt(s.substring(j) + s.substring(0, j)); if (A <= n && n < m && m <= B) { set.add(new pair(n, m)); } } } out.println(""Case #"" + i + "": "" + set.size()); } } static class pair implements Comparable { int a, b; public pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(pair p) { if (a == p.a) return b - p.b; return a - p.a; } } } " B21777,"package com.google.codejam.utils.files; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class ManejoArchivos { private static String path = ""D:\\Proyectos\\Google\\files\\2012\\""; public static int[][] readFile(String name) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path + name))); int arr[][] = new int[Integer.parseInt(br.readLine())][2]; for(int i=0;i set; public static void main(String[] args) { try { /* Reading */ FileInputStream fstream = new FileInputStream(""input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); /* Writing */ FileWriter fw = new FileWriter(new File(""output"")); BufferedWriter bw = new BufferedWriter(fw); String strLine; Integer T = 0; int caseCounter = 0; while ((strLine = br.readLine()) != null) { if (caseCounter == 0) { T = new Integer(strLine); } else { set = new HashSet(); int index =strLine.indexOf(' '); A = new Integer(strLine.substring(0, index).trim()); B = new Integer(strLine.substring(index).trim()); int nbRecycledPairs = 0; for (int i = A; i <= B; i++) { if (!set.contains(i)) { nbRecycledPairs += findRecycled(i); } } String toPrint; if (caseCounter == T) { toPrint = ""Case #"" + caseCounter + "": "" + nbRecycledPairs; } else { toPrint = ""Case #"" + caseCounter + "": "" + nbRecycledPairs + ""\n""; } System.out.print(toPrint); bw.write(toPrint); } caseCounter++; } in.close(); bw.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } static int findRecycled(int n) { String s = Integer.toString(n); int nbRecycled = 0; int nbRecycledPairs = 0; for (int i = 0; i < s.length(); i++) { String t = s.substring(i) + s.substring(0, i); if (t.charAt(0) != '0' && isInSet(t) && !t.equals(s) && !set.contains(new Integer(t))) { set.add(new Integer(t)); nbRecycled++; } } if (nbRecycled != 0) { nbRecycled++; } nbRecycledPairs = nbRecycled * (nbRecycled - 1) / 2; return nbRecycledPairs; } static boolean isInSet(String n) { int i = new Integer(n); if (i >= A && i <= B) { return true; } return false; } } " B21312,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycle.number; import dancing.gogglers.Googlers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; /** * * @author Raveesh */ public class Recycler { public static void main(String[] args) throws FileNotFoundException, IOException { String filePath = ""C:\\Users\\Raveesh\\Downloads\\C-large.in""; String filePathOutput = filePath + ""_out""; BufferedReader stdin = new BufferedReader(new FileReader(new File(filePath))); FileWriter fileWriter = new FileWriter(filePathOutput); ArrayList stringList = Recycler.getInputList(stdin); int count = 1; Iterator iter = stringList.iterator(); while (iter.hasNext()) { String inputStr = (String) iter.next(); String[] inputStrArr = inputStr.split(""\\ ""); int startNum = Integer.valueOf(inputStrArr[0]); int endNum = Integer.valueOf(inputStrArr[1]); int output = Recycler.performPerm(startNum,endNum); String out = ""Case #"" + count + "": "" + output; fileWriter.write(out); fileWriter.write(""\n""); count++; } fileWriter.close(); } private static int performPerm(int start,int end ) { finalSet = new ArrayList(); inputSet = new HashSet(); for (int i=start;i<=end;i++) { // System.out.println(""Running"" + i); StringBuffer val = new StringBuffer(String.valueOf(i)); // System.out.println(""Running"" + val); checkVal(start, end, val); } // Iterator iter = finalSet.iterator(); // while (iter.hasNext()) { // System.out.println(""Val "" + iter.ne); // } // System.out.println(""=========================COUNT "" + finalSet.size()/2); return finalSet.size()/2; } private static ArrayList finalSet = new ArrayList(); private static HashSet inputSet = new HashSet(); private static boolean checkVal (int start,int end, StringBuffer val) { for (int i =0;i< val.length() ; i++) { String temp = val.substring(0,i+1); String rem = val.substring(i+1,val.length()); String val1 = rem + temp; // System.out.println(""temp"" + temp + "" rem : "" + rem); // for (int j = 0;j <= rem.length() ; j++) { // StringBuffer val1 = new StringBuffer(rem); // if (j==i) { // continue; // // } // val1.insert(j, temp); // System.out.println(""iNPUT :; "" + val + "" :: Output : "" + val1); // System.out.println(""iNPUT :; "" + val + "" :: Output : "" + val1); int t = Integer.valueOf(val1.toString()); if (t >= start && t <= end && !val.toString().equals(val1.toString())) { // System.out.println(""iNPUT :; "" + val + "" :: Output : "" + val1 + "" t :: "" + t ); if (inputSet.add(val + "","" + val1)) { finalSet.add(t); } //// System.out.println(""dding :: "" + t); // String key = val.toString() + "","" + val1.toString(); // String key1 = val1.toString() + "","" + val.toString(); // if(!(finalSet.containsKey(key)|| finalSet.containsKey(key1))) { // finalSet.put(key, t); // } //// finalSet.put(Integer.valueOf(val1.toString())); // } // System.out.println(""num :: "" + val1); } } return true; } private static ArrayList getInputList(BufferedReader stdin) throws IOException { ArrayList stringList = new ArrayList(); String line; int inputLineCount = 0; Integer testCaseCount = 0; while ((line = stdin.readLine()) != null && line.length() != 0 && inputLineCount <= testCaseCount.intValue()) { // System.out.println(""line :: "" + line); if (inputLineCount == 0) { try { testCaseCount = Integer.valueOf(line); } catch (NumberFormatException pe) { System.out.println(""Invalid input for # of test cases""); System.exit(0); } inputLineCount++; continue; } stringList.add(line); inputLineCount++; if (inputLineCount == testCaseCount + 1) { break; } } return stringList; } } " B20533,"//import java.io.*; import java.util.*; public class ProblemC { public static void main(String[] args) { /* try { System.setIn(new FileInputStream(""c-example.in"")); } catch (Exception e) {} */ new ProblemC(); } public ProblemC() { Scanner input = new Scanner(System.in); int cases = input.nextInt(); for (int n = 0; n < cases; n++) { int lower = input.nextInt(); int upper = input.nextInt(); System.out.println(""Case #"" + (n+1) + "": "" + findPairs(lower, upper)); } } private int findPairs(int lower, int upper) { List pairs = new ArrayList(); for (int i = lower; i <= upper; i++) { List p = recycle(i); for (int j : p) { if (j >= i && j <= upper) { pairs.add(j); //System.out.println(i + "", "" + j); } } } return pairs.size(); } private List recycle(int n) { List p = new ArrayList(); int m = n; int len = Integer.toString(n).length(); int mult = (int)Math.pow(10, len - 1); for (int i = 0; i < len; i++) { int d = m % 10; m /= 10; m += (d * mult); if (m != n && len == Integer.toString(m).length() && !p.contains(m)) { p.add(m); } } return p; } } " B21857,"import java.util.Scanner; import jp.ne.sakura.yuki2006.CodeJam.CodeJam; import jp.ne.sakura.yuki2006.CodeJam.ITestCase; /** * */ /** * @author yuki * */ public class RecycledNumbers implements ITestCase { /** * @param args */ public static void main(String[] args) { new CodeJam(new RecycledNumbers(), ""Cout.txt""); } /* * (非 Javadoc) * * @see jp.ne.sakura.yuki2006.CodeJam.ITestCase#testCase(java.util.Scanner) */ @Override public String testCase(Scanner stdIn) { int A = stdIn.nextInt(); int B = stdIn.nextInt(); int totalCount = 0; for (int i = A; i <= B; i++) { int length = String.valueOf(i).length(); for (int j = 0; j < length; j++) { int radix = (int) (Math.pow(10, j)); int top = i / radix; int other = i % radix; Integer rn = Integer.parseInt(String.valueOf(other) + String.valueOf(top)); if (rn<=B && i < rn) { System.err.println(i); System.err.println(rn); System.err.println(); totalCount++; } } } return totalCount + """"; } } " B20973,"/* Author: Gaurav Gupta Date: 14 Apr 2012 */ import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Recycled { /** * TODO Put here a description of what this method does. * * @param args */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub. FileWriter fw = new FileWriter(""Output3.txt""); PrintWriter pw = new PrintWriter(fw); Scanner sc = new Scanner(System.in); int T = sc.nextInt(); int sum = 0; int A, B; for (int i = 0; i < T; i++) { A = sc.nextInt(); B = sc.nextInt(); sum = 0; for (int j = A; j <= B; j++) { int n = j; int m; String ns = String.valueOf(n); String ms; int count = 0; int found = 0; int rep[] = new int[ns.length()]; for (int k = 0; k < ns.length(); k++) { ms = ns.substring(k, ns.length()) + ns.substring(0, k); m = Integer.parseInt(ms); if (m > n && m >= A && m <= B) { found = 0; for (int l = 0; l < count; l++) if (rep[l] == m) { found = 1; } if (found == 0) { rep[count] = m; count++; sum++; // System.out.println(n + "" "" + m); } } } } pw.println(""Case #"" + (i + 1) + "": "" + sum); System.out.println(""Case #"" + (i + 1) + "": "" + sum); } pw.close(); } } " B21374,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googleJamCode2; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.*; /** * * @author gollum1er */ public class Permutation { private String chemin = ""C:\\Users\\gollum1er\\Desktop\\""; public Integer moveNDigits(Integer nb, Integer nbDigitsToMove) { String strNb = nb.toString(); String res = strNb.substring(strNb.length() - nbDigitsToMove, strNb.length()) + strNb.substring(0, strNb.length() - nbDigitsToMove); return Integer.parseInt(res); } public List findAllPermutationsWithDigits(Integer nb, Integer nbDigitsToMove, Integer min, Integer max) { List resListTmp = new ArrayList(); Integer tmpRes = this.moveNDigits(nb, nbDigitsToMove); if (tmpRes > nb && tmpRes >= min && tmpRes <= max) { resListTmp.add(tmpRes); } Set set = new HashSet(); set.addAll(resListTmp); ArrayList resList = new ArrayList(set); return resList; } public List findAllPermutations(Integer nb, Integer min, Integer max) { String strNb = nb.toString(); List resListTmp = new ArrayList(); for (int i = 1; i < strNb.length(); i++) { List resListTmp2 = this.findAllPermutationsWithDigits(nb, i, min, max); resListTmp.addAll(resListTmp2); } Set set = new HashSet(); set.addAll(resListTmp); ArrayList resList = new ArrayList(set); return resList; } public Integer findRes(int min, int max) { Integer res = 0; for (int i = min; i < max + 1; i++) { List tmpList = this.findAllPermutations(i, min, max); res += tmpList.size(); } return res; } //lecture pour le fichier de recherche public List readFile(String nFichier) { List res = new ArrayList(); String nomFichier = chemin + nFichier; try { BufferedReader in = new BufferedReader(new FileReader(nomFichier)); String line =in.readLine(); while ((line = in.readLine()) != null) { res.add(line); } in.close(); } catch (Exception e) { e.printStackTrace(); } return res; } //écrit le résultat des trie public void writeFile(List content, String nFichier) { String nomFichier = chemin + nFichier; try { PrintWriter out = new PrintWriter(new FileWriter(nomFichier)); Iterator it = content.iterator(); int cpt = 1; while (it.hasNext()) { String str = (String) it.next(); out.println(""Case #"" + cpt + "": "" +str); cpt++; } out.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String args[]) { Permutation pm = new Permutation(); List inputList = pm.readFile(""C-large.in""); Iterator it = inputList.iterator(); List resList = new ArrayList(); while (it.hasNext()) { String resTmp = (String)it.next(); String str[] = resTmp.split("" ""); Integer res = pm.findRes(Integer.parseInt(str[0]), Integer.parseInt(str[1])); resList.add(Integer.toString(res)); } pm.writeFile(resList, ""toto.txt""); } } " B21708,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class C { static final int MAX_N = 2000000; static int[][] precalc; static { precalc = new int[MAX_N + 1][]; List values = new ArrayList(); for (int i = 1, deg = 1; i <= MAX_N; ++i) { if (i == deg * 10) { deg *= 10; } values.clear(); int curr = (i % 10) * deg + (i / 10); while (curr != i) { if (curr > i) { values.add(curr); } curr = (curr % 10) * deg + (curr / 10); } int[] z = new int[values.size()]; for (int j = 0; j < z.length; ++j) { z[j] = values.get(j); } precalc[i] = z; } } public void run(Scanner in, PrintWriter out, int nCase) { int min = in.nextInt(); int max = in.nextInt(); int count = 0; for (int i = min; i <= max; ++i) { for (int j : precalc[i]) { if (j <= max) { ++count; } } } out.printf(""Case #%d: %d%n"", nCase, count); } public static void main(String[] args) throws FileNotFoundException { String filename = C.class.getSimpleName().toLowerCase(); Scanner in = new Scanner(new File(filename + "".in"")); PrintWriter out = new PrintWriter(filename + "".out""); int nCases = in.nextInt(); for (int i = 1; i <= nCases; ++i) { new C().run(in, out, i); } out.close(); in.close(); } } " B21986,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package numbers; /** * * @author Serban */ public class Numbers { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Input in = new Input(""C-large.in""); } } " B20171,"import java.io.*; class yo { public static void main(String args[]) throws IOException { try { FileWriter fs=new FileWriter(""o1.out""); FileInputStream f1=new FileInputStream(""C-large.in""); DataInputStream d=new DataInputStream(f1); BufferedReader br=new BufferedReader(new InputStreamReader(d)); BufferedWriter out=new BufferedWriter(fs); String s,s1; s=br.readLine(); int T=Integer.parseInt(s); int cnt=0,nn,f,ll,ul,p; String w1; char temp; for(int i=0;i0;l--) { c[l]=c[l-1]; } c[0]=temp; w1=""""; for(int m=0;mll) if(nn>f) if(nn<=ul) cnt=cnt+1; } f=f+1; } String h=Integer.toString(cnt); out.write(h); out.write(""\r\n""); cnt=0; } out.close(); br.close(); } catch(Exception e){ System.out.println(""Error :""+e); } } }" B20234,"package C; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class C { private ArrayList shift1 = new ArrayList(2000000); private ArrayList shift2 = new ArrayList(2000000); private ArrayList shift3 = new ArrayList(2000000); private ArrayList shift4 = new ArrayList(2000000); private ArrayList shift5 = new ArrayList(2000000); private ArrayList shift6 = new ArrayList(2000000); public static void main(String[] args) { C c = new C(); c.run(args[0], ""result""); } public C() { for (int i = 0; i < 2000000; i++) { if (i > 9) { if (i > 999999) { shift1.add(i % 1000000 * 10 + i / 1000000); } else if (i > 99999) { shift1.add(i % 100000 * 10 + i / 100000); } else if (i > 9999) { shift1.add(i % 10000 * 10 + i / 10000); } else if (i > 999) { shift1.add(i % 1000 * 10 + i / 1000); } else if (i > 99) { shift1.add(i % 100 * 10 + i / 100); } else { shift1.add(i % 10 * 10 + i / 10); } } else { shift1.add(9999999); } } for (int i = 0; i < 2000000; i++) { if (i > 99) { if (i > 999999) { shift2.add(i % 100000 * 100 + i / 100000); } else if (i > 99999) { shift2.add(i % 10000 * 100 + i / 10000); } else if (i > 9999) { shift2.add(i % 1000 * 100 + i / 1000); } else if (i > 999) { shift2.add(i % 100 * 100 + i / 100); } else { shift2.add(i % 10 * 100 + i / 10); } } else { shift2.add(9999999); } } for (int i = 0; i < 2000000; i++) { if (i > 999) { if (i > 999999) { shift3.add(i % 10000 * 1000 + i / 10000); } else if (i > 99999) { shift3.add(i % 1000 * 1000 + i / 1000); } else if (i > 9999) { shift3.add(i % 100 * 1000 + i / 100); } else { shift3.add(i % 10 * 1000 + i / 10); } } else { shift3.add(9999999); } } for (int i = 0; i < 2000000; i++) { if (i > 9999) { if (i > 999999) { shift4.add(i % 1000 * 10000 + i / 1000); } else if (i > 99999) { shift4.add(i % 100 * 10000 + i / 100); } else { shift4.add(i % 10 * 10000 + i / 10); } } else { shift4.add(9999999); } } for (int i = 0; i < 2000000; i++) { if (i > 99999) { if (i > 999999) { shift5.add(i % 100 * 100000 + i / 100); } else { shift5.add(i % 10 * 100000 + i / 10); } } else { shift5.add(9999999); } } for (int i = 0; i < 2000000; i++) { if (i > 999999) { shift6.add(i % 10 * 1000000 + i / 10); } else { shift6.add(9999999); } } } public void run(String inputFile, String outputFile) { FileReader fileReader = null; BufferedReader bufferedReader = null; String directory = this.getClass().getResource("""").getPath() + ""\\""; inputFile = directory + inputFile; outputFile = directory + outputFile; try { fileReader = new FileReader(inputFile); bufferedReader = new BufferedReader(fileReader); } catch (Exception e) { e.printStackTrace(); return; } if (bufferedReader != null) { int testCount = 0; try { testCount = Integer.parseInt(bufferedReader.readLine()); } catch (Exception e) { e.printStackTrace(); return; } StringBuilder builder = new StringBuilder(3400); for (int i = 1; i <= testCount; i++) { if (i > 1) { builder.append(""\r\n""); } builder.append(""Case #""); builder.append(i); builder.append("": ""); String input = null; try { input = bufferedReader.readLine(); } catch (Exception e) { e.printStackTrace(); return; } int count = 0; if (input != null) { String[] strs = input.split("" ""); int start = 0; int end = 0; try { start = Integer.parseInt(strs[0]); end = Integer.parseInt(strs[1]); System.out.print(start); System.out.print(' '); System.out.println(end); } catch (Exception e) { e.printStackTrace(); break; } for (int j = start; j < end; j++) { int test1 = shift1.get(j); int test2 = shift2.get(j); int test3 = shift3.get(j); int test4 = shift4.get(j); int test5 = shift5.get(j); int test6 = shift6.get(j); if (test1 > j && test1 <= end) { count++; } else { test1 = 0; } if (test2 > j && test2 <= end && test1 != test2) { count++; } else { test2 = 0; } if (test3 > j && test3 <= end && test1 != test3 && test2 != test3) { count++; } else { test3 = 0; } if (test4 > j && test4 <= end && test1 != test4 && test2 != test4 && test3 != test4) { count++; } else { test4 = 0; } if (test5 > j && test5 <= end && test1 != test5 && test2 != test5 && test3 != test5 && test4 != test5) { count++; } else { test5 = 0; } if (test6 > j && test6 <= end && test1 != test6 && test2 != test6 && test3 != test6 && test4 != test6 && test5 != test6) { count++; } } } builder.append(count); } //System.out.println(builder.toString()); try { FileWriter writer = new FileWriter(outputFile); writer.append(builder.toString()); writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); return; } try { bufferedReader.close(); fileReader.close(); } catch (Exception e) { e.printStackTrace(); } } } }" B21482,"import java.io.*; import java.util.*; public class Pilot { int Globe_k = 0; int max_units = 30; public static void main(String[] args) { Pilot my = new Pilot(); Calendar cal1 = Calendar.getInstance(); my.doAll(); Calendar cal2 = Calendar.getInstance(); // System.out.println(""seconds : "" + (cal2.getTimeInMillis() - // cal1.getTimeInMillis())/1000); } private static void doME(Vector combination) { System.out.println(combination.toString()); } public void doAll() { try { String out = """"; FileInputStream fstream = new FileInputStream(""in.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = """"; int glob = Integer.parseInt(strLine = br.readLine()); for (int j = 0; j < glob; j++) { Hashtable> H = new Hashtable>(); // Vector> results = new // Vector>(); strLine = br.readLine(); String[] splitted = strLine.split("" ""); int A = Integer.parseInt(splitted[0]); int B = Integer.parseInt(splitted[1]); int num = 0; for (int k = A; k <= B; k++) { int L = Integer.toString(k).length(); int e = L - 1; int C = k; Integer[][] T = new Integer[L][2]; for (int i = 0; i < L; i++) { T[i][0] = (C % 10); C /= 10; T[i][1] = i; } for (int i = 0; i < e; i++) { for (int q = 0; q < L; q++) { T[q][1] = (q + e - i) % L; } // for (int u = 0; u < L; u++) // System.out.println(T[u][0] + "" "" + T[u][1]); int n = k; int m = 0; for (int q = 0; q < L; q++) m += T[q][0] * (int) Math.pow(10, T[q][1]); if (A <= n && n < m && m <= B) { if (H.containsKey(m)) { if (!H.get(m).contains(n)) { //System.out.println(m + "" "" + H.get(m).toString()); H.get(m).add(n); num++; }//else //System.out.println(""---""); } else{ Vector now = new Vector(); now.add(n); H.put(m, now); num++; } } // System.out.println(""---""); } } out += (""Case #"" + (j + 1) + "": "" + num + ""\n""); } in.close(); out = out.trim(); Writer output = null; File file = new File(""out.out""); output = new BufferedWriter(new FileWriter(file)); output.write(out); output.close(); System.out.print(out); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } } " B20053," package codejam; import java.io.*; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class C { static String str = ""C:\\carl\\cl.txt""; static String text = """"; static int A, B, T, cnt; static HashMap hm; public static void main(String[] args) { try { int count = 0; hm = new HashMap(); File file = new File(str); BufferedReader br = new BufferedReader(new FileReader(file)); PrintWriter outer = new PrintWriter(new FileWriter(""C:\\carl\\clo.txt"")); while((text = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(text); if(count == 0) { T = Integer.parseInt(st.nextToken()); count++; } else { A = Integer.parseInt(st.nextToken()); int n = A; B = Integer.parseInt(st.nextToken()); while (n != B) { char[] temp = Integer.toString(n).toCharArray(); scramble(temp, n); n++; } outer.println(""Case #"" + count + "": "" + hm.entrySet().size()); //System.out.println(hm.entrySet().size()); hm.clear(); count++; } } outer.close(); } catch(IOException ex) { System.out.println(""Error with IO you foooool""); } catch(Exception ex) { System.out.println(""Generic Error. Noob.""); ex.printStackTrace(); } } public static void scramble(char[] temp, int n) { Integer[] no = new Integer[temp.length]; for(int i=0; i map = new HashMap(); int total = 0; int D = (""""+N).length() -1; int divisor = (int) Math.round(Math.pow(10, D)); for (int i = N; i <= M; i++){ int rotation = i; int minimum = i; for (int j = 0; j < D; j++){ int msd = rotation/divisor; rotation = (rotation - divisor*msd)*10 + msd; if (rotation < minimum){ // if (accepted == 1){System.out.print(""\n@@@@@@@@@@\n""+i + "" "");} // System.out.print(rotation+"" ""); minimum = rotation; } } Integer previous = map.put(minimum, 1); if (previous != null){ map.put(minimum, (previous + 1)); } } for (Integer i : map.values()){ total += (i*(i-1))/2; } return total; } public static void main(String[] args) throws FileNotFoundException, IOException{ String dir = ""C:/Users/ale/Desktop/GoogleCodeJam/""; String[] files = new File(dir).list(); int[][] instances = parseInput(dir+files[0]); //parseInput(""C:/Users/ale/Desktop/GoogleCodeJam/C-small-attempt0.in""); PrintStream writer = new PrintStream(new File(""C:/Users/ale/workspace/GoogleCodeJam/src/output.out"")); for (int i = 0; i < instances.length; i++){ int sol = solveInstance(instances[i][0], instances[i][1]); writer.println(""Case #""+(i+1)+"": ""+sol); } writer.close(); } } " B20540," import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; public class Processor { public void process(TestCaseFactory factory, String filenameIn, String filenameOut) throws IOException, MalformedInputFileException { System.out.println(""Started!""); final Reader in = new FileReader(filenameIn); final BufferedReader br = new BufferedReader(in); final PrintWriter out = new PrintWriter(new File(filenameOut)); final String str1 = br.readLine(); final int ncases = Integer.parseInt(str1); for (int i = 0; i < ncases; i++) { final TestCase item = factory.getInstance(i); item.readInput(br); item.solve(); item.writeOutput(out); } in.close(); out.close(); System.out.println(""Finished!""); } }" B20095,"package codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class Recycled { /** * @param args */ private boolean[] b; private int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 }; private String in, temp; private int count = 0; private int total = 0; private char[] c; public int getMaxRecycle(int min, int max) { b = new boolean[max + 1 - min]; count = 0; total = 0; for (int i = min; i <= max; i++) { if (!b[i - min]) { b[i - min] = true; total++; in = """" + i; c = in.toCharArray(); StringBuilder sb = new StringBuilder(in); total = c.length; for (int j = 0; j < c.length - 1; j++) { sb.append(c[j]); if (c[j + 1] != '0') { temp = sb.substring(j + 1); if (!temp.equals(in)) { int pos = Integer.parseInt(temp); if (pos <= max && pos >= min && !b[pos - min]) { b[pos - min] = true; } else { total--; } } else { total--; } } else { total--; } } if (total >= 2) { count += (factorial[total] / (2 * factorial[total - 2])); } } } return count; } // Input // 4 // 1 9 // 10 40 // 100 500 // 1111 2222 // // Output // Case #1: 0 // Case #2: 3 // Case #3: 156 // Case #4: 287 public static void main(String[] args) { Recycled r = new Recycled(); long start = System.currentTimeMillis(); try { FileInputStream fstream = new FileInputStream(""C-large.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fwriter = new FileWriter(""C-large.out""); BufferedWriter out = new BufferedWriter(fwriter); String strLine; strLine = br.readLine(); int testCases = Integer.parseInt(strLine); int currentCase = 0; String[] input; int min, max, temp; while ((strLine = br.readLine()) != null && currentCase < testCases) { input = strLine.split("" ""); min = Integer.parseInt(input[0]); max = Integer.parseInt(input[1]); if (min > max) { temp = min; min = max; max = temp; } out.write(""Case #"" + ++currentCase + "": "" + r.getMaxRecycle(min, max)); out.newLine(); } System.out.println(""Time is: "" + (System.currentTimeMillis() - start) * 10E-3 + "" Sec.""); in.close(); out.close(); } catch (Exception e) { System.err.println(""I/O Error while reading file.""); } } } " B21815,"import java.io.IOException; import java.util.List; public class StoreCredit extends JamProblem { public static void main(String[] args) throws IOException { StoreCredit problem= new StoreCredit(); problem.go(); } @Override String solveCase(JamCase jamCase) { StoreCreditCase cas = (StoreCreditCase) jamCase; for (int i=0; i file, int line) { StoreCreditCase cas = new StoreCreditCase(); String fist = file.get(line); String second = file.get(line+1); String third = file.get(line+2); cas.credit= Integer.parseInt(fist); cas.lineCount = 3; cas.itemCount = Integer.parseInt(second); cas.prices = JamUtil.parseIntList(third, cas.itemCount); return cas; } } class StoreCreditCase extends JamCase { int itemCount; int[] prices; public int credit; } " B21222," public class RecycledPair { private int lower; private int higher; RecycledPair() { lower = 0; higher = 0; } RecycledPair(RecycledPair other) { lower = other.lower; higher = other.higher; } public void set(int left, int right) { this.lower = Math.min(left, right); this.higher = Math.max(left, right); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + lower; result = prime * result + higher; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RecycledPair other = (RecycledPair) obj; if (lower != other.lower) return false; if (higher != other.higher) return false; return true; } } " B21220,"public class CodeJamUtils { /** * Makes sure that the line separator written by BufferedWriter is a single * newline character */ public static void initLineEndings() { System.setProperty(""line.separator"", ""\n""); } } " B21867,"import java.io.FileInputStream; import java.util.*; import java.math.*; public class Main { static int[] toDigits(int val) { int count = 1; int temp = val / 10; while (temp > 0) { count++; temp /= 10; } int[] arr = new int[count]; temp = val; for (int i = 0; i < arr.length; i++) { arr[i] = temp % 10; temp /= 10; } return arr; } static int toInt(int[] digits) { int res = 0; int p = 1; for (int i = 0; i < digits.length; i++) { res += p * digits[i]; p *= 10; } return res; } public static void main(String[] args) throws Exception{ Scanner scan = new Scanner(System.in); //Scanner scan = new Scanner(new FileInputStream(""C:\\Users\\wd\\Desktop\\"")); char[] map = ""yhesocvxduiglbkrztnwjpfmaq"".toCharArray(); int taskCount = scan.nextInt(); scan.nextLine(); for (int taskIndex = 1; taskIndex <= taskCount; taskIndex++) { int A = scan.nextInt(); int B = scan.nextInt(); long result = 0; for (int i = A; i <= B; i++) { HashSet checker = new HashSet(); int[] base = toDigits(i); int[] copy = new int[base.length]; for (int j = 0; j < base.length; j++) { int index = base.length - 1; for (int k = j; k >= 0; k--) { copy[index--] = base[k]; } for (int k = base.length - 1; k > j; k--) { copy[index--] = base[k]; } int convert = toInt(copy); if (convert <= i || convert > B || checker.contains(convert)) { continue; } //System.out.println(i + "" "" + convert); checker.add(convert); result++; } } System.out.println(""Case #"" + taskIndex + "": "" + result); } } }" B22256,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class recycle { static int lim,start; static HashMap> set ; /** * @param args */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new FileReader(""problem.in"")); int t = Integer.parseInt(br.readLine()); for (int i = 1; i <= t; i++) { set = new HashMap>(); String line = br.readLine(); String val1 = line.split("" "")[0]; String val2 = line.split("" "")[1]; if (val1.length() == 1) { System.out.println(""Case #"" + i + "": 0""); continue; } int v1 = Integer.parseInt(val1); int v2 = Integer.parseInt(val2); start = v1; lim = v2; int count = 0; for (int j = v1; j <= v2; j++) { recycle(j); } Set key = set.keySet(); Iterator k = key.iterator(); int c = 0; while (k.hasNext()) { String ne = (String)k.next(); c+= set.get(ne).size(); } System.out.println(""Case #"" + i + "": "" + c); } } public static void recycle(Integer i) { String s = i.toString(); boolean flag = false; for (int j = s.length() - 1; j > 0; j--) { String temp = """"; temp += s.substring(j); temp += s.substring(0,j); if (temp.equals(s) == false && Integer.parseInt(temp) < lim && Integer.parseInt(temp) > start) { Integer lesser = Math.min(Integer.parseInt(s), Integer.parseInt(temp)); Integer greatr = Math.max(Integer.parseInt(s), Integer.parseInt(temp)); if (set.containsKey(lesser.toString()) == false) { HashSet n = new HashSet(); n.add(greatr.toString()); set.put(lesser.toString(), n); } else { HashSet n = set.get((String)lesser.toString()); n.add(greatr.toString()); set.put(lesser.toString(),n); } } } } } " B21814,"import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; public class MinimumScalar extends JamProblem { public static void main(String[] args) throws IOException { MinimumScalar p = new MinimumScalar(); p.go(); } @Override String solveCase(JamCase jamCase) { MSCase c= (MSCase) jamCase; Arrays.sort(c.a); Arrays.sort(c.b); BigDecimal b = new BigDecimal(0); for (int i=0; i< c.lengh; i++) { BigDecimal aaa = new BigDecimal(c.a[i]); BigDecimal bbb = new BigDecimal(c.b[c.lengh - i - 1]); b = b.add(aaa.multiply(bbb)); } return """" + b; } @Override JamCase parseCase(List file, int line) { MSCase c= new MSCase(); c.lineCount=3; int i = line; c.lengh = Integer.parseInt(file.get(i++)); c.a = JamUtil.parseIntList(file.get(i++),c.lengh); c.b = JamUtil.parseIntList(file.get(i++),c.lengh); return c; } } class MSCase extends JamCase { int lengh; int[] a; int[] b; } " B21530,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { public static void main(String[] args) { List lines = getline(""C:\\Users\\Ami\\Downloads\\C-large.in""); System.out.println(""number of TestCases-->>"" + lines.remove(0)); Process(lines); } private static void Process(List lines) { int i = 1; for (String line : lines) { int k = 0; String[] nums = line.split("" ""); long A = Long.valueOf(nums[0]); long B = Long.valueOf(nums[1]); for (long j = A; j < B; j++) { String j2 = """" + j; for (int x = 1; x <=j2.length(); x++) { long num = Long.parseLong(j2.substring(x) + j2.substring(0, x)); if (num > j && num <= B){ k++; //System.out.println(j2+"" : ""+num); } } } System.out.println(""Case #"" + i + "": "" + k); i++; } } private static List getline(String path) { List ls = new ArrayList(); try { FileInputStream fstream = new FileInputStream(path); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { ls.add(strLine); } in.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } return ls; } } " B21493,"//package RecycleNumber; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class C { public static HashSet hm = new HashSet(); public static void main(String [] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(in.readLine()); int count = 1; rotate(1234,10,2222); while(num-- != 0){ String [] token = in.readLine().split("" ""); int num1 = Integer.parseInt(token[0]); int num2 = Integer.parseInt(token[1]); for(int i = num1; i <= num2; i++){ rotate(i,num1,num2); } System.out.println(""Case #""+ count++ +"": "" +hm.size()); hm.clear(); } } public static void rotate(int current, int num1, int num2){ int times = (current+"""").length()-1; int check = current; String temp = current+""""; while(times >= 0 ){ temp = temp.charAt(temp.length()-1) + temp.substring(0,temp.length()-1); times--; if(Integer.parseInt(temp) > num1 && Integer.parseInt(temp) <= num2 && Integer.parseInt(temp) > check){ hm.add(check +"": ""+temp); //System.out.println(check + "": "" + temp); } } } } " B20912,"import java.io.File; import java.io.PrintWriter; import java.util.HashMap; import java.util.Scanner; public class C { public static void main(String[] args) { try { Scanner reader = new Scanner(new File(""c:\\codejam\\Csmall.txt"")); PrintWriter writer = new PrintWriter(new File(""c:\\codejam\\Csmallout"")); int numCases = Integer.parseInt(reader.next()); for(int caseNum=0;caseNum candidates = new HashMap(); new C().getCandidates(current,numLen,candidates); for(Integer key : candidates.keySet()) { int value = candidates.get(key); if(current getCandidates(int current, int length, HashMap candidates) { String numStr = String.valueOf(current); Integer value; for(int loop=1;loop= a && i2 <= b && i < i2) { nbOk++; } } } sb.append(nbOk); } private static int shift(int i, int nbDigits) { String s = String.valueOf(i); while (s.length() < nbDigits) { s = ""0"" + s; } return Integer.valueOf(s.charAt(s.length() - 1) + s.substring(0, s.length() - 1)); } // DONT TOUCH THIS public static void main(String[] args) throws Exception { run(); } } " B21520,"import java.io.*; import java.util.*; public class Solution { private StringTokenizer st; private BufferedReader in; private PrintWriter out; final String file = ""C-large""; public void solve() throws IOException { int tests = nextInt(); int[] pows10 = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; for (int test = 0; test < tests; ++test) { int a = nextInt(); int b = nextInt(); int[] o = new int[6]; int pow10 = 0; int ans = 0; for (int i = a; i <= b; ++i) { int c = 0; while (pows10[pow10] <= i) { ++pow10; } for (int sh = 1; sh < pow10; ++sh) { int val = i / pows10[sh] + (i % pows10[sh]) * pows10[pow10 - sh]; if (i < val && val <= b) { o[c++] = val; } } Arrays.sort(o, 0, c); for (int j = 0; j < c; ++j) { if (j == 0 || o[j] != o[j - 1]) { ans++; } } } out.printf(""Case #%d: %d%n"", test + 1, ans); } } public void run() throws IOException { in = new BufferedReader(new FileReader(file + "".in"")); out = new PrintWriter(file + "".out""); eat(""""); solve(); out.close(); } void eat(String s) { st = new StringTokenizer(s); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Solution().run(); } }" B20004,"package qualification; import java.util.HashMap; import java.util.Scanner; public class RecycledNumbers { //recycled numbers between A and B //OK, the key is being able to reduce each number to a single comparable value instead of comparing every possible match. //Let's say: We will take the permutation that has the smallest value. //creating them may be slow as long as looking them up is fast. //[not needed] Cache values to improve performance // perf test - worst possible case was solved in seconds. //we've only given 50 cases at most. //[DONE] what if more than two match? does that make 3 distinct recycled pairs? public static void main(final String[] args) { new RecycledNumbers().start(); } private void start() { final Scanner s = new Scanner(System.in); final int numTests = s.nextInt(); for (int i = 0; i < numTests; i++) { // deb(""Case "" + (i + 1) + ""---------""); final int startNum = s.nextInt(); final int endNum = s.nextInt(); final HashMap values = new HashMap(); int distinctPairsCount = 0; for (int val = startNum; val <= endNum; val++) { final String newValue = findSmallestPermutation(""""+val); if (values.containsKey(newValue)) { final int count = values.get(newValue); distinctPairsCount += count; values.put(newValue, count + 1); // deb(""found a match of "" + count + "", total matches: "" + distinctPairsCount); } else { values.put(newValue, 1); } } System.out.println(""Case #"" + (i+1) + "": "" + distinctPairsCount); } } //We can't compare every permutation to every permutation //so we find the smallest and only use that. //this function looks slow, but it isn't called that often so should be OK. private String findSmallestPermutation(final String value) { int bestValue = Integer.MAX_VALUE; String bestString = null; final String valueTwice = value + value; //We will extract the substrings from this. for (int i = 0; i < value.length(); i++) { final String permutation = valueTwice.substring(i, value.length() + i); final int permutationValue = Integer.parseInt(permutation); if (permutationValue < bestValue) { bestValue = permutationValue; bestString = permutation; } } // deb(""source: "" + value +"", adding "" + bestString); return bestString; } // private void deb(final Object o) { // System.out.println(o.toString()); // } } " B22088,"import java.io.*; import java.util.*; public class RecycledNumbers { String shift(String a) { return a.substring(1) + a.charAt(0); } void solve() throws Exception { int a = nextInt(); int b = nextInt(); int length = (b + """").length(); Set set = new HashSet(); int ans = 0, eq = 0; for (int i = a; i <= b; i++) { String s = i + """"; set.clear(); for (int j = 0; j < length; j++) { int t = Integer.parseInt(s); if (t >= a && t <= b && t != i) { set.add(t); } s = shift(s); } ans += set.size(); } out.println(ans / 2); } void run() { try { in = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(""output.txt""); int tests = nextInt(); for (int i = 0; i < tests; i++) { out.print(""Case #"" + (i + 1) + "": ""); solve(); System.err.println(""test "" + (i + 1)); } out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } BufferedReader in; StringTokenizer st; PrintWriter out; final String filename = new String(""RecycledNumbers"").toLowerCase(); String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(nextToken()); } long nextLong() throws Exception { return Long.parseLong(nextToken()); } double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } public static void main(String[] args) { new RecycledNumbers().run(); } } " B21363,"import java.util.*; public class CodeJamC { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); for (int i = 1; i <= t; i++) { int n = 0; int a = scan.nextInt(); int b = scan.nextInt(); for (int j = a; j <= b; j++) { int x = j; int m = 1; while (true) { x = rotate(x); if (x == j) { // Cycled n += m * (m - 1) / 2; break; } else if (a <= x && x <= b) { if (x < j) // Duplicate break; else m++; } } } System.out.printf(""Case #%d: %d%n"", i, n); } } private static int rotate(int x) { String s = x + """"; while (true) { s = s.substring(1) + s.charAt(0); if (s.charAt(0) != '0') return Integer.parseInt(s); } } }" B21166,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.common; /** * * @author jim */ public interface Processor { public String processLine(String line); } " B21101,"package recyclednumbers; import java.util.ArrayList; public class RecycledNumbers { static SimpleReader reader; static SimpleWriter writer; static int low; static int high; public static void main(String[] args) { if (args.length != 1) { reader = new SimpleReader(); writer = new SimpleWriter(); } else { reader = new SimpleReader(args[0]); writer = new SimpleWriter(args[1]); } int cases = reader.readInt(); int[] lohi; for (int i = 0; i < cases; i++) { lohi = reader.readIntArray(); low = lohi[0]; high = lohi[1]; solve(i + 1); System.out.println(""Case "" + (i + 1) + "" done""); } writer.flush(); System.out.println(""Done""); } private static void solve(int caseNo) { int ans = 0; int length = Integer.toString(low).length(); for (int i = low; i <= high; i++) { String s = Integer.toString(i); ArrayList seen = new ArrayList<>(); for (int j = 1; j < length; j++) { int cycle = Integer.parseInt(s.substring(j, length) + s.substring(0, j)); if (!seen.contains(cycle) && cycle <= high && cycle > i) { ans++; //System.out.println(Integer.toString(i) + "" "" + Integer.toString(cycle)); } seen.add(cycle); } } writer.writeLine(""Case #"" + caseNo + "": "" + ans); } private static boolean isRecycled(int n, int m) { String ns = Integer.toString(n); String ms = Integer.toString(m); if (ns.length() != ms.length()) { return false; } for (int i = 1; i < ns.length(); i++) { if (ns.equals(ms.substring(i, ms.length()) + ms.substring(0, i))) { return true; } } return false; } } " B20239,"package sebastianco; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) throws Exception { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(new File(args[0]))); writer = new BufferedWriter(new FileWriter(new File(args[1]))); final int nrOfTestCases = Integer.valueOf(reader.readLine()); String lineSepartor = """"; for (int i = 1; i <= nrOfTestCases; i++) { writer.write(lineSepartor); writer.write(String.format(""Case #%d: %d"", i, new TestCase(reader.readLine()).computePairs())); lineSepartor = ""\n""; } } finally { if (writer != null) { writer.flush(); writer.close(); } reader.close(); } } public static class TestCase { private int a; private int b; public TestCase(String caseLine) { String[] tokens = caseLine.split("" ""); a = Integer.parseInt(tokens[0]); b = Integer.parseInt(tokens[1]); } public int computePairs() { Set distinctPairs = new HashSet(); final String strB = String.valueOf(b); final int maxRotations = strB.length() - 1; int recycledPairs = 0; for (int i = a; i < b; i++) { String strI = String.valueOf(i); // System.out.println(""=="" + strI); StringBuilder number = new StringBuilder(strI); for (int j = 1; j <= maxRotations; j++) { rotate(number); String strNumber = number.toString(); if (strI.compareTo(strNumber) < 0 && strNumber.compareTo(strB) <= 0) { if (distinctPairs.add(strI + strNumber)) { recycledPairs++; // System.out.println(strNumber); } } } } return recycledPairs; } private void rotate(StringBuilder number) { char c = number.charAt(number.length() - 1); for (int i = number.length() - 1; i > 0; i--) { number.setCharAt(i, number.charAt(i-1)); } number.setCharAt(0, c); } } } " B21723,"import java.io.*; import java.util.*; class Recycled { public static void main(String[] args) throws IOException { Scanner s = new Scanner(new File(args[0])); int numTests = s.nextInt(); for (int i = 1; i <= numTests; i++) { // Clear the trailing newline on this line. s.nextLine(); int A = s.nextInt(); int B = s.nextInt(); int L = (""""+A).length()-1; int E = (int)Math.pow(10, L); int count = 0; List seen = new ArrayList(L); for (int j = A; j < B; j++) { int curr = j; for (int k = 0; k < L; k++) { curr = (curr / 10) + (curr % 10) * E; if (curr > j && curr <= B && !seen.contains(curr)) { count++; seen.add(curr); } } seen.clear(); } System.out.println(""Case #"" + i + "": "" + count); } } } " B20439,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class GCJ3 { public static int pow(int num, int p) { int n = 1; while (p > 0) { p--; n *= num; } return n; } public static int exp(int num) { int e = 0; while (num > 0) { e++; num /= 10; } return e; } public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader(new File(""input.txt""))); BufferedWriter bw = new BufferedWriter(new FileWriter(new File(""output.txt""))); String firstLine = br.readLine(); int lineNum = Integer.parseInt(firstLine); for (int i=0; i set = new HashSet(); String line = br.readLine(); String[] segs = line.split("" ""); int a = Integer.parseInt(segs[0]); int b = Integer.parseInt(segs[1]); int result = 0; int exp = exp(a); long off = (long)(b+1); for (int num=a; num num && recycle <= b) { if (set.contains(off*num+recycle)) { } else { set.add(off*num+recycle); result++; } } } } bw.write(""Case #"" + (i+1) + "": "" + result); if (i != (lineNum-1)) bw.newLine(); } bw.flush(); bw.close(); } catch (Exception e) { e.printStackTrace(); } } } " B20144," import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Scanner; public class C { public static HashMap> recycledNumbers = new HashMap>( ); public ArrayList getRecycledNumbers( Integer n, Integer a, Integer b ) { if ( n < 10 || ( n < 100 && n % 10 == 0 ) ) return null; ArrayList aList = recycledNumbers.get( n ); if ( aList == null ) { aList = new ArrayList( ); String s = n.toString( ); int len = s.length( ); for ( int i = 1; i < len; i++ ){ Integer m = new Integer( s.substring( len-i ) + s.substring( 0, len-i) ); if ( m > n && m.toString( ).length( ) == s.length( ) ) { if ( !aList.contains( m ) ) { aList.add( m ); } } } recycledNumbers.put( n, aList ); } return filterRecycledNumbers( aList, a, b ); } public ArrayList filterRecycledNumbers( ArrayList list, Integer a, Integer b ) { ArrayList retList = new ArrayList( ); Iterator iterator =list.iterator( ); while ( iterator.hasNext( ) ) { Integer i = iterator.next( ); if ( ( a <= i && i <= b ) ) { retList.add( i ); } } return retList; } public void solve( Scanner sc, PrintWriter pw ) { int tests = sc.nextInt( ); sc.nextLine( ); for ( int i = 0 ; i < tests; i++ ) { int a = sc.nextInt( ); int b = sc.nextInt( ); ArrayList recycledNumbers = new ArrayList( ); for ( int j = a; j <= b; j++ ) { ArrayList lst = getRecycledNumbers( j, a, b ); if ( lst != null && lst.size( ) > 0 ) { recycledNumbers.addAll( lst ); } } pw.print( ""Case #"" + (i+1) + "": "" + recycledNumbers.size( ) ); pw.println( ); pw.flush( ); } } public static void main ( String[] args ) throws IOException { Scanner sc = new Scanner(new FileReader(""C-large.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""C-large.out"")); new C( ).solve( sc, pw ); pw.close( ); sc.close( ); } }" B20460,"import java.util.*; public class RecycledNumber { int digits; Collection set = new HashSet(); public int countInInterval(int a, int b) { int count = 0, rotation; String temp = """"+ a; this.digits = temp.length(); for(int i = a; ii&&!set.contains(i+"" ""+rotation)){ count++; set.add(i + "" "" + rotation); } } } return count; } private int rotate(int num, int distance) { String temp = """"+num; temp = temp.substring(distance)+temp.substring(0,distance); num = Integer.parseInt(temp); return num; } } " B20534," import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.ObjectInputStream.GetField; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.math.BigInteger; public class C { private static char[] alph; private static String fileIN = ""./A.in""; //archivo de entrada (en el dir local del programita) private static String fileOUT = ""./out.txt""; //salida public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(fileIN)); PrintWriter out = new PrintWriter(new File(fileOUT)); int T = in.nextInt(); for (int i = 0; i < T; i++) { String s = ""Case #"" + (i + 1) + "": "" + new C().solve(in); out.println(s); System.out.println(s); } out.close(); //getCombinaciones(1234); } /** * Retorna la solucion a un caso **/ private String solve(Scanner in) { int min, max = 0; min= in.nextInt(); max= in.nextInt(); int tot = 0; int tot_[] = new int[6]; int prov = 0; for(int i = min; i< max; i++){ for(Integer j: getCombinaciones(i)){ //System.out.println(j); if(j>i) if(isValid(j, min, max)) prov++; } tot_[prov]++; tot+= prov; prov =0; } /* for(int i = 0; i < tot_.length; i++){ tot-= }*/ return String.valueOf(tot); } private boolean isValid(Integer j, int min, int max) { return j<=max && j>=min; } private static List getCombinaciones(int i) { ArrayList l = new ArrayList(); String is = String.valueOf(i); String aux = String.valueOf(i); if(symetric(is)) return l; do{ aux = aux.charAt(aux.length()-1)+ aux.substring(0, aux.length()-1); if(aux.charAt(0)!='0') l.add(Integer.valueOf(aux)); } while(!is.equals(aux)); l.remove(l.size()-1); return l; } private static boolean symetric(String is) { if(is.length() % 2 ==1) return false; else return is.substring(0, is.length()/2).equals(is.substring(is.length()/2 + 1, is.length())); } } " B21821,"import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class C2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); in.nextLine(); //for each test case for (int i = 1; i <= T; i++) { int A = in.nextInt(); int B = in.nextInt(); int result = 0; for (int n = A; n <= B - 1; n++) { String strN = """" + n; int length = strN.length(); List foundNewNums = new LinkedList(); for (int j = 1; j < length; j++) { String newNum = """"; for (int k = 0; k < length; k++) newNum += strN.charAt((j + k) % length); int newNumInt = new Integer(newNum); if (newNumInt > n && newNumInt <= B && !foundNewNums.contains(newNumInt)) { foundNewNums.add(newNumInt); result++; } } } System.out.format(""Case #%d: %d\n"", i, result); } } }" B21939,"package tw.csc.gcj; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; public class Main { /** * @param args */ public static String str1 = ""abcdefghijklmnopqrstuvwxyz""; public static String str2 = ""ynficwlbkuomxsevzpdrjgthaq""; public static void main(String[] args) { try { goC(); } catch (Exception e) { } } public static void goC() throws NumberFormatException, IOException { File fin = new File(""C-large.in""); File fout = new File(""C-large.out""); BufferedReader br = new BufferedReader(new FileReader(fin)); FileOutputStream fos = new FileOutputStream(fout); int c = Integer.parseInt(br.readLine()); String op = """"; for (int i = 0 ; i < c ;i ++ ){ op+=""Case #""+ (i+1)+"": ""; String[] strin = br.readLine().split(""[ ]""); op += test(Integer.parseInt(strin[0]), Integer.parseInt(strin[1])) + ""\n""; } fos.write(op.getBytes()); fos.close(); } public static String test(int a , int b){ String ret = """"; HashSet set = new HashSet(); for (int n = a ; n <=b ; n++){ String strn = String.valueOf(n); for (int i = 1 ; i < strn.length() ; i ++){ String strtest = strn.substring(strn.length() - i, strn.length() ) + strn.substring(0 , strn.length() -i); int m = Integer.parseInt(strtest); if (m > n && m <= b){ set.add(strn+String.valueOf(m)); } } } return ret + set.size(); } public static void goA() throws NumberFormatException, IOException { HashMap map = new HashMap(); for (int i = 0 ; i < str1.length() ; i ++){ map.put(str2.charAt(i), str1.charAt(i)); } File fin = new File(""A-small-attempt1.in""); File fout = new File(""A-small-attempt1.out""); BufferedReader br = new BufferedReader(new FileReader(fin)); FileOutputStream fos = new FileOutputStream(fout); int c = Integer.parseInt(br.readLine()); String op = """"; for (int i = 0 ; i < c ;i ++ ){ op+=""Case #""+ (i+1)+"": ""; String strin = br.readLine(); String strout = """"; for (int k = 0 ;k < strin.length() ;k ++){ if (strin.charAt(k) == ' '){ strout+="" ""; } else{ strout+= map.get(strin.charAt(k)); } } op+=strout+""\n""; } fos.write(op.getBytes()); fos.close(); }; } " B21062,"/* * @author Magix.Lu */ import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNum { public static void main(String[] args) throws IOException { Scanner scanInput = new Scanner(System.in); String target = scanInput.next(); File inputFile = new File(target); Scanner fileScan = new Scanner(inputFile); String outpFileName = ""output.txt""; FileWriter googlewriter = null; googlewriter = new FileWriter(outpFileName); PrintWriter diskFile = new PrintWriter(googlewriter); int count = fileScan.nextInt(); int min = 0; int max = 0; int len = 0; int a = 0; int b = 0; int counter = 0; for (int i = 0; i < count; i++) { min = fileScan.nextInt(); max = fileScan.nextInt(); a = min; len = Integer.toString(a).length(); counter = 0; if (len == 1) { diskFile.print(""Case #"" + (i + 1) + "": "" + counter + ""\n""); System.out.println(counter); } else { while (a <= max) { b = a; String num = Integer.toString(b); for (int j = 0; j < len - 1; j++) { if (len == 2) { String result = Character.toString(num.charAt(1)) + num.charAt(0); num = result; b = Integer.parseInt(result); } else { String front = Character.toString(num.charAt(num .length() - 1)); String behind = num.substring(0, num.length() - 1); String result = front + behind; num = result; b = Integer.parseInt(num); } if (min <= a && a < b && b <= max) { counter++; System.out.println(a + "" "" + b); } } a++; } diskFile.print(""Case #"" + (i + 1) + "": "" + counter + ""\n""); System.out.println(counter); } } diskFile.close(); } } " B20838,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; public class Recycled { private static String FileNameFrom = """"; private static String FileNameTo = """"; /** * @param args */ private int calculate(int n, int m){ HashSet pairsTest = null; int totalPairs = 0; String n_Str = null; int n_Length = 0; for(int i_n = n; i_n < m; i_n++){ n_Str = String.valueOf(i_n); //System.out.println(n_Str); n_Length = n_Str.length(); int afterShift = 0; pairsTest = new HashSet(); for(int move_n = 1; move_ni_n)&&(afterShift <= m)){ if(!pairsTest.contains(i_n + "" "" + afterShift)){ pairsTest.add(i_n + "" "" + afterShift); totalPairs = totalPairs + 1; } else{ //System.out.println(i_n + "" "" + afterShift); } } } pairsTest = null; } return totalPairs; } private int getShifted(int n,int moveToLast){ StringBuffer n_SB = new StringBuffer(); char[] moveThisPart = new char[moveToLast]; n_SB.append(n); n_SB.getChars(0, moveToLast, moveThisPart, 0); n_SB.delete(0, moveToLast); n_SB.append(moveThisPart); return Integer.valueOf(n_SB.toString()); } public static void main(String[] args) { // TODO Auto-generated method stub Recycled rec = new Recycled(); rec.loadPropertiesFile(""recycle""); int testCaseNumber = 0; BufferedReader input = null; BufferedWriter bufferedWriter = null; String line = null; try { input = new BufferedReader(new FileReader(FileNameFrom)); bufferedWriter = new BufferedWriter(new FileWriter(FileNameTo)); line = input.readLine(); testCaseNumber = Integer.parseInt(line); for(int k =0;k 0; j--) { // Substring goes from start to end - 1, hence need to add 1 // as 'magnitude' already has 1 subtracted from it. str_n = str_m.substring(j, magnitude + 1) + str_m.substring(0, j); n = Integer.parseInt(str_n); if ((n > m) && (n <= B)) { // If m is of even length and first half matches second half // two duplicate entries can be generated, so subtract 1 from count // ie. xyz|xyZ => Zxyz|xy or z|xyZxy if (!alreadySubtractedOne && (((m % halfPower) * halfPower) == (m - (m % halfPower)))) { alreadySubtractedOne = true; pairs--; } pairs++; } } } return pairs; } } " B20466,"package qual; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class C { static long count(int n , int B){ String s = String.valueOf(n); Set set = new TreeSet(); for(int i = 1 ; i < s.length() ; ++i){ String rot = s.substring(i) + s.substring(0, i); if(rot.charAt(0) == '0')continue; int v = Integer.parseInt(rot); if(n < v && v <= B){ set.add(v); } } return set.size(); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int cn = 1 ; cn <= T ; ++cn){ int A = sc.nextInt(); int B = sc.nextInt(); long ret = 0; for(int n = A ; n <= B ; ++n){ ret += count(n , B); } System.out.printf(""Case #%d: %d\n"", cn , ret); } } } " B21256,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package util; import java.util.ArrayList; import java.util.List; /** * * @author bohmd */ public class Util { public static List getIntList(String listString) { String[] listArray = listString.split("" ""); List list = new ArrayList(); for (String str : listArray) { list.add(Integer.parseInt(str)); } return list; } public static int getInt(String string) { return Integer.parseInt(string); } public static List getLongList(String listString) { String[] listArray = listString.split("" ""); List list = new ArrayList(); for (String str : listArray) { list.add(Long.parseLong(str)); } return list; } } " B21549," import java.io.*; /* * To change this template, choose Tools | Templates and open the template in * the editor. */ /** * Problem C. Recycled Numbers * * @author admin */ public class ProblemC_RecycledNumbers { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(""c:/C-large.in""))); br.readLine(); // Ignore T StringBuilder sb = new StringBuilder(); int row = 1; for (String line = br.readLine(); line != null; line = br.readLine()) { sb.append(""Case #""); sb.append(row); sb.append("": ""); int ret = 0; String[] numbers = line.split("" ""); int A = Integer.parseInt(numbers[0]); int B = Integer.parseInt(numbers[1]); for (int m = A+1; m <= B; m++) { for (int n = A; n < m; n++) { if(recycled(n, m)) { ret++; } } } sb.append(ret); // System.out.println(ret); sb.append('\n'); row++; } File file=new File(""ProblemC_RecycledNumbers.out""); DataOutputStream output=new DataOutputStream(new FileOutputStream(file)); output.write(sb.toString().getBytes()); output.close(); } public static boolean recycled(int n, int m) { String strN = String.valueOf(n); String strM = String.valueOf(m); for(int i=1; i seen = new TreeSet(); for (int test = 0; test < tests; test++) { int result = 0; int A = scan.nextInt(); int B = scan.nextInt(); int s = (""""+A).length(); int Z = 1; for ( int i = 0; i < s; i++) Z *= 10; for ( int n = A; n < B; n++) { seen.clear(); for ( int select = 10; select < Z; select *= 10) { int v = n / select; int w = n % select; int m = (Z/select) * w + v; if ( m > n && m <= B && !seen.contains(m) ) { seen.add(m); // System.out.printf(""pair n = %d m = %d select = %d\n"", n, m, select); result++; } } } String resultStr = String.format(""Case #%d: %d"", test + 1, result); // add answer here System.out.println(resultStr); out.println(resultStr); } out.close(); System.out.println(""*** in file = "" + getInFileName()); System.out.println(""*** out file = "" + getOutFileName()); } } " B21134,"package gcj2012.qual; import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Character.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.math.BigInteger.*; public class C { static final char PROB = C.class.getSimpleName().charAt(0); static final boolean PRAC = false; static final double EPS = 1e-12; static final int INF = 1 << 20; static final int[] di = { -1, 0, 0, 1 }; static final int[] dj = { 0, -1, 1, 0 }; static Scanner sc = new Scanner(System.in); final int A, B; public C() { A = sc.nextInt(); B = sc.nextInt(); } public String solve() { final boolean[] f = new boolean[2000001]; int num = 0; for (int i = A; i > 0; i /= 10) num++; int d = 1; for (int i = 1; i < num; i++) d *= 10; int ans = 0; for (int X = A; X <= B; X++) { for (int i = 0, Y = X; i < num; i++, Y = Y % 10 * d + Y / 10) if (A <= Y && Y < X && !f[Y]) { ans++; f[Y] = true; } for (int i = 0, Y = X; i < num; i++, Y = Y % 10 * d + Y / 10) if (Y < X) f[Y] = false; } return """" + ans; } public static void main(String... args) { large(); int T = Integer.parseInt(sc.nextLine()); for (int t = 1; t <= T; t++) { System.err.printf(""Case #%s%n"", t); System.out.printf(""Case #%s: %s%n"", t, new C().solve()); } System.err.println(""done.""); } public static void small() { String in = PROB + ""-small"" + (PRAC ? ""-practice"" : ""-attempt"" + 0) + "".in""; String out = PROB + ""-small.out""; if (!PRAC) for (int i = 1; new File(PROB + ""-small"" + ""-attempt"" + i + "".in"").exists(); i++) in = PROB + ""-small"" + ""-attempt"" + i + "".in""; try { System.setIn(new BufferedInputStream(new FileInputStream(in))); System.setOut(new PrintStream(out)); } catch (Exception e) { e.printStackTrace(); System.exit(0); } sc = new Scanner(System.in); } public static void large() { String in = PROB + ""-large"" + (PRAC ? ""-practice"" : """") + "".in""; String out = PROB + ""-large.out""; try { System.setIn(new BufferedInputStream(new FileInputStream(in))); System.setOut(new PrintStream(out)); } catch (Exception e) { e.printStackTrace(); System.exit(0); } sc = new Scanner(System.in); } private static void debug(Object... os) { System.err.println(deepToString(os)); } }" B22198,"//input file must be in.txt in this directory //output file will be out.txt import java.io.*; import java.util.*; public class C { public static Scanner in; public static PrintStream out; public static void main(String [] args) throws Throwable { in = new Scanner(new File(""in.txt"")); int cases = in.nextInt(); in.nextLine(); out = new PrintStream(new File(""out.txt"")); for (int i = 1; i <= cases; i++) { out.print(""Case #"" + i + "": ""); printResult(); out.println(); } } public static void printResult() { int a,b; a = in.nextInt(); b = in.nextInt(); int i = a; int firstDigit = 1; int numDigits = 0; while (i > 0) { i /= 10; firstDigit *= 10; numDigits++; } int [] alreadyDone = new int[numDigits]; firstDigit /= 10; int cur,m; int tot = 0; boolean notDone; for (i = a; i < b; i++) { cur = i; for (int j = 1; j < numDigits; j++) alreadyDone[j] = -1; for (int j = 1; j < numDigits; j++) { m = cur % 10; cur = (cur / 10) + (m * firstDigit); if (cur > i && cur <= b) { notDone = true; for (int k = 1; k < j; k++) { if (alreadyDone[k] == cur) { notDone = false; break; } } if (notDone) { alreadyDone[j] = cur; tot++; } } } } out.print(tot); } } " B22090," import java.util.*; import java.io.*; public class template { private StringBuilder result = new StringBuilder(); public static void main(String[] args) { new template().go(); } public void go() { File inputFile = new File(""/Users/amornchaikanokpullwad/Documents/input.in""); BufferedReader br = null; try { br = new BufferedReader(new FileReader(inputFile)); int numTests = Integer.parseInt(br.readLine()); for (int testCounter = 0; testCounter < numTests; ++testCounter) { int count = 0; String text[] = br.readLine().split("" ""); long A = Long.parseLong(text[0]); long B = Long.parseLong(text[1]); for (long i = A; i <= B; i++) { for (int j = 1; j < Long.toString(i).length(); j++) { //System.out.println(j + "" "" + i); long temp = reverse(Long.toString(i),j); if (temp <= i) continue; if (temp <= B) { //System.out.println(i+""+""+B); count++; } } //System.out.println(i+""+""+B); } appendResult(testCounter, count); } } catch (FileNotFoundException fe) { fe.printStackTrace(); } catch (IOException ie) { ie.printStackTrace(); } finally { try { if (br != null) { br.close(); } } catch (IOException ex) { ex.printStackTrace(); } } writeResultToFile(); //System.out.println(result); } private void appendResult(int testCase, int outp) { result.append(""Case #"" + (testCase+1) + "": ""); result.append(outp+""""); result.append(""\n""); } private void writeResultToFile() { PrintWriter pr = null; try { pr = new PrintWriter(new File(""/Users/amornchaikanokpullwad/Documents/output.in"")); pr.print(result); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (pr != null) { pr.close(); } } } private long reverse(String in,int le){ StringBuilder temp = new StringBuilder(); for (int i = le; i > 0; i--) { //System.out.println(in); temp.append(in.charAt(in.length()-i)); } for (int i = 0; i < in.length()-le; i++) { temp.append(in.charAt(i)); } return Long.parseLong(temp.toString()); } }" B20310,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashSet; public class Recycle { public static void main(String[] args) throws IOException{ FileInputStream inFile = new FileInputStream(""C-large.in""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(inFile); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String inputCnt = br.readLine(); FileOutputStream outFile = new FileOutputStream(""output.txt""); DataOutputStream out = new DataOutputStream(outFile); BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(out)); int cnt = Integer.parseInt(inputCnt); for(int line=1;line<=cnt;line++){ String inputString = br.readLine(); String[] splited = inputString.split("" ""); int A = Integer.parseInt(splited[0]); int B = Integer.parseInt(splited[1]); String outputString = ""Case #""+line+"": ""; int result = 0; for(Integer num = A; num<=B; num++){ //for each number String s = num.toString(); result += permute(s,num,B); } outputString += result+""""; wr.write(outputString); wr.newLine(); wr.flush(); } wr.close(); out.close(); br.close(); in.close(); inFile.close(); outFile.close(); } public static int permute(String original, int min, int max) { String target = original; HashSet resultSet = new HashSet(); for(int i = 1;imin && potential <= max) resultSet.add(potential); target = shifted; } return resultSet.size(); } } " B21594,"import java.io.*; import java.awt.geom.Point2D; import java.text.*; import java.math.*; import java.util.*; public class Main implements Runnable { final String problem = ""C""; // final String filename = problem + ""-sample""; // final String filename= problem+""-small-attempt0""; // final String filename= problem+""-small-attempt1""; final String filename= problem+""-large""; long ans; public void solve(int A, int B) throws Exception { ans = 0; boolean[] was = new boolean[B + 1]; for (int num = A; num <= B; num++) { if (was[num]) continue; int dig = 0, p = 1; while (p <= num) { dig++; p *= 10; } int count = 1; int x = num; p /= 10; for (int i = 1; i < dig; i++) { int high = x / p; int y = (x - high * p) * 10 + high; if (y==num) break; if (y >= p && y>=A && y<=B) { was[y] = true; count++; } x = y; } ans += count * (count - 1) / 2; } } public void solve_gcj() throws Exception { int tests = iread(); for (int test = 1; test <= tests; test++) { out.write(""Case #"" + test + "": ""); solve(iread(), iread()); out.write(ans + ""\n""); } } public void run() { try { // in = new BufferedReader(new InputStreamReader(System.in)); // out = new BufferedWriter(new OutputStreamWriter(System.out)); in = new BufferedReader(new FileReader(filename + "".in"")); out = new BufferedWriter(new FileWriter(filename + "".out"")); solve_gcj(); out.flush(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public int iread() throws Exception { return Integer.parseInt(readword()); } public double dread() throws Exception { return Double.parseDouble(readword()); } public long lread() throws Exception { return Long.parseLong(readword()); } BufferedReader in; BufferedWriter out; public String readword() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return """"; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) { try { Locale.setDefault(Locale.US); } catch (Exception e) { } new Thread(new Main()).start(); // new Thread(null, new Main(), ""1"", 1<<25).start(); } }" B21338,"package com.google.codejam.util; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class CodeJamOutputFile extends File { /** * */ private static final long serialVersionUID = -6971460798309687528L; private FileWriter writer; private Boolean caseZero = false; public CodeJamOutputFile(String pathname) { super(pathname); try { this.setWriter(); } catch (IOException e) { } } private void setWriter() throws IOException { this.writer = new FileWriter(this); } public FileWriter getWriter() { return writer; } public void writeCase(int caseId, String result){ if(caseId == 0){ caseZero = true; } caseId = caseZero ? caseId + 1 : caseId; try { writer.write(""Case #""+(caseId) +"": "" + result + ""\n""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void close(){ try { writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B20117,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; /** * * @author eblanco */ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import javax.swing.JFileChooser; public class RecycledNumbers { public static String DatosArchivo[] = new String[10000]; public static int[] convertStringArraytoIntArray(String[] sarray) throws Exception { if (sarray != null) { int intarray[] = new int[sarray.length]; for (int i = 0; i < sarray.length; i++) { intarray[i] = Integer.parseInt(sarray[i]); } return intarray; } return null; } public static boolean CargarArchivo(String arch) throws FileNotFoundException, IOException { FileInputStream arch1; DataInputStream arch2; String linea; int i = 0; if (arch == null) { //frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JFileChooser fc = new JFileChooser(System.getProperty(""user.dir"")); int rc = fc.showDialog(null, ""Select a File""); if (rc == JFileChooser.APPROVE_OPTION) { arch = fc.getSelectedFile().getAbsolutePath(); } else { System.out.println(""No hay nombre de archivo..Yo!""); return false; } } arch1 = new FileInputStream(arch); arch2 = new DataInputStream(arch1); do { linea = arch2.readLine(); DatosArchivo[i++] = linea; /* if (linea != null) { System.out.println(linea); }*/ } while (linea != null); arch1.close(); return true; } public static boolean GuardaArchivo(String arch, String[] Datos) throws FileNotFoundException, IOException { FileOutputStream out1; DataOutputStream out2; int i; out1 = new FileOutputStream(arch); out2 = new DataOutputStream(out1); for (i = 0; i < Datos.length; i++) { if (Datos[i] != null) { out2.writeBytes(Datos[i] + ""\n""); } } out2.close(); return true; } public static void echo(Object msg) { System.out.println(msg); } public static void main(String[] args) throws IOException, Exception { String[] res = new String[10000], num = new String[2]; int i, j, k, ilong; int ele = 1; ArrayList al = new ArrayList(); String FName = ""C-large"", istr, irev, linea; if (CargarArchivo(""C:\\eblanco\\Desa\\CodeJam\\Code Jam\\test\\"" + FName + "".in"")) { for (j = 1; j <= Integer.parseInt(DatosArchivo[0]); j++) { linea = DatosArchivo[ele++]; num = linea.split("" ""); al.clear(); // echo(""A: ""+num[0]+"" B: ""+num[1]); for (i = Integer.parseInt(num[0]); i <= Integer.parseInt(num[1]); i++) { istr = Integer.toString(i); ilong = istr.length(); for (k = 1; k < ilong; k++) { if (ilong > k) { irev = istr.substring(istr.length() - k, istr.length()) + istr.substring(0, istr.length() - k); //echo(""caso: "" + j + "": isrt: "" + istr + "" irev: "" + irev); if ((Integer.parseInt(irev) > Integer.parseInt(num[0])) && (Integer.parseInt(irev) > Integer.parseInt(istr)) && (Integer.parseInt(irev) <= Integer.parseInt(num[1]))) { al.add(""("" + istr + "","" + irev + "")""); } } } } HashSet hs = new HashSet(); hs.addAll(al); al.clear(); al.addAll(hs); res[j] = ""Case #"" + j + "": "" + al.size(); echo(res[j]); LeerArchivo.GuardaArchivo(""C:\\eblanco\\Desa\\CodeJam\\Code Jam\\test\\"" + FName + "".out"", res); } } } } " B20148,"package codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; /* import lib.tuple.Pair; import lib.tuple.Tuple; import lib.util.StringUtil; */ public class CodeJam2012RQC { static final String fileIn = ""/Users/jhorwitz/Documents/workspace/test/src/codejam/data/RQ-C-in.txt""; //""data/in.txt""; static final String fileOut = ""/Users/jhorwitz/Documents/workspace/test/src/codejam/data/RQ-C-out.txt""; //""data/out.txt""; public static void main(String[] args) throws Exception { BufferedReader r = new BufferedReader(new FileReader(fileIn)); BufferedWriter w = new BufferedWriter(new FileWriter(fileOut)); String line = r.readLine(); int T = Integer.parseInt(line); for (int caseNum = 1; caseNum <= T; caseNum++) { line = r.readLine(); String str = ""Case #"" + caseNum + "": "" + solve(line); w.write(str + ""\n""); System.out.println(str); } w.close(); r.close(); } private static int solve(String line) { String[] stringVerOfAAndB = line.split("" ""); int A = Integer.parseInt(stringVerOfAAndB[0]); int B = Integer.parseInt(stringVerOfAAndB[1]); int digits = stringVerOfAAndB[0].length(); // == stringVerOfAAndB[1] (guaranteed by GCJ) int numRecycledPairsTimesTwo = 0; // each pair will be counted twice--we then simply divide by 2 in the end int rotatedNum; for (int curNum=A; curNum<=B; ++curNum) { for (int rot=1; rot<=digits; ++rot) { rotatedNum = rotate(curNum, rot, digits); if (A<=rotatedNum && rotatedNum<=B && isFirstSuchRotation(curNum,rotatedNum,rot,digits)) { ++numRecycledPairsTimesTwo; } } } return numRecycledPairsTimesTwo/2; } private static boolean isFirstSuchRotation(int numToRotate, int rotatedNum, int rot1, int digits) { for (int rot2=0; rot2 exist = new HashSet(); String[] splitResult = input.split("" ""); int numberA = Integer.parseInt(splitResult[0]); int numberB = Integer.parseInt(splitResult[1]); for(int i = numberA; i < numberB; i++){ int current = i; exist.clear(); int length1 = String.valueOf(current).length(); int j = 10; while(j<=current){ int remain = current%j; int length2 = String.valueOf(j).length(); double b = Math.pow(10, length2-1); double a = Math.pow(10,length1); int currentResult = (int)(remain*a/b+current/j); if(current == 2022){ System.out.println(remain+"":""+(length2-1)+"":""+currentResult); } if(currentResult <= numberB && currentResult > current){ if(!exist.contains(currentResult)){ exist.add(currentResult); resultInt++; } } j = j*10; } } return """"+resultInt; } public static void readFile() throws IOException{ FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); FileReader input = new FileReader(""in.txt""); BufferedReader bufRead = new BufferedReader(input); String line = bufRead.readLine(); String current = getResult(line); int i = 1; out.write(""Case #"" + i + "": "" + current); line = bufRead.readLine(); while (line != null){ i++; out.write('\n' + ""Case #"" + i + "": "" + getResult(line)); line = bufRead.readLine(); } bufRead.close(); out.close(); } } " B20365,"package qualification2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { static int rotationCount(int x, int lower) { String s = String.valueOf(x); List rotations = new ArrayList(); for (int i = 1; i < s.length(); i++) if (s.charAt(i) != '0') { int r = Integer.parseInt(s.substring(i) + s.substring(0, i)); if(r >= lower && r < x && !rotations.contains(r)) rotations.add(r); } return rotations.size(); } static int solve(int A, int B) { int result = 0; for (int x = A + 1; x <= B; x++) result += rotationCount(x, A); return result; } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(args[0])); PrintWriter writer = new PrintWriter(args[1]); int ntests = Integer.parseInt(reader.readLine()); for (int test = 0; test < ntests; test++) { String[] fields = reader.readLine().split("" ""); int A = Integer.parseInt(fields[0]); int B = Integer.parseInt(fields[1]); writer.println(""Case #"" + (test + 1) + "": "" + solve(A,B)); writer.flush(); } writer.close(); } } " B20633,"import java.io.*; import java.util.Scanner; public class Main3 { public static void main(String args[]) throws FileNotFoundException { //String test = ""123400""; //System.out.println(test.substring(2,4)); Scanner in = new Scanner(new FileReader(""input.in"")); PrintWriter out = new PrintWriter(""output.txt""); int T = 0; String S1 = in.nextLine(); T = Integer.parseInt(S1); for(int i=0;in && m<=B) { int repeat = 0; for(int k= 0;k void solve(String filePath, String fileName, InputConverter inputConverter, SolverBase solver) { File folder = new File(filePath); File fin = getInputFile(folder, fileName); File fout = getOutputFile(folder, fileName); if (!fout.exists()) { try { fout.createNewFile(); } catch (IOException e) { System.err.println(""Error creating file "" + fout.getAbsolutePath()); e.printStackTrace(); } } InputReader reader = null; SolutionWriter writer = null; try { reader = new InputReader(fin, inputConverter); solver.init(reader); writer = new SolutionWriter(fout); int caseNum = 1; String solution; long startTime = System.currentTimeMillis(); while ((solution = solver.solveNext()) != null) { writer.writeSolution(caseNum++, solution); writer.flush(); } int time = (int)(System.currentTimeMillis() - startTime); System.out.println(""Done in "" + (time / 1000) + "" seconds ("" + (time / (caseNum - 1)) + ""ms average)""); } catch (Exception e) { System.err.println(""Error solving""); e.printStackTrace(); } if (reader != null) { try { reader.close(); } catch (IOException e) { // do nothing } } if (writer != null) { writer.flush(); writer.close(); } } public static File getInputFile(File folder, String fileName) { return new File(folder, fileName + FILE_IN_EXTENSION); } public static File getOutputFile(File folder, String fileName) { DateFormat dateFormat = new SimpleDateFormat(OUT_DATE_FORMAT); String date = dateFormat.format(Calendar.getInstance().getTime()); return new File(folder, fileName + date + FILE_OUT_EXTENSION); } public static String[] convertToStringArray(String line) { return line.split("" ""); } public static int[] convertToIntArray(String line, int count) { int[] items = new int[count]; int wordStart = 0; for (int i = 0; i < count; i++) { int wordEnd = line.indexOf(' ', wordStart); if (wordEnd < 0) { wordEnd = line.length(); } int param = Integer.parseInt(line.substring(wordStart, wordEnd)); items[i] = param; wordStart = wordEnd + 1; } return items; } public static int convertToIntArray(String line, int[] itemsOut) { int count = 0; int wordStart = 0; int length = line.length(); while (wordStart < length) { int wordEnd = line.indexOf(' ', wordStart); if (wordEnd < 0) { wordEnd = line.length(); } int param = Integer.parseInt(line.substring(wordStart, wordEnd)); itemsOut[count++] = param; wordStart = wordEnd + 1; } return count; } } " B21242,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.ArrayList; public class Problem extends Template { public static void main(String[] args) throws Exception { _iFILE = ""sample""; _oFILE = ""output""; // Base ProblemA = new Base(new int[] {0, 1}) { // String lhs = "" abcdefghijklmnopqrstuvwxyz""; // String rhs = "" yhesocvxduiglbkrztnwjpfmaq""; // // @Override // protected String implementation(String[][] params) { // String trans = """"; // String input = ArrayUtil.join(params[0], "" ""); // for (int i = 0; i < input.length(); i++) { // trans += rhs.charAt(lhs.indexOf(input.charAt(i))); // } // // return trans; // } // }; // Base ProblemB = new Base(new int[] {0, 1}) { // @Override // protected String implementation(String[][] params) { // int count = 0; // // int n = new Integer(params[0][0]).intValue(); // int s = new Integer(params[0][1]).intValue(); // int p = new Integer(params[0][2]).intValue(); // // boolean[][] match = new boolean[n][2]; // // int[] t = new int[n]; // for (int i = 0; i < n; i++) { // t[i] = new Integer(params[0][3 + i]).intValue(); // // //Assuming x <= y <= z // boolean s_match = false; // boolean n_match = false; // // for (int x = 0; x <= 10; x++) { // { // int z = x + 2; // int y = t[i] - x - z; // // if(x <= y && y <= z && z >= p) { // //System.out.println(""\t("" + x + "","" + y + "","" + z + "") "" + p); // s_match = true; // } // } // { // int z = x + 1; // int y = t[i] - x - z; // // if(x <= y && y <= z && z >= p) { // //System.out.println(""\t("" + x + "","" + y + "","" + z + "") "" + p); // n_match = true; // } // } // { // int z = x; // int y = t[i] - x - z; // // if(x <= y && y <= z && z >= p) { // //System.out.println(""\t("" + x + "","" + y + "","" + z + "") "" + p); // n_match = true; // } // } // } // match[i][0] = s_match; // match[i][1] = n_match; // // /*System.out.print(t[i]); // if(s_match) System.out.print("" *""); // if(n_match) System.out.print("" +""); // System.out.println();*/ // // if(n_match) // count++; // else if(s > 0 && s_match) { // s--; // count++; // } // } // return Integer.toString(count); // } // }; Base ProblemC = new Base(new int[] {0, 1}) { @Override protected String implementation(String[][] params) { int count = 0; try { int len = params[0][0].length(); Integer[] p = ArrayUtil.convert(params[0], Integer.class); for (int n = p[0]; n <= p[1]; n++) { int m = n; while(true) { m = (int) ((m%10)*Math.pow(10, len - 1)) + m/10; if(n < m && m <= p[1]) count++; if(n == m) break; } } }catch (Exception e) { e.printStackTrace(); System.exit(0); } return Integer.toString(count); } }; // Base ProblemD = new Base(new int[] {1, 0}) { // @Override // protected String implementation(String[][] params) { // int r = new Integer(params[0][0]).intValue(); // int c = new Integer(params[0][1]).intValue(); // int d = new Integer(params[0][2]).intValue(); // // // // // return """"; // } // }; ProblemC.run(); } } class Template { public static String _oFILE; public static String _iFILE; public static abstract class Base { static { System.out.println(""--- GOOGLE CODE JAM 2012 ---------------------------------------""); } private int[] inputType; private String columnSeperator = "" ""; private Template.Base.iCollection input; abstract protected String implementation(String[][] params) throws Exception; public Base(int[] inputType) throws Exception { this.inputType = inputType; if (new File(_iFILE).exists()) { input = new Template.Base.iCollection(); String strLine; BufferedReader buffReader = new BufferedReader(new FileReader(_iFILE)); while ((strLine = buffReader.readLine()) != null) input.add(strLine.split(columnSeperator)); buffReader.close(); input.index(); }else { throw new Exception(""Input File Missing""); } } public void run() throws Exception { int inputSize = new Integer(input.get(0)[0]).intValue(); BufferedWriter buffWriter = new BufferedWriter(new FileWriter(new File(_oFILE))); for (int i = 1; i <= inputSize; i++) { String result = implementation(Template.ArrayUtil.convert(input.item(i))); printResult(input.item(i), result); buffWriter.write(""Case #"" + i + "": "" + result + ""\n""); buffWriter.flush(); } buffWriter.close(); System.out.println(""----------------------------------------- GOOGLE INPUT TYPES ---""); System.out.println(""{0,n} : EACH CASE WITH n (n > 0) ROWS""); System.out.println(""{1,0} : EACH CASE WITH DYNAMIC (DEFINED @ FIRST ROW) SET OF ROWS""); System.out.println(""--------------------------------------------- Subodh Gairola ---""); } private void printResult(ArrayList params, String result) { for (int i = 0; i < params.size(); i++) { for (int j = 0; j < params.get(i).length; j++) { System.out.print(params.get(i)[j] + "" ""); } System.out.println(); } System.out.println(""\t\t|"" + result + ""|""); } class iCollection extends ArrayList { private static final long serialVersionUID = 1L; int[][] _index; public void index() { _index = new int[new Integer(this.get(0)[0]).intValue() + 1][2]; _index[0][0] = inputType[0]; _index[0][1] = inputType[1]; for (int i = 1; i < _index.length; i++) { if (_index[0][0] == 0) { int len = inputType[1]; _index[i][0] = 1 + (i - 1) * len; _index[i][1] = len; } else if (_index[0][0] == 1) { int lastPos = _index[i - 1][0]; int lastLen = _index[i - 1][1]; _index[i][0] = lastPos + lastLen; _index[i][1] = new Integer(this.get(_index[i][0])[0]).intValue() + 1; } } } public Template.Base.iCollection item(int index) { int pos = _index[index][0]; int len = _index[index][1]; Template.Base.iCollection params = new Template.Base.iCollection(); for (int i = pos; i < pos + len; i++) { params.add(this.get(i)); } return params; } } } public static class Generator { public int[] a; public BigInteger numLeft; public BigInteger total; public void reset() { for (int i = 0; i < a.length; i++) { a[i] = i; } numLeft = new BigInteger(total.toString()); } public BigInteger getNumLeft() { return numLeft; } public BigInteger getTotal() { return total; } public boolean hasMore() { return numLeft.compareTo(BigInteger.ZERO) == 1; } public static BigInteger getFactorial(int n) { BigInteger fact = BigInteger.ONE; for (int i = n; i > 1; i--) { fact = fact.multiply(new BigInteger(Integer.toString(i))); } return fact; } public static class Permutation extends Template.Generator { public Permutation(int n) { if (n < 1) { throw new IllegalArgumentException(""Minimum 1""); } a = new int[n]; total = Template.Generator.getFactorial(n); reset(); } public int[] getNext() { if (numLeft.equals(total)) { numLeft = numLeft.subtract(BigInteger.ONE); return a; } int temp; int j = a.length - 2; while (a[j] > a[j + 1]) { j--; } int k = a.length - 1; while (a[j] > a[k]) { k--; } temp = a[k]; a[k] = a[j]; a[j] = temp; int r = a.length - 1; int s = j + 1; while (r > s) { temp = a[s]; a[s] = a[r]; a[r] = temp; r--; s++; } numLeft = numLeft.subtract(BigInteger.ONE); return a; } } public static class Combination extends Template.Generator { private int n; private int r; public Combination(int n, int r) { if (r > n) { throw new IllegalArgumentException(); } if (n < 1) { throw new IllegalArgumentException(); } this.n = n; this.r = r; a = new int[r]; BigInteger nFact = Template.Generator.getFactorial(n); BigInteger rFact = Template.Generator.getFactorial(r); BigInteger nminusrFact = Template.Generator.getFactorial(n - r); total = nFact.divide(rFact.multiply(nminusrFact)); reset(); } public int[] getNext() { if (numLeft.equals(total)) { numLeft = numLeft.subtract(BigInteger.ONE); return a; } int i = r - 1; while (a[i] == n - r + i) { i--; } a[i] = a[i] + 1; for (int j = i + 1; j < r; j++) { a[j] = a[i] + j - i; } numLeft = numLeft.subtract(BigInteger.ONE); return a; } } } public static class ArrayUtil { @SuppressWarnings(""unchecked"") public static T[][] permutations(T[] array) { Template.Generator.Permutation x = new Template.Generator.Permutation(array.length); ArrayList permutations = new ArrayList(); while (x.hasMore()) { int[] indices = x.getNext(); T[] permutation = (T[]) Array.newInstance(array[0].getClass(), indices.length); for (int i = 0; i < indices.length; i++) { permutation[i] = array[indices[i]]; } permutations.add(permutation); } return convert(permutations); } @SuppressWarnings(""unchecked"") public static T[][] combinations(T[] array, int n) { Template.Generator.Combination x = new Template.Generator.Combination(array.length, n); ArrayList combinations = new ArrayList(); while (x.hasMore()) { int[] indices = x.getNext(); T[] combination = (T[]) Array.newInstance(array[0].getClass(), indices.length); for (int i = 0; i < indices.length; i++) { combination[i] = array[indices[i]]; } combinations.add(combination); } return convert(combinations); } @SuppressWarnings(""unchecked"") public static T[] convert(String[] array, Class cl) throws Exception { T[] n = (T[]) Array.newInstance(cl, array.length); for (int i = 0; i < array.length; i++) { n[i] = cl.getConstructor(String.class).newInstance(array[i]); }; return n; } public static String[] convert(T[] array) throws Exception { String[] n = new String[array.length]; for (int i = 0; i < array.length; i++) { n[i] = array[i].toString(); } return n; } @SuppressWarnings(""unchecked"") public static T[] convert(ArrayList arrayList) { if (arrayList.size() == 0) { return null; } T[] array = (T[]) Array.newInstance(arrayList.get(0).getClass(), arrayList.size()); for (int i = 0; i < array.length; i++) { array[i] = arrayList.get(i); } return array; } public static String join(T[] array, String seperator) { String string = """"; for (int i = 0; i < array.length; i++) { string += array[i].toString(); if (i < array.length - 1) { string += seperator; } } return string; } public static T[] remove(T[] array, int index) { ArrayList arrayList = new ArrayList(); for (int i = 0; i < array.length; i++) { if (i != index) { arrayList.add(array[i]); } } return convert(arrayList); } public static T[] unique(T[] array) { ArrayList arrayList = new ArrayList(); for (int i = 0; i < array.length; i++) { if (!arrayList.contains(array[i])) { arrayList.add(array[i]); } } return convert(arrayList); } } } " B21803,"package util.graph; public abstract class Edge implements Cloneable{ public abstract State travel(State current); public Node target; public void connect(Node start, Node end) { try { Edge clone = (Edge) this.clone(); start.edges.add(clone); clone.target=end; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public void biConnect(Node n1, Node n2) { connect(n1,n2); connect(n2,n1); } } " B20266,"import java.io.*; import java.util.*; public class RecycledNumbers implements Runnable { public static void main(String[] args) throws IOException { new Thread(new RecycledNumbers()).start(); } public BufferedReader br; public StringTokenizer in; public PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } int[] was; int[] count; long ans; int A, B; public void go(int i, int c) { if (i < A || i > B) return; if (was[i] > 0) return; ans += count[c]; was[i] = c; count[c]++; String s = """" + i; for (int j = 0; j < s.length() - 1; j++) { String t = s.substring(j + 1) + s.substring(0, j + 1); if (t.charAt(0) != '0') { go(Integer.parseInt(t), c); } } } public void solve() throws IOException { A = nextInt(); B = nextInt(); was = new int[2000001]; count = new int[2000001]; ans = 0; int c = 0; for (int i = A; i <= B; i++) { if (was[i] == 0) { c++; go(i, c); } } out.println(ans); } public void run() { try { br = new BufferedReader(new FileReader(""C-small.in"")); out = new PrintWriter(""c.out""); int t = nextInt(); for (int i = 0; i < t; i++) { System.err.println(i); out.print(""Case #"" + (i + 1) + "": ""); solve(); } out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } } " B21976,"import java.util.*; import java.util.regex.*; import java.text.*; import java.math.*; import java.io.*; public class RecycledNumbers { private final static String FILE_IN = RecycledNumbers.class.getSimpleName() + "".in""; private final static String FILE_OUT = RecycledNumbers.class.getSimpleName() + "".out""; public static void main(String[] args) throws Exception { final Scanner in = new Scanner(new File(FILE_IN)); final PrintWriter out = new PrintWriter(FILE_OUT); final int testCnt = in.nextInt(); for (int caseNum = 1; caseNum <= testCnt; ++ caseNum){ final int a = in.nextInt(); final int b = in.nextInt(); final int last [] = new int [b + 1]; int result = 0; for (int i = a; i <= b; ++ i){ final String s = String.valueOf(i); for (int pos = 1; pos < s.length(); ++ pos){ final String newNum = s.substring(pos) + s.substring(0, pos); final int newInt = Integer.valueOf(newNum); if (newInt > i && newInt <= b){ if (last[newInt] != i){ ++ result; last[newInt] = i; } } } } out.println(String.format(""Case #%d: %d"", caseNum, result)); } in.close(); out.close(); } } " B21975,"import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws NumberFormatException, IOException { FileInputStream inFile = new FileInputStream(new File(""resources/codejam/RecycledNumbers.in"")); DataInputStream in = new DataInputStream(inFile); FileOutputStream outFile = new FileOutputStream(new File(""resources/codejam/RecycledNumbers.out"")); DataOutputStream out = new DataOutputStream(outFile); int cases = Integer.parseInt(in.readLine()); for(int i=0;i 1) { //check for recycles String firstStr = String.valueOf(numbers.charAt(0)); int firstNo = Integer.parseInt(firstStr); HashSet record = new HashSet(); for(int j = 1; j < len; j++) { int currNo = Integer.parseInt(String.valueOf(numbers.charAt(j))); if(currNo > firstNo || currNo == 0) { continue; } String newNo = numbers.substring(j) + numbers.substring(0, j); Integer newVal = Integer.valueOf(newNo); if(newVal < i && newVal >= a) { record.add(newVal); } } recycles+= record.size(); } } sb.append(recycles); out.writeBytes(sb.toString()); } } " B21026,"import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledTester { public static void main(String[] args) throws IOException { new RecycledTester().run(""C-large.in""); // new RecycledTester().run(""problem.txt""); } public void run(String fileName) throws IOException { parseFile(fileName); } private void parseFile(String fileName) throws FileNotFoundException { File file = new File(fileName); Scanner scanner = new Scanner(file); int numTests = Integer.parseInt(scanner.nextLine()); for (int i = 1; i <= numTests; i++) { System.out.println(""Case #"" + i + "": "" + solve(scanner.nextLine())); } scanner.close(); } public String solve(String line) { Scanner ls = new Scanner(line); Solver solver = new Solver(ls.nextInt(), ls.nextInt()); return Integer.toString(solver.solve()); } } class Solver { private final int a; private final int b; private final int c; private final Set counted = new HashSet(); Solver(int a, int b) { this.a = a; this.b = b; this.c = Integer.toString(a).length(); } public int solve() { if (c == 0) return 0; int n = 0; for (int i = a; i <= b; i++) { n += isRecycled(i); } return n; } public int isRecycled(int n) { String t = Integer.toString(n); Set pairCandidates = new HashSet(); pairCandidates.add(n); for (int i = 0; i < c - 1; i++) { t = shift(t); int m = Integer.valueOf(t); if (n != m && a <= m && m <= b && !counted.contains(m)) { pairCandidates.add(m); counted.add(m); } } counted.add(n); return pairCandidates.size() * (pairCandidates.size() - 1) / 2; } public String shift(String t) { return t.substring(1) + t.charAt(0); } } " B20185,"package com.codejam.practice; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class Recycled { public static void main(String[] args) { //File read & write variables File inputFile = new File(""C:/Users/SNALLAMA/Desktop/C-large.in""); File outputFile = new File(""C:/Users/SNALLAMA/Desktop/C-large.out""); String line = null; int t, a, b, noOfDigits, divider, localnumber; //long outNumber=0; Set finalOP = new HashSet(); try { BufferedReader bReader = new BufferedReader(new FileReader(inputFile)); BufferedWriter bWriter = new BufferedWriter(new FileWriter(outputFile)); try { t = Integer.parseInt(bReader.readLine().trim()); //System.out.println(""No. Of Cases""+t); for(int index=0;index(); if(noOfDigits!=1){ for(int i=a;i<=b;i++){ for(int localIndex=1;localIndexA;original--){ numbers = original.toString().toCharArray(); perm: do{ newNumbers = new char[numbers.length]; newNumbers[0]=numbers[numbers.length-1]; for(int i=1; iB || newNumber=A && newNumber0 ) { a/=10 ; size++; } int count = 0; int[] rev = new int[10]; int[] pow = new int[]{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 }; for( int n=A ; n<=B ; n++ ){ int ir = 0; for( int k=1 ; k lis = new ArrayList(); //ArrayList lis = new ArrayList(); //ArrayList lis = new ArrayList(); static long sum=0; public static void main(String[] args) throws IOException { //googlein.txt C-small-attempt0.in Scanner sc =new Scanner(new File(""C-large.in"")); File file = new File(""file.txt""); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file))); // sc.useDelimiter(""(\\s)+|[,]""); int T=sc.nextInt(); for(int k=1; k<=T; k++){ int c=0, a=sc.nextInt(),b =sc.nextInt(); for(int t=a;t<=b;t++){ String s=String.valueOf(t); int l=s.length(),g=1; ArrayList lis = new ArrayList(); for(int u=0;u 0) { brCif++; res /= 10; } HashSet hs = new HashSet(); for (int i = a; i <= b; i++) { if (i == stepeni[brCif]) brCif++; int tmp = i; for (int j = 1; j < brCif; j++) { tmp = (tmp % 10) * stepeni[brCif - 1] + tmp / 10; if (i < tmp && tmp <= b && !hs.contains(tmp)) { res++; hs.add(tmp); } } hs.clear(); } out.println(""Case #"" + (testCase + 1) + "": "" + res); } in.close(); out.close(); } } " B21268,"package gcj.y2012.qual; import java.io.*; import java.util.*; public class C { private static String fileName = C.class.getSimpleName().replaceFirst(""_.*"", """").toLowerCase(); private static String inputFileName = fileName + "".in""; private static String outputFileName = fileName + "".out""; private static Scanner in; private static PrintWriter out; private void solve() { int from = in.nextInt(); int to = in.nextInt(); int n = ("""" + to).length(); int ten = (int) Math.pow(10, n - 1); int ans = 0; Set recycled = new HashSet(); for (int a = from; a <= to; a++) { int b = a; for (int j = 1; j < n; j++) { int d = b % 10; b = (b / 10) + d * ten; if (a < b && b <= to) { recycled.add(b); } } ans += recycled.size(); recycled.clear(); } out.println(ans); } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); if (args.length >= 2) { inputFileName = args[0]; outputFileName = args[1]; } in = new Scanner(new FileReader(inputFileName)); out = new PrintWriter(outputFileName); int tests = in.nextInt(); in.nextLine(); for (int t = 1; t <= tests; t++) { out.print(""Case #"" + t + "": ""); new C().solve(); System.out.println(""Case #"" + t + "": solved""); } in.close(); out.close(); } } " B20763,"import java.io.*; import java.util.*; public class C { BufferedReader ins; PrintStream outs; static String INPUT = ""C-large.in""; static String OUTPUT; static { OUTPUT = ""C-large.out""; } Map> map = new HashMap>(); public C(BufferedReader ins, PrintStream outs) { this.ins = ins; this.outs = outs; } public void preprocess() { for(int j = 1; j<=2000000; j++) { String k = new Integer(j).toString(); Set set = new HashSet(); int sz = k.length(); for(int i = 1; i set = new HashSet(); for(int i = 0; i k && newk <=b) { if(!set.contains(x+""-""+sb)) { set.add(x+""-""+sb); } ret++; } } return set.size(); } public int permuteL(int k, int b) { String m = new Integer(k).toString(); int count = 0; for(String r : map.get(m)) { int newk = Integer.parseInt(r); if(newk>k && newk<=b) count++; } return count; } public int go(int a, int b) { int count = 0; for(int k = a; k < b; k++) { count += permuteK(k, b); } return count; } public void process() throws Exception { // preprocess(); // System.out.println(""Hi""); //Read input int t = Integer.parseInt(ins.readLine()); for(int T=1; T<=t;T++) { String x = ins.readLine().trim().replaceAll("" +"", "" ""); String[] tokens = x.split("" ""); int a = Integer.parseInt(tokens[0]); int b = Integer.parseInt(tokens[1]); outs.println(""Case #"" + T + "": "" + go(a,b)); } } public static void main(String args[]) throws Exception { //Input InputStreamReader fis = new FileReader(INPUT); BufferedReader bis = new BufferedReader(fis); //Output PrintStream ps = OUTPUT!=null ? new PrintStream(OUTPUT) : System.out; C c = new C(bis, ps); c.process(); return; } } " B22067,"import java.io.*; import java.util.*; public class ReNum { static BufferedReader br; static PrintWriter pw; public static void main(String args[]) { try { br = new BufferedReader(new FileReader(""C-large.in"")); pw = new PrintWriter(new File(""ReNumAns.out"")); String no = br.readLine(); int number = Integer.parseInt(no); for (int h = 0; h <= number - 1; h++) { int finAns =0; String nos = br.readLine(); String[] n = nos.split("" ""); int num1 = Integer.parseInt(n[0]); int e = Integer.parseInt(n[1]); int size = n[0].length(); for (int i=num1;i<=e;i++){ String t = Integer.toString(i); for (int j = 1;ji && num2<=e && num2>=num1){ finAns++; } } } int caseNo = 1 + h; String ans = ""Case #"" + caseNo + "": "" + finAns; pw.println(ans); pw.flush(); } } catch (IOException e) { e.printStackTrace(); } } } " B21662,"import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; public class Recycle { public static void main(String[] args) throws IOException { long time = System.currentTimeMillis(); File iFile = new File(""A-large-practice.in""); BufferedReader in= new BufferedReader(new FileReader(iFile)); File oFile = new File(""A-large-practice.out""); FileOutputStream fos = new FileOutputStream(oFile); BufferedOutputStream bos = new BufferedOutputStream(fos); PrintStream out = new PrintStream(bos); int numCases = Integer.parseInt(in.readLine()); for(int i=0; i possibleMs = new HashSet(); for(int rotate=1; rotate i && thisNum<=B){ possibleMs.add(thisRot); } } return possibleMs.size(); } }" B21904,"package com.dagova.recycledNumbers; import java.util.TreeSet; public class RecycledNumbersSolver { private static int solution; private static int aNumber; private static int bNumber; public static int solve(String line) { solution = 0; String[] splittedLine = line.split("" ""); aNumber = Integer.parseInt(splittedLine[0]); bNumber = Integer.parseInt(splittedLine[1]); for(int number = aNumber; number < bNumber-1; number++) { solution += solveNumber(number); } return solution; } public static int solveNumber(int number) { // con el treeset evita que un n de varias veces el mismo m. Antes usaba el contador recycledNumbers y por eso fallaba. TreeSet ms = new TreeSet(); // int recycledNumbers = 0; String numberAsString = Integer.toString(number); int numberLength = numberAsString.length(); for(int charIterator = 1; charIterator < numberLength; charIterator++) { if(numberAsString.charAt(charIterator) >= numberAsString.charAt(0)) { int recycledNumber = generateRecycledNumber(numberAsString, charIterator); if(recycledNumber <= bNumber && recycledNumber > number) { ms.add(recycledNumber); // recycledNumbers++; } } } return ms.size(); // return recycledNumbers; } public static int generateRecycledNumber(String numberAsString, int charIterator) { String prefix = numberAsString.substring(0, charIterator); String sufix = numberAsString.substring(charIterator); return Integer.parseInt(sufix.concat(prefix)); } } " B20875,"import java.io.*; import java.util.*; import java.math.*; public class Solution { public static void main(String args[]) throws Exception { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int t = 0; t < T; t++) { int A=sc.nextInt(); int B=sc.nextInt(); int dig=digi(A); int mdig=minDig(A); int mdig10=mdig*10; int curr=A; int count=0; //System.out.println(A+"" ""+B+"" ""+dig+"" ""+mdig+"" ""+mdig10+"" ""+curr); HashSet set = new HashSet(); while(curr<=B) { int curr2=curr; for(int i=0;i9) { i/=10; n++; } return n; } static int minDig(int i) { int n=1; while(i>9) { i/=10; n*=10; } return n; } } " B21197,"import java.util.ArrayList; import java.util.Scanner; public class QuestionC extends Question{ private int A; private int B; private int significant; private int digits; public QuestionC(Result result, Counter counter) { super(result, counter); } @Override public void readInput(Scanner scanner) { A = scanner.nextInt(); B = scanner.nextInt(); digits = Integer.toString(A).length(); significant = (int)Math.pow(10, digits-1); } @Override public String solution() { int counter = 0; ArrayList used = new ArrayList(); for (int i = A; i < B; i++) { int shifted = i; for (int j = 0; j < digits-1; j++) { shifted = (shifted%10)*significant+shifted/10; if (shifted > i && shifted <= B && !used.contains(shifted)) { counter++; used.add(shifted); } } used.clear(); } return Integer.toString(counter); } } " B20579,"package quals; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Recycler { public static void main(String args[]) { try { System.setIn(new FileInputStream(""C-large.in"")); Scanner scanner = new Scanner(System.in); int testCases = scanner.nextInt(); scanner.nextLine(); for (int i = 1; i <= testCases; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); int numRecycledPairs = recycler(a, b); System.out.println(String.format(""Case #%d: %d"", i, numRecycledPairs)); } } catch (FileNotFoundException e) { e.printStackTrace(); } } private static int recycler(int a, int b) { int numRecycled = 0; int digits = (int) Math.log10(a) + 1; Set recycled = new HashSet(); for (int m = a; m <= b; m++) { for (int pos = 1; pos <= digits; pos++) { int n = recycle(m, pos); if (m < n && n <= b && !recycled.contains(n)) { numRecycled++; recycled.add(n); } } recycled.clear(); } return numRecycled; } private static int recycle(int a, int pos) { return a / (int) Math.pow(10, pos) + (a % (int) Math.pow(10, pos)) * (int) Math.pow(10, (int) Math.log10(a) - pos + 1); } } " B20802,"package org.nos.gcj; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.StringTokenizer; public class GCJ_Q_03 { // static final String path = ""F:/GCJ/GCJ_Qalification_03/Small_1""; static final String path = ""F:/GCJ/GCJ_Qalification_03/Large""; class TestCase { int A,B; } public TestCase readTestCase(BufferedReader br) throws Exception { TestCase tc = new TestCase(); String line = br.readLine(); StringTokenizer st = new StringTokenizer(line); tc.A = Integer.valueOf(st.nextToken()); tc.B = Integer.valueOf(st.nextToken()); return tc; } public void writeTestResult(BufferedWriter bw, TestCase tc) throws Exception { int rpCount = 0; for (int i = tc.A; i < tc.B; i++) { int digits = Long.valueOf(Math.round(Math.floor(Math.log10(i)))).intValue()+1; List local = new ArrayList(); for (int d = 1; d <= digits - 1; d++) { int recycled = Integer.valueOf((""""+i).substring(d, digits) +(""""+i).substring(0, d)); int rdigits = Long.valueOf(Math.round(Math.floor(Math.log10(recycled)))).intValue()+1; if (rdigits != digits) continue; if (recycled < i) continue; if (recycled > tc.B) continue; if (recycled == i) continue; if (local.contains(recycled)) continue; else local.add(recycled); rpCount++; } } bw.write(""""+rpCount); } public void solve() throws Exception { BufferedReader br = new BufferedReader(new FileReader(path+""/input.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(path+""/output.out"")); int testCases = new Integer(br.readLine()); for (int i=0; i= 0; j--){ temp2 = temp2 + A.charAt(n-1-j); } for(k = 0; k < n-index-1; k++){ temp2 = temp2 + A.charAt(k); } int c = Integer.parseInt(temp2); if ( c <= b && c > Integer.parseInt(A)) { for(jj = 0; jj < 8; jj++){ if(array[jj] == c){ break; } } if(jj == 8){ result = result + 1; array[kk++] = c; } } } A = Integer.toString(Integer.parseInt(A)+1); i++; } return result; } } " B22063,"package hu.hke.gcj; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { static RecycledNumbers rn = new RecycledNumbers(); /** * @param args */ public static void main(String[] args) { readAndCalculate(args[0], args[1]); } private static void readAndCalculate(String inputF, String outputF) { BufferedReader input = null; BufferedWriter output = null; try { String line = null; input = new BufferedReader(new FileReader(inputF)); output = new BufferedWriter(new FileWriter(outputF)); boolean first = true; int expectedRows = 0; int actualRows = -1; while ((( line = input.readLine()) != null) && (actualRows < expectedRows)) { System.out.print(actualRows+1); System.out.println(""----------------------------------------------------""); if (first) { first = false; expectedRows = Integer.parseInt(line); } else { output.write(""Case #"" +(actualRows+1)+"": ""+ rn.recicledNumbers(line)); if (actualRows +1 < expectedRows) { output.write(""\n""); } } actualRows++; } input.close(); output.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } } private String recicledNumbers(String line) { C c = new C(line); return c.calculate(); } class C { int a; int b; public C(String line) { String[] numbers = line.split("" ""); a = Integer.parseInt(numbers[0]); b = Integer.parseInt(numbers[1]); } public String calculate() { int result = 0; for (int i = a; i counted = new ArrayList(); for (int j = 1; j < digits.length; j++) { if (digits[j]>=digits[0]) { cycled = cycle(digits, j); if ( (i 0) { a2 /= 10; size++; } for (int j = a; j < b; j++) { int prev = -1; for (int k = 1; k < size; k++) { int swapNum = swap(j, k, size); if (j < swapNum && swapNum <= b && swapNum != prev) { prev = swapNum; result++; } } } pw.println(""Case #"" + (i + 1) + "": "" + result); } pw.close(); } private static int swap(int raw, int posNum, int size) { return (raw % power[posNum]) * power[size - posNum] + raw / power[posNum]; } } " B21764,"import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); int noCases = in.nextInt(); for(int i = 0; i < noCases; i++){ int a = in.nextInt(); int b = in.nextInt(); int noDigits = Integer.toString(a).length(); Set checkedPairs = new HashSet(); for(int number = a; number <= b; number++){ for (int digit = 1; digit < noDigits; digit++) { if(number % Math.pow(10, digit) == 0){ continue; } int rotatedNumber = rotate(number, digit, noDigits); Pair pair = new Pair(rotatedNumber,number); if (rotatedNumber >= a && rotatedNumber <= b && !checkedPairs.contains(pair) && number != rotatedNumber) { checkedPairs.add(pair); } } } System.out.println(""Case #""+(i+1)+"": "" + checkedPairs.size()); } } static class Pair{ int value1, value2; public Pair(int value1, int value2){ this.value1 = value1; this.value2 = value2; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (value1+value2); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (value1 != other.value1 && value1 != other.value2) return false; if (value2 != other.value2 && value2 != other.value1) return false; return true; } public String toString(){ return ""(""+value1+"",""+value2+"")""; } } public static int rotate(int number, int noPlaces, int noDigits){ int rotatedNumber = number; int divider = (int) Math.pow(10, noDigits-1); for(int i = 0; i < noPlaces; i++){ int digit = rotatedNumber % 10; rotatedNumber = digit*divider + rotatedNumber / 10; } return rotatedNumber; } } " B22262,"import java.io.IOException; class Round1C { private int Case; public Round1C(int Case, int A, int B) { this.Case = Case; int result = this.Computer(A, B); this.outPut(result); } /* * N±qA¨ìB * §â¨C­Ó¼Æ¦rN§@±ÛÂà«áªºµ²ªG¡A * §PÂ_¡A¬O§_¤j©óN¥B¤p©óµ¥©óB * ¬Oresult++ * * */ private int Computer(int A, int B){ int result = 0; if(this.degree(A) == this.degree(B)){ for(int N = A; N <= B; N++){ for(int i = 1; i <= degree(N); i++){ int r = Rotation(N, i); // System.out.println(""\t"" + r); if(N < r && r <= B){ result++; } } } } return result; } private int Rotation(int temp, int order){ int result = 0; String rotation = Integer.valueOf(temp).toString(); rotation = rotation.substring(order) + rotation.substring(0, order); result = Integer.parseInt(rotation); return result; } private int degree(int temp){ for(int i = 1; ;i++){ temp /= 10; if(temp == 0){ return i; } } } private void outPut(int result) { try { System.out.println(""Case #"" + Case + "": "" + result); Main.bufWriter.write(""Case #"" + Case + "": "" + result); Main.bufWriter.newLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B20557,"import java.io.File; import java.util.HashSet; import java.util.Scanner; public class C { public static void main(String[] args) throws Exception { // Scanner in = new Scanner(new File(""C-small-attempt0.bin"")); Scanner in = new Scanner(new File(""C-large.bin"")); // Scanner in = new Scanner(new File(""test.in"")); int T = in.nextInt(); for (int zz = 1; zz <= T; ++zz) { int A = in.nextInt(); int B = in.nextInt(); int r = 0; // HashSet tested = new HashSet<>(); for (int i = A; i < B; ++i) { int log = (int) Math.log10(i); int n = i; int p = (int) Math.pow(10, log+1); HashSet tested = new HashSet<>(log); for (int l = 1; l <= log; ++l) { n *= 10; n = (n%p) + (n/p); if (tested.add(n) && n > i && n <= B) r++; } } System.out.format(""Case #%d: %d\n"", zz, r); } } } " B21300,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; public class CRecycledNumbers { public static HashSet hs = new HashSet(); public static int m; public static void solve() throws NumberFormatException, IOException { File f = new File(""E:\\downloads\\C-large.in""); BufferedReader reader = new BufferedReader(new FileReader(f)); File f2 = new File(""C:\\Users\\kimo\\Desktop\\out.txt""); BufferedWriter writer = new BufferedWriter(new FileWriter(f2)); int x = Integer.parseInt(reader.readLine()); String st[] = null; for (int k = 0; k < x; k++) { st = reader.readLine().split("" ""); int n = Integer.parseInt(st[0]); m = Integer.parseInt(st[1]); int count = 0; for (int i = n; i < m + 1; i++) { if (i < m) { count += numOfways(i + """"); } } writer.write(""Case #"" + (k + 1) + "": "" + count); writer.newLine(); } writer.close(); reader.close(); } // public static boolean check(String n, String m) { // boolean found = false; // int i = 0; // for (; i < n.length() && !found; i++) { // if (n.charAt(i) == m.charAt(0)) { // found = true; // } // } // // int j = 0; // i = i - 1; // while (j < m.length() && found) { // // if (n.charAt(i) != m.charAt(j)) // found = false; // j++; // i = (i + 1) % m.length(); // } // return found; // } public static int numOfways(String n) { String tail = """"; String head = """"; String ss = """"; int counter = 0; hs.clear(); for (int i = 1; i < n.length(); i++) { tail = n.substring(i, n.length()); head = n.substring(0, i); ss = tail + head; int ssi = Integer.parseInt(ss); if ((ssi + """").length() == n.length()&&ssi>Integer.parseInt(n)) { if ( ssi <= m&&!hs.contains(ssi)) { hs.add(ssi); counter++; } } } return counter; } public static void main(String[] args) throws NumberFormatException, IOException { solve(); //m=500; //System.out.println(numOfways(""301"")); } } " B21252,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class Shell { private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private static final String ERROR = ""Error!""; private static final String ERROR_INVALID_INT = ""Ungueltige Integer-Zahl! (Nochmal eingeben) ""; private static int numberOfCases = Integer.MAX_VALUE; public static void main(String[] args) { numberOfCases = readInt(); int x = 0; while (x < numberOfCases) { String[] tokens = getTokens(); int a = Integer.parseInt(tokens[0]); int b = Integer.parseInt(tokens[1]); int y = recycle(a, b); x++; System.out.println(""Case #"" + x + "": "" + y); } } private static String[] getTokens() { String line; try { line = in.readLine(); } catch (IOException e) { throw new Error(e); } if (line == null) { System.err.println(ERROR); return null; } else { return line.split(""\\s""); } } private static int readInt() { while (true) { for (String token : getTokens()) { try { return Integer.parseInt(token); } catch (NumberFormatException e) { System.err.println(ERROR_INVALID_INT); } } } } private static int[] intToArray(int i) { String stringInt = Integer.toString(i); String[] splittedString = stringInt.split(""""); int[] resultArray = new int[splittedString.length - 1]; int index = 0; while ((index + 1) < splittedString.length) { resultArray[index] = Integer.parseInt(splittedString[index + 1]); index++; } return resultArray; } private static boolean validRecycledNumber(int[] a, int[] b, int m) { if (m > 0 && m < a.length && a[m] >= a[0] && a.length == b.length && checkSmallerThan(a, b, m)) { if (a[m] == a[0]) { int indexMoved = m + 1; int indexOriginal = 1; int arrayLength = a.length; while (indexMoved < arrayLength) { if (a[indexMoved] > a[indexOriginal]) { return true; } else if (a[indexMoved] < a[indexOriginal]) { return false; } indexMoved++; indexOriginal++; } int i = 0; int delta = arrayLength - m; while ((i + delta) < a.length) { if (a[i] > a[i + delta]) { return true; } else if (a[i] < a[i + delta]) { return false; } i++; } return false; } else { return true; } } else { return false; } } private static boolean checkSmallerThan(int a[], int b[], int m) { int changableM = m; int arrayLength = a.length; int actualIndex = 0; while (changableM < arrayLength) { if (a[changableM] < b[actualIndex]) { return true; } else if (a[changableM] > b[actualIndex]) { return false; } changableM++; actualIndex++; } int indexA = 0; while (indexA < m) { if (a[indexA] < b[actualIndex]) { return true; } else if (a[indexA] > b[actualIndex]) { return false; } indexA++; actualIndex++; } return true; } private static int recycle(int a, int b) { int counter = 0; int[] bArray = intToArray(b); int constantM = bArray.length - 1; while (a <= b) { int[] aArray = intToArray(a); int m = constantM; ArrayList listOfChangedNumbers = new ArrayList<>(); while (m > 0) { if (validRecycledNumber(aArray, bArray, m)) { int recycledNumber = moveRecycled(aArray, m); if (!listOfChangedNumbers.contains(recycledNumber)) { listOfChangedNumbers.add(recycledNumber); counter++; } } m--; } a++; } return counter; } private static int moveRecycled(int[] a, int m) { int result = 0; int changableM = m; int aLength = a.length; String[] resultArray = new String[aLength]; int index = 0; while (changableM < aLength) { resultArray[index] = Integer.toString(a[changableM]); changableM++; index++; } int actualIndex = 0; while (index < aLength) { resultArray[index] = Integer.toString(a[actualIndex]); index++; actualIndex++; } String resultString = """"; int i = 0; while (i < resultArray.length) { resultString = resultString + resultArray[i]; i++; } result = Integer.parseInt(resultString); return result; } } " B21823,"import java.util.Scanner; /** * * @author Yasura */ public class C { public static void main(String[] args) { Scanner scanInt = new Scanner(System.in); int noOfCases = scanInt.nextInt(); int count, length, A, B, tmp, base, invBase; for (int i = 0; i < noOfCases; i++) { count = 0; A = scanInt.nextInt(); B = scanInt.nextInt(); length = (Integer.toString(A)).length(); for (int k = A; k <= B; k++) { for (int j = 1; j < length; j++) { base = (int) Math.pow(10, j); invBase = (int) Math.pow(10, length - j); tmp = ((k % base) * invBase + k / base); if (tmp > k && tmp <= B ) { count++; } } } System.out.println(""Case #""+(i+1)+"": ""+count); } } } " B21230,"package round03; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; /** * Problem Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers. Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros. Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A ¡Â n < m ¡Â B? Input The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B. Output For each test case, output one line containing ""Case #x: y"", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A ¡Â n < m ¡Â B. Limits 1 ¡Â T ¡Â 50. A and B have the same number of digits. Small dataset 1 ¡Â A ¡Â B ¡Â 1000. Large dataset 1 ¡Â A ¡Â B ¡Â 2000000. Sample input 4 1 9 10 40 100 500 1111 2222 output Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 * @author chmin * */ public class RecycledNumbers { public static class RNumber { String n; int cntShift = 0; public RNumber( int n){ init(n); } public void init( int n ){ this.n = """" + n; cntShift = 0; } public int next() { int pos = n.length()-1; cntShift ++; while ( n.charAt(pos) == '0'){ pos --; cntShift ++; } if ( pos > 0 ) { String v = n.substring(pos , n.length()) + n.substring(0, pos); n = v; } return Integer.parseInt(n); } public boolean hasNext() { return cntShift < n.length(); } } public void solve() throws IOException{ Scanner scanner = new Scanner (getClass().getResourceAsStream(""R3-large.in"")); int T = scanner.nextInt(); RNumber rnum = new RNumber(0); HashSet set = new HashSet<>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < T ; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); set.clear(); for( int n = A ; n <= B ; n++){ rnum.init(n); while ( rnum.hasNext() ){ int m = rnum.next(); if ( n < m && m <= B) { set.add(n + "" "" + m); } } } sb.append(""Case #"" + (i+1) + "": "" + set.size() + System.getProperty(""line.separator"")); } BufferedWriter bw = new BufferedWriter(new FileWriter(""R3-large.out"")); bw.write(sb.toString()); bw.close(); } /** * @param args */ public static void main(String[] args) { try { new RecycledNumbers().solve(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B20967,"import java.io.*; import java.util.*; public class Main implements Runnable { Scanner in = new Scanner(System.in); HashMap map; long[] cnt = new long[2000000]; public Integer[] findPartner(int n) { ArrayList arr = new ArrayList(); String num = String.valueOf(n); for (int i = 1; i < num.length(); i++) { String s = num.substring(i); s += num.substring(0, i); arr.add(Integer.parseInt(s)); } return (Integer[]) arr.toArray(new Integer[arr.size()]); } public void run() { int a, b, c, t = in.nextInt(); long ans; for (int i = 1; i <= t; i++) { a = in.nextInt(); b = in.nextInt(); c = 0; Arrays.fill(cnt, 0); map = new HashMap(); for (int j = a; j <= b; j++) { if (!map.containsKey(j)) { c++; Integer[] arr = findPartner(j); map.put(j, c); for (int k = 0; k < arr.length; k++) if (arr[k] >= a && arr[k] <= b) map.put(arr[k], c); } } for (int j = a; j <= b; j++) cnt[(Integer)map.get(j)]++; ans = 0l; for (int j = 1; j <= c; j++) ans += (cnt[j] - 1l) * cnt[j] / 2; System.out.println(""Case #"" + i + "": "" + ans); } } public static void main(String[] args) { new Thread(new Main()).start(); } }" B21957,"/** * C.java * @author Joel C. Soares */ import java.util.Scanner; import java.util.HashSet; public class C { public static int inv( int n, int l ) { int x = n % 10, p = ( int ) Math.pow( 10, l - 1 ); for( int i = 0; i < l - 1; i++ ) { x = x * 10 + n / p; n = n % p; p = p / 10; } return x; } // fim de método public static int length( int n ) { int i = 0; if( n == 0 ) return 1; while( n != 0 ) { n = n / 10; i++; } return i; } public static void main( String args[] ) { Scanner input = new Scanner( System.in ); int t, a, b, n, q, p, l, total, count; HashSet set = new HashSet(); t = input.nextInt(); for( int i = 0; i < t; i++ ) { a = input.nextInt(); b = input.nextInt(); // computa resultado set.clear(); total = 0; for( n = a; n < b; n++ ) { q = n; l = length( q ); set.add( q ); count = 1; for( int j = 0; j < l - 1; j++ ) { q = inv( q, l ); // verifica restricoes if( q >= a && q <= b && !set.contains( q ) ) { set.add( q ); count++; } // fim de if } total += ( count - 1 ) * count / 2; } // fim de for System.out.printf( ""Case #%d: %d\n"", i + 1, total ); } } }" B21249,"package gcj2012.qualificationround; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) throws Exception { solve(System.in, System.out); } private static void solve(InputStream in, PrintStream out) throws IOException { Scanner scanner = new Scanner(in); int T = scanner.nextInt(); for (int t=1; t<=T; t++) { final int A = scanner.nextInt(); final int B = scanner.nextInt(); Map> pairs = new LinkedHashMap>(); for (int i=A; i<=B; i++) { pairs.put(i, new LinkedHashSet()); } for (int i=A; i<=B; i++) { String s = Integer.toString(i); for (int splitPoint=1; splitPoint<=numDigitsIn(A)-1; splitPoint++) { String sa = s.substring(0, splitPoint); String sb = s.substring(splitPoint); int newnum = Integer.parseInt(sb+sa); if (i < newnum && newnum <= B) { pairs.get(i).add(newnum); } } } int numRecycledPairs = 0; for (int n=A; n= i && checkRev(i) && i!=rev) { if(checkSymmetry(i)) sym++; counter++; } } } sym = sym/2; } private boolean checkRev(int i) { char ch[] = (i + """").toCharArray(); for (char c : ch) { if (ch[0] == c) { continue; } else { return true; } } return false; } public int permuteNumber(String st, int pos) { String s = st.substring(st.length() - pos) + st.substring(0, st.length() - pos); return Integer.parseInt(s); } private boolean checkSymmetry(int i){ String s =(i+""""); if(s.substring(0,s.length()/2).equals(s.substring(s.length()/2))){ return true; } else{ return false; } } } " B21024,"import java.util.*; public class C { Scanner in = new Scanner(System.in); int sols; ArrayList possibles = new ArrayList(); public C() { int ncases = in.nextInt(); for (int i = 0; i < ncases; i++) { sols = 0; int n = in.nextInt(); int m = in.nextInt(); findSolutions(n, m); System.out.println(""Case #"" + (i + 1) + "": "" + sols); possibles.clear(); } } private void findSolutions(int n, int m) { while (n < m) { findPairs(n, m); checkdups(); possibles.clear(); n++; } } private void findPairs(int n, int m) { String value = Integer.toString(n); for (int i = 1; i < value.length(); i++) { String nose = value.substring(0, i); String ass = value.substring(i, value.length()); String news = ass.concat(nose); compare(value, news, m); } } private void compare(String value, String curvalue, int m) { if (Integer.toString(Integer.parseInt(value)).length() == Integer.toString( Integer.parseInt(curvalue)).length()) { if (Integer.parseInt(curvalue) <= m && Integer.parseInt(value) < Integer.parseInt(curvalue)) { possibles.add(curvalue); } } } private void checkdups() { for (int i = 0; i < possibles.size(); i++) { for (int x = i + 1; x < possibles.size(); x++) { if (possibles.get(i).equals(possibles.get(x))) { possibles.remove(x); } } } sols += possibles.size(); } public static void main(String[] args) { new C(); } } " B20954,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class recycled { static HashMap> found; static Set touched; public static int calc(long a, long b){ int compteur = 0; int nbchiffres = 1; long pow = 10; while(powpow){ pow=pow*10; nbchiffres++; } //System.out.println(n+"" ""+a+"" ""+b); compteur+= nbpossibleM(a,b,n, nbchiffres, pow); } return compteur; } private static int nbpossibleM(long a, long b, long n, int nbchiffre, long pow) { long smallpow = 10; long bigpow = pow/10; //System.out.println(""-------- ""+nbchiffre+"" ""+smallpow+"" ""+bigpow+""\n\n\n""); long m=0; int possibilities =0; touched.clear(); for(int k=1; k=a && !touched.contains(m)){ /*if(found.containsKey(m)){ HashMap map = found.get(m); if(map.containsKey(n)){ map.put(n, map.get(n)+1); } else{ map.put(n, 1); } } else{ HashMap map = new HashMap(); map.put(n, 1); found.put(m, map); }*/ possibilities++; touched.add(m); } smallpow=smallpow*10; bigpow=bigpow/10; } return possibilities; } public static void main(String[] args) throws FileNotFoundException{ //found = new HashMap>(); touched = new HashSet(); Scanner s = new Scanner(new File(""input.txt"")); int nbcas = s.nextInt(); for(int i=0; i map = found.get(m); for(long n: map.keySet()){ if(map.get(n)==2){ System.out .println(m+"" ""+n); } } }*/ } } " B21514,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Problem3_D { public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File(""C-large.in"")); int num = scanner.nextInt(); for (int count = 1; count <= num; count++) { int ii = scanner.nextInt(); int jj = scanner.nextInt(); int counter = 0; for (int i = ii; i <= jj; i++) { String s2 = """" + i; for (int k = 0; k <= s2.length(); k++) { String a = s2.substring(0, k); String b = s2.substring(k, s2.length()); int j = Integer.parseInt(b + a); if (j > i && j <= jj) counter++; } } System.out.println(""Case #"" + count + "": "" + counter); } } } " B20820,"/** * Created by IntelliJ IDEA. * User: Administrator * Date: 3/3/12 * Time: 11:00 AM * To change this template use File | Settings | File Templates. */ import SRMLib.MathLibrary; import SRMLib.TestSRMLib; import com.sun.org.apache.bcel.internal.generic.F2D; import java.io.*; import java.util.*; import java.util.logging.Handler; import java.util.zip.Inflater; public class SRM { public static void main(String[] args) throws IOException { //TestSRMLib.run(); codeJam.main(); return; } } class codeJam { public static void main() throws IOException { String inputPath = ""E:\\input.txt""; String outputPath = ""E:\\output.txt""; BufferedReader input = new BufferedReader(new FileReader(inputPath)); BufferedWriter output = new BufferedWriter(new FileWriter(outputPath)); String line; line = input.readLine(); int T = Integer.parseInt(line); for (int i = 1; i <= T; ++i) { line = input.readLine(); String[] words = line.split("" ""); Integer A = Integer.parseInt(words[0]); Integer B = Integer.parseInt(words[1]); int res = 0; int l = A.toString().length(); int multiplier = 1; for (int k = 1; k < l; ++k) multiplier *= 10; for (int n = A; n < B; ++n) { int m = n; Set set = new HashSet(); for (int j = 1; j < l; ++j) { m = (m % multiplier) * 10 + m / multiplier; if ((n < m) && (m <= B)) { if (!set.contains(m)) { res++; set.add(m); } } } } output.write(""Case #"" + i + "": "" + res); output.newLine(); } input.close(); output.close(); } }" B22016,"package codeJam; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; @SuppressWarnings(""serial"") public class Problem3 extends JFrame { //TODO Set file names static final String INFILE = ""codeJam/inFile3l.txt""; static final String OUTFILE = ""codeJam/outFile3l.txt""; // variable declaration JTextArea inText, outText; public static void main(String[] args) { new Problem3(); } public Problem3() { DefaultHandler aHandler = new DefaultHandler(); setTitle(""Title""); Container content = this.getContentPane(); content.setLayout(null); //////////////////////////////////////////////////////////////////////// LABELS //////// JLabel aLabel = new JLabel(""Input:""); aLabel.setBounds(258, 5, 50, 20); content.add(aLabel); aLabel = new JLabel(""Output:""); aLabel.setBounds(791, 5, 50, 20); content.add(aLabel); /////////////////////////////////////////////////////////////////////// TEXTAREAS ////// inText = new JTextArea(); JScrollPane scroll = new JScrollPane(inText); scroll.setBounds(33, 33, 500, 200); content.add(scroll); outText = new JTextArea(); scroll = new JScrollPane(outText); scroll.setBounds(566, 33, 500, 200); content.add(scroll); //////////////////////////////////////////////////////////////////////// BUTTONS /////// JButton aButton = new JButton(""Test File""); aButton.addActionListener(aHandler); aButton.setBounds(33, 250, 233, 40); content.add(aButton); aButton = new JButton(""Run File""); aButton.addActionListener(aHandler); aButton.setBounds(300, 250, 233, 40); content.add(aButton); aButton = new JButton(""Test TextBox""); aButton.addActionListener(aHandler); aButton.setBounds(566, 250, 233, 40); content.add(aButton); aButton = new JButton(""Run TextBox""); aButton.addActionListener(aHandler); aButton.setBounds(833, 250, 233, 40); content.add(aButton); setSize(1100, 325); setResizable(false); setLocation(100, 100); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private class DefaultHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(""Test File"")) { ArrayList fileContents = new ArrayList(); Scanner scanner; try { scanner = new Scanner(new File(INFILE)); while (scanner.hasNextLine()) fileContents.add(scanner.nextLine()); scanner.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } String[] output = new String[fileContents.size()]; fileContents.toArray(output); outText.setText(""""); for (int i = 0; i < output.length; i++) outText.setText(outText.getText() + ""."" + output[i] + ""."" + ""\n""); } else if (e.getActionCommand().equals(""Run File"")) { ArrayList fileContents = new ArrayList(); Scanner scanner; try { scanner = new Scanner(new File(INFILE)); while (scanner.hasNextLine()) fileContents.add(scanner.nextLine()); scanner.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } String[] output = new String[fileContents.size()]; fileContents.toArray(output); String[] answer = myAlgorithm(output); Writer out; try { out = new OutputStreamWriter(new FileOutputStream(OUTFILE)); for (int i = 0; i < answer.length; i++) out.write(answer[i] + ""\n""); out.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } outText.setText(""File Written""); } else if (e.getActionCommand().equals(""Test TextBox"")) { String[] output = inText.getText().split(""\n""); outText.setText(""""); for (int i = 0; i < output.length; i++) outText.setText(outText.getText() + ""."" + output[i] + ""."" + ""\n""); } else if (e.getActionCommand().equals(""Run TextBox"")) { String[] output = inText.getText().split(""\n""); String[] answer = myAlgorithm(output); outText.setText(""""); for (int i = 0; i < answer.length; i++) outText.setText(outText.getText() + answer[i] + ""\n""); } } // IMPORTANT NOTE:: INFILE is read and OUTFILE is written // in the Project Directory. // TODO:: Write all of your algorithm code here // String[] myData is the lines of input // You must return a String[] public String[] myAlgorithm(String[] myData) { int numProbs = Integer.parseInt(myData[0]); String[] workSet = new String[numProbs]; for (int i = 0; i < numProbs; i++) { // mess with myData[i + 1] here and output to workSet[i] String[] testVals = myData[i + 1].split("" ""); int myMin = Integer.parseInt(testVals[0]); int myMax = Integer.parseInt(testVals[1]); int count = 0; int mySize = 2000001; int[] hugeArray = new int[mySize]; for (int j = 0; j < mySize; j++) hugeArray[j] = 0; for (int j = myMin; j <= myMax; j++) { String curNum = Integer.toString(j); int[] myInts = new int[curNum.length()]; for (int k = 0; k < curNum.length(); k++) myInts[k] = Integer.parseInt("""" + curNum.charAt(k)); int smallestInt = 2000004; for (int k = 0; k < myInts.length; k++) { String nextStr = """"; for (int l = k; l < myInts.length; l++) nextStr += """" + myInts[l]; for (int l = 0; l < k; l++) nextStr += """" + myInts[l]; int finalInt = Integer.parseInt(nextStr); if (finalInt < smallestInt) smallestInt = finalInt; } count += hugeArray[smallestInt]; hugeArray[smallestInt]++; } workSet[i] = """" + count; } String[] myOutput = new String[numProbs]; for (int i = 0; i < numProbs; i++) myOutput[i] = ""Case #"" + (i + 1) + "": "" + workSet[i]; return myOutput; } } } " B22033,"package com.menzus.gcj._2012.qualification.c; import java.util.HashSet; import java.util.Set; import com.menzus.gcj.common.OutputProducer; public class COutputProducer implements OutputProducer { @Override public COutputEntry produceOutput(CInput input) { int lowerLimit = input.getLowerLimit(); int upperLimit = input.getUpperLimit(); long recycledPairNumber = 0; Set pairs = new HashSet(); for (int i = lowerLimit; i < upperLimit; i++) { pairs.clear(); int numberLength = getNumberLength(i); int numberMajor = getMajorNumber(i); int rotatedNumber = i; for (int j = 0; j < numberLength - 1; j++) { rotatedNumber = rotateNumber(rotatedNumber, numberMajor); if (numberLength == getNumberLength(rotatedNumber)) { if (rotatedNumber >= lowerLimit && rotatedNumber <= upperLimit && rotatedNumber > i) { if (!pairs.contains(rotatedNumber)) { recycledPairNumber++; pairs.add(rotatedNumber); } } } } } COutputEntry outputEntry = new COutputEntry(); outputEntry.setRecycledPairNumber(recycledPairNumber); return outputEntry; } // // private int rotateNumber(int i, int majorNumber) { // return (i / 10) + ((i % 10) * majorNumber); // } private int rotateNumber(int i, int majorNumber) { return ((i % majorNumber) * 10) + (i / majorNumber); } private int getMajorNumber(int i) { if (i < 10) { return 1; } else if (i < 100) { return 10; } else if (i < 1000) { return 100; } else if (i < 10000) { return 1000; } else if (i < 100000) { return 10000; } else if (i < 1000000) { return 100000; } else { return 1000000; } } private int getNumberLength(int i) { if (i < 10) { return 1; } else if (i < 100) { return 2; } else if (i < 1000) { return 3; } else if (i < 10000) { return 4; } else if (i < 100000) { return 5; } else if (i < 1000000) { return 6; } else { return 7; } } } " B21722," //Author KNIGHT0X300 import java.util.Scanner; import java.util.TreeSet; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); TreeSet ts=new TreeSet(); int[] A1=new int[8]; A1[0]=1; A1[1]=10; A1[2]=100; A1[3]=1000; A1[4]=10000; A1[5]=100000; A1[6]=1000000; A1[7]=10000000; int t=s.nextInt(); long time = System.nanoTime(); for(int i=0;iA;j--) { int y=j ; ts.clear(); int sz= (int)Math.floor(Math.log10(j)); for(int k=1;k=A)){ if(!ts.contains(y)) tot++;ts.add(y);} } } System.out.println(""Case #""+(i+1)+"": ""+tot); } System.out.println(""Finished in: "" + (System.nanoTime() - time) / Math.pow(10, 6) + ""ms""); } } " B21199,"import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class QuestionA extends Question{ private static Map translationMap; private static boolean isInit; private StringBuilder sb; public QuestionA(Result result, Counter counter) { super(result, counter); if (!isInit) { init(); isInit=true; } } private void init() { translationMap = new HashMap(); String text = ""zyeq""+""ejp mysljylc kd kxveddknmc re jsicpdrysi""+""rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd""+""de kr kd eoya kw aej tysr re ujdr lkgc jv""; String translation = ""qaoz""+""our language is impossible to understand""+""there are twenty six factorial possibilities""+""so it is okay if you want to just give up""; for (int i = 0; i < text.length(); i++) { if (!translationMap.containsKey(text.charAt(i))) translationMap.put(text.charAt(i), translation.charAt(i)); } } @Override public void readInput(Scanner scanner) { sb = new StringBuilder(); sb.append(scanner.nextLine()); } @Override public String solution() { for (int i = 0; i < sb.length(); i++) { sb.setCharAt(i, translationMap.get(sb.charAt(i))); } return sb.toString(); } } " B21435,"package jp.funnything.competition.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.apache.commons.io.IOUtils; public class AnswerWriter { private static final String DEFAULT_FORMAT = ""Case #%d: %s\n""; private final BufferedWriter _writer; private final String _format; public AnswerWriter( final File output , final String format ) { try { _writer = new BufferedWriter( new FileWriter( output ) ); _format = format != null ? format : DEFAULT_FORMAT; } catch ( final IOException e ) { throw new RuntimeException( e ); } } public void close() { IOUtils.closeQuietly( _writer ); } public void write( final int questionNumber , final Object result ) { write( questionNumber , result.toString() , true ); } public void write( final int questionNumber , final String result ) { write( questionNumber , result , true ); } public void write( final int questionNumber , final String result , final boolean tee ) { try { final String content = String.format( _format , questionNumber , result ); if ( tee ) { System.out.print( content ); System.out.flush(); } _writer.write( content ); } catch ( final IOException e ) { throw new RuntimeException( e ); } } } " B20196,"import sun.reflect.generics.tree.Tree; import java.io.*; import java.util.TreeSet; /** * User: Andrii Baranov * Date: 14.04.12 * Time: 14:11 */ public class RecycledNumbers { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new FileReader(""in/C/C-large.in"")); int testCases = Integer.parseInt(br.readLine()); int results[] = new int[testCases]; for(int i = 0; i < testCases; i++){ String paramsStr = br.readLine(); String[] params = paramsStr.split("" ""); results[i] = countRecycled(Integer.parseInt(params[0]), Integer.parseInt(params[1])); } br.close(); BufferedWriter bw = new BufferedWriter(new FileWriter(""in/C/large-out.txt"")); for(int i = 0; i < testCases; i++){ bw.write(""Case #"" + (i + 1) + "": "" + results[i]); if (i + 1 < testCases) { bw.write(""\n""); } } bw.close(); } static int countRecycled(int A, int B) { String rep; int res = 0; for (int first = A; first < B; first++) { rep = Integer.toString(first); TreeSet recNumbers = new TreeSet(); for (int j = rep.length() - 1; j > 0; j--) { if (rep.charAt(j) != '0') { String replaced = rep.substring(j) + rep.substring(0, j); Integer num = new Integer(replaced); if (num.intValue() <= B && num.intValue() > first) { recNumbers.add(num); } } } res += recNumbers.size(); } return res; } } " B20970,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Recycled_Numbers { public static int recycled(int A, int B) { int n = 0, j = 0, m = 0, c = 0; String tmp = """", subB = """", subE = """", recycled = """"; for (n = A; n <= B; n++) { // System.out.println(""""); tmp = String.valueOf(n); for (j = 0; j < tmp.length(); j++) { subB = tmp.substring(0, j + 1); subE = tmp.substring(j + 1); recycled = subE + subB; m = Integer.parseInt(recycled); if ((m > n) && (m <= B)) { c++; //System.out.println(n+"",""+m); } // System.out.println(recycled); } } return c; } public static void main(String[] args) { String filename = ""/myown/developpement/Google_Code_Jam/recycled_numbers.in""; String ligne = """"; StringTokenizer st1; int i = 0, j = 0; int nbrLigne = 0; String tmp = """"; int A = 0, B = 0; try { FileInputStream fStream = new FileInputStream(filename); BufferedReader in = new BufferedReader(new InputStreamReader( fStream)); if (in.ready()) { ligne = in.readLine(); nbrLigne = Integer.parseInt(ligne); for (j = 0; j < nbrLigne; j++) { ligne = in.readLine(); st1 = new StringTokenizer(ligne, "" ""); A = Integer.parseInt(st1.nextToken()); // tmp = """"; B = Integer.parseInt(st1.nextToken()); //System.out.println(A + "","" + B); System.out.println(""Case #""+(j+1)+"": "" + recycled(A, B)); } } } catch (IOException e) { System.out.println(""File input error""); } } } " B20979,"package codejam; import java.util.ArrayList; public class RecycledNumbers { public static void recycled(String in,String out){ InOutTool iot = new InOutTool(in,out); ArrayList js = new ArrayList(); for(int i=1;i1){ ArrayList list = new ArrayList(); for(int k=ns.length()-1;k>0;k--){ String temp = ns.substring(k) + ns.substring(0, k);//move if(!temp.startsWith(""0"")){ int t = Integer.parseInt(temp); if(t=f&&(String.valueOf(t).length()==ns.length())&&(!list.contains(String.valueOf(t)))){ list.add(String.valueOf(t)); count ++; } } } } n++; } js.add(""Case #"" + i + "": "" + count); } iot.clear();iot.addAll(js); System.out.println(iot.outText()); } public static void main(String...args){ RecycledNumbers.recycled(""C-large.in"", ""C-large.out""); } } " B20759,"package codejam; public class DirConsts { public static final String // INPUT_DIR = ""/home/luke/Downloads"", // OUTPUT_DIR = ""/home/luke/Downloads/CodeJam""; } " B20668,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.Properties; import java.util.Set; /** * Works good for CF * * @author cykeltillsalu */ public class RecycleNumbers { // some local config static boolean test = true; static String testDataFile = ""testdata.txt""; static String feedFile = ""feed.txt""; CompetitionType type = CompetitionType.CF; private static String ENDL = ""\n""; // solution private void solve() throws Throwable { int n = iread(); for (int i = 0; i < n; i++) { solveIt(i + 1); } } Set pairs = new HashSet(); int min, max; private void solveIt(int nr) throws Throwable { pairs.clear(); long ans = 0; min = iread(); max = iread(); for (int i = min; i <= max; i++) { ans += cnt(Integer.valueOf(i).toString()); } System.out.println(""Case #"" + nr + "": "" + ans); } private long cnt(String string) { pairs.clear(); long ret = 0; for (int i = 1; i < string.length(); i++) { String asStr = string.substring(i) + string.substring(0,i); Integer valueOf = Integer.valueOf(asStr); if(valueOf > Integer.valueOf(string) && valueOf >= min && valueOf <= max){ ret ++; String save = string + "">"" + asStr; pairs.add(save); } } return pairs.size(); } public int iread() throws Exception { return Integer.parseInt(wread()); } public double dread() throws Exception { return Double.parseDouble(wread()); } public long lread() throws Exception { return Long.parseLong(wread()); } public String wread() throws IOException { StringBuilder b = new StringBuilder(); int c; c = in.read(); while (c >= 0 && c <= ' ') c = in.read(); if (c < 0) return """"; while (c > ' ') { b.append((char) c); c = in.read(); } return b.toString(); } public static void main(String[] args) throws Throwable { if (test) { // run all cases from testfile: BufferedReader testdataReader = new BufferedReader(new FileReader(testDataFile)); String readLine = testdataReader.readLine(); int casenr = 0; out: while (true) { BufferedWriter w = new BufferedWriter(new FileWriter(feedFile)); if (!readLine.equals(""input"")) { break; } while (true) { readLine = testdataReader.readLine(); if (readLine.equals(""output"")) { break; } w.write(readLine + ""\n""); } w.close(); System.out.println(""Answer on case "" + (++casenr) + "": ""); new RecycleNumbers().solve(); System.out.println(""Expected answer: ""); while (true) { readLine = testdataReader.readLine(); if (readLine == null) { break out; } if (readLine.equals(""input"")) { break; } System.out.println(readLine); } System.out.println(""----------------""); } testdataReader.close(); } else { // run on server new RecycleNumbers().solve(); } out.close(); } public RecycleNumbers() throws Throwable { if (test) { in = new BufferedReader(new FileReader(new File(feedFile))); } } InputStreamReader inp = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(inp); static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); enum CompetitionType { CF, OTHER }; }" B21273,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class Numbers { public static FileReader fr; public static BufferedReader br; public static FileWriter fw; public static BufferedWriter bw; public void read(String path) throws Exception { fr = new FileReader(path); br=new BufferedReader(fr); } public void write(String path) throws Exception { } public void execute(BufferedReader br,String path)throws Exception { String s; fw =new FileWriter(path,false); bw=new BufferedWriter(fw); s=br.readLine(); int i1=1; while((s=br.readLine())!=null) { int count =0; String st[]=s.split(""\\s""); int a=Integer.parseInt(st[0]); int b=Integer.parseInt(st[1]); for(int i=a;i<=b;i++) { int temp=i; String abc=Integer.toString(temp); int length=abc.length(); int index=length-1; String tempString=abc; while(index>0) { String first=tempString.substring(0, index); String second=tempString.substring(index,length); abc=second+first; int newnumber=Integer.parseInt(abc); if((newnumber<=b && newnumber>temp )&& !abc.startsWith(""0"") && (Integer.toString(temp).length())==abc.length()) count++; index--; } } bw.write(""Case #""+ i1++ +"": "" +count +""\n""); } bw.close(); fr.close(); } public static void main(String[] args) throws Exception { Numbers t=new Numbers(); t.read(""E:\\codejam\\Files\\C.in""); t.execute(br,""E:\\codejam\\Files\\C.out""); } } " B21035,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class Main { public static HashMap mapp = new HashMap(); public static void main(String[] args) throws Exception { PrintWriter writer = new PrintWriter(new FileWriter(""output.txt"")); BufferedReader input = new BufferedReader(new FileReader(""C-large.in"")); int size=Integer.parseInt(input.readLine()); for(int i=0; i Sett = new HashSet(); String tokens[] = input.readLine().split("" ""); int Llimit = Integer.parseInt(tokens[0]); int Hlimit = Integer.parseInt(tokens[1]); for(int j=Llimit; jj && Integer.parseInt(temp)<=Hlimit) { Sett.add(str1+temp); } } } writer.println(""Case #""+(i+1)+"": ""+Sett.size()); } writer.close(); input.close(); } }" B21463,"package com.renoux.gael.codejam.utils; public class TechnicalException extends RuntimeException { private static final long serialVersionUID = 1L; public TechnicalException() { super(); } public TechnicalException(String message, Throwable cause) { super(message, cause); } public TechnicalException(String message) { super(message); } public TechnicalException(Throwable cause) { super(cause); } } " B21280,"/************************************************************************* * Compilation: javac In.java * Execution: java In * * Reads in data of various types from: stdin, file, URL. * * % java In * * Remarks * ------- * - isEmpty() returns true if there is no more input or * it is all whitespace. This might lead to surprising behavior * when used with readChar() * *************************************************************************/ import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.URL; import java.net.URLConnection; import java.util.Locale; import java.util.Scanner; /** * Input. This class provides methods for reading strings * and numbers from standard input, file input, URL, and socket. *

* The Locale used is: language = English, country = US. This is consistent * with the formatting conventions with Java floating-point literals, * command-line arguments (via Double.parseDouble()) * and standard output (via System.out.print()). It ensures that * standard input works the number formatting used in the textbook. *

* For additional documentation, see Section 3.1 of * Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. */ public final class In { private Scanner scanner; // assume Unicode UTF-8 encoding //private String charsetName = ""UTF-8""; private String charsetName = ""ISO-8859-1""; // assume language = English, country = US for consistency with System.out. private Locale usLocale = new Locale(""en"", ""US""); /** * Create an input stream for standard input. */ public In() { scanner = new Scanner(new BufferedInputStream(System.in), charsetName); scanner.useLocale(usLocale); } /** * Create an input stream from a socket. */ public In(Socket socket) { try { InputStream is = socket.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + socket); } } /** * Create an input stream from a URL. */ public In(URL url) { try { URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + url); } } /** * Create an input stream from a file. */ public In(File file) { try { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + file); } } /** * Create an input stream from a filename or web page name. */ public In(String s) { try { // first try to read file from local file system File file = new File(s); if (file.exists()) { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); return; } // next try for files included in jar URL url = getClass().getResource(s); // or URL from web if (url == null) { url = new URL(s); } URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println(""Could not open "" + s); } } /** * Does the input stream exist? */ public boolean exists() { return scanner != null; } /** * Is the input stream empty? */ public boolean isEmpty() { return !scanner.hasNext(); } /** * Does the input stream have a next line? */ public boolean hasNextLine() { return scanner.hasNextLine(); } /** * Read and return the next line. */ public String readLine() { String line; try { line = scanner.nextLine(); } catch (Exception e) { line = null; } return line; } /** * Read and return the next character. */ public char readChar() { // (?s) for DOTALL mode so . matches any character, including a line termination character // 1 says look only one character ahead // consider precompiling the pattern String s = scanner.findWithinHorizon(""(?s)."", 1); return s.charAt(0); } // return rest of input as string /** * Read and return the remainder of the input as a string. */ public String readAll() { if (!scanner.hasNextLine()) { return null; } // reference: http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html return scanner.useDelimiter(""\\A"").next(); } /** * Return the next string from the input stream. */ public String readString() { return scanner.next(); } /** * Return the next int from the input stream. */ public int readInt() { return scanner.nextInt(); } /** * Return the next double from the input stream. */ public double readDouble() { return scanner.nextDouble(); } /** * Return the next float from the input stream. */ public double readFloat() { return scanner.nextFloat(); } /** * Return the next long from the input stream. */ public long readLong() { return scanner.nextLong(); } /** * Return the next byte from the input stream. */ public byte readByte() { return scanner.nextByte(); } /** * Return the next boolean from the input stream, allowing ""true"" or ""1"" * for true and ""false"" or ""0"" for false. */ public boolean readBoolean() { String s = readString(); if (s.equalsIgnoreCase(""true"")) return true; if (s.equalsIgnoreCase(""false"")) return false; if (s.equals(""1"")) return true; if (s.equals(""0"")) return false; throw new java.util.InputMismatchException(); } /** * Read ints from file */ public static int[] readInts(String filename) { In in = new In(filename); String[] fields = in.readAll().trim().split(""\\s+""); int[] vals = new int[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Integer.parseInt(fields[i]); return vals; } /** * Read doubles from file */ public static double[] readDoubles(String filename) { In in = new In(filename); String[] fields = in.readAll().trim().split(""\\s+""); double[] vals = new double[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Double.parseDouble(fields[i]); return vals; } /** * Read strings from a file */ public static String[] readStrings(String filename) { In in = new In(filename); String[] fields = in.readAll().trim().split(""\\s+""); return fields; } /** * Read ints from standard input */ public static int[] readInts() { In in = new In(); String[] fields = in.readAll().trim().split(""\\s+""); int[] vals = new int[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Integer.parseInt(fields[i]); return vals; } /** * Read doubles from standard input */ public static double[] readDoubles() { In in = new In(); String[] fields = in.readAll().trim().split(""\\s+""); double[] vals = new double[fields.length]; for (int i = 0; i < fields.length; i++) vals[i] = Double.parseDouble(fields[i]); return vals; } /** * Read strings from standard input */ public static String[] readStrings() { In in = new In(); String[] fields = in.readAll().trim().split(""\\s+""); return fields; } /** * Close the input stream. */ public void close() { scanner.close(); } /** * Test client. */ public static void main(String[] args) { In in; String urlName = ""http://introcs.cs.princeton.edu/stdlib/InTest.txt""; // read from a URL System.out.println(""readAll() from URL "" + urlName); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(urlName); System.out.println(in.readAll()); } catch (Exception e) { System.out.println(e); } System.out.println(); // read one line at a time from URL System.out.println(""readLine() from URL "" + urlName); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(urlName); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { System.out.println(e); } System.out.println(); // read one string at a time from URL System.out.println(""readString() from URL "" + urlName); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(urlName); while (!in.isEmpty()) { String s = in.readString(); System.out.println(s); } } catch (Exception e) { System.out.println(e); } System.out.println(); // read one line at a time from file in current directory System.out.println(""readLine() from current directory""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""./InTest.txt""); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { System.out.println(e); } System.out.println(); // read one line at a time from file using relative path System.out.println(""readLine() from relative path""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""../stdlib/InTest.txt""); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { System.out.println(e); } System.out.println(); // read one char at a time System.out.println(""readChar() from file""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""InTest.txt""); while (!in.isEmpty()) { char c = in.readChar(); System.out.print(c); } } catch (Exception e) { System.out.println(e); } System.out.println(); System.out.println(); // read one line at a time from absolute OS X / Linux path System.out.println(""readLine() from absolute OS X / Linux path""); System.out.println(""---------------------------------------------------------------------------""); in = new In(""/n/fs/csweb/introcs/stdlib/InTest.txt""); try { while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } } catch (Exception e) { System.out.println(e); } System.out.println(); // read one line at a time from absolute Windows path System.out.println(""readLine() from absolute Windows path""); System.out.println(""---------------------------------------------------------------------------""); try { in = new In(""G:\\www\\introcs\\stdlib\\InTest.txt""); while (!in.isEmpty()) { String s = in.readLine(); System.out.println(s); } System.out.println(); } catch (Exception e) { System.out.println(e); } System.out.println(); } } " B20537,"import java.io.*; import java.util.*; import java.math.*; import static java.lang.System.out; // import static java.lang.Math.*; public class BaiC implements Runnable { public void run() { int ntest = nextInt(); int[] ndigits = new int[2000001]; for (int i = 0; i < 10; ++i) { ndigits[i] = 1; } for (int i = 10; i < ndigits.length; ++i) { ndigits[i] = ndigits[i / 10] + 1; } int[] p10 = new int[9]; p10[0] = 1; for (int i = 1; i < p10.length; ++i) p10[i] = p10[i - 1] * 10; int[] s = new int[111]; for (int test = 1; test <= ntest; ++test) { out.print(""Case #"" + test + "": ""); int A = nextInt(); int B = nextInt(); int res = 0; for (int i = A; i < B; ++i) { int x = i; int nd = ndigits[x]; int ns = 0; for (int k = 1; k < nd; ++k) { x = x / 10 + x % 10 * p10[nd - 1]; if (i < x && x <= B) { boolean ok = true; for (int j = 0; j < ns; ++j) if (x == s[j]) ok = false; if (ok) { s[ns++] = x; ++res; } } } } out.println(res); } } int[] ar(int st, int en) { int[] res = new int[Math.max(en - st, 0)]; for (int i = st; i < en; ++i) res[i - st] = i; return res; } int[] ar(int n) { return ar(0, n); } void viet(Object...os) { System.err.println(Arrays.deepToString(os)); } BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer strtok = null; String nextStr() { try { while(strtok == null || !strtok.hasMoreTokens()) strtok = new StringTokenizer(keyboard.readLine()); return strtok.nextToken(); } catch(Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); return null; } } int nextInt() { return Integer.parseInt(nextStr()); } long nextLong() { return Long.parseLong(nextStr()); } double nextDouble() { return Double.parseDouble(nextStr()); } public static void main(String[] args) { new BaiC().run(); } }" B21255,"package util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author bohmd */ public abstract class BaseResolver { private final String file; private BufferedReader reader; private BufferedWriter writer; int lineNum = 0; int caseNum = 0; public BaseResolver(String file) { this.file = file; } public void resolve() throws Exception { reader = new BufferedReader(new FileReader(input())); writer = new BufferedWriter(new FileWriter(output())); while (reader.ready()) { executeLine(reader.readLine()); lineNum++; } reader.close(); writer.close(); } private String input() { return file + "".in""; } private String output() { return file + "".out""; } protected abstract void executeLine(String line) throws Exception; protected void write(String result) throws Exception { writer.write(""Case #"" + (++caseNum) + "":"" + result); writer.newLine(); } public int getLineNum() { return lineNum; } } " B20059,"package qualification; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.PrintStream; public class C { static byte[][] MAP = new byte[1000][1000]; private static final char[] CASE = ""Case #"".toCharArray(); public static void main(String[] args) throws Throwable { // in = System.in; // out = System.out; // in = new FileInputStream(""in/C-small-attempt0.in""); in = new FileInputStream(""in/C-large.in""); out = new PrintStream(new FileOutputStream(""out/C.out"")); int T = readInt(); for (int test = 1; test <= T; test++) { int A = readInt(); int B = readInt(); int result = 0; for (int n = A; n < B; n++) { int nLen = length(n); // find all possible recycled numbers for this one for (int i = 1; i < nLen; i++) { int tenpow = pow(10,i); int tenpowfront = pow(10, nLen-i); int m = (n/tenpow) + ((n%tenpow) * tenpowfront); if (m == n) break;// if we found n back, it is a circular number (ex: 123123), and if we keep going, we'll duplicate the results found // the recycled numbers have to be: n < m; m <= B if (n < m && m <= B) { result++; } } } writeOut(CASE); writeOutNumber(test); writeOut(':'); writeOut(' '); writeOutNumber(result); writeOutLn(); flush(); } flush(); } static int length(int num) { int len = 1; int powerTen = 10; while (num >= powerTen) { powerTen *= 10; len++; } return len; } static InputStream in; static PrintStream out; static byte[] buffer = new byte[8192]; static int pos; static int max; static final int maxOut = 8192; static byte[] output = new byte[maxOut]; static int posOut = 0; static char[] tmpcharr = new char[128]; static int pow2(int v) { return v * v; } static int pow(int v, int mag) { return (int) Math.pow(v, mag); } static boolean reachedEndOfLine() throws Throwable { while (true) { int data = read(); if (data == -1) return true; if (data == '\r' || data == '\n') { return true; } if (data == ' ') { continue; } pos--; return false; } } // COMPARISION FUNCTIONS static boolean isValidChar(int v) { // nao verifica o 'DELETE' (127) return (v & 0xE0) != 0; } static boolean isNum(int v) { return v >= '0' && v <= '9'; } static boolean isLowercase(int cur) { return cur >= 'a' && cur <= 'z'; } static boolean isUppercase(int cur) { return cur >= 'A' && cur <= 'Z'; } // is a letter (alphabetic) static boolean isAlpha(int cur) { return isLowercase(cur) || isUppercase(cur); } // is alphanumeric (letters and numbers) static boolean isAlphaNum(int cur) { return isAlpha(cur) || isNum(cur); } static boolean isMinus(int cur) { return cur == '-'; } static boolean isPlus(int cur) { return cur == '+'; } // INPUT FUNCTIONS static void goToBeginOfNextWord() throws Throwable { int cur; // se for -1 já sai do método while ((cur = read()) != -1) { // se for um char válido então deixa o ponteiro nele if (cur > 32) { pos--; return; } } } // return the length of the string read static String readWord() throws Throwable { int len = 0; int cur; // descarta os espacos em branco primeiro while ((cur = read()) < 33) { if (cur == -1) return """"; } tmpcharr[len++] = (char) cur; while ((cur = (char) read()) > 32) { tmpcharr[len++] = (char) cur; } return new String(tmpcharr, 0, len); } static void discardWord() throws Throwable { int cur; // descarta os espacos em branco primeiro while ((cur = read()) < 33) { if (cur == -1) return; } // descarta os valores 'validos' while ((cur = read()) > 32) ; } static int readInt() throws Throwable { int cur; while (!isNum(cur = read()) && !isMinus(cur)) if (cur == -1) return -1; int v = 0; boolean minus = false; if (isMinus(cur)) { minus = true; cur = read(); } while (isNum(cur)) { v *= 10; v += (cur - '0'); cur = read(); } return minus ? -v : v; } static char readChar() throws Throwable { int cur; for (;;) { cur = read(); if (cur == -1) return 0; if (cur == '\r' || cur == '\n' || cur == ' ') continue; return (char) cur; } } static long readLong() throws Throwable { int cur; while (!isNum(cur = read()) && !isMinus(cur)) if (cur == -1) return -1; long v = 0; boolean minus = false; if (isMinus(cur)) { minus = true; cur = read(); } while (isNum(cur)) { v *= 10; v += (cur - '0'); cur = read(); } return minus ? -v : v; } static boolean hasInput() throws Throwable { while (true) { int data = read(); if (data == -1) return false; if ((data & 0xE0) != 0) { pos--; return true; } } } static int read() throws Throwable { if (pos >= max) { max = in.read(buffer); if (max < 0) return -1; pos = 0; } return buffer[pos++] & 0xff; } // OUTPUT FUNCTIONS // escreve um char static void writeOut(char c) { if (posOut >= maxOut) { writeOutToStream(); } output[posOut++] = (byte) c; } // escreve a quebra de linha static void writeOutLn() { writeOut('\n'); } // escreve um char[] static void writeOut(char[] cs) { writeOut(cs, 0, cs.length); } // escreve uma cadeia de caracteres static void writeOut(char[] chars, int offset, int length) { final int end = offset + length; for (int i = offset; i < end; i++) { writeOut(chars[i]); } } static void writeOutNumber(int value) { int len = 0; int pos = tmpcharr.length; if (value == 0) { writeOut('0'); return; } boolean negative = value < 0; if (negative) value = -value; while (value > 0) { tmpcharr[--pos] = (char) ((value % 10) + '0'); len++; value /= 10; } if (negative) writeOut('-'); writeOut(tmpcharr, pos, len); } static void writeOutNumberAsBin(int num) { int len = 0; int pos = tmpcharr.length; if (num == 0) { writeOut('0'); return; } while (num > 0) { tmpcharr[--pos] = ((num & 1) == 1) ? '1' : '0'; len++; num >>>= 1; } writeOut(tmpcharr, pos, len); } static void flush() { writeOutToStream(); out.flush(); } // PRIVATE methods must be used only by the utility methods private static void writeOutToStream() { out.write(output, 0, posOut); posOut = 0; } }" B21424,"/** * */ package code.google.codejam; import java.util.HashSet; /** * @author sunilkumarp * */ public class RecycledNumbers extends Template { int A = 0; int B = 0; int digits = 0; int[] n = null; int m = 0; /* (non-Javadoc) * @see code.google.codejam.Template#doSolveProblem() */ @Override protected Object doSolveProblem() throws Exception { if (A >= B) { return 0; } int result = 0; n = new int[digits]; int counter = digits; int A_ = A; for (;--counter >= 0;) { n[counter] = A_ % 10; A_ = A_ / 10; } counter = B - A; for (int i = 0; i < counter; ++i) { HashSet unique = new HashSet(); for (int j = 1; j < digits; ++j) { if (isGreaterThanA(j) && isLessOrEqThanB(j)) { if(unique.add(m)) { ++result; } continue; } } incrementA(); } return result; } private boolean isLessOrEqThanB(int j) { return m <= B; } private boolean isGreaterThanA(int j) { m = 0; for (int k = j; k < digits; ++k) { m *= 10; m += n[k]; } for (int k = 0; k < j; ++k) { m *= 10; m += n[k]; } int A_ = 0; for (int k = 0; k < digits; ++k) { A_ *= 10; A_ += n[k]; } return m > A_; } /*private boolean isLessOrEqThanB(int j) { boolean notSwitched = true; for (int i = 0; i < digits; ++i) { if (notSwitched && i+j == digits) { j = -i; notSwitched = false; } if (b[i] > a[i+j]) { return true; } else if (b[i] < a[i+j]) { return false; } } return true; } private boolean isGreaterThanA(int j) { boolean notSwitched = true; for (int i = 0; i < digits; ++i) { if (notSwitched && i+j == digits) { j = -i; notSwitched = false; } if (a[i] > a[i+j]) { return false; } else if (a[i] < a[i+j]) { return true; } } return false; }*/ private void incrementA() { for (int i = digits - 1; i >= 0; --i) { if ((n[i] += 1) == 10) { n[i] = 0; } else { break; } } } /* (non-Javadoc) * @see code.google.codejam.Template#printInput() */ @Override protected void printInput() throws Exception { System.out.println(""Digits-"" +digits + "":"" + A + ""-"" + B); } /* (non-Javadoc) * @see code.google.codejam.Template#initializeTestCase() */ @Override protected void initializeTestCase() throws Exception { readLine(); A = readNextInteger(); digits = linePointer; B = readNextInteger(); } } " B21691,"package cg.y2012.Q3; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class Q3 { /** * @param args */ public static void main(String[] args) { BufferedWriter out = null; try { String newLine = System.getProperty(""line.separator""); out = new BufferedWriter(new FileWriter(args[0]+"".output"")); BufferedReader b = new BufferedReader(new FileReader(args[0])); int number_of_test_cases = Integer.parseInt(b.readLine().split("" "")[0]); for( int tc = 0; tc < number_of_test_cases; tc++) { int[] data = convertToInt(b.readLine()); int A = data[0]; int B = data[1]; Set s = new HashSet(); int count = 0; for (int n = A; n <= B; n++) { for (int m : getRecycled(n)) { if(m> n && m <= B){ count++; // if(tc < number_of_test_cases-1) // if(!s.add(""("" + n + "","" + m + "")"")) // System.out.println(""("" + n + "","" + m + "")""); } } } out.write(""Case #""+(tc+1)+"": ""+count+newLine); } } catch (IOException e) { System.out.println(""Exception : ""+e); } finally { if(out != null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static Set getRecycled(int A){ String a = Integer.toString(A); Set r = new HashSet(); String temp=""""; for(int i =a.length();i>0;i--){ temp = a.charAt(i-1)+temp; String x = temp+a.substring(0, i-1); r.add(Integer.parseInt(x)); } return r; } private static boolean isRecycled(int A, int B){ String a = Integer.toString(A); String b = Integer.toString(B); String temp=""""; for(int i =a.length();i>0;i--){ temp = a.charAt(i-1)+temp; String x = temp+a.substring(0, i-1); if(x.equals(b)){ return true; } } return false; } private static int[] convertToInt(String line){ String data[] = line.split("" ""); int[] rtn = new int[data.length]; for(int i=0;i< data.length ;i++){ rtn[i]=Integer.parseInt(data[i].trim()); } return rtn; } }" B21079,"import java.io.*; import java.util.StringTokenizer; public class RecycledNumbers { static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(String fileName) throws IOException { br = new BufferedReader(new FileReader(new File(fileName))); } public String nextToken() throws IOException, NullPointerException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public String nextString() throws IOException, NullPointerException { st = null; return br.readLine(); } public Integer nextInt() throws IOException { return Integer.parseInt(nextToken()); } void close() throws IOException { br.close(); } } public static void main(String[] args) throws IOException { final String name = ""C-large""; MyScanner in = new MyScanner(name + "".in""); PrintWriter out = new PrintWriter(name + "".txt""); int t = in.nextInt(); for (int i = 1; i <= t; i++) { int a = in.nextInt(); int b = in.nextInt(); int res = 0; for (int n = a; n < b; n++) { int m = n; int l = 0; int k = 1; while (m != 0) { m /= 10; l++; k *= 10; } m = n; k /= 10; int[] w = new int[l]; for (int j = 1; j < l; j++) { m = (m % 10) * k + m / 10; w[j] = m; boolean f = true; for (int q = 1; q < j; q++) { if (m == w[q]) { f = false; continue; } } if (m > n && a <= m && m <= b && f) { res++; } } } out.println(""Case #"" + i + "": "" + res); } in.close(); out.close(); } } " B20882,"package com.google.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; public class Utils { static final String outputFileName = ""D:\\output.txt""; static ArrayList outputData = new ArrayList(); public static void run(Class cls){ Object obj = null; try { obj = cls.newInstance(); } catch (Exception e1) { e1.printStackTrace(); } outputData.clear(); String[] args = Utils.readInput(cls); Method method = getMethod(obj.getClass()); executeMethod(obj, args, method); writeToFile(); } private static void executeMethod(Object obj, String[] args, Method method) { int index = 0; int n = Integer.valueOf(args[index++]); if (n == args.length - 1){ for(int i = 0; i < n; i++){ Class[] t = method.getParameterTypes(); Object[] par = new Object[t.length]; for (int j = 0; j < t.length; j++) { par[j] = parseParameter(args[index++], t[j]); } try { printOutput(i+1, method.invoke(obj, par)); } catch (Exception e) { e.printStackTrace(); } } }else{ for(int i = 0; i < n; i++){ Class[] t = method.getParameterTypes(); Object[] par = new Object[t.length]; String[] sp = args[index++].split("" ""); if(t.length == sp.length){ for (int j = 0; j < t.length; j++) { String[] sArr = new String[Integer.valueOf(sp[j])]; for (int k = 0; k < sArr.length; k++) { sArr[k] = args[index++]; } par[j] = sArr; } } try { printOutput(i+1, method.invoke(obj, par)); } catch (Exception e) { e.printStackTrace(); } } } } private static String[] readInput(Class cls){ String fileName = cls.getSimpleName() + "".in""; BufferedReader in = new BufferedReader(new InputStreamReader(cls.getResourceAsStream(fileName))); ArrayList res = new ArrayList(); String s; try { while((s = in.readLine()) != null){ res.add(s); } } catch (IOException e) { e.printStackTrace(); } return res.toArray(new String[]{}); } private static Method getMethod(Class cls){ Method[] methods = null; try { methods = cls.getDeclaredMethods(); for(Method m : methods) if(Modifier.isPublic(m.getModifiers())) return m; } catch (Exception e) { e.printStackTrace(); } return null; } private static Object parseParameter(String arg, Class cls) { if(cls == int.class){ return Integer.valueOf(arg); }else if(cls == int[].class){ String[] split = arg.split("" ""); int[] res = new int[split.length]; for (int i = 0; i < res.length; i++) { res[i] = Integer.valueOf(split[i]); } return res; }else if(cls == long[].class){ String[] split = arg.split("" ""); long[] res = new long[split.length]; for (int i = 0; i < res.length; i++) { res[i] = Long.valueOf(split[i]); } return res; }else if(cls == String.class){ return arg; } return null; } private static void printOutput(int count, Object res) { Class cls = res.getClass(); String data = ""Case #"" + count + "": ""; if(cls == int[].class){ int[] array = (int[]) res; for (int i = 0; i < array.length; i++) { data += array[i] + "" ""; } data = data.substring(0, data.length() - 1); }else{ data += res; } System.out.println(data); outputData.add(data); } private static void writeToFile() { try { FileWriter fstream = new FileWriter(outputFileName); BufferedWriter out = new BufferedWriter(fstream); for(String s : outputData){ out.write(s); out.newLine(); } out.close(); fstream.close(); } catch (IOException e1) { e1.printStackTrace(); } } }" B20420,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; /** * * @author cristian */ public class CodeJam { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here StringBuffer sb; Boolean firstLine = true; try { // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(""/tmp/problemB.txt""); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line int line = 1; while ((strLine = br.readLine()) != null) { if (firstLine) { firstLine = false; continue; } sb = new StringBuffer(); // Print the content on the console int A = Integer.parseInt(strLine.split("" "")[0]); int B = Integer.parseInt(strLine.split("" "")[1]); int n = A; int m; int recycled = 0; while (n < B) { recycled += moveLast(n, B); n++; } System.out.println(""Case #"" + line + "": "" + recycled); line++; } //Close the input stream in.close(); } catch (Exception e) {//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } private static int moveLast(int n, int B) { int recycled = 0; int tmpN = n; int m; StringBuffer sb; for (int i = 0; i < (n + """").length() - 1; i++) { sb = new StringBuffer(); sb.append((tmpN + """").charAt((tmpN + """").length() - 1)); if ((tmpN + """").length() < (n + """").length()) { sb.append(""0""); } sb.append((tmpN + """").substring(0, (tmpN + """").length() - 1)); m = Integer.parseInt(sb.toString()); //A ≤ n < m ≤ B if ((n < m) && (m <= B)) { recycled++; } tmpN = m; } return recycled; } } " B21294,"package gcj2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.BufferedWriter; import java.io.FileWriter; public class RecycledNumber { public String count(int A, int B, int caseNr) { StringBuffer sb = new StringBuffer(""""); sb.append(""Case #""); sb.append(caseNr); sb.append("": ""); int result = 0; for (int i = A; i <= B; i++) { result += recycled(i, B); } sb.append(result); return sb.toString(); } public int recycled(int nr, int max) { if (nr < 12) return 0; int test = nr; int count = 0; int length = (int)Math.ceil(Math.log10((double)nr)); int[] digits = new int[length]; for (int i = length-1; i >=0; i--) { digits[i] = test%10; test = test/10; } int[] valuesFound = new int[length]; for (int i = 0; i < length; i++) { if (digits[i] != 0) { int value = 0; for (int j = 0; j < length; j++) { value = value*10; value += digits[(i+j)%length]; } valuesFound[i] = value; if ((value > nr) && (value <= max)) { boolean found = false; for (int k = 0; k < i; k++) { if (valuesFound[k] == valuesFound[i]) found = true; } //System.out.println(nr + "" "" + value); if (!found) count++; } } } return count; } /** * @param args */ public static void main(String[] args) { RecycledNumber test = new RecycledNumber(); String fileName = ""in3.txt""; String outName = ""out3.txt""; try { BufferedReader br = new BufferedReader(new FileReader(fileName)); String line = br.readLine(); BufferedWriter bw = new BufferedWriter(new FileWriter(outName)); int tests = new Integer(line).intValue(); for (int i = 0; i < tests; i++) { line = br.readLine(); String[] parts = line.split("" ""); int A = new Integer(parts[0]).intValue(); int B = new Integer(parts[1]).intValue(); String line2 = test.count(A, B, i+1); System.out.println(line2); bw.write(line2+""\n""); } bw.flush(); } catch (Exception e) { e.printStackTrace(); } } } /** Input Ê 4 1 9 10 40 100 500 1111 2222 Output Ê Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 */" B22179,"import java.io.*; import java.util.*; import java.math.*; public class Qual22C { public static void main(String[] args) throws IOException { BufferedReader ips=new BufferedReader(new FileReader(""C-large.in"")); PrintWriter ops=new PrintWriter(new FileWriter(""recno.in"")); int T=Integer.parseInt(ips.readLine()); for(int i=0;i=0; j--) { t=ca[j]-'0'; A=A+(int)(Math.pow(10,count)*t); count++; } //System.out.println(""A: ""+A+"" B: ""+B+"" nog: ""+count); n=A; int pw=0; for(int k=0; k<=(B-A); k++) { //n++; m=n; temp=m; rev=0; pw=0; while(temp!=0) { t=temp%10; rev=(rev*10)+t; temp=temp/10; pw++; } //System.out.println(rev); t=rev%10; tryy=(t*(int)(Math.pow(10,(count-1)))); m=((m-tryy)*10)+t; //System.out.println(n+"" : ""+m); while(m!=n) { if(n=A && m<=B) rnc++; temp=m; rev=0; pw=0; while(temp!=0) { t=temp%10; rev=(rev*10)+t; temp=temp/10; } //System.out.println(rev); t=rev%10; tryy=(t*(int)(Math.pow(10,(count-1)))); //System.out.println(t); //System.out.println(tryy); if((m-tryy)<0) m=(m*10); else m=((m-tryy)*10)+t; //System.out.println(""1. ""+n+"" : ""+m); } n++; } ops.println(""Case #""+(i+1)+"": ""+rnc); System.out.println(""Case #""+(i+1)+"": ""+rnc); } ips.close(); ops.close(); } }" B20860,"import java.util.*; public class RecycledNumbers { private static final Scanner sc = new Scanner(System.in); /** * @param args */ public static void main(String[] args) { int T = sc.nextInt(); for (int i = 0; i < T; i++){ int A = sc.nextInt(); int B = sc.nextInt(); int m; HashMap mMap = new HashMap(); int results = 0; final int digits = 1 + (int)Math.floor(Math.log10(A)); for (int n = A; n < B; n++){ if (digits == 1) break; //System.out.println(n); m = flipNumber(n, 1); mMap.put(m, m); if (n < m && m <= B) results++; if (digits > 2){ m = flipNumber(n, 2); if (n < m && m <= B && !mMap.containsKey(m)){ mMap.put(m, m); results++; } } if (digits > 3){ m = flipNumber(n, 3); if (n < m && m <= B && !mMap.containsKey(m)){ mMap.put(m, m); results++; } } if (digits > 4){ m = flipNumber(n, 4); if (n < m && m <= B && !mMap.containsKey(m)){ mMap.put(m, m); results++; } } if (digits > 5){ m = flipNumber(n, 5); if (n < m && m <= B && !mMap.containsKey(m)){ mMap.put(m, m); results++; } } if (digits > 6){ m = flipNumber(n, 6); if (n < m && m <= B && !mMap.containsKey(m)){ mMap.put(m, m); results++; } } mMap.clear(); } System.out.println(""Case #"" + (i + 1) + "": "" + results); } } private static int flipNumber(int x, int way){ String num = """" + x; if (way == 1) num = num.substring(num.length() - 1) + num.substring(0, num.length() - 1); else if (way == 2) num = num.substring(num.length() - 2) + num.substring(0, num.length() - 2); else if (way == 3) num = num.substring(num.length() - 3) + num.substring(0, num.length() - 3); else if (way == 4) num = num.substring(num.length() - 4) + num.substring(0, num.length() - 4); else if (way == 5) num = num.substring(num.length() - 5) + num.substring(0, num.length() - 5); else if (way == 6) num = num.substring(num.length() - 6) + num.substring(0, num.length() - 6); int p = Integer.parseInt(num); return p; } } " B22093,"import java.awt.Polygon; import java.awt.geom.Point2D; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class C implements Runnable { int rotate(int a, int pw) { return (a / 10) + (a % 10) * pw; } private void solve() throws IOException { int a = nextInt(); int b = nextInt(); int pw10 = 1; for (; pw10 * 10 <= a; pw10 *= 10) ; // System.out.println(rotate(1, 10)); boolean[] was = new boolean[b + 1]; int qlen = 0; long ans = 0; for (int i = a; i <= b; ++i) { qlen = 1; was[i] = true; for (int j = rotate(i, pw10); j > b || !was[j]; j = rotate(j, pw10)) { if (a <= j && j <= b) { was[j] = true; ++qlen; } } ans += qlen * (qlen - 1) / 2; } out.println(ans); } /** * @param args */ public static void main(String[] args) { (new Thread(new C())).start(); } private BufferedReader br; private StringTokenizer st; private PrintWriter out; private String filename = """"; @Override public void run() { try { br = new BufferedReader(new FileReader(""input.txt"")); st = new StringTokenizer(""""); out = new PrintWriter(""output.txt""); int T = nextInt(); for (int i = 1; i <= T; ++i) { out.print(""Case #"" + i + "": ""); solve(); } out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } String next() throws IOException { while (!st.hasMoreTokens()) { String temp = br.readLine(); if (temp == null) { return null; } st = new StringTokenizer(temp); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } " B21786,"package main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashSet; public class ProblemB { public static void main(String args[]){ try{ FileInputStream fileInputStream = new FileInputStream(args[0] + "".in""); DataInputStream in = new DataInputStream(fileInputStream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fstream = new FileWriter(args[0] + "".out""); BufferedWriter out = new BufferedWriter(fstream); String strLine; strLine = br.readLine(); int T = Integer.parseInt(strLine); for(int i = 1; i <= T; i++){ strLine = br.readLine(); String[] limits = strLine.split("" "", 2); int lowerLimit = Integer.parseInt(limits[0]); int upperLimit = Integer.parseInt(limits[1]); int count = 0; for(int j = lowerLimit; j < upperLimit; j++){ int n = j; String temp = Integer.toString(j); HashSet hashSet = new HashSet(); for(int k = 0; k < temp.length() - 1; k++){ temp = temp.substring(temp.length() - 1, temp.length()) + temp.substring(0, temp.length() - 1); int m = Integer.parseInt(temp); if(n < m && m <= upperLimit){ String temp1 = temp; hashSet.add(temp1); } } count = count + hashSet.size(); } System.out.println(""Case #"" + i + "": "" + count); out.write(""Case #"" + i + "": "" + count + ""\n""); } out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } } " B20956,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; class Pair{ int x; int y; Pair(int x,int y){ this.x = x; this.y = y; } public boolean equals(Pair p){ return this.x == p.x && this.y ==p.y; } } public class RecycledNumbers { static int [] x = new int [300]; static int count = 0; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); int A,B; StringTokenizer st; for (int i = 1; i <= T; i++) { st = new StringTokenizer(br.readLine()); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); System.out.println(""Case #"" + i + "": ""+get(A,B)); } } private static int get(int a, int b) { int res = 0; for (int i = a; i < b; i++) { res += recycled(i,b); } return res; } private static int recycled(int a, int lim) { HashSet set = new HashSet(); int b = a,c; String s = a+""""; int len =s.length()-1; for(int i = 0 ; i <= len ; i++ ){ c = (int) (b/10 + b%10* Math.pow(10, len)); if(c > a && c <= lim){ set.add(c); } b = c; } return set.size(); } } " B21014,"package recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new FileReader(new File(""./recyclednumbers/c-large.in""))); BufferedWriter bw=new BufferedWriter(new FileWriter(new File(""./recyclednumbers/large.out""))); int numberOfCase=Integer.parseInt(br.readLine()); StringBuilder out=new StringBuilder(); for(int i=1;i<=numberOfCase;i++){ out.append(""Case #""+i+"": ""); int count=0; String input=br.readLine(); int start=Integer.parseInt(input.substring(0,input.indexOf("" ""))); int end=Integer.parseInt(input.substring(input.indexOf("" "")+1)); for(int j=start;j<=end;j++){ ArrayListlist=new ArrayList(); int n=10; while(j>=n){ int last=j%n; int first=j/n; int recycle=last*(int)Math.pow(10, String.valueOf(first).length())+first; if(recycle>j && recycle<=end){ if(!list.contains(recycle)){ count++; list.add(recycle); } } n*=10; } } out.append(count); if(i> h=new HashMap>(); int temp=b,d=0,req=0; // System.out.println(a+"" ""+b); // System.out.println(""********""); while(temp!=0) { temp/=10; d++; } for(int j=a;j=a && oth>j) { if(h.containsKey(j)) { if(h.get(j).containsKey(oth)) continue; h.get(j).put(oth,1); // System.out.println(j+"" ""+oth); req++; } else { HashMap ht=new HashMap(); ht.put(oth,0); h.put(j,ht); // System.out.println(j+"" ""+oth); req++; } } } } ans[i]=""Case #""+(i+1)+"": ""+req; // System.out.println(""------""); // System.out.println(req); // System.out.println(""**********""); } for(int i=0;i elements = new Vector(); numberOfElementForEachTest = 0; Reader.setFile(""input.txt""); Writer.setFile(""output.txt""); String s = Reader.readLine(); int numberTest = Integer.parseInt(s); for (int i=0; i(); s = Reader.readLine(); String s1 = s.substring(0, s.indexOf("" "")); s=s.substring(s.indexOf("" "")+1); int numberOfDigits = s1.length(); int[] digits = new int[numberOfDigits]; int firstNumber = Integer.parseInt(s1); int secondNumber = Integer.parseInt(s); int result = 0; switch (numberOfDigits) { case 1: break; case 2: for (int n1=firstNumber; n1n1 && n2<=secondNumber) result++; } break; case 3: for (int n1=firstNumber; n1n1 && n2<=secondNumber) result++; n2 = n1/10 + n1%10*100; if (n2>n1 && n2<=secondNumber) result++; } break; case 4: // System.out.println(System.currentTimeMillis()); for (int n1=firstNumber; n1secondNumber) n1 = (n1/1000 + 1) *1000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/100 + 1) *100; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/10 + 1) *10; else if (n2>n1) { result++; if (n1/1000 == n1%100/10 && n1%1000/100 == n1%10) result--; } } // System.out.println(System.currentTimeMillis()); break; case 5: for (int n1=firstNumber; n1secondNumber) n1 = (n1/10000 + 1) *10000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/1000 + 1) *1000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/100 + 1) *100; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/10 + 1) *10; else if (n2>n1) { result++; } } break; case 6: for (int n1=firstNumber; n1secondNumber) n1 = (n1/100000 + 1) *100000; else if (n2>n1) { result++; } // if (n2>n1 && n2<=secondNumber) result++; } for (int n1=firstNumber; n1secondNumber) n1 = (n1/10000 + 1) *10000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/1000 + 1) *1000; else if (n2>n1) { result++; if (n1/100000 == n1%10000/1000 && n1%10000/1000 == n1%100/10 && n1%100000/10000 == n1%1000/100 && n1%1000/100 == n1%10) result-=2; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/100 + 1) *100; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/10 + 1) *10; else if (n2>n1) { result++; } } break; case 7: // System.out.println(System.currentTimeMillis()); for (int n1=firstNumber; n1secondNumber) n1 = (n1/1000000 + 1) *1000000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/100000 + 1) *100000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/10000 + 1) *10000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/1000 + 1) *1000; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1secondNumber) n1 = (n1/100 + 1) *100; else if (n2>n1) { result++; } } for (int n1=firstNumber; n1n1 && n2 strings = new ArrayList(); strings.add(s); for (int j=0; j seen = new LinkedList(); for (int j = a; j < b; j++) { String n = Integer.toString(j); seen.clear(); for (int k = 1; k < n.length(); k++) { int r = Integer.parseInt(n.substring(k) + n.substring(0, k)); if ((r > j) && (r <= b) && !seen.contains(r)) { seen.add(r); cnt++; } } } out.printf(""Case #%d: %d\n"", i+1, cnt); } } " B20867,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; /** * * @author malgia */ public class Recycled { /** * @param args the command line arguments */ public static void main(String[] args) { Integer number=0; Integer total=0; Integer a,b; String numbers[]; Integer result; String current; String pair; String previous; try{ BufferedReader fin=new BufferedReader(new InputStreamReader(new FileInputStream(new File(""C-large.in"")))); PrintWriter fout = new PrintWriter (new BufferedWriter (new FileWriter (""C-large.out""))); total=Integer.parseInt(fin.readLine()); for (int i=0;i9) { for(int j=a;j<=b;j++){ current=j+""""; for(int k=1; kInteger.parseInt(current) && Integer.parseInt(current)>=a && previous.compareTo(current+"",""+pair)!=0){ result++; previous=current+"",""+pair; } } } } number=i+1; fout.println(""Case #""+number+"": ""+result); } fin.close(); fout.close(); }catch(Exception e){ System.out.println(e.toString()); } } } " B20654,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.HashMap; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class Recycle { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""C-large.in"")); int t; // number of test cases int n = 1; int counter=0; int A, B; HashMap map = new HashMap(); t = sc.nextInt(); //System.out.println(""Output""); for (int i = 0; i < t; i++) { A = sc.nextInt(); B = sc.nextInt(); String aStr = String.valueOf(A); int len = aStr.length(); for (int c = A; c < B+1; c++) { for (int k=1; k(); } } public static char[] shiftLeft(char[] array, int amount) { for (int j = 0; j < amount; j++) { char a = array[0]; int i; for (i = 0; i < array.length - 1; i++) array[i] = array[i + 1]; array[i] = a; } return array; } public static char[] shiftRight(char[] array, int amount) { for (int j = 0; j < amount; j++) { char a = array[array.length - 1]; int i; for (i = array.length - 1; i > 0; i--) array[i] = array[i - 1]; array[i] = a; } return array; } } " B22145,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; public class C { void run() { try { BufferedReader bfd = new BufferedReader(new InputStreamReader( System.in)); int tc = Integer.parseInt(bfd.readLine()), i, k, a, b, n, len, num, cnt; String sp[], rot, s; HashSet hset; for(k=0; k(); for(n=a; n<=b; ++n){ s = n+""""; len = s.length(); if(len==1)continue; for(i=0; i=a && num<=b){ if(!hset.contains(n+"" ""+num)) cnt++; hset.add(n+"" "" +num); } } } System.out.print(""Case #""+(k+1)+"": ""); System.out.print(cnt); System.out.println(); } } catch (Exception e) { } } public static void main(String[] args) { new C().run(); } } " B20222,"package qual1; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster BufferedReader f = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-large.out""))); int cases = Integer.parseInt(f.readLine()); for (int zz = 1; zz <= cases; zz++) { StringTokenizer st = new StringTokenizer(f.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int[] list = new int[b-a+1]; for (int i=a; i<=b; i++) { list[i-a] = i; } HashMap> dump = new HashMap>(); long ans = 0; for (int i=a; i<=b; i++) { if (list[i-a]==0) continue; String x = i+""""; ArrayList xzc = new ArrayList(); for (int j=1; j=a && t2<=b) { if (list[t2-a]==0) { continue; } list[t2-a] = 0; xzc.add(t2); } } dump.put(i, xzc); } for (int key : dump.keySet()) { ArrayList xzc = dump.get(key); if (xzc.isEmpty()) continue; //Collections.sort(xzc); //System.out.println(key+"" : ""+xzc); if (xzc.size()==1) ans++; else ans+= ((xzc.size()+1)*(xzc.size())/2); } System.out.println(""Case #"" + zz + "": ""+ans); out.println(""Case #"" + zz + "": ""+ans); } out.close(); // close the output file System.exit(0); // don't omit this! } }" B22175,"package com.google.code.codejam._2012.qualification; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Problem * * Do you ever become frustrated with television because you keep seeing the same things, recycled * over and over again? Well I personally don't care about television, but I do sometimes feel that * way about numbers. * * Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving * some digits from the back of n to the front without changing their order. For example, (12345, * 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the * front. Note that n and m must have the same number of digits in order to be a recycled pair. * Neither n nor m can have leading zeros. * * Given integers A and B with the same number of digits and no leading zeros, how many distinct * recycled pairs (n, m) are there with A ≤ n < m ≤ B? * * The RecycledNumbers is the second problem. * *

* Apr 14, 2012 9:25:48 PST AM *

* * @author Marcello de Sales (marcello.desales@gmail.com) * */ public class RecycledNumbers extends CommandLineClient { /** * Input * * The first line of the input gives the number of test cases, T. T test cases follow. Each test * case consists of a single line containing the integers A and B. * * Output * * For each test case, output one line containing ""Case #x: y"", where x is the case number * (starting from 1), and y is the number of recycled pairs (n, m) with A ≤ n < m ≤ B. * * Limits * * 1 ≤ T ≤ 50. A and B have the same number of digits. * * Small dataset * * 1 ≤ A ≤ B ≤ 1000. * * Large dataset * * 1 ≤ A ≤ B ≤ 2000000. * * Sample * * * Input * 4 1 9 10 40 100 500 1111 2222 * Output * Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 * * @param args the input arguments from the stdin. */ public static void main(String[] args) { try { new RecycledNumbers().execute(args); System.exit(0); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } @Override public void process(Scanner input, PrintWriter output) throws Exception { int numberOfTestCases = Integer.valueOf(input.nextLine()); StringBuilder builder = null; for (int testIndex = 0; testIndex < numberOfTestCases; testIndex++) { int numberOfPairs = 0; output.printf(""Case #%d: "", testIndex + 1); // get the value of A and B String[] aAndB = input.nextLine().split("" ""); // if the number is only one digit, then leave as it is zero. if (aAndB[0].length() == 1 || aAndB[1].length() == 1) { output.printf(""%d\n"", numberOfPairs); continue; } // the inputs A and B int a = Integer.valueOf(aAndB[0]); int b = Integer.valueOf(aAndB[1]); // caching the current results to avoid counting the same value twice. Set resultsSoFar = new HashSet<>(); // Generating all the numbers between a and b, inclusive [a, b] String[] ranges = new String[b - a]; for (int i = 0, rangeValue = a; i < ranges.length; i++) { ranges[i] = String.valueOf(rangeValue++); } String n = """"; String m = """"; for (int i = 0; i < ranges.length; i++) { n = ranges[i]; m = ranges[i]; int length = String.valueOf(ranges[i]).length(); for (int j = 0; j < length; j++) { // rotate number m String stringValue = String.valueOf(m); builder = new StringBuilder(); builder.append(stringValue.charAt(stringValue.length() - 1)); builder.append(stringValue.subSequence(0, stringValue.length() - 1)); m = builder.toString(); // a recycle pair is one such that A ≤ n < m ≤ B if (a <= Integer.valueOf(n) && Integer.valueOf(n) < Integer.valueOf(m) && Integer.valueOf(m) <= b) { if (!resultsSoFar.contains(n + m)) { resultsSoFar.add(n+m); numberOfPairs++; } //output.printf(""%s, %s count: %d \n"", n, m, numberOfPairs); // could see the repeated value!!! } } } output.printf(""%d\n"", numberOfPairs); } } } " B20886,"package qualification; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.Scanner; public class C { static int pow(int b) { return (int)Math.pow(10,b); } public static void main(String args[]) throws FileNotFoundException { Scanner sin=new Scanner(new File(""C:\\Users\\DELL\\Desktop\\CodeJam\\C-large.in"")); PrintStream ps=new PrintStream(new File(""C:\\Users\\DELL\\Desktop\\CodeJam\\COut.out"")); int cases=sin.nextInt(); for(int test=1;test<=cases;test++) { int start=sin.nextInt(); int stop=sin.nextInt(); int count=0; int max=0; while(start/pow(max) >0) max++; max--; String s; for(int i=start;i<=stop;i++) { s=""""; int temp=max; while(temp>0) { int t=((i%pow(temp))*(pow(max-temp+1)))+i/pow(temp); temp--; if(t>i && t<=stop) { if(s.indexOf(t+""|"")!=-1) continue; s+=t+""|""; count++; } } } ps.println(""Case #""+test+"": ""+count); } } } " B21475,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) throws IOException { FileWriter wr=new FileWriter(""Output.txt""); BufferedWriter buff=new BufferedWriter(wr); FileReader read=new FileReader(""C-large.in""); BufferedReader buffr=new BufferedReader(read); String str; str=buffr.readLine(); int n=Integer.parseInt(str); int j=1; int a,b; int num,lower,upper; long total; while(j<=n) { str=buffr.readLine(); Scanner sc=new Scanner(str); sc.useDelimiter("" ""); a=sc.nextInt(); b=sc.nextInt(); upper=b; lower=a; total=0; while(a<=b) { String first=Integer.toString(a); String orig=first; String newStr; int curr=Integer.parseInt(first); if(first.length()!=1) { while(true) { first=first.charAt(first.length()-1)+first.substring(0,first.length()-1); if(first.equals(orig)) break; if(!first.startsWith(""0"")) { num=Integer.parseInt(first); if(num<=upper && num>=lower && num>curr) ++total; } } } ++a; } StringBuffer temp = new StringBuffer(""Case #""+j+"": ""); temp=temp.append(Long.toString(total)); buff.write(temp.toString()); buff.newLine(); ++j; } buff.close(); } } " B21705,"package codejam.recyclednumbers; public class RecycledNumbersProblem { private int minValue; private int maxValue; public RecycledNumbersProblem(String problemAsString) { String[] split = problemAsString.split("" ""); minValue = Integer.parseInt(split[0]); maxValue = Integer.parseInt(split[1]); } public int solve() { int result = 0; DigitsArray minValueDigitsArray = new DigitsArray(minValue); DigitsArray maxValueDigitsArray = new DigitsArray(maxValue); for (int i = 0; i <= maxValue - minValue; i++) { DigitsArray toTest = new DigitsArray(minValue + i); result += toTest.numberRecycles(minValueDigitsArray, maxValueDigitsArray); } return result; } } " B21329,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.Scanner; public class Recycled implements Runnable { static final int MAX = 2000000; public void run(){ try { Scanner in = new Scanner(new File(""C-large.in"")); PrintWriter out = new PrintWriter(new File(""c.out"")); int testNum = in.nextInt(); for (int test = 1; test <= testNum; test++) { //System.out.println(""!!! new test""); int a = in.nextInt(); int b = in.nextInt(); int p = 0; int k = 1; boolean[] u = new boolean[MAX + 1]; while (a > k * 10) { p++; k *= 10; } long res = 0; for(int i = a; i <= b; i++) { //System.out.println(""in "" + i); if (u[i]) { //System.out.println("" skipped""); continue; } u[i] = true; if (i == k * 10) { p++; k *= 10; } // System.out.println("" p = "" + p); int ll = 1; int ii = i; for (int j = 0; j < p; j++) { ii = (ii / 10) + (ii % 10) * k; //System.out.println("" found "" + ii); if (a <= ii && ii <= b) { if (u[ii]) continue; //System.out.println("" ok""); u[ii] = true; ll++; } } //System.out.println("" ll = "" + ll); res += ll * (ll - 1) / 2; } out.println(""Case #"" + test + "": "" + res); } out.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new Recycled().run(); } } " B20173,"import java.util.Scanner; public class C2 { /** * @param args */ public static void main(String[] args) { new C2(); } int a, b, nbrDigits; // All numbers that we have already seen boolean[] seen; C2() { Scanner sc = new Scanner(System.in); int nbrCases = sc.nextInt(); for (int i = 1; i <= nbrCases; ++i) { sc.nextLine(); System.out.print(""Case #"" + i + "": ""); a = sc.nextInt(); b = sc.nextInt(); nbrDigits = nbrDigits(a); seen = new boolean[b + 1]; for (int j = 0; j <= b; ++j) { seen[j] = false; } int result = 0; for (int j = a; j <= b; ++j) { result += nbrRecycledLocal(j); } System.out.println(result); } } /** * Get the number of recycled pairs starting from the given number * * @param start * the number to start from * @return the number of recycled pairs between a and b */ int nbrRecycledLocal(int start) { if (seen[start]) { return 0; } seen[start] = true; byte[] parts = separate(start); int hits = 0; for (int i = 1; i < nbrDigits; ++i) { int recycled = getRecycled(parts, i); if (recycled != start && recycled >= a && recycled <= b && !seen[recycled]) { ++hits; seen[recycled] = true; } } if (hits <= 1) { return hits; } int res = 1; for (int i = 2; i <= hits; ++i) { res += i; } return res; } /** * Get the number of digits in the given number * * @param number * the number * @return the number of digits in the number */ int nbrDigits(int number) { int digits = 0; while (number != 0) { number /= 10; digits++; } return digits; } /** * Separate the given number into its digits * * @param start * the number * @return an array with the digits of the number */ byte[] separate(int start) { byte[] res = new byte[nbrDigits]; for (int i = 0; i < nbrDigits; ++i) { res[nbrDigits - 1 - i] = (byte) (start % 10); start = start / 10; } return res; } /** * Get the recycled number given the start number and the number of steps to * move the digits * * @param start * the original number in digits * @param steps * the steps to take * @return the recycled number */ int getRecycled(byte[] start, int steps) { int res = 0; int factor = 1; int size = start.length; for (int i = 0; i < size; ++i) { int pos = (size - 1 - i + steps) % size; res += factor * start[pos]; factor *= 10; } return res; } } " B20660," import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author nzeyi */ public class C { public static void main(String[] arg) throws Exception { long a = System.currentTimeMillis(); String in = ""/home/nzeyi/Downloads/C-large.in""; String out = ""/home/nzeyi/Desktop/out""; BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(in))); PrintWriter w = new PrintWriter(new FileOutputStream(out)); int c = 0; int t = Integer.parseInt(r.readLine()); String s; while ((s = r.readLine()) != null) { if (!"""".equals(s)) { c++; w.print(""Case #"" + c + "": "" + r(s)); if (c < t) { w.println(); } } } r.close(); w.flush(); w.close(); long b = System.currentTimeMillis(); System.out.println(""Done(MS): "" + (b - a)); } public static int r(String line) { int ret = 0; String[] t = line.trim().split(""\\s""); int a = Integer.parseInt(t[0]); int b = Integer.parseInt(t[1]); for (int i = a; i <= b; i++) { ret += p(i, b); } return ret; } public static int p(int n, int b) { int ret = 0; String ns = """" + n; int l = ns.length(); Set set = new HashSet(); for (int i = l - 1; i > 0; i--) { int r = Integer.parseInt(ns.substring(i) + ns.substring(0, i)); if ((r > n) && (r <= b) && !set.contains(r)) { ret++; set.add(r); } } return ret; } } " B20626,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam.y12.round0; import utils.Jam; import utils.JamCase; /** * * @author fabien */ public class DancingGooglers extends Jam { public DancingGooglers(String filename) { super(filename); } @Override public JamCase getJamCase(int number) { return new Line(this, number, lines[number]); } private class Line extends JamCase { private String line; private int s; private int p; private int[] scores; public Line(Jam parent, int number, String line) { super(parent, number); this.line = line; } @Override public void parse() { String[] integers = line.split("" ""); scores = new int[Integer.parseInt(integers[0])]; s = Integer.parseInt(integers[1]); p = Integer.parseInt(integers[2]); int j = 0; for (int i = 3; i < integers.length; i++) { scores[j++] = Integer.parseInt(integers[i]); } } @Override public void solve() { int r = 0; if (p == 0) { r = scores.length; } else { float average = 0; float pnor = p - 1; float psus = p - 1.4f; for (int score : scores) { if (score > 0) { average = score / 3.0f; if (average > pnor) { r++; } else if (s > 0 && average >= psus) { r++; s--; } } } } result = Integer.toString(r); } } } " B21383,"package recycledNumbers; public class RecycledPair { private int n; private int m; public RecycledPair(int n, int m) { this.n = n; this.m = m; } /** * @return the n */ public int getN() { return n; } /** * @return the m */ public int getM() { return m; } @Override public boolean equals(Object o) { if (!(o instanceof RecycledPair)) { throw new ClassCastException(""Invalid object""); } RecycledPair rp = (RecycledPair) o; if ((this.getM() == rp.getM() && this.getN() == rp.getN()) || (this.getM() == rp.getN() && this.getN() == rp.getM())) { return true; } return false; } @Override public int hashCode() { if (this.getM() < this.getN()) { return this.getM() + 13 * this.getN(); } else { return this.getN() + 13 * this.getM(); } } } " B20962,"package codejam2012.r0; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; /** * @author julian */ public class C { public static final void main(String[] args) throws IOException { (new C()).run(); } public void run() throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""C.out"")); int t = Integer.parseInt(in.readLine()); for (int i = 0; i < t; i++) { StringTokenizer stok = new StringTokenizer(in.readLine()); int a = Integer.parseInt(stok.nextToken()); int b = Integer.parseInt(stok.nextToken()); out.write(""Case #"" + (i + 1) + "": "" + solve(a, b) + ""\n""); } in.close(); out.flush(); out.close(); } public int solve(int a, int b) { int ret = 0; for (int n = a; n <= b; n++) { String str = """" + n; Set perm = new HashSet(); int ndig = str.length(); for (int k = 0; k < ndig - 1; k++) { str = str.substring(1) + str.charAt(0); int m = Integer.parseInt(str); if (n < m && m <= b) { perm.add(m); } } ret += perm.size(); } return ret; } } " B20248,"import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static int f(int x, int min, int max) { String s = Integer.toString(x); String s2 = null; Set set = new HashSet(); for (int i = 1; i < s.length(); i++) { s2 = s.substring(i) + s.substring(0, i); if (Integer.valueOf(s2) > x && Integer.valueOf(s2) <= max && Integer.toString(Integer.valueOf(s2)).length() == s.length()) { set.add(Integer.valueOf(s2)); } } return set.size(); } public static void main(String[] args) throws Exception { System.setOut(new PrintStream(""zz"")); Scanner s = new Scanner(System.in); int T = s.nextInt(); for (int t = 1; t <= T; t++) { int A = s.nextInt(); int B = s.nextInt(); System.err.println(t); int n = 0; for (int x = A; x < B; x++) { n += f(x, A, B); } System.out.println(""Case #"" + t + "": "" + n); } } } " B21489,"import java.io.*; import java.util.*; import java.math.*; public class C { public static void main(String[] args) throws IOException { long start = System.currentTimeMillis(); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(""C-large.in"")); BufferedReader br = new BufferedReader(new InputStreamReader(bis)); PrintWriter out = new PrintWriter(""C-large.out""); int cases = Integer.parseInt(br.readLine().trim()); StringTokenizer st; for (int c = 1; c <= cases; c++) { int res = 0; st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); for (int i = A; i <= B; i++) { String iStr = i+""""; int len = iStr.length(); for (int j = 1; j < len; j++) { int curr = getNext(iStr, j, len); if(curr > i && curr <= B) res++; } } out.println(""Case #"" + c + "": "" + res); } out.close(); long finish = System.currentTimeMillis(); System.out.println(finish - start); } public static int getNext(String s, int st, int len) { String res = s.charAt(st)+""""; for (int i = st+1; i%len != st; i++) { res += s.charAt(i%len); } return Integer.parseInt(res); } }" B20664,"import java.io.IOException; import java.io.PrintWriter; public class RecycledNumbers { public static void main(String[] args) { RecycledNumbers bt = new RecycledNumbers(); bt.solveProblem(); } public void solveProblem() { String[] testCases = ReadFile.readFile(""C:/Users/Pablo/Documents/codejam/RN.in""); int i = 0; StringBuilder res = new StringBuilder(); for (String testCase : testCases) { if(!res.toString().equals("""")) { res.append(""\n""); } res.append(processTestCase(testCase, ++i)); } System.out.print(res.toString()); try { PrintWriter pw = new PrintWriter(""C:/Users/Pablo/Documents/codejam/RN.out""); pw.print(res.toString()); pw.close(); } catch (IOException e) { System.out.println(""Error writing file!!""); } } private String processTestCase(String testCase, int caseNum) { Long a = Long.valueOf(testCase.split("" "")[0]); Long b = Long.valueOf(testCase.split("" "")[1]); Long lim = Double.valueOf(Math.floor((a + b)/ 2d)).longValue() + 1L; int cantNumbers = 0; if(a.compareTo(10L) >= 0) { cantNumbers = verifNumbers(b, a, 0); } return ""Case #"" + caseNum + "": "" + cantNumbers; } private int verifNumbers(Long b, Long num, int cantNumbers) { for(; num.compareTo(b) < 0; num = num + 1L) { String n = num.toString(); n = n.replaceAll(String.valueOf(n.charAt(0)), """"); if(!n.equals("""")) { for(int i = 1; i <= num.toString().length(); i++) { String s = num.toString().substring(num.toString().length() - i, num.toString().length()) + num.toString().substring(0, num.toString().length() - i); Long tmp = Long.valueOf(s); if(tmp.compareTo(b) <= 0 && tmp.compareTo(num) > 0) { cantNumbers ++; } } } } return cantNumbers; } } " B20815,"import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class RecycledNumbers { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""C-large.in"")); int numTests = in.nextInt(); in.nextLine(); for (int i = 0; i < numTests; ++i) { int A = in.nextInt(); int B = in.nextInt(); in.nextLine(); System.out.println(""Case #"" + (i + 1) + "": "" + recycle(A, B)); } } private static int recycle(int A, int B) { int count = 0; for (int n = A; n < B; ++n) { String nStr = """" + n; count += compareM(n, B, nStr); } return count; } private static int compareM(int n, int B, String nStr) { int numberOfMGreaterThanN = 0; // and they must be less than B too int nStrLength = nStr.length(); for (int i = 1; i < nStrLength; ++i) { String mBegin = nStr.substring(0, nStrLength - i); String mEnd = nStr.substring(nStrLength - i, nStrLength); String mStr = mEnd + mBegin; if (hasSameNumDigits(nStr, mStr)) { int m = Integer.parseInt(mStr); if (n < m && m <= B) { ++numberOfMGreaterThanN; } } } return numberOfMGreaterThanN; } private static boolean hasSameNumDigits(String n, String m) { boolean foundFirstNonZero = false; int numDigitsOfN = 0; int numDigitsOfM = 0; for (int i = 0; i < n.length(); ++i) { char curChar = n.charAt(i); if (curChar != '0') { foundFirstNonZero = true; } if (foundFirstNonZero) { ++numDigitsOfN; } } foundFirstNonZero = false; for (int i = 0; i < m.length(); ++i) { char curChar = m.charAt(i); if (curChar != '0') { foundFirstNonZero = true; } if (foundFirstNonZero) { ++numDigitsOfM; } } return numDigitsOfM == numDigitsOfN; } } " B21840,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class C { private static final String PROBLEM_NAME = ""C-large""; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader r = new BufferedReader(new FileReader(PROBLEM_NAME + "".in"")); BufferedWriter w = new BufferedWriter(new FileWriter(PROBLEM_NAME + "".out"")); int testsNumber = Integer.parseInt(r.readLine()); for (int i = 0; i < testsNumber; ++i) { String[] line = r.readLine().split("" ""); int a = Integer.parseInt(line[0]); int b = Integer.parseInt(line[1]); long res = 0L; int len = 0; int tmp = a; while (tmp != 0) { ++len; tmp /= 10; } if (a == 0) { len = 1; } int m = 1; for (int j = 1; j < len; ++j) { m *= 10; } while (a < b) { Set counted = new HashSet(); int t = a; boolean sh = false; for (int j = 1; j < len; ++j) { int x = t % 10; if (x == 0) { sh = true; t = t / 10; } else { sh = false; t = x * m + t / 10; } if (!sh && t <= b && t > a && !counted.contains(t)) { counted.add(t); ++res; } } ++a; } w.write(""Case #"" + (i + 1) + "": ""); w.write(res + """"); w.newLine(); } r.close(); w.close(); } } " B22020,"package com.afarok.google.codejam2012.qualificationround; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class CRecycledNumber { public static void main(String[] ags) { //System.setIn(new FileInputStream(""src/com/afarok/google/codejam2012/qualificationround/C-small-attempt0.in"")); //System.setOut(new PrintStream(new File(""src/com/afarok/google/codejam2012/qualificationround/C-small-attempt0.out""))); //System.setIn(new FileInputStream(""src/com/afarok/google/codejam2012/qualificationround/C-large.in"")); //System.setOut(new PrintStream(new File(""src/com/afarok/google/codejam2012/qualificationround/C-large.out""))); Scanner stdIn = new Scanner(System.in); int t = stdIn.nextInt(); for(int tCase = 1;tCase<=t;++tCase) { int a = stdIn.nextInt(); int b = stdIn.nextInt(); //boolean[] recycled = new boolean[b+1]; int y=0; for(int i=a;i<=b;++i) { Set recyledSet = new HashSet(); for(int x=10;;x=x*10) { int r = i%x; if(r==0) continue; int d = i/x; if(d==0) break; int lenghtOfd = (int) Math.floor(Math.log10(d)) + 1; int recycledNum = (int) (r*Math.pow(10, lenghtOfd))+d; if(recycledNum<=i) continue; if(recyledSet.contains(recycledNum)) continue; if(recycledNum>=a&&recycledNum<=b) { ++y; recyledSet.add(recycledNum); } } } System.out.println(""Case #""+tCase+"": "" + y); } } } " B20476,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class RecycledNumber { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader in = new BufferedReader(new FileReader(""./test3.txt"")); FileWriter fstream = new FileWriter(""./out3.txt""); BufferedWriter out = new BufferedWriter(fstream); String str,str2; int i = 0; int numTestCase = Integer.parseInt(in.readLine()); while ((str = in.readLine()) != null) { str2=""""; int numOK = 0; String[] toks; toks = str.split("" ""); int LB = Integer.parseInt(toks[0]); int UB = Integer.parseInt(toks[1]); int numDigit = toks[0].length(); int []prev = new int[numDigit-1]; if(numDigit >1){ for(int k = LB; k < UB;k++) { for(int j = 1; j< numDigit; j++) { String temp = Integer.toString(k); String temp1 = temp.substring(0,j); String temp2 = temp.substring(j,numDigit); String result = temp2+temp1; int res = Integer.parseInt(result); if(res > k && res <= UB) { numOK++; for(int l = 0;l { // public static final String smallSet = ""small.txt""; // public static final String largeSet = ""large.txt""; private BufferedReader reader; public TestCaseReader(String file) { try { File small = new File(file); reader = new BufferedReader(new FileReader(small)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public int getTestCases() { String line = null; try { line = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } if (line != null) { return Integer.parseInt(line); } throw new RuntimeException(); } public T getNextTestCase() { String line = null; try { line = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } if (line != null) { return parseTestCase(line); } // EOF return null; } protected abstract T parseTestCase(String line); } " B20873,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycle; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; /** * * @author admin */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here FileReader fr=new FileReader(""C-large.in""); BufferedReader br=new BufferedReader(fr); FileWriter fw=new FileWriter(""result.txt""); PrintWriter pw=new PrintWriter(fw); getOutPut(br,pw); pw.close(); } public static void getOutPut(BufferedReader br,PrintWriter pw) throws IOException { int t=Integer.parseInt(br.readLine()); int A,B; for(int i=0;i num; String Sa,Sb; int count=0; Sa=Integer.toString(A); Sb=Integer.toString(B); for(int i=A;i<=B;i++){ num=new ArrayList(); for(int j=Sa.length()-1;j>0;j--){ Sa=Integer.toString(i).substring(j)+Integer.toString(i).substring(0,j); if(Integer.parseInt(Sa)<=B&&Sa.charAt(0)!='0'&&ij&&y<=b) c[i]++; } while(y!=j); } } for(int i=0;i set = new HashSet(); int tests = sc.nextInt(); for (int i = 0; i < tests; i++) { int a = sc.nextInt(); int b = sc.nextInt(); for (int j = a; j < b; j++) { List list = getRecycledNumbers(j); for (int k : list) { if (k > j && k <= b) { set.add(j + "" "" + k); } } } System.out.println(""Case #"" + (i+1) + "": "" + set.size()); set.clear(); } } private static List getRecycledNumbers(int num) { List list = new ArrayList(); String s = String.valueOf(num); for (int i = s.length() - 1; i > 0; i--) { String temp = s.substring(i, s.length()) + s.substring(0, i); if (!temp.startsWith(""0"")) { int cur = Integer.valueOf(temp); list.add(cur); } } return list; } } " B21711,"import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; public class Recycled { static int n = 1; static void solve(int A, int B) { int len = ("""" + A).length(); int min = 1; for (int a = 1; a < len; a++) min *= 10; int res = 0; int[] seen = new int[len]; int nseen; for (int n = A; n < B; n++) { int m = n; nseen = 0; for (int a = 1; a < len; a++) { m = (m / 10) + (m % 10) * min; if (m >= min && n < m && m <= B) { boolean already = false; for (int b = 0; b < nseen; b++) if (seen[b] == m) already = true; if (!already) { res++; seen[nseen++] = m; } } } } System.out.println(""Case #"" + (n++) + "": "" + res); } public static void main(String[] args) throws IOException { LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine().trim()); for (int a = 0; a < n; a++) { String[] l = in.readLine().trim().split("" ""); solve(Integer.parseInt(l[0]), Integer.parseInt(l[1])); } } } " B21730,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.SortedSet; import java.util.TreeSet; public final class RecycledNumbers { /** * @param args */ public static void main(String[] args) { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(""test.txt""))); int count = 1; String input; int cases = Integer.valueOf(br.readLine()); while (((input = br.readLine()) != null) && (count <= cases)) { String output = ""Case #""+(count++)+"": ""+process(input); System.out.println(output); } } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } finally { if (br!=null) try { br.close(); } catch(IOException e) {} } } private static final int process(String input) { String[] s = input.split("" ""); if (s[0].length()==1) return 0; int A = Integer.valueOf(s[0]); int B = Integer.valueOf(s[1]); int counter = 0; for (int n=A; n rotates = rotate(n, A, B); if (n != rotates.first()) continue; counter += count(rotates.size()); } return counter; } private final static int count(int n) { if (n < 2) return 0; if (n == 2) return 1; return --n + count(n); } private static final SortedSet rotate(int N, int min, int max) { SortedSet set = new TreeSet(); set.add(N); String sN = Integer.toString(N); for (int i = 0; i < sN.length()-1;i++) { //if (sN.charAt(1) == '0') continue; sN = sN.substring(1)+sN.charAt(0); int n = Integer.valueOf(sN); if (min<=n && n<=max) set.add(n); } return set; } } " B20989,"package fun.codeslam.recycling; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Integer testCaseCount = Integer.parseInt(reader.readLine()); for (Integer testCaseNumber = 1; testCaseNumber <= testCaseCount; testCaseNumber++) { String[] elements = reader.readLine().split("" ""); System.out.append(""Case #"" + testCaseNumber + "": ""); System.out.append(numberOfReyclingsInRange(Integer.parseInt(elements[0]), Integer.parseInt(elements[1])) .toString()); System.out.append('\n'); } } private static Integer numberOfReyclingsInRange(Integer min, Integer max) { Integer numberOfReyclings = 0; for (Integer number = min; number <= max; number++) { numberOfReyclings += numberOfReyclings(number, max); } return numberOfReyclings; } private static Integer numberOfReyclings(Integer number, Integer max) { Map isset = new HashMap(); Integer numberOfReyclings = 0; Integer length = number.toString().length(); for (Integer beginIndex = 1; beginIndex < length; beginIndex++) { String endPart = number.toString().substring(beginIndex); String frontPart = number.toString().substring(0, beginIndex); Integer newNumber = Integer.parseInt(endPart + frontPart); if (newNumber.toString().length() == number.toString().length() && number < newNumber && newNumber <= max && isset.get(newNumber) == null) { isset.put(newNumber, true); numberOfReyclings++; } } return numberOfReyclings; } } " B20767," import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class PC { private static int[] div = {10, 100, 1000, 10000, 100000, 1000000, 10000000}; public static void main(String[] args) throws FileNotFoundException { if (args.length != 1) { System.exit(1); } File inFile = new File(args[0]); Scanner sc = new Scanner(inFile); int T = sc.nextInt(); try (PrintWriter out = new PrintWriter(""out.txt"")) { for (int i = 1; i <= T; i++) { int A = sc.nextInt(), B = sc.nextInt(), count = 0, maxPow = 0; for (int j = 0; j < 7; j++) { if (A / div[j] == 0) { maxPow = j - 1; break; } } int[] prevFound = new int[2000000]; for (int j = A; j <= B; j++) { int pow = 0; while (true) { int numFront = j / div[pow]; if (numFront == 0) { break; } int numBack = j % div[pow]; int newNum = numBack * div[maxPow - pow] + numFront; if (j < newNum && A <= newNum && newNum <= B && prevFound[newNum - 1] < j) { prevFound[newNum - 1] = j; count++; } pow++; } } out.println(""Case #"" + i + "": "" + count); } } System.out.println(""Completed!""); } }" B22263,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Main { private static int T = 0; public static BufferedReader bufReader; public static BufferedWriter bufWriter; public static File wFile, rFile; private static int tMinLimit = 1; private static int tMaxLimit = 2000000; private static String rFilename = ""C-large.in""; private static String wFilename = ""OUTPUT0.txt""; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub rFile = new File(rFilename); bufReader = new BufferedReader(new InputStreamReader( new FileInputStream(rFile), ""utf8"")); wFile = new File(wFilename);// «Ø¥ßÀɮסA·Ç³Æ¼gÀÉ bufWriter = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(wFile, false), ""utf8"")); T = Integer.valueOf(bufReader.readLine().trim()); if (tMinLimit <= T && T <= tMaxLimit) { for (int i = 1; i <= T; i++) { String[] AB = bufReader.readLine().split("" ""); new Round1C(i, Integer.parseInt(AB[0]), Integer.parseInt(AB[1])); } } bufWriter.close(); } }" B20082,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class ProblemC { public void write(String m){ try{ FileWriter fstream = new FileWriter(""out.txt""); BufferedWriter out = new BufferedWriter(fstream); out.write(m); out.close(); } catch (Exception e){//Catch exception if any System.err.println(""Error: in writing"" + e.getMessage()); } } public static void main(String[] args) { ProblemC r = new ProblemC(); String result = """"; try{ FileInputStream fstream = new FileInputStream(""input.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); int cases = Integer.parseInt(strLine); for (int i = 0 ; i < cases ; i++){ String []m = br.readLine().split("" ""); int x1 = Integer.parseInt(m[0]); int x2 = Integer.parseInt(m[1]); result += ""Case #""+(i+1)+"": ""+r.solve(x1,x2)+""\n""; } in.close(); } catch (Exception e){//Catch exception if any System.err.println(""Error: "" + e.getMessage()); } r.write(result); } private String solve(int x1 , int x2) { String n = """"; int c = 0; for (int i = x1 ; i < x2 ; i++){ int [] x = array(i); for (int j = 0 ; j < x.length ; j++){ if (x[j] <= x2 && x[j] > i){ c++; // n+= i+"" ""+x[j]+""\n""; } } } n += c+""""; return n; } private int[] array(int x) { String m = x+""""; int [] array = new int[m.length()]; array[0] = x; for (int i = 1 ; i < m.length() ; i++){ String g = m.substring(i,m.length())+m.substring(0,i); array[i] = Integer.parseInt(g); } return array; } } " B21729,"import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Scanner; public class CodeJam2012Ex3 { public static void main(String arg[]) throws FileNotFoundException { File file = new File(""C-large.in""); String output; Scanner scanner = new Scanner(file); int numTestCases = scanner.nextInt(); for (int i = 0; i < numTestCases; i++) { StringBuffer buffer = new StringBuffer(""Case #"" + (i + 1) + "": ""); int A = scanner.nextInt(); int B = scanner.nextInt(); buffer.append(CodeJam2012Ex3.countPairs(A, B)); if (i != numTestCases - 1) { buffer.append(""\n""); } output = buffer.toString(); System.out.print(output); } } public static int countPairs(int A, int B) { int pairs = 0; HashMap map = new HashMap(); for (int i = A; i <= B; i++) { String n = i + """"; int len = n.length(); for (int j = 1; j < len; j++) { String m = n.substring(len - j) + n.substring(0, len - j); int nNum = Integer.parseInt(n); int mNum = Integer.parseInt(m); if (nNum < mNum && n.length() == (mNum + """").length() && mNum <= B && !map.containsKey((n + m))) { map.put(n + m, (Boolean) true); pairs++; } } } return pairs; } } " B21487,"package Recycled; public class Couple { public Couple(int x, int y) { super(); this.x = x; this.y = y; } int x, y; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Couple other = (Couple) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } " B21340,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class MainB { private static final String toRead = ""/home/jean/tmp/C-large.in""; private static final String toWrite = ""/home/jean/tmp/C-large.out""; private static final Map> permutations = new HashMap>(2000000, 1); public static void main(String[] args) throws IOException { // InputStream is = System.in; BufferedReader br = new BufferedReader(new FileReader(toRead)); BufferedWriter bw = new BufferedWriter(new FileWriter(toWrite, false)); compute(br, bw); } private static void compute(BufferedReader br, BufferedWriter bw) throws IOException { Scanner sc = new Scanner(br); int t = sc.nextInt(); sc.nextLine(); for (int i = 0; i < t; ++i) { System.out.println(i); String res = computeOne(sc); write(res, i, bw); } bw.flush(); if (bw != null) { bw.close(); } } private static void write(String res, int i, BufferedWriter bw) throws IOException { StringBuilder sb = new StringBuilder(""Case #"").append(i + 1) .append("": "").append(res); bw.write(sb.toString()); // System.out.println(sb.toString()); bw.newLine(); } public static String computeOne(Scanner sc) { int min = sc.nextInt(); int max = sc.nextInt(); // System.out.println(""A: "" + min + "" | "" + ""B :"" + max); long count = 0; for (int i = min ; i < max ; ++i) { if(i % 100000 == 0) { System.out.println(i); } count += count(i, max); } return Long.toString(count); } private static long count(int number, int max) { if(number < 10) { return 0; } long count = 0; List numberPermutations = permutations.get(number); if(numberPermutations == null) { if(number % 100000 == 0) { System.out.println(""ENTERING !""); } String numberString = String.valueOf(number); final int length = numberString.length(); StringBuilder builder = new StringBuilder(length << 0); builder.append(numberString).append(numberString); numberPermutations = new ArrayList(length - 1); permutations.put(number, numberPermutations); for(int start = 1 ; start < length ; ++start) { String nString = builder.substring(start, start + length); int n = Integer.parseInt(nString); if(n > number && !numberPermutations.contains(n)) { numberPermutations.add(n); } } Collections.sort(numberPermutations); } // for(int n : numberPermutations) { // if (n > number && n <= max) { // ++count; // } // } int c = Collections.binarySearch(numberPermutations, max); if(c >= 0) { count = c + 1; } else { count = -c-1; } return count; } } " B20715,"import java.util.Scanner; class recycled{ public static void main(String args[]) { Scanner s=new Scanner(System.in); int t,i,n,m,a,b,o,f=0,c=0,ca=1; t=s.nextInt(); for(i=1;i<=t;i++) { a=s.nextInt(); b=s.nextInt(); for(n=a;n0;o--) { m=Integer.parseInt(str.substring(o)+str.substring(0,o)); if(m>n && m>a && m<=b) { c++; } } f=0; } System.out.println(""Case #""+ca+"": ""+c); c=0; ca++; } } private static int rep(String str,int l,int b) { int i,f=0; if(l%2==0 && l>3 && (int)(str.charAt(0))<(int)(str.charAt(1)) && Integer.parseInt(str.charAt(l-1)+str.substring(0,l-1))<=b) { for(i=2;i j) && (value <= maxValue)) ++numPairs; } } dataWriter.write (""Case #"" + (i + 1) + "": "" + numPairs); dataWriter.newLine (); dataWriter.flush (); } } catch (IOException ioE) { ioE.printStackTrace (); } } } " B20622,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package utils; /** * * @author fabien */ public interface JamCaseSolver { public void parse(); public void solve(); }" B20118,"import java.util.*; public class C { public static String shift(String a, int d) { String end = a.substring(d, a.length()); String start = a.substring(0, d); return end + start; } public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); for (int ca = 0; ca < t; ca++) { long ct = 0; int A = s.nextInt(), B = s.nextInt(); for (int a = A; a <= B; a++) { String astr = """"+a; HashSet seen = new HashSet(); for (int l = 1; l < astr.length(); l++) { String shift = shift(astr, l); int c = Integer.parseInt(shift); if (!seen.contains(shift) && a < c && c <= B) { seen.add(shift); ct++; } } } System.out.printf(""Case #%d: %d\n"",ca+1,ct); } } } " B20639,"package com.khajochi.codejam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { try { RecycledNumbers sp = new RecycledNumbers(); FileInputStream fstream = new FileInputStream(""/Users/msmart/Documents/My Work/Workspace/M/resource/2012round1/1CSmall.in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String str = br.readLine(); int count = 1; while ((str = br.readLine()) != null) { // System.out.println(str); int start = Integer.parseInt(str.split("" "")[0]); int end = Integer.parseInt(str.split("" "")[1]); int possible = findPossible(start,end); System.out.println(""Case #"" + count++ + "": "" + possible); } in.close(); } catch (Exception e) { System.err.println(e); } } private static int findPossible(int start, int end) { int count = 0; HashMap exclude = new HashMap (); for (int i = start; i <= end; i++) { String num = String.valueOf(i); if ( num.length() > 1 ) { for (int j = 1; j < num.length(); j++) { int newNum = Integer.valueOf(num.substring(j,num.length()) + num.substring(0,j)).intValue(); // System.out.println(newNum); if ( newNum >= start && newNum <= end && newNum != Integer.parseInt(num) ) { boolean skip = false; if ( exclude.get(num) != null && exclude.get(num).equals(String.valueOf(newNum)) ) skip = true; if ( exclude.get(newNum) != null && exclude.get(String.valueOf(newNum)).equals(num) ) skip = true; if ( skip == false ) { // System.out.println(""Yes : "" + num + "" > "" + newNum); exclude.put(num, String.valueOf(newNum)); count++; continue; } } } } } // System.out.println(count/2); return count/2; } } " B20208,"import java.util.*; public class Recycled { public static void main(String[] args) throws Exception { Scanner s = new Scanner(System.in); int T = Integer.parseInt(s.nextLine()); for (int t = 0; t < T; t++) { int A = s.nextInt(); int B = s.nextInt(); long[] values = new long[B + 1]; Set set = new HashSet(); for (int i = A; i <= B; i++) { String istr = """" + i; for (int j = 1; j < istr.length(); j++) { String prefix = istr.substring(istr.length() - j, istr.length()); String suffix = istr.substring(0, istr.length() - j); // Set set = new HashSet(); if (prefix.charAt(0) != '0') { String newNumber = prefix + suffix; int newNumberInt = Integer.parseInt(newNumber); // System.out.println(newNumberInt); if (newNumberInt > i && newNumberInt <= B && String.valueOf(i).length() == String.valueOf(newNumberInt).length()) { // if (set.contains(newNumberInt)) // if (set.contains(newNumberInt)) // System.out.println(newNumberInt); // set.add(newNumberInt); values[newNumberInt] += 1; Pair p = new Pair(i, newNumberInt); set.add(p); // System.out.println(""("" + i + "", "" + newNumberInt + "")""); } } } } // long sum = 0; // for (int i = A; i <= B; i++) { // sum += values[i]; // } System.out.println(""Case #"" + (t + 1) + "": "" + set.size()); } } } class Pair { int n; int m; public Pair(int n, int m) throws Exception { if (n >= m) throw new Exception(); this.n = n; this.m = m; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (m != pair.m) return false; if (n != pair.n) return false; return true; } @Override public int hashCode() { int result = n; result = 31 * result + m; return result; } }" B20106,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Problem3 { public static void main(String[] args) throws FileNotFoundException { String inputFile = ""C-large.in""; Scanner inputScanner = new Scanner(new FileInputStream(""d:\\input\\"" + inputFile)); PrintStream ps = new PrintStream(new FileOutputStream( ""d:\\output\\pro3.txt"")); int totalCaseNum = inputScanner.nextInt(); inputScanner.nextLine(); // ----------------------------------------------- // ----------------------------------------------- for (int caseNum = 1; caseNum <= totalCaseNum; caseNum++) { String line = inputScanner.nextLine(); String prefix = ""Case #"" + caseNum + "": ""; StringBuilder output = new StringBuilder(prefix); // ----------------------------------------------- Scanner sc = new Scanner(line); String A = sc.next(); String B = sc.next(); int len = A.length(); int count = 0; int numA = Integer.parseInt(A); int numB = Integer.parseInt(B); for (int n = numA; n <= numB; n++) { String sn = String.valueOf(n); StringBuilder sb = new StringBuilder(); for (int j = 0; j < len - sn.length(); j++) { sb.append('0'); } sb.append(sn); Set recycle = new HashSet(); for (int j = 1; j < len; j++) { int m = genRecycleNum(sb, j); if (n < m && m <= numB) { recycle.add(m); } } count += recycle.size(); } output.append(count); // ----------------------------------------------- System.out.println(output); ps.println(output); } } private static int genRecycleNum(StringBuilder sb, int j) { String sm = sb.substring(j, sb.length()) + sb.substring(0, j); // System.out.println(sb +""::""+sm); return Integer.parseInt(sm); } } " B22265,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class RecycledNumbers { private long low; private long high; private Map map = new HashMap(); private int recycycled = 0; public static void main(String[] args) throws NumberFormatException, IOException { File file = new File(""C:\\Users\\xebia\\Downloads\\C-large.in""); FileInputStream fis = new FileInputStream(file); DataInputStream in = new DataInputStream(fis); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int numberOfTestCases = new Integer(br.readLine()); for (int j = 0; j < numberOfTestCases; j++) { RecycledNumbers re = new RecycledNumbers(); String[] strings = br.readLine().split("" ""); String s = strings[0]; String s2 = strings[1]; long high = new Long(s2); long low = new Long(s); int numberOfDigits = s.length(); for (long i = low; i <= high; i++) { int roundOffFigure = 1; for (int k = 0; k < numberOfDigits - 1; k++) { roundOffFigure = roundOffFigure * 10; long lastDigit = (long) (i % roundOffFigure); String str = """" + lastDigit; if (str.length() == k + 1) { long startingCombination = (long) (i / roundOffFigure); if (lastDigit == 0) { continue; } long number = (long) (lastDigit * (Math.pow(10, numberOfDigits - str.length())) + startingCombination); if (number >= low && number <= high) { if (number != i) { Boolean bool = re.map.get(number * i); if (bool == null) { re.map.put(number * i, true); re.recycycled++; } } } } } } System.out.println(""Case #"" + (j + 1) + "": "" + re.recycycled); } } public void setLow(long low) { this.low = low; } public long getLow() { return low; } public void setHigh(long high) { this.high = high; } public long getHigh() { return high; } public void setRecycycled(int recycycled) { this.recycycled = recycycled; } public int getRecycycled() { return recycycled; } } " B20283,"package jam2012; import java.io.*; import java.util.*; // Marian G Olteanu public class QC { public static void main(String[] args) throws Exception { initRecycle(2020202); BufferedReader inputFile = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]))); int cases = Integer.parseInt(inputFile.readLine()); PrintStream outFile = new PrintStream(new FileOutputStream(args[1])); for (int i = 1; i <= cases; i++) { String lineT[] = tokenize(inputFile.readLine()); int A = Integer.parseInt(lineT[0]); int B = Integer.parseInt(lineT[1]); int out = 0; for (int j = A; j <= B; j++) if (recycle[j] != null) for (int e : recycle[j]) if (e >= A) out++; outFile.println(""Case #"" + i + "": "" + out); } outFile.close(); inputFile.close(); } private static int[][] recycle; private static int totalR = 0; public static void initRecycle(int len) { recycle = new int[len][]; Set r = new HashSet(); for (int i = 0; i < recycle.length; i++) { String s1 = """" + i; for (int cut = 1; cut < s1.length(); cut++) { String s2 = s1.substring(cut) + s1.substring(0, cut); //System.out.println(s1 + "".."" + s2); if (!s2.startsWith(""0"")) { int v2 = Integer.parseInt(s2); if (v2 < i) r.add(v2); } } //System.out.println(i + "": "" + r); if (r.size() > 0) { recycle[i] = toArray(r); r.clear(); } } //System.out.println(totalR); } private static int[] toArray(Collection r) { int[] out = new int[r.size()]; int i = 0; for (Integer e : r) out[i++] = e.intValue(); // for (int i = 0; i < out.length; i++) // out[i] = r.get(i).intValue(); totalR += out.length; return out; } public static String[] tokenize(String input) { StringTokenizer st = new StringTokenizer(input); String[] k = new String[st.countTokens()]; for (int i = 0; i < k.length; i++) k[i] = st.nextToken(); return k; } public static String[] tokenize(String input, String sep) { StringTokenizer st = new StringTokenizer(input , sep); String[] k = new String[st.countTokens()]; for (int i = 0; i < k.length; i++) k[i] = st.nextToken(); return k; } } " B20223,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package code_jam_3; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; /** * * @author Neo */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int line_counter=0; try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream(""textfile.txt""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter ostream = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(ostream); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console if(line_counter==0){ } else{ String delims = ""[ ]+""; String[] tokens = strLine.split(delims); int a =Integer.parseInt(tokens[0]); int b = Integer.parseInt(tokens[1]); if(a<10){ out.write(""Case #""+line_counter+"": ""+0); out.newLine(); }else{ int output = 0; int a_lenght = String.valueOf(a).trim().length(); if(a_lenght==2){ for(int i =a;in&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&mn&&m list = swap(str); for (int x : list){ if (x >j && x<=b){ count ++; } } } println(""Case #"" + (i+1) + "": "" + count); } //Close the input stream in.close(); }catch (Exception e){ e.printStackTrace(); } } private static HashSet swap(String str){ HashSet list = new HashSet(); for (int i=1; i recycle_numbers = new HashSet(); while (input_file.hasNextLine()) { input_line = input_file.nextLine(); numb_arr = input_line.split("" ""); if(numb_arr != null && numb_arr.length == 1) { /*numberOfTestCases = Integer.parseInt(numb_arr[0]);*/ } else if (numb_arr != null && numb_arr.length == 2) { digitCount = numb_arr[0].length(); st_num = Integer.parseInt(numb_arr[0]); end_num = Integer.parseInt(numb_arr[1]); while(st_num <= end_num) { newNumberString = """" + st_num; for(int i = 1; i < digitCount; i++) { recycle_number = recycle_number.append(newNumberString.substring(i) + newNumberString.substring(0, i)); newNumber = Integer.parseInt(recycle_number.toString()); if(newNumber > st_num && newNumber <= end_num) { recycle_numbers.add(recycle_number.toString()); } recycle_number.delete(0, digitCount); } pair_count = pair_count + recycle_numbers.size(); st_num++; recycle_numbers.clear(); } System.out.println(""Case #"" + Case_Count + "": "" + pair_count); } Case_Count++; pair_count = 0; st_num = 0; end_num = 0; digitCount = 0; newNumber = 0; recycle_number.delete(0, digitCount); } //System.out.println(System.currentTimeMillis() - currentTime); } } " B21161,"import java.util.*; import java.io.*; public class C { private static boolean isRecycledPair(int n, int m) { String sn = Integer.toString(n); String sm = Integer.toString(m); if(sn.length() != sm.length()) return false; int l = sn.length(); for(int i = l; --i >= 0; ) { if(sm.equals(sn.substring(i, l) + sn.substring(0, i))) return true; } return false; } private static long recycledNumbers(String s) { StringTokenizer st = new StringTokenizer(s); final int A = Integer.parseInt(st.nextToken()); final int B = Integer.parseInt(st.nextToken()); long r = 0; for(int n = A; n < B; n++) { char c[] = Integer.toString(n).toCharArray(); for(int i = c.length; --i > 0; ) { char a = c[0]; for(int j = 1; j < c.length; j++) c[j - 1] = c[j]; c[c.length - 1] = a; if(c[0] != '0') { int m = Integer.parseInt(new String(c)); if(m > n && m <= B) r++; } } // for(int m = n; ++m <= B; ) { // if(isRecycledPair(n, m)) // r++; // } } return r; } public static void main(String args[]) throws Exception { //String fileName = ""C.in""; //String fileName = ""C-small-attempt0.in""; String fileName = ""C-large.in""; BufferedReader in = new BufferedReader(new FileReader(fileName)); PrintStream out = new PrintStream(fileName.substring(0, fileName.lastIndexOf('.')) + "".out""); int T = Integer.parseInt(in.readLine()); for(int i = 1; i <= T; i++) { out.print(""Case #"" + i + "": ""); String s = in.readLine(); out.println(recycledNumbers(s)); } out.close(); in.close(); } }" B20707,"package codejam; import java.io.*; import java.util.HashSet; public class Numb { public static void main(String[] args)throws IOException{ HashSet hs; BufferedReader cin=new BufferedReader(new FileReader(""C-large.in"")); PrintWriter cout=new PrintWriter(new BufferedWriter(new FileWriter(""out3.txt""))); String[] in; int x,y,j,num,count; int t=Integer.parseInt(cin.readLine()); for(int i=0;i(); String s=Integer.toString(j); int l=s.length(); for(int k=l-1;k>0;k--){ if(s.charAt(k)=='0') continue; num=Integer.parseInt(s.substring(k)+s.substring(0,k)); if(num>j && num<=y && !hs.contains(num)){ hs.add(num); count++; } } } cout.println(""Case #""+(i+1)+"": ""+count); } cout.flush(); } } " B20726,"package fixjava; import java.util.Map; import java.util.Map.Entry; public class Join { // TODO: write a join-of-joins (2D join) that joins lists-of-lists without the complexity of using a lambda. public static String join(Iterable list, String delim) { if (list == null) return null; StringBuilder buf = new StringBuilder(); int idx = 0; for (T item : list) { if (idx++ > 0) buf.append(delim); buf.append(item.toString()); } return buf.toString(); } public static String join(Iterable list, String delim, Lambda customToString) { if (list == null) return null; StringBuilder buf = new StringBuilder(); int idx = 0; for (T item : list) { if (idx++ > 0) buf.append(delim); buf.append(customToString.apply(item)); } return buf.toString(); } public static String join(T[] array, String delim) { if (array == null) return null; StringBuilder buf = new StringBuilder(); for (int i = 0, n = array.length; i < n; i++) { if (i > 0) buf.append(delim); buf.append(array[i].toString()); } return buf.toString(); } public static String join(int[] array, String delim) { if (array == null) return null; StringBuilder buf = new StringBuilder(); for (int i = 0, n = array.length; i < n; i++) { if (i > 0) buf.append(delim); buf.append(array[i]); } return buf.toString(); } public static String join(float[] array, String delim) { if (array == null) return null; StringBuilder buf = new StringBuilder(); for (int i = 0, n = array.length; i < n; i++) { if (i > 0) buf.append(delim); buf.append(array[i]); } return buf.toString(); } public static String join(double[] array, String delim) { if (array == null) return null; StringBuilder buf = new StringBuilder(); for (int i = 0, n = array.length; i < n; i++) { if (i > 0) buf.append(delim); buf.append(array[i]); } return buf.toString(); } public static String join(char[] array, String delim) { if (array == null) return null; StringBuilder buf = new StringBuilder(); for (int i = 0, n = array.length; i < n; i++) { if (i > 0) buf.append(delim); buf.append(array[i]); } return buf.toString(); } public static String join(Iterable list) { return join(list, """"); } public static String join(T[] array) { return join(array, """"); } public static String join(Iterable list, String delim, String prefix, String suffix) { return prefix + join(list, """") + suffix; } public static String join(T[] array, String prefix, String suffix) { return prefix + join(array, """") + suffix; } /** Recursively join an Iterable that may optionally consist of Iterables. If the items within the Iterable are of type Entry, they are joined as ""key : value"". If value is an Iterable, it is recursed upon. */ @SuppressWarnings(""rawtypes"") public static String joinRecursive(Iterable iterable, String delim, String prefix, String suffix) { if (iterable == null) return null; StringBuilder buf = new StringBuilder(); buf.append(prefix); int idx = 0; for (Object item : iterable) { if (idx++ > 0) buf.append(delim); if (item instanceof Iterable) { buf.append(joinRecursive((Iterable) item, delim, prefix, suffix)); } else if (item instanceof Entry) { Entry ent = (Entry) item; buf.append(ent.getKey().toString()); buf.append("" : ""); Object val = ent.getValue(); if (val instanceof Iterable) buf.append(joinRecursive((Iterable) val, delim, prefix, suffix)); else buf.append(val.toString()); } else { buf.append(item.toString()); } } buf.append(suffix); return buf.toString(); } /** Join a map and recursively join values in the map */ public static String joinRecursive(Map map, String delim, String prefix, String suffix) { return joinRecursive(map.entrySet(), delim, prefix, suffix); } } " B21567,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class ProblemC { // private static String inputFile = ""input.txt""; // private static String inputFile = ""C-small-attempt0.in""; private static String inputFile = ""C-large.in""; public static void main(String[] args) throws IOException { BufferedReader input = null; try { input = new BufferedReader(new FileReader(inputFile)); String line = null; int numOfTestCases = 0; if ((line = input.readLine()) != null) { numOfTestCases = Integer.parseInt(line.trim()); } for (int i = 1; i <= numOfTestCases; i++) { if ((line = input.readLine()) != null) { String ab = line; String[] ab_array = ab.split("" ""); int a = Integer.parseInt(ab_array[0]); int b = Integer.parseInt(ab_array[1]); if (a<10 && b<10) { System.out.println(""Case #"" + i + "": 0""); } else { Set recycled = new HashSet(); if (a < 10) { a = 10; } for (int n=a; nn && m<=b) { recycled.add(n_string + "", "" + m_string); } } } System.out.println(""Case #"" + i + "": "" + recycled.size()); } } else { System.out.println(""ERROR: Could not read the test case #"" + i); } } } catch (FileNotFoundException e) { System.out.println(""ERROR: FileNotFoundException for the input file.""); e.printStackTrace(); } finally { input.close(); } } } " B20884,"package com.google.codejam; public class RecycledNumbers { public int solve(int[] n){ int res = 0; int len = getLen(n[0]); int[] sh = new int[len-1]; for (int i = n[0]; i <= n[1]; i++) { for (int j = 1; j < len; j++) { int ni = shift(i, j, len); sh[j-1] = ni; if(ni > i && ni <= n[1]) { boolean dup = false; for (int k = 0; k < j-1; k++) { if(sh[k] == ni) dup = true; } if(!dup) res++; } } } return res; } private int shift(int i, int j, int len) { int ex = i % ((int)Math.pow(10, j)); int div = i / (int)Math.pow(10, j); return ex * (int)Math.pow(10, len-j) + div; } private int getLen(int n) { int c = 0; while(n > 0){ n /= 10; c++; } return c; } } " B20925,"import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ProblemSample implements Problem { private int solution; private int A; @Override public void solve() { int resultat = 0; for (int n = A; n <= B; n++) { // on trouve toutes les rotations de n String stringN = Integer.toString(n); int size = stringN.length(); Set mySet = new HashSet(); for (int i = 0; i < size; i++) { String actuel = rotation(stringN, size, i); // le set contient les candidats mais pas les doublons mySet.add(Integer.parseInt(actuel)); } // on vérifie si les rotations trouvées sont bonnes ou pas. for (Integer candidat : mySet) { if (candidat > n && candidat <= B) { // si la solution est bonne alors on incrémente. resultat++; } } } this.setSolution(resultat); } private String rotation(String stringN, int size, int nbRotation) { String res = stringN; return res.substring(size - nbRotation, size) + res.substring(0, size - nbRotation); } @Override public Object getSolution() { return solution; } public void setSolution(int solution) { this.solution = solution; } public int getA() { return A; } public void setA(int a) { A = a; } public int getB() { return B; } public void setB(int b) { B = b; } public List getSums() { return sums; } public void setSums(List sums) { this.sums = sums; } private int B; private List sums = new ArrayList(); }" B20469,"import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * C */ /** * @author devang * */ public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException, IOException { int n = 0; String input[] = null; int A, B = 0; List recycledNumbers = null; File f = new File(""//home//devang//Desktop//C-large.in""); //File f = new File(""//home//devang//Desktop//input""); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f))); String testcases = reader.readLine(); n = Integer.parseInt(testcases); FileWriter fw = new FileWriter(""//home//devang//Desktop//output""); for(int i = 0; i < n; i++) { int count = 0; input = reader.readLine().split("" ""); if(input[0].length() == 1) { //Do not increment count. } else { A = Integer.parseInt(input[0]); B = Integer.parseInt(input[1]); HashMap record = new HashMap(); recycledNumbers = getRecycledNumbers(input[0], input[1]); int j = 0; int a = A; int subtract = 0; for(;j < B - A + 1; j++) { //iterate over list. for(int k = (j * (input[0].length() - 1)), l = 0; l < input[0].length() - 1; k++, l++) { String m = (String)recycledNumbers.get(k); if(m.length() == input[0].length() && Integer.parseInt(m) > a && Integer.parseInt(m) <= B) { List list = (List)record.get(String.valueOf(a)); if(list != null && !list.contains(m)) { list.add(m); count++; } else if(list == null) { list = new ArrayList(); list.add(m); record.put(String.valueOf(a), list); count++; } else if(list.contains(String.valueOf(a))) ;//Do nothing. } } a++; } } /*System.out.print(""Case #""+(i+1)+"": ""+count+""\n"");*/ fw.write(""Case #""+(i+1)+"": ""+count+""\n""); } reader.close(); fw.close(); } @SuppressWarnings(""unchecked"") private static List getRecycledNumbers(String A, String B) { List l = new ArrayList(); int a, b, diff = 0; StringBuilder builder = new StringBuilder(A.length()); short numberOfRecycledNumbers = (short)(A.length() - 1); a = Integer.parseInt(A); b = Integer.parseInt(B); diff = b - a + 1; //Do it for each number in the range A to B. for(int j = 0; j < diff; j++) { A = String.valueOf(a + j); for(short i = 0; i < numberOfRecycledNumbers; i++) { char first = A.charAt(0); builder.insert(0, A.substring(1)); builder.insert(A.length() - 1, first); if(builder.length() > A.length()) { //suppress all the un-required characters. builder.replace(A.length(), builder.length(), """"); } A = builder.toString(); l.add(builder.toString()); } } return l; } } " B20146,"// usage: java c infile > outfile import java.io.BufferedReader; import java.io.FileReader; import java.util.Set; import java.util.HashSet; public class c { public static void main(String[] args) throws Exception { String infile = args[0]; BufferedReader reader = new BufferedReader(new FileReader(infile)); int T = Integer.parseInt(reader.readLine()); for (int t = 1; t <= T; t++) { Set pairs = new HashSet(); String[] inputs = reader.readLine().split("" ""); int A = Integer.parseInt(inputs[0]); int B = Integer.parseInt(inputs[1]); int length = inputs[0].length(); //System.out.println(""test = "" + A + "", "" + B + "", "" + length); int total = 0; for (int i = A; i <= B; i++) { String trial = """" + i; //System.out.println(""i = "" + i); for (int n = 1; n < length; n++) { int j = Integer.parseInt(trial.substring(n) + trial.substring(0, n)); //System.out.println(trial.substring(n) + "":"" + trial.substring(0, n)); if (trial.charAt(n) == '0') { continue; } String pair = i + "" "" + j; if (i < j && j <= B && !pairs.contains(pair)) { total++; pairs.add(pair); } } } System.out.println(""Case #"" + t + "": "" + total); } reader.close(); } } " B21799,"import sun.reflect.generics.tree.Tree; import java.util.ArrayList; import java.util.List; public class MathUtil { static List convertToBase (int num, int base) { ArrayList integers = new ArrayList<>(); if (num == 0) { integers.add(0); return integers; } while (num!=0) { integers.add(num % base); num /= base; } return integers; } static int sumList(Iterable iterable) { int sum = 0; for (Integer integer : iterable) { sum += integer; } return sum; } static int sumSquaredList(Iterable iterable) { int sum = 0; for (Integer integer : iterable) { sum += integer * integer; } return sum; } } " B21556,"package codejam.round1; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class ProblemC { public static void main(String[] args) throws Exception { BufferedReader bufferedReader = new BufferedReader(new FileReader(args[0])); PrintStream out = new PrintStream(args[1]); int testsCount = Integer.parseInt(bufferedReader.readLine()); for (int test = 1; test <= testsCount; test++) { String testString = bufferedReader.readLine(); StringTokenizer tokenizer = new StringTokenizer(testString); int A = Integer.parseInt(tokenizer.nextToken()); int B = Integer.parseInt(tokenizer.nextToken()); int recycledCounts = 0; for (int i = A; i <= B; i++) { String n = Integer.toString(i); int digitsCount = n.length(); int currentDigitIndex = 1; Set mSet = new HashSet(); while (currentDigitIndex < digitsCount) { int currentDigit = Integer.parseInt("""" + n.charAt(currentDigitIndex)); int possibleM = Integer.parseInt(n.substring(currentDigitIndex) + n.substring(0, currentDigitIndex)); if (currentDigit != 0 && !mSet.contains(possibleM) && possibleM <= B && i < possibleM) { mSet.add(possibleM); recycledCounts++; } currentDigitIndex++; } } out.println(String.format(""Case #%s: %s"", test, recycledCounts)); } out.close(); bufferedReader.close(); } } " B21416,"import java.util.Scanner; public class RecycleNum { static int digit(int x){ int d = 0; while( x>0 ){ d++; x /= 10; } return d; } static int power(int x){ int n = 1; while(x>0){ n *= 10; x--; } return n; } static int cirNum(int n, int m){ int d = digit(n); n = (n%power(d-m))*power(m) + (n/power(d-m)); return n; } static int result(int A, int B){ int d = digit(A); int count = 0; for(int i = A; i <= B; i++){ int[] key = new int[d-1]; for(int j = 1; j < d; j++){ key[j-1] = cirNum(i, j); for(int k = 0; k < j-1; k++){ if( key[j-1] == key[k] ){ if( key[j-1] != i && key[j-1] >= A && key[j-1] <= B ) count--; } } if( key[j-1] != i && key[j-1] >= A && key[j-1] <= B ){ count++; } } } return count/2; } public static void main(String[] args){ Scanner stdIn = new Scanner(System.in); int T = stdIn.nextInt(); // the number of test cases String[] str = new String[T+1]; String[][] data = new String[T][2]; for(int i = 0; i < T+1; i++){ str[i] = stdIn.nextLine(); } for(int i = 0; i < T; i++){ data[i] = str[i+1].split("" "", 2); } int[] A = new int[T]; int[] B = new int[T]; for(int i = 0; i < T; i++){ A[i] = Integer.parseInt(data[i][0]); B[i] = Integer.parseInt(data[i][1]); } for(int i = 0; i < T; i++){ System.out.println(""Case #"" + (i+1) + "": "" + result(A[i], B[i])); } } } " B20982,"//package com.GoogleCodeJam.y2012.Qualification.RecycledNumbers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new FileReader(new File(""C-large.in""))); int numberOfCases = Integer.parseInt(in.readLine()); for (int caseNumber = 1; caseNumber <= numberOfCases; caseNumber++) { String[] bounds = in.readLine().split("" ""); int min = Integer.parseInt(bounds[0]); int max = Integer.parseInt(bounds[1]); int number = getNumber(min, max); System.out.println(""Case #"" + caseNumber + "": "" + number); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static int getNumber(int min, int max) { int sum = 0; int length = (min+"""").length(); for (int i=min; i<=max; i++) { if (isMinimalRotation(i, min, max, length)) { sum += getNumberOfPairs(i, min, max, length); } } return sum; } public static boolean isMinimalRotation(int posit, int min, int max, int length) { String doubledIn = posit + """" + posit; for (int j = 0; j= min && theorem < posit) { return false; } } return true; } public static int getNumberOfPairs(int posit, int min, int max, int length) { Set seen = new HashSet(); String doubledIn = posit + """" + posit; int counted = 0; for (int j = 0; j= min && theorem <= max && !seen.contains(subSequence)) { seen.add(subSequence); counted += 1; } } if (counted == 1) { return 0; } if (counted == 2) { return 1; } if (counted == 3) { return 3; } if (counted == 4) { return 6; } if (counted == 5) { return 10; } if (counted == 6) { return 15; } if (counted == 7) { return 21; } return counted*(counted-1)/2; } } " B22106,"import java.io.*; class Recycle{ public static void main(String arg[])throws Exception { File f=new File(""C-large.in""); FileInputStream fin=new FileInputStream(f); File f2=new File(""bo.txt""); FileOutputStream fout=new FileOutputStream(f2); BufferedWriter bwr=new BufferedWriter(new OutputStreamWriter(fout)); BufferedReader br=new BufferedReader(new InputStreamReader(fin)); String g=""""; long ipn=Long.parseLong(br.readLine()); long ipni=1; long a,b; String e=""""; long n,m; while(--ipn >=0) { long count=0; g=br.readLine(); a=Long.parseLong(g.substring(0,g.indexOf("" "")) ); b=Long.parseLong( g.substring(g.indexOf("" "")+1,g.length())) ; for(long i=a;i<=b;i++) { n=i; for(long j=0 ; j<(i+"""").length()-1; j++) { m=shift(n); if(m>-1) if(i createChallenges(String[] lines); } " B20672,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; public class ProblemC { public int countDistinctRecycledPairsBetween(int min, int max) { int count = 0; int digit = Integer.toString(min).length(); for (int i = min; i <= max; i++) { count += this.countDistinctRecycledPairOf(i, min, max, digit); } return count; } public int countDistinctRecycledPairOf(int number, int min, int max, int digit) { List used = new ArrayList(digit); int count = 0; int rotated = number; for (int i = 0, rotateCount = digit - 1; i < rotateCount; i++) { rotated = this.shiftRightAndRotate(rotated, digit); if (rotated > number && rotated <= max && used.indexOf(rotated) == -1) { count++; used.add(rotated); } } return count; } private int shiftRightAndRotate(int number, int digit) { return (number % 10) * (int)Math.pow(10, digit - 1) + (number / 10); } public void solve(String inputFileName, String outputFileName) { try { BufferedReader reader = new BufferedReader(new FileReader(new File(inputFileName))); BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName)); int testCount = Integer.parseInt(reader.readLine()); for (int i = 0; i < testCount; i++) { String testCase = reader.readLine(); String[] fields = testCase.split("" ""); int min = Integer.parseInt(fields[0]); int max = Integer.parseInt(fields[1]); int count = this.countDistinctRecycledPairsBetween(min, max); writer.write(""Case #"" + (i + 1) + "": "" + count); writer.newLine(); } reader.close(); writer.close(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } public static void main(String[] args) { ProblemC problem = new ProblemC(); // problem.solve(""C-small-attempt.in"", ""C-small-attempt.out""); // problem.solve(""C-small-attempt0.in"", ""C-small-attempt0.out""); problem.solve(""C-large.in"", ""C-large.out""); } } " B21056,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package problem.c.recycled.numbers; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Scanner; /** * * @author Park */ public class ProblemCRecycledNumbers { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { PrintStream out = new PrintStream(new File(""/Users/Park/Desktop/output.txt"")); Scanner in = new Scanner(new File(""/Users/Park/Desktop/C-large.in"")); int testCase = Integer.parseInt(in.next()); for (int n = 0; n < testCase; n++) { int count = 0; // int start = Integer.parseInt(in.next()); int end = Integer.parseInt(in.next()); for (int i = start; i <= end; i++) { boolean chk = true; String num = i + """"; int numLength = num.length(); int[] alreadySearch = new int[numLength - 1]; for (int j = 1; j < numLength; j++) { String f = num.substring(0, j); String b = num.substring(j); int search = Integer.parseInt(b + f); for (int k = 0; k < j - 1; k++) { if (search == alreadySearch[k]) { chk = false; break; } chk = true; } alreadySearch[j - 1] = search; if (chk && (search + """").length() == numLength && search != i && search >= start && search <= end) { count++; } } } out.println(""Case #"" + (n + 1) + "": "" + count / 2); System.out.println(""Case #"" + (n + 1) + "": "" + count / 2); } in.close(); out.close(); } } " B20955,"import java.util.Scanner; public class C { int A = 0; int B = 0; int cnt = 0; public int getDig(int x){ int temp = x; int dig = 0; while(temp>0){ dig++; temp/=10; } return dig; } public int flip(int x, int time){ int temp = x; int base = 1; for(int i = 1; i<=time;i++) base*=10; int last = temp %base; for(int i = 1; i<=time; i++) temp/=10; for(int i = 1; i<=getDig(x)-time; i++) last*=10; int ans = last + temp; return ans; } public void getPair(int x){ if (x<10) return; int dig = getDig(x); for (int i = 1; i<=dig-1;i++){ int next = flip(x,i); if (dig!=getDig(A)) continue; if (nextB||next dup = new ArrayList(); dup.add(A); for(int i = 1 ; i < A.length();i++){ String n= A.substring(i); String n1= A.substring(0,i); String aa = new String(n+n1); //System.out.println(aa); long a1= Long.parseLong(aa); if ( a1 < a0 && a1>= a && a1<=b && !dup.contains(aa)){ ++s; dup.add(aa); } } return s ; } public static void main(String[] args) throws IOException { RecycledNumbersCodeJam2012Q si = new RecycledNumbersCodeJam2012Q(); int T ; String CurLine = """"; InputStreamReader converter = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(converter); CurLine = in.readLine(); T= Integer.parseInt(CurLine); for(int i = 0 ; i < T;i++) { CurLine = in.readLine(); String A = CurLine.split("" "")[0]; String B = CurLine.split("" "")[1]; System.out.println(""Case #""+ (i+1)+"": ""+si.solves(A,B)); } } } " B20389,"import java.io.*; import java.util.HashMap; class probC{ public static void main(String[] args){ Code b=new Code(); } } class Code{ public Code(){ try { FileWriter fstream = new FileWriter(""output.txt""); BufferedWriter out = new BufferedWriter(fstream); File fin = new File(""C-large.in""); FileReader fr = new FileReader(fin); BufferedReader reader = new BufferedReader(fr); int t = Integer.parseInt(reader.readLine()); for (int qq=0;qqi && cek<=akhir){ jwb++; } ck=ck.substring(1)+ck.charAt(0); cek=Integer.parseInt(ck); } } out.write(""Case #""+(qq+1)+"": ""+jwb+""\n""); } reader.close(); out.close(); } catch (Exception e) { System.err.println(e.getMessage()); } } }" B20480,"import java.io.FileReader; import java.io.LineNumberReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class go3 { public static final String IN_FILE = ""C-large.in""; public static final String OUT_FILE = ""out.txt""; public static void main(String[] args) throws Throwable { try (LineNumberReader reader = new LineNumberReader(new FileReader(IN_FILE))) { try (PrintWriter writer = new PrintWriter(OUT_FILE)) { int T = Integer.parseInt(reader.readLine()); //Tests for (int t = 1; t <= T; t++) { Scanner scanner = new Scanner(reader.readLine()); int LOW = scanner.nextInt(); int HIGH = scanner.nextInt(); HashSet pairs = new HashSet<>(); for(int i = LOW; i <= HIGH ; i++) { Set set = validPermutations(i,LOW,HIGH); Integer[] permutations = set.toArray(new Integer[0]); Arrays.sort(permutations); for(int n = 0; n < permutations.length ; n++){ for(int m = n+1; m < permutations.length; m++) { pairs.add(new Pair(permutations[n],permutations[m])); } } } writer.printf(""Case #%d: %s\n"", t, pairs.size()); } } } } public static Set validPermutations (Integer n,int LOW, int HIGH){ int lastIndex = n.toString().length() - 1; StringBuilder b = new StringBuilder(n.toString()); Set result = new HashSet<>(); result.add(Integer.parseInt(b.toString())); for(int i = 1 ; i <= lastIndex; i++){ char c = b.charAt(lastIndex); if (c == '0') continue; b = b.deleteCharAt(lastIndex).insert(0,c); int k = Integer.parseInt(b.toString()); if(k >= LOW && k <= HIGH){ result.add(k); } } return result; } } class Pair { int n; int m; Pair(int n, int m) { this.n = n; this.m = m; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (m != pair.m) return false; if (n != pair.n) return false; return true; } @Override public int hashCode() { int result = n; result = 31 * result + m; return result; } @Override public String toString() { return ""("" + n + "","" + m + "")""; } }" B20644,"package google.codejam; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; public class Stark_C { /** * @param args */ public static int getDig(int t1){ if(t1==0) return 0; else if(t1<10) return 1; else if(t1<100) return 2; else if(t1<1000) return 3; else if(t1<10000) return 4; else if(t1<100000) return 5; else if(t1<1000000) return 6; else return 7; } public static int times(int t){ if(t==0)return 1; else if(t==1) return 10; else if(t==2) return 100; else if(t==3) return 1000; else if(t==4) return 10000; else if(t==5) return 100000; else if(t==6) return 1000000; else if(t==7) return 10000000; else return 100000000; } public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Scanner sc = new Scanner(new FileReader(""C_small.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""C_small.out"")); int total = sc.nextInt(); for(int i=0; it1 && m>n && m<=t2) ans++; //pw.print("" ans-->""+ans+"" ""); te = te*10; } n++; } pw.println(ans); } pw.flush(); pw.close(); sc.close(); } } " B21417,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; class Recycle extends Question{ public Recycle(String in, String out) { super(in, out); } public void solve(){ ArrayList rst=new ArrayList(); try { data=read(file_in); } catch (IOException e) { e.printStackTrace(); } int cases=pInt(0); data.remove(0); int count=1; for(String s:data){ int tot=0; ArrayList arr=splitInt(s,"" ""); int min=arr.get(0); int max=arr.get(1); for(int i=min;i<=max;i++){ tot+=cycles(i,min,max); } tot=tot/2; rst.add(""Case #""+count+"": ""+tot); count++; } try { write(file_out,rst); } catch (IOException e) { e.printStackTrace(); } } public int cycles(int val,int min,int max){ String s=val+""""; Set ints=new HashSet(); for(int i=0;i=min&&val2<=max){ ints.add(val2); } } } return ints.size()-1; } public String shift(String s){ return s.substring(1)+s.substring(0,1); } } class Question{ String file_in; String file_out; ArrayList data; public Question(String in,String out){ file_in=in; file_out=out; try { data=read(file_in); } catch (IOException e) { e.printStackTrace(); } } public void solve(){} public int pInt(int index){ return Integer.parseInt(data.get(index)); } public int pInt(String s){ return Integer.parseInt(s); } public ArrayList splitString(String s,String sep){ ArrayList arr=new ArrayList(); String[] ss=s.split(sep); for(int i=0;i splitInt(String s,String sep){ ArrayList arr=new ArrayList(); String[] ss=s.split(sep); for(int i=0;i splitString(int index,String sep){ return splitString(data.get(index), sep); } public ArrayList splitInt(int index,String sep){ return splitInt(data.get(index), sep); } public ArrayList read(String filename) throws IOException{ ArrayList arr=new ArrayList(); BufferedReader br=null; br=new BufferedReader(new FileReader(filename)); String l=null; while((l=br.readLine())!=null){ arr.add(l); } br.close(); return arr; } public void write(String filename,ArrayList data) throws IOException{ PrintWriter pw=new PrintWriter(filename); for(String s:data){ pw.println(s); } pw.close(); } } public class Answer3 { public static void main(String[] args){ Question a=new Recycle(""C-large.in"",""rst.txt""); a.solve(); } } " B21160,"package com.codejam; import java.io.File; import java.io.FileNotFoundException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""C-large.in"")); int T = sc.nextInt(); sc.nextLine(); for (int i = 0; i < T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); System.out.println(""Case #"" + (i + 1) + "": "" + solve(A, B)); } } private static long solve(int a, int b) { if (a < 10) { return 0L; } long count = 0L; int len = (int) Math.floor((Math.log10((double) a))); int factor = 1; for (int i = 0; i < len; i++) { factor *= 10; } boolean[] mark = new boolean[b - a + 1]; for (int n = a; n <= b; n++) { if (mark[n - a]) { continue; } int nn = n; Set pairs = new HashSet(); pairs.add(nn); mark[nn - a] = true; for (int i = 0; i < len; i++) { nn = (nn % 10) * factor + nn / 10; if (nn >= a && nn <= b) { pairs.add(nn); mark[nn - a] = true; } } count += cn2(pairs.size()); } return count; } private static long cn2(int size) { long s = (long) size; return s * (s - 1) / 2L; } } " B20499,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class Q3 { private static void run(int CASE) throws Exception { HashSet countedSet = new HashSet(); StringBuilder sb = new StringBuilder(); StringTokenizer st = new StringTokenizer(readLine()); int A = parseInt(st.nextToken()); int B = parseInt(st.nextToken()); int count = 0; for (int n = A; n < B; n++) { countedSet.clear(); String sA = toStr(n); for (int c = 1; c < sA.length(); c++) { sb.delete(0, sb.length()); sb.append(sA.substring(c)).append(sA.substring(0, c)); String sM = sb.toString(); if(sM.charAt(0)=='0') continue; if(countedSet.contains(sM)) continue; countedSet.add(sM); int m = parseInt(sM); if(n= a) sum++; } } System.out.printf(""Case #%d: %d%n"", ti + 1, sum); } } } " B21379,"import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashSet; public class Num { /** * @param args */ public static void main(String[] args) { try { String fname = ""C-large""; FileInputStream fstream = new FileInputStream(fname + "".in""); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; int numCase = 0; int i = 0; while ((strLine = br.readLine()) != null) { if (numCase == 0) numCase = Integer.valueOf(strLine); else if (strLine.length() > 0) runCase(strLine, ++i); } in.close(); } catch (Exception e) {// Catch exception if any e.printStackTrace(); } } static void runCase(String line, int caseNum) { String[] borders = line.split("" ""); int length = borders[0].length(); int a = Integer.valueOf(borders[0]); int b = Integer.valueOf(borders[1]); HashSet pairs = new HashSet(); for (int i = a; i <= b; i++) { for (int j = 1; j < length; j++) { int pos = (int) Math.pow(10, j); int pair = i / pos + (i % pos) * (int) Math.pow(10, length - j); if (pair >= a && pair <= b && pair != i) { if (i < pair) pairs.add(i + "","" + pair); else pairs.add(pair + "","" + i); } } } System.out.println(""Case #"" + caseNum + "": "" + pairs.size()); } } " B22184,"package com.qualification; import java.io.*; import java.util.ArrayList; import java.util.List; public class Two { public static void main(String[] args) throws FileNotFoundException, IOException { FileReader fr = new FileReader(""/Users/minerva/Desktop/input.txt""); FileWriter fw = new FileWriter(""/Users/minerva/Desktop/output.txt""); BufferedReader br = new BufferedReader(fr); PrintWriter pr = new PrintWriter(fw); int numInputs = Integer.valueOf(br.readLine()); for(int i=0;i rmap = new ArrayList(); public Shifter(long input) { this.input = input; } private List generate() { int length = new Long(input).toString().length(); long pow10 = (long)Math.pow(10,length); for (int pow = 10;;pow *= 10) { long n1 = input / pow; long n2 = input % pow; if (n1 == 0) break; long n3 = n2 * pow10 / pow + n1; //System.out.print(n1 + "","" + n2 + "" ("" + input + "","" + n3 + "")""); if (n3 > input) { //System.out.println(""*""); int n3len = new Long(n3).toString().length(); if (n3len == length && !rmap.contains(n3)) rmap.add(n3); } else { //System.out.println(); } } return rmap; } public static long count(long num1, long num2) { long count = 0; for (long i = num1; i <= num2; i++) { List results = new Shifter(i).generate(); for(Long item:results) { if (item <= num2) { count++; //System.out.println(""("" + i + "","" + item + "")""); } } } return count; } } /* in op * 1234 2341 */ " B21167,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.common; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; /** * * @author jim */ public class Output { private final String[] data; public Output(String[] data) { this.data = data; } public Output(ArrayList data) { this(data.toArray(new String[0])); } public int size() { return data.length; } public String get(int i) { StringBuilder sb = new StringBuilder(data[i].length() + 10); sb.append(""Case #""); sb.append(i + 1); sb.append("": ""); sb.append(data[i]); return sb.toString(); } public void export(String fileName) { if (fileName == null) print(); else { try { save(fileName); } catch (IOException ioe) { System.out.println(ioe.getMessage()); ioe.printStackTrace(); } } } private void print() { for (int i = 0; i < size(); i++) System.out.println(get(i)); } private void save(String fileName) throws IOException { FileWriter fw = new FileWriter(fileName); PrintWriter pw = new PrintWriter(fw); for (int i = 0; i < size(); i++) { pw.println(get(i)); } pw.flush(); pw.close(); fw.close(); } } " B20472,"import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class recycle { public static void main(String args[]) throws IOException { Scanner s = new Scanner(new File(""D:\\workspace\\GC12\\src\\input2.txt"")); FileWriter fo = new FileWriter(new File(""D:\\workspace\\GC12\\src\\output2.txt"")); int number = s.nextInt(); for(int i = 1; i<= number; i++) { fo.write(""Case #"" + i + "": ""); int a = s.nextInt(); int b = s.nextInt(); Set aCounted = new HashSet(); for (int j = a;j<=b;j++) { StringBuffer n = new StringBuffer(String.valueOf(j)); for (int p = 0; p < n.length(); p++) { n.append(n.charAt(0)); n.deleteCharAt(0); if (j < Integer.parseInt(n.toString()) && Integer.parseInt(n.toString()) <= b) { aCounted.add(String.valueOf(j) + n.toString()); } } } fo.write(aCounted.size() + ""\n""); } fo.close(); s.close(); } } " B22156,"package com.vp.impl; import java.util.ResourceBundle; import com.vp.iface.Problem; public class SpeakGooglerese implements Problem { @Override public String solve(String[] dataset) { ResourceBundle rb = ResourceBundle.getBundle(""Mapping""); String strReturnValue = """"; //System.out.println(""Translated Text: "" + strReturnValue); String strGooglereseSentence = dataset[0]; String[] strGooglereseWords = strGooglereseSentence.split("" ""); for(int i=0; i0 ) { strReturnValue += "" ""; } char strChars[] = strGooglereseWords[i].toCharArray(); for(int j=0;j set = new HashSet(); for (int i = 0; i < l; ++i) { m = m / 10 + ((int) Math.pow(10, l-1)) * (m % 10); if (m > n && m <= B) { set.add(m); } } count += set.size(); } return count; } public static void main(String[] args) throws IOException { String filename = args[0]; BufferedReader br = new BufferedReader(new FileReader(filename)); int T = Integer.parseInt(br.readLine()); for (int i = 1; i <= T; ++i) { String[] line = br.readLine().split("" ""); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); System.out.println(""Case #"" + i + "": "" + count(A, B)); } } }" B21369,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class C { static int[] resu; /** * @param args */ public static void main(String[] args) { File input=new File(""D:\\Users\\xiaoguo\\Downloads\\C-small.in""); File output=new File(""D:\\Users\\xiaoguo\\Desktop\\output.txt""); readCaseFromInput(input); writeToOutput(output); System.out.println(""Programe exist!""); } static class Couple{ private int a; private int b; public Couple(int a, int b) { this.a=a; this.b=b; } public boolean equals(Object o){ return (this.a==((Couple)o).a && this.b==((Couple)o).b); } } static void readCaseFromInput(File input ) { try { FileReader reader=new FileReader(input); BufferedReader buf=new BufferedReader(reader); int numberCase=Integer.parseInt(buf.readLine()); resu=new int[numberCase]; String contentLine=null; int numerLine=0; while((contentLine=buf.readLine())!=null) { String[] line=contentLine.split(""\\s""); int a=Integer.parseInt(line[0]); int b=Integer.parseInt(line[1]); int n=0; ArrayList liste=new ArrayList(); if(a>=10 && b>=10) { for(int i=a;i<=b;i++) { String number=String.valueOf(i); for(int j=number.length()-1;j>=1;j--) { int x=Integer.parseInt(number.substring(j)+number.substring(0, j)); C.Couple couple=new C.Couple(i, x); if(x<=b && x>i && !liste.contains(couple)) { n++; liste.add(couple); } } } } resu[numerLine]=n; numerLine++; } buf.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } } static void writeToOutput(File output) { try { FileWriter out=new FileWriter(output); BufferedWriter buf=new BufferedWriter(out); String headLine=""Case #""; for(int i=0;i= A && (int)tempNumber <= B) { total++; } } } output.write(""Case #"" + (i + 1) + "": "" + (total/2)); if (i != T - 1) { output.write(""\n""); } i++; } output.close(); } } " B21911," import java.util.*; public class C { public static void main (String[] args) { String bIn; Scanner in = new Scanner(System.in); int T = Integer.parseInt(in.nextLine()); for (int test = 0 ; test < T ; test++) { String range = in.nextLine(); String[] cIN = range.split("" ""); int max = Integer.parseInt(cIN[1]); int min = Integer.parseInt(cIN[0]); int count = 0; for (int findPair = min ; findPair <= max ; findPair ++) { String thisOne = String.valueOf(findPair); String[] gothrough = thisOne.split(""""); int digitLength = gothrough.length-1; int sameTest = Integer.parseInt(thisOne); // System.out.println(digitLength); for (int shuffle1 = 0 ; shuffle1 < digitLength ; shuffle1++) { String temp = thisOne.substring(shuffle1)+thisOne.substring(0,shuffle1); // System.out.println(temp); int test1 = Integer.parseInt(temp); if (test1 <= max && test1 >= min && test1 != sameTest) { // System.out.println(test1); // System.out.println(""( ""+thisOne+"",""+test1+"")""); count++; } } } count = count/2; System.out.println(""Case #""+(test+1)+"": ""+count); } } }" B21573,"package cj2012.qual; import java.io.File; import java.io.PrintWriter; import java.util.Scanner; import java.util.TreeSet; public class C { public static void main(String[] args) throws Exception { Scanner scan = new Scanner(new File(""in/C-large.in"")); int T = scan.nextInt(); PrintWriter out = new PrintWriter(new File(""out/C-large.txt"")); for (int z = 1; z <= T; z++) { int A = scan.nextInt(); int B = scan.nextInt(); int D = 1 + (int) Math.log10(B); int C = (int) Math.pow(10, D - 1); int res = 0; TreeSet set = new TreeSet(); for (int n = A; n <= B; n++) { for (int s = 1; s < D; s++) { int m = n; for (int k = 0; k < s; k++) m = (m % 10) * C + (m / 10); if (m < A || m > B || n >= m) continue; set.add(m); } res += set.size(); set.clear(); } out.println(""Case #"" + z + "": "" + res); } out.close(); } } " B22005,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Hashtable; public class Recycled_Numbers { public static void main(String[] args) throws IOException { BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); String x=reader.readLine(); long cases=Long.parseLong(x); Hashtable hash=new Hashtable(); String input=""""; long a=0; String result=""""; long b=0; long i=a; String temp=""""; String ctemp=""""; long counter=0; String []array; for(int j=0;j0){ int A = s.nextInt(); int B = s.nextInt(); try{s.nextLine();}catch(Exception e){} Set pairs = new HashSet(); long num=0; for (int i= A; i <=B;i++){ int k=i; int digits = 0; int mult = 1; while (k>0){ digits++; k/=10; mult *= 10; } k=i; int sum = 0; int m2 = 1; while (k>0){ sum += m2*(k%10); boolean zero =k%10 == 0; mult/=10; k/=10; int a = i; int b = sum*mult+k; if (!zero && b >= A && b <= B && a!=b){ pair p = new pair(); p.a = b; p.b = i; if(!pairs.contains(p)) { p.a = i; p.b=b; if (!pairs.contains(p)){ num++;pairs.add(p); // System.out.println(p.a + ""-""+p.b); } } } m2*=10; } } System.out.println(""Case #""+casen++ +"": ""+ num); } } } " B21388,"import java.io.*; import java.util.*; public class Main { private static IO io; public static void main(String[] args) throws IOException { new Main().run(); } private void run() throws IOException { io = new IO(System.getProperty(""ONLINE_JUDGE"")!=null);//false->files; true->console solve(); io.flush(); } private void solve() throws IOException { int n = io.nI(); for(int z = 1; z<=n; z++){ int a = io.nI(), b = io.nI(), l = String.valueOf(a).length(), r = 0; for(int i = a; i<=b; i++){ Set L = new HashSet(); String S = String.valueOf(i); char c[] = S.toCharArray(); for(int j = 0; j exist = new HashMap(); for (int i = 0; i <= strn.length() ; i ++) { String startNewN = strn.substring(strn.length() - i,strn.length() ); if (startNewN.equals("""")) { continue; } String endNewN = strn.substring(0, strn.length() - i); if (endNewN.equals("""")) { continue; } String newN = startNewN.concat(endNewN); long longN =Long.parseLong(newN); if ( longN <= B && longN > n) { if (exist.get(longN) == null) { exist.put(longN, 1); countRecycle ++; } } } } out.println(countRecycle); } out.close(); } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } } " B20777,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package solution; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; /** * * @author 144key (tux_daemon) */ public class Main { // Problem 3 : Problem C. Recycled Numbers public static void recycledNumbers(String fileIn, String fileOut) { try { FileInputStream fis = new FileInputStream(new File(fileIn)); FileOutputStream fos = new FileOutputStream(new File(fileOut)); int chars = 0; StringBuffer tmpStrLine = null; int nbCase = 0; int processedCase = 1; int guide = 0; while ((chars != -1) && ((nbCase == 0) || (processedCase <= nbCase))) { tmpStrLine = new StringBuffer(); while (((chars = fis.read()) != -1) && (((char) chars) != '\n')) { tmpStrLine.append((char) chars); } if (guide == 0) { // searching for nbCase nbCase = Integer.parseInt(tmpStrLine.toString()); guide = 1; } else if (guide == 1) { // process // init //System.out.println(""IN : "" +tmpStrLine.toString()); String[] tmp = tmpStrLine.toString().split(""\\s""); int bottomLimit = Integer.parseInt(tmp[0]); int topLimit = Integer.parseInt(tmp[1]); int nbRecycledPair = 0; for (int processedNumber = bottomLimit; processedNumber <= topLimit; processedNumber++) { char[] numberElmt = (""""+processedNumber).toCharArray(); int numberElmtLength = numberElmt.length; if (numberElmtLength > 1) { for (int j = 0; j < (numberElmtLength-1); j++) { char lastElmt = numberElmt[numberElmtLength-1]; for (int k = (numberElmtLength-1); k > 0; k--) { numberElmt[k] = numberElmt[k-1]; } numberElmt[0] = lastElmt; int tmpRecycle = Integer.parseInt(String.valueOf(numberElmt, 0, numberElmtLength)); if (tmpRecycle > processedNumber && tmpRecycle <= topLimit) { nbRecycledPair++; } } } } // output result fos.write((""Case #""+processedCase+"": ""+nbRecycledPair+""\n"").getBytes()); //System.out.println(""Case #""+processedCase+"": ""+nbRecycledPair); // back to search tmpCredit processedCase++; } } fis.close(); fos.close(); } catch (FileNotFoundException e) { System.err.println(""FileNotFound : "" + e); } catch (IOException e) { System.err.println(""IOException : "" + e); } catch (Exception e) { System.err.println(""Other Exception : "" + e); } } /** * @param args the command line arguments **/ public static void main(String[] args) { // TODO code application logic here recycledNumbers(""C-large.in"", ""C-large.out""); } } " B22225,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class ProblemC { static Scanner kb = null; static FileWriter fw = null; public static void main(String [] args) { try { kb = new Scanner(new File(""input.in"")); } catch (FileNotFoundException e) {} int T = kb.nextInt(); //int result = solve(1111, 2222); //System.out.println(""Case #""+2+"": ""+result); FileWriter fstream = null; try { fstream = new FileWriter(""output.txt""); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } BufferedWriter out = new BufferedWriter(fstream); for(int i=1; i<=T; i++) { int A = kb.nextInt(); int B = kb.nextInt(); int result = solve(A, B); try { out.append(""Case #""+i+"": ""+result+""\n""); //out.write(""Case #""+i+"": ""+result); } catch (IOException e) { System.out.println(""error ""+e.getMessage() ); } //System.out.println(""Case #""+i+"": ""+result); } try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static int solve(int A, int B) { // 100 500 int count = 0; for(int i=A; i<=B; i++) { String istr = i+""""; // 100 String icyc = istr + istr; // 100100 int len = istr.length(); //System.out.println(""cyc: ""+icyc); ArrayList savedInts = new ArrayList(); savedInts.add(i); for(int j=1; j ""+recycInt); if(recycInt <= B && recycInt>=A && !savedInts.contains(recycInt)) { //System.out.println(""*""); savedInts.add(recycInt); count++; } } } return count/2; } } " B21236,"package com.google.code; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public abstract class GCJ { private BufferedReader input; private BufferedWriter output; String inputLine; String[] brokenUpInputLine; public static final String FOLDER = ""/tmp/""; protected GCJ() throws IOException { String subclass = this.getClass().getSimpleName(); input = new BufferedReader(new FileReader(new File(FOLDER, subclass+"".in""))); output = new BufferedWriter(new FileWriter(new File(FOLDER, subclass+"".out""))); } public void run() throws NumberFormatException, IOException { int loop = Integer.valueOf(input.readLine()); for (int i = 0; i < loop; i++) answering(i+1); output.flush(); } protected void write(String s) throws IOException { System.out.print(s); output.write(s); } protected void writeln(String s) throws IOException { System.out.println(s); output.write(s+""\n""); } protected void writeln() throws IOException { System.out.println(); output.write(""\n""); } protected void write(int s) throws IOException { System.out.print(String.valueOf(s)); output.write(String.valueOf(s)); } protected void writeln(int s) throws IOException { System.out.println(String.valueOf(s)); output.write(String.valueOf(s)+""\n""); } protected void readLine() throws IOException { inputLine = input.readLine(); brokenUpInputLine = inputLine.split("" ""); } protected String getStringInput(int i) { return brokenUpInputLine[i]; } protected int getIntInput(int i) { return Integer.parseInt(brokenUpInputLine[i]); } protected long getLongInput(int i) { return Long.parseLong(brokenUpInputLine[i]); } protected double getDoubleInput(int i) { return Double.parseDouble(brokenUpInputLine[i]); } private void answering(int ordinalityOfProblem) throws IOException { writeOrdinalityOfAnswer(ordinalityOfProblem); code(ordinalityOfProblem); } private void writeOrdinalityOfAnswer(int ordinalityOfProblem) throws IOException { write(""Case #""+ordinalityOfProblem+"": ""); } protected abstract void code(int count) throws IOException; } " B21053,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNumbers { private PrintWriter out; private Scanner in; private void init() { } private void solve() { int A = in.nextInt(); int B = in.nextInt(); int r = 0; for (int i = A; i <= B; i++) { int j = rotate(i); while (i != j) { if (i < j && j <= B) { r++; } j = rotate(j); } } out.println(r); } private int rotate(int number) { int pos = 1; while (number % 10 == 0) { pos *= 10; number /= 10; } int rest = number % 10; number /= 10; int numberCopy = number; while (numberCopy > 0) { pos *= 10; numberCopy /= 10; } return rest * pos + number; } private void runTests() { init(); int T = Integer.parseInt(in.nextLine()); for (int i = 0; i < T; i++) { out.print(""Case #"" + (i + 1) + "": ""); solve(); } } private void run() { try { runTests(); } finally { close(); } } private void close() { out.close(); in.close(); } public RecycledNumbers() throws FileNotFoundException { this.in = new Scanner(new File(""C-large.in"")); this.out = new PrintWriter(new File(""C-large.out"")); } public static void main(String[] args) throws FileNotFoundException { new RecycledNumbers().run(); } } " B22197,"import static java.lang.System.in; import static java.lang.System.out; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Recycled { public static void main(String[] args) throws IOException { Scanner asdf = new Scanner(in); Scanner file = new Scanner(new File(""C-large.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""C-large.out""))); int t = file.nextInt(); for(int r=1; r<=t; r++){ run(r, file, out, asdf); } out.close(); } public static void run(int r, Scanner file, PrintWriter out, Scanner asdf){ int a = file.nextInt(); int b = file.nextInt(); int count = 0; ArrayList list = new ArrayList(); /*for(int s=1; s<=Integer.toString(b).length()/2+1; s++) for(int x=a; x<=b; x++) for(int y=b; y>=x; y--) if(!list.contains(x*y) && x!=y && x==rotateDig(y, s)){ count++; list.add(x*y); //System.out.println(x+"" ""+y); }*/ int l = Integer.toString(b).length(); for(int z=a; z<=b; z++){ for(int s=1; s<=l; s++){ int temp = rotateDig(z,s); if(temp>z && temp<=b){ if(list.isEmpty()) count++; else if(!list.isEmpty() && !(temp==list.get(list.size()-1))) count++; list.add(temp); //System.out.println(rotateDig(z,s)); } } } //System.out.println(""Case #""+r+"": ""+count); out.println(""Case #""+r+"": ""+count); } public static int rotateDig(int n, int shift){ String s = Integer.toString(n); String t = """"; t = s.substring(shift); t += s.substring(0,shift); return Integer.parseInt(t); } } " B20426,"import java.io.*; import java.util.*; public class Prob3 { public static void main (String[] args) throws IOException { BufferedReader in = new BufferedReader (new FileReader (""C-large.in"")); PrintWriter out = new PrintWriter (new FileWriter (""OUT3.txt"")); int T = Integer.parseInt (in.readLine ().trim ()), c, a, b; StringTokenizer st; String temp, hold; ArrayList p; for (int x = 0 ; x < T ; x += 1) { c = 0; st = new StringTokenizer (in.readLine ()); a = Integer.parseInt (st.nextToken ()); b = Integer.parseInt (st.nextToken ()); for (int y = a ; y < b ; y += 1) { if (y > 10) { temp = Integer.toString (y); p = new ArrayList (); for (int z = 0 ; z < temp.length () - 1 ; z += 1) { hold = temp.substring (z + 1) + temp.substring (0, z + 1); if (hold.charAt (0) != '0' && Integer.parseInt (hold) > Integer.parseInt (temp) && Integer.parseInt (hold) <= b && p.contains (hold) == false) { c += 1; p.add (hold); } } } } out.println (""Case #"" + (x + 1) + "": "" + c); } out.close (); } } " B20150,"/* * Yasser Rabi */ package c; import java.io.*; import java.util.*; public class main { public static int recycled (int A, int B){ int m = 0, c=0; String tmp = """", subB = """", subE = """", recycled = """"; for (int n = A; nn) && (m<=B)) {c++;} } } return c; } public static void main(String[] args) throws FileNotFoundException, IOException { String ligne = """"; int nbrLigne = 0,res,a,b; StringTokenizer st1; FileInputStream fStream = new FileInputStream(""C:\\C-large.in""); BufferedReader in = new BufferedReader(new InputStreamReader(fStream)); if (in.ready()) { ligne = in.readLine(); nbrLigne = Integer.parseInt(ligne); for (int j = 0; j < nbrLigne; j++) { ligne = in.readLine(); st1=new StringTokenizer(ligne,"" ""); a=Integer.parseInt(st1.nextToken()); b=Integer.parseInt(st1.nextToken()); System.out.print(""Case #""+(j+1)+"": ""); res=recycled(a,b); System.out.print(res); System.out.println(""""); } } } } " B21213,"import java.util.*; import java.io.*; public class recycle { public static int[] pow10 = {1,10,100,1000,10000,100000,1000000,10000000}; public static void main(String[] args) throws Throwable { Scanner input=new Scanner(new File(""recycle.in"")); PrintWriter out=new PrintWriter(new File(""recycle.out"")); int cases=input.nextInt(); for(int test=1;test<=cases;test++) { boolean[] visited=new boolean[2000001]; int a=input.nextInt(); int b=input.nextInt(); int rank=0, num=1; int ans=0; for(;num<=a;num*=10,rank++); // rank = #digits for(int i=a;i<=b;i++) { if(visited[i]) continue; visited[i]=true; int temp=i; int count=1; for(int j=0;jb || visited[temp]) continue; visited[temp]=true; count++; } ans+=count*(count-1)/2; //count choose 2 } out.println(""Case #""+test+"": ""+ans); } out.close(); } }" B21046,"import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class problem { public static void main(String[] args) throws IOException{ final String filein = ""C:\\Users\\BYTE\\Downloads\\C-small-attempt0.in""; //final String filein = ""C:\\Users\\byte\\Downloads\\NewFolder\\C-small-attempt6.txt""; BufferedReader in = new BufferedReader(new FileReader(filein)); int tests=Integer.parseInt(in.readLine()); int a=0,b=0,num=0; for(int i=0;i0;k--) { if(arr[k]== '0') continue; else { String s = new String(arr); int z= Integer.parseInt(s.substring(k,arr.length)+s.substring(0,k)); if(z >= a && z<=b && z!=j && !(z helper = new HashSet(); for (int i = 1; i <= 6; ++i) pow[i] = pow[i - 1] * 10; for (int init = 1; init < transform.length; ++init) { int shiftsCount = getDigitsCount(init), n = 0; helper.clear(); for (int currentShift = 1; currentShift < shiftsCount; ++currentShift) { int left = init / pow[currentShift], right = init % pow[currentShift]; int result = right * pow[shiftsCount - currentShift] + left; if (result != init) helper.add(result); } transform[init] = new int[helper.size()]; for (int t : helper) { transform[init][n++] = t; } } } static final int getDigitsCount(int what) { String represents = Integer.toString(what); return represents.length(); } final long doit2() throws Throwable { int A = nextInt(), B = nextInt(); long result = 0; for (int i = A; i <= B; ++i) { for (int j = 0; j < transform[i].length; ++j) { if (transform[i][j] >= A && transform[i][j] <= B) ++result; } } return result / 2; } final String doit(int ID) throws Throwable { return String.format(""Case #%d: %d"", ID, doit2()); } private void solve() throws Throwable { int testCases = nextInt(); for (int i = 1; i <= testCases; ++i) { output.println(doit(i)); } } public void run() { try { solve(); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } finally { output.close(); } } public static void main(String... args) { new Main(""input.txt"", ""output.txt"").start(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } private double nextDouble() throws IOException { return Double.parseDouble(next()); } private long nextLong() throws IOException { return Long.parseLong(next()); } private String next() throws IOException { while (tokens == null || !tokens.hasMoreTokens()) { tokens = new StringTokenizer(input.readLine()); } return tokens.nextToken(); } private StringTokenizer tokens; private BufferedReader input; private PrintWriter output; } "

* For additional documentation, see Section 1.5 of * Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. */ public final class StdOut { // force Unicode UTF-8 encoding; otherwise it's system dependent private static final String UTF8 = ""UTF-8""; // assume language = English, country = US for consistency with StdIn private static final Locale US_LOCALE = new Locale(""en"", ""US""); // send output here private static PrintWriter out; // this is called before invoking any methods static { try { out = new PrintWriter(new OutputStreamWriter(System.out, UTF8), true); } catch (UnsupportedEncodingException e) { System.out.println(e); } } // singleton pattern - can't instantiate private StdOut() { } // close the output stream (not required) /** * Close standard output. */ public static void close() { out.close(); } /** * Terminate the current line by printing the line separator string. */ public static void println() { out.println(); } /** * Print an object to standard output and then terminate the line. */ public static void println(Object x) { out.println(x); } /** * Print a boolean to standard output and then terminate the line. */ public static void println(boolean x) { out.println(x); } /** * Print a char to standard output and then terminate the line. */ public static void println(char x) { out.println(x); } /** * Print a double to standard output and then terminate the line. */ public static void println(double x) { out.println(x); } /** * Print a float to standard output and then terminate the line. */ public static void println(float x) { out.println(x); } /** * Print an int to standard output and then terminate the line. */ public static void println(int x) { out.println(x); } /** * Print a long to standard output and then terminate the line. */ public static void println(long x) { out.println(x); } /** * Print a short to standard output and then terminate the line. */ public static void println(short x) { out.println(x); } /** * Print a byte to standard output and then terminate the line. */ public static void println(byte x) { out.println(x); } /** * Flush standard output. */ public static void print() { out.flush(); } /** * Print an Object to standard output and flush standard output. */ public static void print(Object x) { out.print(x); out.flush(); } /** * Print a boolean to standard output and flush standard output. */ public static void print(boolean x) { out.print(x); out.flush(); } /** * Print a char to standard output and flush standard output. */ public static void print(char x) { out.print(x); out.flush(); } /** * Print a double to standard output and flush standard output. */ public static void print(double x) { out.print(x); out.flush(); } /** * Print a float to standard output and flush standard output. */ public static void print(float x) { out.print(x); out.flush(); } /** * Print an int to standard output and flush standard output. */ public static void print(int x) { out.print(x); out.flush(); } /** * Print a long to standard output and flush standard output. */ public static void print(long x) { out.print(x); out.flush(); } /** * Print a short to standard output and flush standard output. */ public static void print(short x) { out.print(x); out.flush(); } /** * Print a byte to standard output and flush standard output. */ public static void print(byte x) { out.print(x); out.flush(); } /** * Print a formatted string to standard output using the specified * format string and arguments, and flush standard output. */ public static void printf(String format, Object... args) { out.printf(US_LOCALE, format, args); out.flush(); } /** * Print a formatted string to standard output using the specified * locale, format string, and arguments, and flush standard output. */ public static void printf(Locale locale, String format, Object... args) { out.printf(locale, format, args); out.flush(); } // This method is just here to test the class public static void main(String[] args) { // write to stdout StdOut.println(""Test""); StdOut.println(17); StdOut.println(true); StdOut.printf(""%.6f\n"", 1.0/7.0); } } " B20257,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Saransh */ import java.io.*; import java.util.*; import java.math.*; import java.lang.*; public class Main { static int pts[]; static int n,s,p; static int memo[][]; static boolean marked[][]; public static void main(String[] args) { try { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); int test=1; while(t-->0) { int A=sc.nextInt(); int B=sc.nextInt(); int count=0; for(int i=A;i<=B;i++) { String str=i+""""; HashSet set=new HashSet(); for(int i1=0;i1<=str.length();i1++) { String tmp=str.substring(i1)+str.substring(0,i1); if(tmp.charAt(0)!='0') { int temp=Integer.parseInt(tmp); if(temp>i&&temp<=B&&!set.contains(temp)) { set.add(temp); count++; } } } } System.out.println(""Case #""+test+"": ""+count); test++; } } catch(Exception e) { e.printStackTrace(); } } } " B20843,"package egWo; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Cl { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int l = 1; l <= T; l++) { in.nextLine(); int n = in.nextInt(); int m = in.nextInt(); int count = 0; for (int i = n; i < m; i++) { int uv = 0; for (int j = 1000000; j >= 1; j = j / 10) { if (m / j > 0 && m / j < 10) { uv = j; } } ArrayList revI = new ArrayList(); int s = 10; for (int c = uv; c >= 10; c = c / 10) { int h = i / c; int t = i % c; int rev = (t * s) + h; s *= 10; revI.add(rev); } Set set = new HashSet(revI); for (Object j : set) { if (i < ((Integer) j).intValue() && ((Integer) j).intValue() <= m) { count++; } } } System.out.format(""\nCase #%d: %d"", l, count); } } } " B21927,"package qualification; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Recycled { public static void main(String[] args) { Scanner s = new Scanner(System.in); int numCases = s.nextInt(); for (int i = 1; i <= numCases; i++) { int a = s.nextInt(); int b = s.nextInt(); int numRecycled = countRecycled(a, b); System.out.printf(""Case #%d: %d\n"", i, numRecycled); } } private static int countRecycled(int a, int b) { int result = 0; StringBuilder sbB = new StringBuilder(); sbB.append(b); List register = new ArrayList(); for (int i = a; i <= b; i++) { register.clear(); if (i < 10) continue; StringBuilder sb = new StringBuilder(); sb.append(i); for (int j = sb.length() - 1; j > 0; j--) { StringBuilder newCombinedSb = new StringBuilder(); newCombinedSb.append(sb.substring(j)).append(sb.substring(0, j)); if (newCombinedSb.charAt(0) == '0') continue; if (newCombinedSb.charAt(0) > sbB.charAt(0)) continue; if (newCombinedSb.charAt(0) < sb.charAt(0)) continue; int newCombinedInt = Integer.parseInt(newCombinedSb.toString()); if (newCombinedInt <= b && newCombinedInt > i) { if (!register.contains(newCombinedInt)) { register.add(newCombinedInt); } } } result += register.size(); } return result; } } " B21513,"import java.io.*; import java.util.*; public class C { static int N = 2000001; static int[][] pair = new int[N][6]; static int[] np = new int[N]; public static void main (String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (int i = 1; i <= 6; i++) gen(i); gen(1000000, 2000000, 7); /*for (int i = 1; i < 1000; i++) for (int j = 0; j < np[i]; j++) System.out.println(i + "" "" + pair[i][j]);*/ int T = Integer.parseInt(in.readLine()); for (int t = 0; t < T; t++) { StringTokenizer st = new StringTokenizer(in.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int count = 0; for (int i = A; i <= B; i++) for (int j = 0; j < np[i]; j++) if (pair[i][j] <= B) count++; System.out.println(""Case #""+(t+1)+"": "" + count); } in.close(); } static void gen (int d) { gen(pow10(d-1), pow10(d)-1, d); } static void gen (int lb, int ub, int d) { for (int i = lb; i <= ub; i++) { int n = i; for (int j = 0; j < d-1; j++) { n = (n%10)*lb+(n/10); if (n > i) { boolean found = false; for (int k = 0; k < np[i]; k++) if (pair[i][k] == n) found = true; if (!found) { pair[i][np[i]] = n; np[i]++; } } } } } static int pow10 (int n) { int res = 1; for (int i = 0; i < n; i++) res *= 10; return res; } }" B20678,"import java.util.*; import java.io.*; class Node implements Comparable{ int x, y; public Node(){} public Node(int a, int b){ x = a; y = b; } public boolean equals(Object key){ Node tmp = (Node)key; if(x==tmp.x && y==tmp.y) return true; else return false; } public int compareTo(Object key){ Node tmp = (Node)key; if(x == tmp.x) return y-tmp.y; else return x-tmp.x; } } public class C{ Set hash = new TreeSet(); void Cal(int A, int B, int n, PrintWriter cout){ int ct = 0; String sn = Integer.valueOf(n).toString(); for(int i = 1; i < sn.length(); i++){ String sm = sn.substring(i) + sn.substring(0, i); int m = Integer.parseInt(sm); Node tmp = new Node(n, m); if(m>n && m<=B && !hash.contains(tmp)) hash.add(tmp); //System.out.println(hash.size()); } } void solve() throws FileNotFoundException{ File fin = new File(""data.in""); File fout = new File(""data.out""); Scanner cin = new Scanner(fin); PrintWriter cout = new PrintWriter(fout); int T, A, B; T = cin.nextInt(); for(int k = 1; k <= T; k++){ A = cin.nextInt(); B = cin.nextInt(); hash.clear(); for(int i = A; i < B; i++) Cal(A, B, i, cout); cout.printf(""Case #%d: %d\n"", k, hash.size()); } cout.flush(); } public static void main(String [] args) throws Exception{ C test = new C(); test.solve(); } } " B21531,"import java.util.*; public class QC { public static void main(String[] args) { Scanner in = new Scanner(System.in); int[][] ROT = new int[2000001][7]; for(int i=1; i<=2000000; i++) { int A = i; int pow10 = 1; while(A > 0) { pow10*=10; A/=10; } pow10 /= 10; A = i; int ix = 0; do { if(A < i) ROT[i][ix++] = A; A = pow10*(A%10)+A/10; } while(A != i); } int T = in.nextInt(); for(int cas=0; cas U = new HashSet(); for(int i=A; i<=B; i++) { long cnt = 0; for(int j=0; j<7; j++) { if(ROT[i][j]=A && ROT[i][j]<=B) cnt++; } ans += cnt; } System.out.println(""Case #""+(cas+1)+"": ""+ans); } } }" B21732,"import java.io.*; import java.util.*; import java.math.*; public class recycle { static int A=0; static int B=0; static int C=0; static int T=0; static int ans=0; static HashSet ansset= new HashSet(); public static void main(String[] args) { Scanner scan= new Scanner(System.in); T=scan.nextInt(); for(int i=1; i<=T; i++) { A=scan.nextInt(); B=scan.nextInt(); String s1=""""; C=0; ans=0; if(B>10) for(int n=A; nn && C<=B) ansset.add(C); } ans+=ansset.size(); } System.out.println(""Case #""+i+"": ""+ans); } } }" B21812,"import util.CombinationGenerator; import java.util.ArrayList; import java.util.List; import java.util.Map; public class SetUtil { public static long getOne(int n) { return 1< getList(long set, int n) { ArrayList integers = new ArrayList<>(); for (int i=0;ilong getForList(Map positions, List objs) { long res = 0L; for (T obj : objs) { int pos = positions.get(obj); res |= getOne(pos); } return res; } public static void cycleSubsets(int num, SubsetCallBack callBack) { callBack.run(0, 0); for (int i = 1; i<=num; i++) { CombinationGenerator generator = new CombinationGenerator(num,i); while (generator.hasMore()) { long n = 0; int[] next = generator.getNext(); for (int i1 : next) { n |= getOne(i1); } callBack.run(n,i); } } } public static interface SubsetCallBack { void run(long subset, int i); } } " B21119,"package recyclednumbers; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.List; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Input ip = new Input(""C-large.in""); ip.setInputData(); int number = 0; StringBuffer sb = new StringBuffer(); for (TestCase tc : ip.getCases()){ number++; sb.append(""Case #"" +number+"": "" +executeTestCase(tc).getM().size()+""\n""); } Writer output = null; File file = new File(""out.txt""); output = new BufferedWriter(new FileWriter(file)); output.write(sb.toString()); output.close(); } private static ListRecycledNumbers executeTestCase(TestCase tc) { List n = new ArrayList(); List m = new ArrayList(); ListRecycledNumbers recycledNumbers = new ListRecycledNumbers(); boolean recycledPairAlreadyPresent = false; for (int i = tc.A; i <= tc.B; i++) { for (int j = 1; j < Integer.toString(tc.B).length(); j++) { int newInt = Helper.rotateDigits(i, j, true); if (i != newInt) { if (newInt < tc.B && newInt > tc.A) { recycledPairAlreadyPresent = false; for(int k = 0; k < recycledNumbers.getM().size(); k++){ if((recycledNumbers.getN().get(k) == newInt && recycledNumbers.getM().get(k) == i) || (recycledNumbers.getM().get(k) == newInt && recycledNumbers.getN().get(k) == i)){ recycledPairAlreadyPresent = true; break; } } if(!recycledPairAlreadyPresent) recycledNumbers.add(newInt, i); } } } } return recycledNumbers; //removeRepetitiveRecycledNumbers(recycledNumbers); } /*public static ListRecycledNumbers finalList = new ListRecycledNumbers(); private static void removeRepetitiveRecycledNumbers( ListRecycledNumbers recycledNumbers) { for (int i = 0; i < recycledNumbers.getM().size(); i++) { for (int j = 0; j < recycledNumbers.getM().size(); j++) { if ((recycledNumbers.getM().get(i) != recycledNumbers.getM() .get(j) && recycledNumbers.getN().get(i) != recycledNumbers .getN().get(j) && i != j) || (recycledNumbers.getM().get(i) != recycledNumbers .getN().get(j) && recycledNumbers.getN().get(i) != recycledNumbers .getM().get(j) && i != j)) { finalList.add(recycledNumbers.getN().get(i), recycledNumbers.getM().get(i)); } } } } */ } " B22171,"import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner mark = new Scanner(System.in); int t = mark.nextInt(); int A, B, counter; mark.nextLine(); for (int i = 0; i < t; i++) { A = mark.nextInt(); B = mark.nextInt(); counter = 0; mark.nextLine(); // This is for N for (int n = A; n < B; n++) { HashSet ans = new HashSet(); String strval = String.valueOf(n).trim(); int count = strval.length(); for (int j = 1; j < count; j++) { String beg = strval.substring(0, j); String end = strval.substring(j); // System.out.println(beg+end+"" ""+end+beg); int m = Integer.parseInt( end.concat(beg) ); if( (m > n) && (m <= B)) ans.add(m); } counter += ans.size(); } System.out.printf(""Case #%d: %d\n"",i+1,counter); } } } " B21737,"import java.util.*; import java.io.*; public class ProblemC { public static void main(String arg[])throws IOException { FileReader fin=new FileReader(arg[0]); FileWriter fout=new FileWriter(""Output.txt""); Scanner src=new Scanner(fin); Scanner t1=new Scanner(src.nextLine()); int cases=(t1.nextInt()); int no=0; int ans=0; while(src.hasNext()) { Scanner temp=new Scanner(src.nextLine()); no++; ans=0; long A=temp.nextInt(); long B=temp.nextInt(); long t=A; while(t<=B) { int count=0; long n=t; do { n=n/10; count++; }while(n!=0); for(int i=1;it) ans++; } t++; } fout.write(""Case #""+no+"": ""+ans+""\n""); } fout.close(); } }" B21412,"package RecycledNumbers; public class Pair { int low; int high; public Pair(int low, int high) { this.low =low; this.high=high; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair other = (Pair)o; return ((low == other.getLow() && high == other.getHigh()) || (low == other.getHigh() && high == other.getLow())); } @Override public int hashCode() { return 31 * low + high; } public int getLow() { return low; } public int getHigh() { return high; } } " B21856,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class RecycledNumbers { public static void main(String[] args) throws IOException { //BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(""C-small-attempt0.in""))); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(""C-large.in""))); //BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new FileWriter(""RecycledNumbers.txt"")); int cases = Integer.parseInt(reader.readLine()); for(int i=1; i <= cases; i++) { String line = reader.readLine(); int beg = Integer.parseInt(line.split("" "")[0]); int end = Integer.parseInt(line.split("" "")[1]); HashSet h = new HashSet(); int count = 0; for(int j=beg; j<=end;j++) { String str = j+""""; int c = 0; for(int m = str.length()-1; m>=0; m--) { str = str.substring(1) + str.charAt(0); int number = Integer.parseInt(str); if(number >= beg && number <= end && !h.contains(number)) { h.add(number); c++; } } count = count + ((c-1)*c)/2; } //out.write((p*3-2) + "" "" + (p*3-4) + ""\n""); System.out.print(""Case #"" + i+ "": "" + count+""\n""); out.write(""Case #"" + i+ "": "" + count+""\n""); } out.close(); } } " B20107,"import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; /* * Google Code Jam 2012 * Qualification 2012 * raguenets@gmail.com * Usage : java RecycledNumbers inputFileName outputFileName */ public class RecycledNumbers { public static void main(String[] args) { int T = 0; int A = 0; int B = 0; if (args.length == 2) { String inputFilename = args[0]; File finput = new File(inputFilename); String outputFilename = args[1]; File foutput = new File(outputFilename); Scanner scanner = null; BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(foutput)); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (finput.exists()) { try { scanner = new Scanner(finput); // Reads first line : number of Tests if (scanner.hasNextInt()) { T = scanner.nextInt(); scanner.nextLine(); } for (int i = 0; i < T; i++) { // Read number of flies A = scanner.nextInt(); B = scanner.nextInt(); // Read fly positions bw.write(""Case #"" + (i + 1) + "": "" + numberOfRecycled(A, B) + ""\n""); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { bw.close(); if (scanner != null) { scanner.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } public static int[] getDigits(int number) { List digits = new ArrayList(); while (number > 0) { digits.add(number % 10); number = (number - number % 10) / 10; } int[] d = new int[digits.size()]; for (int i = 0; i < digits.size(); i++) { d[i] = digits.get(digits.size() - 1 - i); } return d; } public static int getValue(int[] digits) { int value = 0; for (int i = 0; i < digits.length; i++) { value += digits[i]; if (i != digits.length - 1) { value *= 10; } } return value; } public static int numberOfRecycled(int A, int B) { if (B < 10) { return 0; } else { int count = 0; for (int i = A; i < B; i++) { int[] digits = getDigits(i); Set set = new HashSet(); for (int j = 1; j < digits.length; j++) { int[] newDigits = new int[digits.length]; for (int k = 0; k < digits.length; k++) { newDigits[k] = digits[(k + j) % digits.length]; } int value = getValue(newDigits); if (value <= B && value > i) { set.add(value); // count++; } } for (Integer val:set) { count++; } } return count; } } } " B20415,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Scanner; public class RecycledNumbersC { static int[] matches; static int A, B; public static void main(String[] args) { // Scanner sc = new Scanner(System.in); Scanner sc; try { sc = new Scanner(new FileInputStream(""C-large.in"")); } catch (FileNotFoundException e) { sc = new Scanner(System.in); // file not exist, so get input from console } Writer out; try { out = new OutputStreamWriter(new FileOutputStream(""C-large.out"")); } catch (FileNotFoundException e) { out = new OutputStreamWriter(System.out); // use console } int T = sc.nextInt(); for (int t = 0; t < T; t++) { A = sc.nextInt(); B = sc.nextInt(); int count = 0; matches = new int[B]; for (int i = B; i > A; i--) findMatches(i, A); // count += findMatches(i, A); count = countMatches(); // output System.out.println(""Case #"" + (t + 1) + "": "" + count); try { out.write(""Case #"" + (t + 1) + "": "" + count + ""\n""); } catch (IOException e) { // do nothing } } try { out.close(); } catch (IOException e) { // do nothing } } @SuppressWarnings({ ""unchecked"", ""rawtypes"" }) static void findMatches(Integer input, int min) { String number = input.toString(); ArrayList checkNums = new ArrayList(); for (int i = 1; i < number.length(); i++) { number = digitShift(number); Integer nextInt = Integer.parseInt(number); if (!checkNums.contains(nextInt)) checkNums.add(nextInt); } Comparator desc = Collections.reverseOrder(); Collections.sort(checkNums, desc); for (Integer n : checkNums) { if (n < input && n >= min) { matches[n]++; } } } static int countMatches() { int count = 0; for (int i = 0; i < B; i++) count += matches[i]; return count; } static String digitShift(String input) { return input.substring(1).concat(input.substring(0, 1)); } } " B20269," import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class testrun { public static void main(String[] args) { BufferedReader in; String line; PrintWriter out; // Inputting File. try { in = new BufferedReader(new FileReader(""C:\\Users\\imumair\\Desktop\\C-large.in"")); int i = Integer.parseInt( in.readLine() ); ArrayList outputlist = new ArrayList(); String outstring = """"; String initstring = """" ; int count = 1 ; int resultcount = 0; while(in.ready() && count <= i){ initstring = ""Case #"" + count+"": "" ; try { line = in.readLine(); outstring = """"; String[] linearray = line.split("" ""); resultcount = 0; int a = Integer.parseInt( linearray[0]); int b = Integer.parseInt( linearray[1]); for (int j = a ; j digitlist = new ArrayList(); int number = j; // = and int LinkedList stack = new LinkedList(); while (number > 0) { stack.push( number % 10 ); number = number / 10; } while (!stack.isEmpty()) { digitlist.add(stack.pop()); } int numdigits = digitlist.size(); if(numdigits > 1 ){ String comb = """"; if(allequal(digitlist)){ resultcount = resultcount + 0; } else { String prevcomb = """"; //going throguh all combinations for (int m = 1 ; m j && !prevcomb.equals(comb) ){ resultcount++; prevcomb = comb; //System.out.println(""( "" +j+"" , "" + comb +"" )"" ); } } } } } outstring = initstring+outstring +resultcount; outputlist.add(outstring); //System.out.println(line); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(""readline fails!!""); } count++; } in.close(); //Outputting File. out = new PrintWriter(new FileWriter(""C:\\Users\\imumair\\Desktop\\A-small-output.out"")); if(i >0){ int k; for (k = 0; k < i ; k++){ out.println(outputlist.get(k)); } }else{ out.println(""""); } out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(""Ready Input fails.""); } } public static boolean allequal(ArrayList digitlist){ int n = digitlist.size(); int start = digitlist.get(0); boolean all = true; for (int i = 0; i map = new HashMap(); int no=0; int temp=A; //int temp=0; while(temp>0){ if((temp=temp/10)>0) no++; } //System.out.println(no); for(int n = A;n<=B;n++){ int a=1; while(a<=no){ int m=(int) ((n/Math.pow(10,a)) + (n%Math.pow(10,a))*Math.pow(10,(no-a+1))); a++; if((m<=B)&&(m>n)){ if(!(map.containsKey(n)&&(map.get(n)==m))){ //System.out.println(n+"" ""+m); count++; map.put(n,m); } //else //System.out.println(n+"" ""+m); } } } System.out.println(""Case #""+i+"": ""+count); } } }" B22237,"package com.abuhijleh.googlejam; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class GoogleJam { static final String code = ""yhesocvxduiglbkrztnwjpfmaq""; public static void main(String[] args) { File input = new File(""inputFile""); String[] result; Scanner scan; try { scan = new Scanner(input); result = new String[scan.nextInt()]; scan.nextLine(); for (int i = 0; i < result.length; i++) { result[i] = ""Case #"" + (i + 1) + "": "" + solve(scan.nextInt(), scan.nextInt()); scan.nextLine(); } System.out.println(""Output""); for (int i = 0; i < result.length; i++) System.out.println(result[i]); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static int solve(int x, int y) { int count = 0; String digits = x + """"; int length = digits.length(); int pa = (int) Math.pow(10, length - 1); for (int i = x; i <= y; i++) { int temp = i; int[] temps = new int[length]; for (int j = 0; j < length ; j++) { temp = (temp % 10) * pa + (temp / 10); if (temp > i && temp <= y){ if(check(temps,temp)){ temps[j] = temp; count++; } } } } return count; } private static boolean check(int[] temps, int temp) { for(int i =0 ;i[]count = new ArrayList[size]; for (int i = 0; i < count.length; i++) { count[i] = new ArrayList(); } for (int i = 10; i < count.length; i++) { String m = i+""""; String n = m; do{ n = rotate(n); if(n.charAt(0) != '0' && Integer.parseInt(n) < i){ count[i].add(Integer.parseInt(n)); } }while(!n.equals(m)); } System.out.println(System.currentTimeMillis()-t); int kases = nextInt(); int kase = 0; while(kases-->0){ kase++; out.print(""Case #""+kase+"": ""); int a = nextInt(); int b = nextInt(); int ans = 0; for (int i = a+1; i <= b; i++) { for (int j = 0; j < count[i].size(); j++) { if(count[i].get(j)>=a) ans++; } } // for (int n = a; n <= b; n++) { // for (int m = n+1; m <= b; m++) { // String x = n+""""; // String y = m+""""; // if(x.length() != y.length()) continue; // String z = x+x; // if(z.contains(y)) ans++; // } // } out.println(ans); } } QualC() throws IOException { in = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(new FileWriter(""output.txt"")); eat(""""); solve(); out.close(); } private void eat(String str) { st = new StringTokenizer(str); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { new QualC(); } int gcd(int a,int b){ if(b>a) return gcd(b,a); if(b==0) return a; return gcd(b,a%b); } } " B21581,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; public class Recycled { /** * @param args */ public static void main(String[] args) { try { System.setIn(new FileInputStream(""../C-large.in"")); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(0); } InputStreamReader inp = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(inp); String line = """"; int inputs = 0; try{ line = br.readLine(); inputs = Integer.parseInt( line ); } catch(Exception x){ System.err.println(x); System.exit(1); } String[] data = {}; for(int i=0; i < inputs; i++){ int count = 0; try{ line = br.readLine(); data = line.split("" ""); } catch(Exception x){ System.err.println(x); System.exit(1); } int a = Integer.parseInt(data[0]); int b = Integer.parseInt(data[1]); for(int n=a; n < b; n++){ String m = """"+n; String[] dup = new String[data[0].length()]; int next = 0; //position to insert into dup for(int k=0; k < data[0].length(); k++){ m = Recycled.shuffle(m); if(a <= n && n < Integer.parseInt(m) && Integer.parseInt(m) <= b){ boolean found = false; for(int x=0; x k ) { output++; // System.out.println(k + ""---"" + // secondNum); } } firstNum = newFirstNum; } } } } return output; } private static boolean same(String s) { for (int i = 0; i < s.length() - 1; i++) { if (s.charAt(i) != s.charAt(i + 1)) return false; } return true; } public static void main(String[] args) { String inputFile = ""C-large.in""; String outPutFile = ""C-large.out""; try { FileInputStream fstream = new FileInputStream(inputFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fstream2 = new FileWriter(outPutFile); BufferedWriter out = new BufferedWriter(fstream2); String strLine; strLine = br.readLine(); int casesNum = Integer.parseInt(strLine); for (int i = 0; i < casesNum; i++) { strLine = br.readLine(); String parse = ""Case #"" + (i + 1) + "": "" + convert(strLine); System.out.println(parse); if (i < casesNum - 1) parse += ""\n""; out.write(parse); } in.close(); out.close(); } catch (Exception e) { System.err.println(""Error: "" + e.getMessage()); } } } " B21394,"import java.util.*; import java.util.regex.*; import java.text.*; import java.math.*; public class C { void start() { Scanner sc=new Scanner(System.in); int nt=sc.nextInt(); for (int tc=1; tc<=nt; tc++) { int a=sc.nextInt(), b=sc.nextInt(), re=0; if (a9) { int p=1; while (p*10x && z>=a && z<=b) re++; } while (z!=x); } } System.out.printf(""Case #%d: %d\n"", tc, re); } } public static void main(String[] args) throws Exception { new C().start(); } }" B20176,"package codejam2; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Date; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public abstract class CodejamRunner { public static final int NUM_WORKERS = 4; public static final int TIMEOUT_MINUTES = 10; // Default behavior is to get number of test cases that follow public int preparse(Scanner s) { String line = s.nextLine(); return new Scanner(line).nextInt(); } public abstract CodejamCase parseCase(Scanner s); public void run(String[] args) { Date start = new Date(); // Set up worker threads ExecutorService es = Executors.newFixedThreadPool(args.length > 0 ? NUM_WORKERS : 1); // Read in file one test at a time and put in work queue try { Scanner s = new Scanner(new FileInputStream(args.length > 0 ? args[0] : ""sample"")); PrintStream o = args.length > 0 ? new PrintStream(new FileOutputStream(args[0]+ "".output"")) : System.out; int numTests = preparse(s); final CodejamCase[] tests = new CodejamCase[numTests]; for (int i = 0; i < numTests; i++) { final int id = i; tests[id] = parseCase(s); es.execute(new Runnable() { @Override public void run() { tests[id].compute(); System.err.print(id + "" ""); } }); } // Wait until work queue is empty try { es.shutdown(); if (!es.awaitTermination(TIMEOUT_MINUTES, TimeUnit.MINUTES)) { System.err.println(""Timeout! "" + es.shutdownNow().size() + "" tests incomplete.""); } } catch (InterruptedException e) { System.err.println(""Interrupted!""); e.printStackTrace(); } // Output results for (int i = 0; i < numTests; i++) { o.println(""Case #"" + (i+1) + "": "" + tests[i].getOutput()); } } catch (IOException e) { System.err.println(""IO error!""); e.printStackTrace(); } System.err.println(""\nExecution time: "" + (new Date().getTime() - start.getTime()) + ""(ms)""); System.exit(0); } public static String padInt(int num, int len) { String s = ""00000000000"" + String.valueOf(num); return s.substring(s.length()-4); } } " B20695,"package org.moriraaca.codejam.recyclednumbers; import org.moriraaca.codejam.TestCase; public class RecycledNumbersTestCase implements TestCase { public int A; public int B; } " B20077,"import java.util.*; import java.io.*; import java.math.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; try { inputStream = new FileInputStream(""c.in""); outputStream = new FileOutputStream(""c.out""); } catch (FileNotFoundException e) { System.err.println(""File not found""); return; } InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(in, out); out.close(); } } class Solver { public void solve(InputReader in, PrintWriter out) { int t = in.nextInt(); for (int i = 0; i < t; i++) { int a = in.nextInt(); int b = in.nextInt(); int ans = 0; for (int j = a; j <= b; ++j) { String s = (new Integer(j)).toString(); TreeSet use = new TreeSet(); for (int k = 0; k < s.length() - 1; k++) { s = (s.substring(1)).concat(s.substring(0, 1)); //System.err.println(s); if (s.charAt(0) == '0') { continue; } int w = Integer.parseInt(s); if (w > j && w <= b && !use.contains(w)) { ans++; use.add(w); } } } out.print(""Case #""); out.print(i + 1); out.print("": ""); out.println(ans); } } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } } " B20545,"import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; public class Main { public static void main(String[] args) { Main main = new Main(); try { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String line = bf.readLine(); int T = Integer.parseInt(line); for (int testcaseIndex=0; testcaseIndex set = new HashSet(); for (int num=A; num<=B; num++) { String numStr = String.valueOf(num); for (int i=1; i l) { int t = s; s = l; l = t; } small = s; large = l; } @Override public boolean equals(Object o) { if (o instanceof Pair) { Pair pair = (Pair)o; return this.small == pair.small && this.large == pair.large; } return false; } @Override public int hashCode() { return small * 23 + large; } } } " B20570,"package problemC; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); FileWriter fw = new FileWriter(""C-large.out""); int T = new Integer(in.readLine()); for (int cases = 1; cases <= T; cases++){ StringTokenizer st=new StringTokenizer(in.readLine()); int A = new Integer(st.nextToken()); int B = new Integer(st.nextToken()); int num_bits = 0; long result = 0; int tempn = B; HashSet hs = new HashSet(); while (tempn > 0){ num_bits++; tempn = tempn/10; } if (num_bits == 1) { result = 0; }else { for (int target = A; target <= B; target++){ if(!hs.contains(target)){ int temp = target; int p = 1; int bit = 0; for (int t = 1 ; t < num_bits; t++){ bit = temp % 10; temp = temp/10; if (bit != 0){ temp = temp + (int) (bit * Math.pow(10, num_bits-1)); if ((temp >= A) && (temp <= B) && (temp!=target)&&(!hs.contains(temp))){ hs.add(target); hs.add(temp); p++; } } } result = result + (p*(p-1))/2; } } } if (cases != T) {fw.write(""Case #"" + cases + "": ""+ result + ""\n""); } else {fw.write(""Case #"" + cases + "": ""+ result);} } fw.flush(); fw.close(); } } " B21385,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; class Case { public int A; public int B; public Case(int a, int b) { A = a; B = b; } } class ProblemC { private String mInputFilename; private int T; private ArrayList mCases; private BufferedReader mReader; private BufferedWriter mWriter; public ProblemC(String inputFilename) { T = 0; mCases = null; mInputFilename = inputFilename; } private boolean openFiles() { if (mInputFilename != null) { try { mReader = new BufferedReader(new FileReader(mInputFilename)); mWriter = new BufferedWriter(new FileWriter(mInputFilename.replace(""in"", ""out""))); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } return true; } return false; } private void closeFiles() { try { mReader.close(); mWriter.close(); } catch (IOException e) { e.printStackTrace(); } } private boolean readInput() { if (mReader != null) { try { String line; // number of test cases line = mReader.readLine(); T = Integer.valueOf(line); System.out.println(""Cases: "" + T); mCases = new ArrayList (); // read input cases for (int i = 0; i 0) { num *= 10; digit--; } return num; } private int getShiftedNum(int num, int digit) { int ret = 0; int digitNum = getDigitInt(digit); int top = num / digitNum; ret = (num%digitNum)*10 + top; return ret; } private void findWay(int seq, Case item) { Case in = item; int A = in.A; int B = in.B; int result = 0; for (int num = A; num<=B; num++) { int digit = getDigit(num); // System.out.println(""num: "" + num + "", digit: "" + digit); int n = num; int m = n; for (int j = 0; j < digit-1; j++) { m = getShiftedNum(m, digit); // System.out.println(""num: "" + num + "", m: "" + m); if (m > n && m <= B) { // System.out.println(""found: ("" + n + "", "" + m + "")""); result++; } } } writeOutput(seq, result); } // test run main public void run() { openFiles(); readInput(); for (int i = 0; i 0) inputFilename = new String(args[0]); else inputFilename = new String(""sample.in""); ProblemC solve = new ProblemC(inputFilename); solve.run(); } } " B20001,"package numbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class Solution { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(""C-large.in"")); BufferedWriter wr = new BufferedWriter(new FileWriter(""output"")); Integer cases = Integer.valueOf(br.readLine()); for (int caseNumber = 1; caseNumber<=cases; ++caseNumber){ String[] line = br.readLine().split("" ""); Integer A = Integer.valueOf(line[0]); Integer B = Integer.valueOf(line[1]); StringBuffer bf = new StringBuffer(); bf.append(""Case #""); bf.append(caseNumber); bf.append("": ""); if (A<11) A = 11; int counter = 0; for (int n=A; n<=B;++n){ counter += findRecycled(n, B); } bf.append(counter); wr.write(bf.toString()); wr.newLine(); wr.flush(); } } private static int findRecycled(int n, int limit) { int retVal = 0; HashSet possibles = new HashSet(); String base = String.valueOf(n); for (int i=1; in && check<=limit) ++retVal; } return retVal; } } " B21811,"import com.sun.org.apache.xerces.internal.impl.xs.opti.DefaultXMLDocumentHandler; import util.graph.DynDjikstra; import util.graph.Edge; import util.graph.Node; import util.graph.State; import javax.xml.crypto.dsig.CanonicalizationMethod; import java.io.IOException; import java.math.BigInteger; import java.util.List; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.TreeSet; public class CrossingRoad extends JamProblem { public static void main(String[] args) throws IOException { CrossingRoad p = new CrossingRoad(); p.go(); } @Override String solveCase(JamCase jamCase) { CrossCase ca = (CrossCase) jamCase; CrossState crossState = new CrossState(); crossState.time = 0; ca.startNode.last = crossState; CrossState state = (CrossState) DynDjikstra.FindShortest(ca.startNode, ca.stopNode); return """" + state.time; } @Override JamCase parseCase(List file, int line) { String first = file.get(line++); int[] size = JamUtil.parseIntList(first, 2); CrossCase ca = new CrossCase(); ca.n = size[0]; ca.m = size[1]; ca.lineCount = ca.n + 1; ca.map = new Crossing[ca.n][ca.m]; Node[][][][] nodes = new Node[ca.n][ca.m][2][2]; Node start = null; Node end = null; for (int y = 0; y < ca.n; y++) { String row = file.get(line++); int[] data = JamUtil.parseIntList(row, 3 * ca.m); for (int x = 0; x < ca.m; x++) { Crossing cr = new Crossing(); ca.map[y][x] = cr; cr.minTime = Integer.MAX_VALUE; cr.s = data[3*x]; cr.w = data[3*x+1]; cr.t = data[3*x+2]; cr.x = x; cr.y = y; Node ne = new CrossNode(); Node se = new CrossNode(); Node sw = new CrossNode(); Node nw = new CrossNode(); CrossStreetSNEdge snEdge1 = new CrossStreetSNEdge(); snEdge1.s =cr.s; snEdge1.w = cr.w; snEdge1.t = cr.t; CrossStreetWEEdge weEdge = new CrossStreetWEEdge(); weEdge.s= cr.s; weEdge.w=cr.w; weEdge.t=cr.t; snEdge1.biConnect(ne,se); snEdge1.biConnect(nw,sw); weEdge.biConnect(ne,nw); weEdge.biConnect(se,sw); Node[][] pack = nodes[y][x]; pack[0][0] = nw; pack[0][1] = ne; pack[1][1] = se; pack[1][0] = sw; ((CrossNode)nw).label = ""y "" + y + "" x "" + x + "" nw""; ((CrossNode)ne).label = ""y "" + y + "" x "" + x + "" ne""; ((CrossNode)se).label = ""y "" + y + "" x "" + x + "" se""; ((CrossNode)sw).label = ""y "" + y + "" x "" + x + "" sw""; if (y==0 && x ==ca.m-1) { ca.stopNode = pack[0][1]; } if (y==ca.n-1 && x == 0) { ca.startNode = pack[1][0]; } if (y>0) { CrossBlockEdge b1 = new CrossBlockEdge(); b1.biConnect(nodes[y][x][0][1],nodes[y-1][x][1][1]); b1.biConnect(nodes[y][x][0][0],nodes[y-1][x][1][0]); } if (x>0) { CrossBlockEdge b1 = new CrossBlockEdge(); b1.biConnect(nodes[y][x][0][0], nodes[y][x - 1][0][1]); b1.biConnect(nodes[y][x][1][0],nodes[y][x-1][1][1]); } } } return ca; } } class CrossCase extends JamCase { int n, m; Crossing[][] map; public Node startNode; public Node stopNode; } class Crossing implements Comparable{ int s, w, t, minTime,x,y; @Override public int compareTo(Crossing o) { return Integer.compare(minTime,o.minTime); } } class CrossState extends State { long time; @Override public int compareTo(Object o) { return Long.compare(time,((CrossState)o).time); } } class CrossBlockEdge extends Edge { @Override public State travel(State current) { CrossState old = (CrossState) current; CrossState newS = new CrossState(); newS.time = old.time + 2; return newS; } } class CrossStreetSNEdge extends Edge { long s,w,t; @Override public State travel(State current) { CrossState old = (CrossState) current; CrossState newS = new CrossState(); long adjusted = old.time - t; long period = s + w; long inCycle = adjusted % period; if (inCycle < s) { newS.time = old.time + 1; return newS; } newS.time = old.time + (period-inCycle); return newS; } } class CrossStreetWEEdge extends Edge { long s,w,t; @Override public State travel(State current) { CrossState old = (CrossState) current; CrossState newS = new CrossState(); long adjusted = old.time - t; long period = s + w; long inCycle = adjusted % period; if (inCycle >= s) { newS.time = old.time + 1; return newS; } newS.time = old.time + (s-inCycle); return newS; } } class CrossNode extends Node { String label; CrossNode() { last = new CrossState(); } @Override public String toString() { return label; } } " B20666,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class recycled { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(""output.txt""))); int nc = Integer.parseInt(in.readLine().trim()); for (int z=1; z<=nc; z++){ String[] line = in.readLine().trim().split(""\\s+""); int a = Integer.parseInt(line[0]); int b = Integer.parseInt(line[1]); boolean[] flgs = new boolean[2000000+1]; int count = 0; for (int i = a; i <=b; i++) { List list = new ArrayList(); list.add(i); if (flgs[i]) continue; int val = 1; String num1 = i+""""; for (int j = 1; j <=num1.length(); j++) { String num2 = num1.substring(j) + num1.substring(0, j); int num = Integer.parseInt(num2); if (num2.charAt(0)!='0') if (num<=b&&num!=i&&num>a) if (!flgs[num]) { list.add(num); val++; flgs[num] = true; } } val = val*(val-1); val>>=1; //if (val>0)tr(list); count+=val; //if (val>0) System.out.println(count); } //MODIFY out.println(String.format(""Case #%d: %d"", z,count)); } out.close(); } public static void tr(Object...objects) { System.out.println(Arrays.deepToString(objects)); } } " B20568,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; public class Fattom2012C { private final String _PROBLEM_NO = ""201201C""; private final String _FILE_DIRECTORY = ""K:/Dropbox/workspace/codejam/"" + _PROBLEM_NO + ""/""; private final String _FILE_PATH = _FILE_DIRECTORY + ""C-large""; public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Fattom2012C().execute(); } public void execute() { BufferedReader br = null; PrintWriter pw = null; try { br = new BufferedReader(new FileReader(_FILE_PATH + "".in"")); pw = new PrintWriter(_FILE_PATH + "".out""); //main int caseno = Integer.parseInt(br.readLine()); Map m = new HashMap(); for(int i=10;i<=1000000;i++) { check(i,m); } // System.out.println(m.get(2)); for (int count = 1; count <= caseno; count++) { // if(count>4)break; pw.print(""Case #"" + count + "": ""); System.out.print(""Case #"" + count + "": ""); String line = br.readLine(); String[] splits = line.split("" ""); int A = Integer.parseInt(splits[0]); int B = Integer.parseInt(splits[1]); int r = 0; if(A < 10 || A >= 1000000 || A==B) { pw.print(""0""); System.out.print(""0""); } else { List tt = m.get((""""+A).length()); for(int t:tt) { // if(t >= A && t <= B) { r += check(A,B,t); // } } pw.print(r); System.out.print(r); } pw.print(""\n""); System.out.print(""\n""); } //end br.close(); pw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(pw != null) pw.close(); } catch(Exception e) {} try { if(br != null) br.close(); } catch(Exception e) {} } } private int check(int a, int b, int t) { String tt = """"+t; // System.out.println(tt); int r =0; Set rr = new HashSet(); for(int i=0;i=a&&t<=b) { // System.out.print(tt + ""!""); rr.add(t); } } r=rr.size(); // System.out.println(r); if(r==1) return 0; if(r!=0) r = (r*(r-1))/2; return r; } private void check(int i, Map m) { String in = """" + i; int b = in.length(); if(!dedup(i)) return; dedup.put(i, true); List target = m.get(b); if(target == null) { target = new ArrayList(); m.put(b, target); } target.add(i); } public static Map dedup = new HashMap(); private boolean dedup(int t) { String tt = """"+t; for(int i=0;i 0) { ac /= 10; digits++; max *= 10; } int min = max / 10; ac = a; for (int j = a; j < b; j++) { if (j == max) { digits++; max *= 10; min *= 10; } count += getNumPair(j, b, digits, min); } System.out.println(""Case #"" + (i+1) + "": "" + count); } } static final int[] temp = new int[10]; private static int getNumPair(int i, int b, int digits, int min) { int ac = i; int numKouho = 0; int count = 0; ddd: for (int k = 0; k < digits - 1; k++) { i = i % min * 10 + i / min; if (ac < i && i <= b) { for (int j = 0; j < numKouho; j++) { if (temp[j] == i) continue ddd; } temp[numKouho++] = i; count++; } } return count; } } " B21183,"import java.text.*; import java.util.*; import java.lang.*; public class solutionRunner { public solutionRunner(){ run(); } private void run(){ int numberOfLines = 1; inpOutHandler io1 = new inpOutHandler(); testCase TC = io1.readInput(""a.txt"", numberOfLines); String result="""";int _i=1; for(String case1:TC.cases){ //int[] a1 = intAfromString(case1.substring(case1.indexOf('\n') +1)); pairs = new HashSet(); long[] a1 = longAfromString(case1.substring(case1.indexOf('\n') +1)); if(_i==TC.cases.length){ result +=""Case #"" + (_i++) +"": "" + numberOfG(a1); }else{ result +=""Case #"" + (_i++) +"": "" + numberOfG(a1) + ""\n""; } } io1.createOutput(""OUTPUT.txt"", result); //System.out.println(result); /* double xx = 1231212.9; DecimalFormat threeDec = new DecimalFormat("".0000000""); String shortString = (threeDec.format(xx)); */ } private long numberOfG(long[] a) { long min = a[0];long max = a[1]; //System.out.println(""<"" + min + "" , "" + max + "">""); for(long n=min; n=min && r<=max){ long temp = encodePair(n,r, max+1); if(!pairs.contains(temp)) pairs.add(temp); } } } } /* for(long _x:pairs){ long[] _tem = decodePair(_x, max+1); System.out.println(""<"" + _tem[0] + "" , "" + _tem[1] + "">""); } */ return pairs.size(); } // returns numbers r : r_i > n and r_i can be recycled from n private long[] largerRecycles(long n) { if(n<10) return null; String _sN = """"+n;int len = _sN.length(); ArrayList recycles = new ArrayList(); long r = leftRotate(n,len); while(r!=n){ if(r>n) recycles.add(r); r = leftRotate(r,len); } if(recycles.size()<1) return null; long[] rs = new long[recycles.size()]; for(int i=0; i pairs;// = new HashSet(); private int[] intAfromString(String s) { String[] words = s.split("" ""); int[] a = new int[words.length]; for(int i=0;iy){ return x; }else{ return y; } } } " B21842,"import java.io.*; class RecycledNumbers { public static void main(String a[]) throws Exception { BufferedReader br=new BufferedReader( new InputStreamReader(System.in) ); int testCases=Integer.parseInt(br.readLine()); int counter=0; for(int i=0;i iLst=getIntLstFromString(str); minNumb=iLst.get(0); maxNumb=iLst.get(1)+1; for(int a=minNumb;a is=new HashSet(); for(int i=1;i it=is.iterator();it.hasNext();){ int a1=it.next(); if(a1>a && a1 getIntLstFromString(String str){ //将一行数字的字符串转为整型List; List iLst=new ArrayList(); int j=0; for(int i=0;i { @Override public CInput parseLineIterator(Iterator lineIterator) { String[] lineParts = lineIterator.next().split("" ""); CInput input = new CInput(); input.setLowerLimit(Integer.parseInt(lineParts[0])); input.setUpperLimit(Integer.parseInt(lineParts[1])); return input; } } " B22043,"package google.solver; public interface ChallengeConstants { public static final String DELIMITER = ""\\""; public static final String CHALLENGE_DEFINITION = ""challengeDefinition""; public static final String BASE_DIR= ""D:\\Development\\Workspaces\\test1\\googleChallanges\\src\\google\\contest""; public static final String CHALLENGE_NAME=""A""; public static final String TEST_IN=""test.in""; } " B20133,"import java.util.*; import java.io.*; class Recycled_Numbers { public static void main(String arg []) { int check =-456; String m=""""; int counter =0; int calculate =0; String sub=""""; int mi =0; int ma=0; String path; String first,second; int numberOfLoops=0; Scanner read = new Scanner(System.in); System.out.println(""pls enter your file""); path = read.nextLine(); BufferedWriter bw; try { File fobj = new File(path); Scanner sc = new Scanner(fobj); bw =new BufferedWriter( new FileWriter(""RecycleOutput.txt"")); int tests = sc.nextInt() ,meter = 1; while (meter <= tests) { mi= sc.nextInt(); ma =sc.nextInt(); while(mi<=ma) { counter =0; m = mi+""""; while(counter mi)&&(Integer .parseInt(sub)<=ma)&&(Integer .parseInt(sub)!=check) ) { calculate++; check= Integer .parseInt(sub); } counter++; } mi++; } bw.write(""Case #""+meter+"": "" +calculate ); bw.newLine(); calculate =0; meter++; } bw.close(); }//end of try catch(IOException e) { System.out.println(e); } } }" B21359,"package com.niall.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class ProbC { String english, goglish; public ProbC(){ } public int solve(int a, int b){ int count = 0; HashSet set; for(int n = a; n<= b; n++){ String x = n + """"; set = new HashSet(); for(int j = 0; j < x.length() - 1; j++){ x = push(x); int m = Integer.parseInt(x); if(n < m && m <=b ){ set.add(m); } } count += set.size(); } return count; } public String push(String x){ return x.substring(1) + x.charAt(0); } /** * @param args */ public static void main(String[] args) { String infile = ""probCin""; String outfile = ""probCans""; try { BufferedReader br = new BufferedReader(new FileReader(new File(infile))); BufferedWriter bw = new BufferedWriter(new FileWriter(new File(outfile))); ProbC p1 = new ProbC(); br.readLine(); int i = 1; String s; while((s=br.readLine())!= null){ String[] ss = s.split("" ""); int a = Integer.parseInt(ss[0]); int b = Integer.parseInt(ss[1]); bw.write(""Case #"" + i + "": "" + p1.solve(a,b)); bw.newLine(); i++; } bw.close(); br.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } " B20999,"import java.io.*; public class mains { public static void main(String[] args) { BufferedReader input; BufferedWriter output; try { input = new BufferedReader(new FileReader(""C-large.in"")); output = new BufferedWriter(new FileWriter(""output.out"")); int caseCount = Integer.parseInt(input.readLine()); String buf; String[] values; int minValue; int maxValue; int currentValue; int highest; int next; int result = 0; int numLength; for(int index = 1 ; index <= caseCount; ++index) { buf = input.readLine(); values = buf.split("" ""); minValue = Integer.parseInt(values[0]); maxValue = Integer.parseInt(values[1]); numLength = values[1].length(); highest = (int)Math.pow(10, numLength - 1); result = 0; if(highest != 1) { for(int num = minValue; num <= maxValue ; ++num) { currentValue = num; for(int i = 0 ; i < numLength ; ++i) { next = currentValue / highest; currentValue %= highest; currentValue *= 10; currentValue += next; if(num < currentValue && currentValue <= maxValue) ++result; } } output.write(""Case #"" + index + "": "" + result); output.newLine(); } else { output.write(""Case #"" + index + "": 0""); output.newLine(); } } output.close(); input.close(); } catch(Exception e) { return; } } } " B20417,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class C { public static void main(String args[]){ String fn=""C:\\codejam\\C.in""; String fnOut=""C:\\codejam\\C.out""; try{ BufferedReader br = new BufferedReader(new FileReader(fn)); BufferedWriter bw = new BufferedWriter(new FileWriter(fnOut)); String line = null; int NCase = Integer.valueOf(br.readLine().trim()); long stime = System.currentTimeMillis(); for(int icase=0;icase num = new ArrayList(); for(long j = 1; j<(new Long(A).toString()).length(); j++){ long p1 = (long) (i/(Math.pow(10,j))); long p2 = (long) (i%(Math.pow(10,j))); long pn = new Long(p2+""""+p1); //System.out.println(""Aca "" + pn ); if(pn>i&&pn<=B){ if(!num.contains(pn)){ num.add(pn); x++; } System.out.println(x + "" - "" + i + "": "" + pn); } } } return (x); } } " B20740,"package fixjava; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Set; /** * Simple multimap class. MultiMap map = MultiMapKeyToSet.make(); map.put(""a"", ""x""); map.put(""a"", ""x""); map.put(""a"", ""y""); map.put(""b"", ""z""); System.out.println(Join.joinRecursive(map.entrySet(), "", "", ""["", ""]"")); * * @author luke */ public class MultiMapKeyToSet { HashMap> map = new HashMap>(); public static MultiMapKeyToSet make() { return new MultiMapKeyToSet(); } /** Return true if this multimap did not already contain the specified value at the specified key. */ public boolean put(S key, T value) { HashSet set = map.get(key); if (set == null) { set = new HashSet(); map.put(key, set); } return set.add(value); } public void putAll(S key, Iterable values) { boolean putSomething = false; for (T val : values) { put(key, val); putSomething = true; } if (!putSomething && !map.containsKey(key)) // If putting an empty collection, need to create an empty set at the key map.put(key, new HashSet()); } public void putAll(S key, T[] values) { if (values.length == 0 && !map.containsKey(key)) // If putting an empty collection, need to create an empty set at the key map.put(key, new HashSet()); else for (T val : values) put(key, val); } public HashSet get(S key) { return map.get(key); } /** * Get the single value mapped to by the key, or null if no value mapped to for this key. * * @throws IllegalRuntimeException * if there is more than one value mapped to by this key. */ public T getSingleVal(S key) { HashSet set = map.get(key); return CollectionUtils.getSingleVal(set); } public boolean containsKey(S key) { return map.containsKey(key); } public int sizeKeys() { return map.size(); } public Set>> entrySet() { return map.entrySet(); } /** * Return the union of all values in all mapped sets (i.e. the union of all values mapped to by some key in this MultiMap). * NOTE: creates a new HashSet with the current union on every invocation, so if you modify the contents of the returned * HashSet, it won't affect the map. */ public HashSet valuesUnion() { return CollectionUtils.union(map.values()); } public HashMap> getRawMap() { return map; } public Set keySet() { return map.keySet(); } /** Invert the mapping */ public MultiMapKeyToSet invert() { MultiMapKeyToSet inv = new MultiMapKeyToSet(); for (Entry> ent : map.entrySet()) { S key = ent.getKey(); for (T val : ent.getValue()) inv.put(val, key); } return inv; } public ArrayList>> toList() { ArrayList>> result = new ArrayList>>(); for (Entry> ent : map.entrySet()) result.add(Pair.make(ent.getKey(), ent.getValue())); return result; } /** Write out to a TSV file */ public void writeOutToFile(String tsvFile) throws IOException { PrintWriter writer = new PrintWriter(tsvFile); for (Entry> ent : map.entrySet()) { S key = ent.getKey(); StringBuilder buf = new StringBuilder(); buf.append(key); for (T val : ent.getValue()) buf.append(""\t"" + val); writer.println(buf.toString()); } writer.close(); } /** Read in a String->String map from a TSV file */ public static MultiMapKeyToSet readFromFile(String tsvFile) throws IOException { MultiMapKeyToSet map = new MultiMapKeyToSet(); for (String line : new FileLineIterator(tsvFile)) { String[] parts = Split.split(line, ""\t""); String key = parts[0]; for (int i = 1; i < parts.length; i++) map.put(key, parts[i]); } return map; } } " B20902,"/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib.converters; import com.isotopeent.codejam.lib.InputConverter; import com.isotopeent.codejam.lib.Utils; public class IntArrayLine implements InputConverter { private int length; private int[] input; private int[] inputBuffer; /** * fixed length arrays */ public IntArrayLine(int length) { this.length = length; } /** * dynamic length arrays */ public IntArrayLine(int[] buffer) { inputBuffer = buffer; } @Override public boolean readLine(String data) { if (length > 0) { input = new int[length]; input = Utils.convertToIntArray(data, length); } else { int count = Utils.convertToIntArray(data, inputBuffer); input = new int[count]; System.arraycopy(inputBuffer, 0, input, 0, count); } return false; } @Override public int[] generateObject() { return input; } } " B21390,"package QualificationC; import java.io.BufferedReader; import java.io.FileReader; import java.util.Arrays; import java.util.HashSet; public class ProblemC { public static void main(String args[]) throws Exception{ // System.out.println(args[0]); FileReader fr = new FileReader(args[0]); BufferedReader br = new BufferedReader(fr); int T = Integer.parseInt(br.readLine()); // System.out.println(T); for(int t=0;t B) continue; if(swapval <= val) continue; result++; // System.out.println(swapval); } } System.out.println(""Case #"" + (t+1) + "": "" + result); } } public static String shiftString(String a) { return a.substring(1) + a.charAt(0); } public static String[] permute(String a) { int len = a.length(); if(len <= 1) return null; String[] result = new String[len - 1]; result[0] = shiftString(a); for(int i=1;i set = new HashSet(Arrays.asList(result)); result = set.toArray(new String[0]); // String[] answer = set.toArray(new String[0]); // if(set.size() != result.length) { // System.out.println(""--b4--""); // System.out.println(Arrays.toString(result)); // // System.out.println(""--after--""); // System.out.println(Arrays.toString(answer)); // System.out.println(""-----""); // } // System.out.println(Arrays.toString(result)); return result; } } " B20819,"import java.util.Scanner; import java.util.List; import java.util.ArrayList; public class Recycled{ private Scanner input; private int min = 0; private int max = 0; private ArrayList> list; public Recycled(){ input = new Scanner(System.in); list = new ArrayList>(); } public void run(){ precompute(2000000); int T = input.nextInt(); for(int i = 1; i<=T; i++){ int A = input.nextInt(); int B = input.nextInt(); System.out.printf(""Case #%d: %d\n"",i,check(A,B)); } } public void precompute(int max){ list.add(new ArrayList()); for(int i = 1; i <= max; i++){ list.add(new ArrayList()); String n = String.valueOf(i); for(int m = 1; m= n && i <= B){ result++; } } } return result; } public static void main(String[] args){ Recycled object = new Recycled(); object.run(); } } " B20620,"package utils; /** * * @author Fabien Renaud */ public abstract class Jam implements Runnable, JamParser { protected final String[] lines; protected final JamCase[] cases; protected final int t; private final String filenameInput; private final String filenameOutput; private final String[] output; private final StopWatch timer; private int count; protected Jam(String filename) { this.filenameInput = filename; this.filenameOutput = filename.replace("".in"", "".out""); this.count = 0; this.lines = File.readAllLines(filenameInput); this.timer = new StopWatch(); this.t = Integer.parseInt(lines[0]); this.cases = new JamCase[t]; this.output = new String[t]; File.delete(filenameOutput); } protected final synchronized void appendOutput(int number, String result) { output[number - 1] = String.format(""Case #%1$d: %2$s"", number, result); count++; if (count == t) { timer.stop(); saveOutput(); } } private void saveOutput() { if (count != t) { System.err.println(String.format(""%1$d results are missing. File not saved."")); } else { File.writeAllLines(filenameOutput, output); System.out.println(""File saved at "" + filenameOutput); System.out.println(""---------- OUTPUT ----------""); for (String s : output) { System.out.println(s); } System.out.println(""--- Processed in "" + timer.getElapsedSeconds() + "" seconds.""); } } @Override public final void run() { int j; count = 0; timer.start(); for (int i = 1; i <= t; i++) { j = i - 1; cases[j] = getJamCase(i); if (cases[j] != null) { new Thread(cases[j]).start(); } } } } " B22047,"package google.contest.C; import google.loader.Challenge; import google.problems.AbstractChallenge; import java.util.HashSet; import java.util.Set; public class CChallenge extends AbstractChallenge implements Challenge { private int B; private int A; private int num; Setpairs ; public CChallenge(int number, String line) { super(number); num=0; pairs = new HashSet(); String[] tokens = line.split("" ""); A = Integer.parseInt(tokens[0]); B = Integer.parseInt(tokens[1]); int i=0; for( i=A ; i<=B; i++){ calcFor(i); } setResult(""""+num); } private void calcFor(int i) { String numString = """"+i; for(int j=1; j<= numString.length()-1; j++){ String first = numString.substring(0,j); String second = numString.substring(j); String third = second+first; check(i, third); } } private void check(int i, String third) { if(third.startsWith(""0"")){ return; } int j = Integer.parseInt(third); if(A<=i && i T-1){ System.out.println(""STOP ! too many test cases !!""); return; } cases[count++] = s; } int count; int T; String[] cases; } " B21665,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int T = 0; int A = 0; int B = 0; int n = 0; int m = 0; int tmp = 0; int totalPasses = 0; int passCtr = 0; int pairs = 0; int movDig = 0; int prevN = 0; //These 4 variables are to capture possible duplicates int prevM = 0; int prevN2 = 0; int prevM2 = 0; String currentCase = null; String inputFilename = ""C-large.in""; String outputFilename = ""C-large.out""; BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(outputFilename)); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } FileInputStream fStream = null; try { fStream = new FileInputStream(inputFilename); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } DataInputStream in = new DataInputStream(fStream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); try { T = Integer.parseInt(br.readLine()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(int i=0;i 0) { try { sc = new Scanner(new File(args[0])); if (args.length > 1) { System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(new File(args[1])), 128))); } } catch (FileNotFoundException e) { // e.printStackTrace(); sc = new Scanner(System.in); } } else { sc = new Scanner(System.in); } int T = Integer.valueOf(sc.nextLine()); for (int i = 0; i < T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int answer = solve(A, B); System.out.printf(""Case #%d: %d\n"", i + 1, answer); } System.out.close(); } public static int solve(int A, int B) { int answer = 0; int seedNum = A; do { answer += hasRecycled(seedNum++, A, B); } while (seedNum < B); return answer; } public static int hasRecycled(long seedNum, long A, long B) { int count = 0; int ptr; char[] old_num_chars = String.valueOf(seedNum).toCharArray(); int length = old_num_chars.length; char[] moved_num_chars = new char[length]; List newNumList = new ArrayList(); for (int i = length - 1; i > 0; i--) { ptr = i; for (int j = 0; j < length; j++) { if (ptr == 0) { moved_num_chars[ptr] = old_num_chars[length - 1]; } else { moved_num_chars[ptr] = old_num_chars[ptr - 1]; } if (--ptr < 0) { ptr += length; } } long newNum = Long.valueOf(new String(moved_num_chars)); if ( seedNum < newNum && newNum <= B) { boolean isNew = true; for (Iterator it = newNumList.iterator(); it.hasNext();) { Long l = it.next(); if (l.equals(newNum)) { isNew = false; break; } } if (isNew) { newNumList.add(newNum); count++; } } old_num_chars = moved_num_chars.clone(); } return count; } } " B22004,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class QRC { // Basics for all problems private static final String LARGE = ""large""; private static final String SMALL = ""small""; private static final String IN = "".in""; private static final String OUT = "".out""; private static String SET; // Problem specific Globals private static Set mPairs; public static void main(String[] args) throws Exception { SET = LARGE; // Which set id being evaluated readInputFile(SET+IN); } private static void readInputFile(String in) throws Exception { BufferedReader br = new BufferedReader(new FileReader(new File(SET+IN))); String line = null; int caseCount = 1; br.readLine(); while ( (line = br.readLine()) != null ) { String[] input = line.split("" ""); final int A = Integer.parseInt(input[0]); final int B = Integer.parseInt(input[1]); mPairs = new HashSet(); for (int n = A; n < B; n++ ) { String rotation = String.valueOf(n); int digitCount = rotation.length(); for ( int i = 0; i < digitCount; i++ ) { rotation = rotateN(rotation); int m = Integer.parseInt(rotation); if ( m > n && m <= B ) { mPairs.add(new Pair(n,m)); //System.out.println("" --> (""+n+"", ""+m+"") @ ""+mPairs.size()); } } } writeOutputLine(String.format(""Case #%d: %d"", caseCount, mPairs.size())); caseCount++; } br.close(); } private static String rotateN(String nAsString) { String bulk = nAsString.substring(0,nAsString.length()-1); char jumper = nAsString.charAt(nAsString.length()-1); return jumper+bulk; } private static void writeOutputLine(String line) throws Exception { BufferedWriter bw = new BufferedWriter(new FileWriter(new File(SET+OUT),true)); bw.append(line); bw.newLine(); bw.flush(); bw.close(); } } " B20500,"import java.util.*; public class probC { public static int N=2000001, K=0 ; public static void main (String[] args) { Scanner scan = new Scanner (System.in) ; int A[] = new int[N]; boolean visited[] = new boolean [N]; for (int i=0 ; i set = new HashSet (); set.add(n); for (int off=0 ; off j && temp <= B && !done[temp]){ done[temp] = true; ++tempAns; } } ans += tempAns*(tempAns+1)/2; } out.println(""Case #""+(i+1)+"": ""+ans); } out.close(); } } " B21327,"package net.jbirch.gcj12qual.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Scanner; /** * * @author Birch */ public class FileLoader { protected String filename; protected InputStream stream; protected Scanner scanner; public FileLoader(String filename) { this.filename = filename; } public InputStream getStream() throws FileNotFoundException { if (stream == null) { stream = new FileInputStream(filename); } return stream; } public Scanner getScanner() throws FileNotFoundException { if (scanner == null) { scanner = new Scanner(this.getStream()); } return scanner; } }" B22086,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package question3; import com.sun.org.apache.xpath.internal.FoundIndex; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * * @author karim */ public class Question3 { static Map found = new HashMap(); /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter(""output.out"")); BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); int numOfcases = Integer.parseInt(in.readLine()); for (int caseNum = 1; caseNum <= numOfcases; caseNum++) { found = new HashMap(); String input = in.readLine(); Scanner s = new Scanner(input); int a = s.nextInt(); int b = s.nextInt(); long output = 0; if (b >= 10) { for (int currentNum = b; currentNum >= a; currentNum--) { int temp = currentNum; int divisor = 10; while (temp / divisor != 0) { int div = temp / divisor; int reminder = temp % divisor; divisor *= 10; int newNumber = Integer.parseInt("""" + reminder + div); if(newNumber == currentNum) break; if (newNumber >= a && newNumber <= b && newNumber != currentNum) { Pair p = new Pair(newNumber, currentNum); if (!found.containsKey(p)) { //System.out.println(currentNum + "" "" + newNumber); found.put(p, 1); output++; } } } } } out.write(""Case #"" + caseNum + "": "" + output); out.newLine(); } out.flush(); out.close(); in.close(); } } " B20547,"public class Main { public static void main(String[] args) throws java.io.FileNotFoundException,java.io.IOException{ java.io.BufferedReader bRead=new java.io.BufferedReader(new java.io.FileReader(""F:\\C-large.in"")); java.io.BufferedWriter bWrite=new java.io.BufferedWriter(new java.io.FileWriter(""F:\\C-large.out"")); java.util.HashMap mVals=new java.util.HashMap(); StringBuffer output=new StringBuffer(); int noCases=Integer.parseInt(bRead.readLine()); for(int i=0;in&&m<=B&&!mVals.containsKey(m)){noPairs++;mVals.put(m,0);} } n++; } output.append(""Case #""+(i+1)+"": ""+noPairs+""\n""); } bWrite.write(output.toString()); bWrite.close();bRead.close(); } } " B20189,"package com.numbers.recycle.io; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.List; public class FileOutputWriter { private FileWriter writer; private BufferedWriter bWriter; public void writeToFile(List outputFileContents) { File file = new File(""C:/Documents and Settings/Administrator/My Documents/Code Jam/output.out""); try{ writer = new FileWriter(file); bWriter = new BufferedWriter(writer); for(String line: outputFileContents){ bWriter.write(line); bWriter.newLine(); } }catch (Exception e) { e.printStackTrace(); } finally { close(writer, bWriter); } } private void close(FileWriter writer, BufferedWriter bWriter) { try{ bWriter.close(); writer.close(); } catch(Exception e){ } } } " B20518,"import java.util.Scanner; import java.io.*; public class Displayer { public static void main(String[] args) throws IOException { Scanner kb = new Scanner(new File(""/Users/mbp13/Documents/Google Code Jam/GCJ_Q3/src/input"")); PrintStream out = new PrintStream(new File(""/Users/mbp13/Documents/Google Code Jam/GCJ_Q3/src/output_q3"")); int testNum,A,B; String tmpStr,tmpStr2,cut1,cut2; int cnt,x; int[] tmp = new int[15]; int tmpCnt; int isRepeat; testNum = kb.nextInt(); for(int i=0;i j && x >= A && x <= B) { isRepeat=0; for(int l = 0; l < tmpCnt; l++) { if(x == tmp[l]) { isRepeat = 1; break; } } if(isRepeat == 0) { //System.out.println(j + "" "" + tmpStr2); cnt++; tmp[tmpCnt] = x; tmpCnt++; } } } } out.println(""Case #""+(i+1)+"": ""+cnt); } } } " B21429,"package jp.funnything.prototype; import java.io.File; import java.io.IOException; import java.util.Set; import jp.funnything.competition.util.CompetitionIO; import jp.funnything.competition.util.Packer; import org.apache.commons.io.FileUtils; import com.google.common.collect.Sets; public class Runner { public static void main( final String[] args ) throws Exception { new Runner().run(); } void pack() { try { final File dist = new File( ""dist"" ); if ( dist.exists() ) { FileUtils.deleteQuietly( dist ); } final File workspace = new File( dist , ""workspace"" ); FileUtils.copyDirectory( new File( ""src/main/java"" ) , workspace ); FileUtils.copyDirectory( new File( ""../../../../CompetitionUtil/Lib/src/main/java"" ) , workspace ); Packer.pack( workspace , new File( dist , ""sources.zip"" ) ); } catch ( final IOException e ) { throw new RuntimeException( e ); } } void run() throws Exception { final CompetitionIO io = new CompetitionIO(); final int t = io.readInt(); for ( int index = 0 ; index < t ; index++ ) { final int[] values = io.readInts(); final int a = values[ 0 ]; final int b = values[ 1 ]; io.write( index + 1 , solve( a , b ) ); } io.close(); pack(); } int solve( final int a , final int b ) { int count = 0; final int nDigit = ( int ) Math.floor( Math.log10( a ) ) + 1; final int next = ( int ) Math.pow( 10 , nDigit - 1 ); final Set< Integer > already = Sets.newTreeSet(); for ( int n = a ; n + 1 <= b ; n++ ) { if ( already.contains( n ) ) { continue; } int inRange = 1; already.add( n ); for ( int base = 10 , m = next ; base < n ; base *= 10 , m /= 10 ) { final int v = n / base + n % base * m; if ( already.contains( v ) ) { continue; } if ( v >= a && v <= b ) { inRange++; already.add( v ); } } count += inRange * ( inRange - 1 ) / 2; } return count; } } " B20473,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub int ten[]=new int[10]; ten[1]=1; for(int i=2;i<10;ten[i]=ten[i-1]*10,i++); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st; int T=Integer.parseInt(br.readLine()); for(int cn=1;cn<=T;cn++){ st=new StringTokenizer(br.readLine()); int A=Integer.parseInt(st.nextToken()); int B=Integer.parseInt(st.nextToken()); int n=(A+"""").length(); int ctr=0; boolean marked[]=new boolean[2000001]; for(int a=A;a<=B;a++){ if(marked[a]) continue; int i=1; int b=a; for(int j=1;ja&&b<=B&&!marked[b]){ i++; marked[b]=true; // System.out.println(a+"" ""+b); } } ctr+=i*(i-1)/2; // System.out.println("">""+ctr); } System.out.println(""Case #""+cn+"": ""+ctr); } } } " B21690," import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Scanner; import java.util.Set; import com.google.common.collect.Sets; public class C { public static void main(String [] args) throws IOException { String inputFile = ""src/C-large.in""; Scanner in = new Scanner(new File(inputFile)); PrintStream out = new PrintStream(inputFile.substring(0, inputFile.length()-2)+""out""); int cases = in.nextInt(); for (int c = 1; c <= cases; c++) { int a = in.nextInt(); int b = in.nextInt(); int count = 0; for (int i = a; i < b; i++) { String is = String.valueOf(i); Set matches = Sets.newHashSet(); for (int j = 1; j < is.length(); j++) { is = is.substring(1) + is.charAt(0); int t = Integer.parseInt(is); if (t > i && t <= b && !matches.contains(t)) { count++; matches.add(t); } } } out.print(""Case #""+c+"": "" + count); out.println(); } out.close(); } } " B20659,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; /** * */ /** * @author antonio081014 * @time: Apr 13, 2012, 5:01:31 PM */ public class Main { /** * @param args */ public static void main(String[] args) throws Exception { Main main = new Main(); main.run(); System.exit(0); } public void run() throws Exception { BufferedReader br = new BufferedReader(new FileReader(""input.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""output.out"")); int T = Integer.parseInt(br.readLine()); for (int t = 1; t <= T; t++) { out.write(""Case #"" + Integer.toString(t) + "": ""); String[] strs = br.readLine().split(""\\s""); int A = Integer.parseInt(strs[0]); int B = Integer.parseInt(strs[1]); Set set; int count = 0; for (int n = A; n <= B; n++) { String tmp = Integer.toString(n); set = new HashSet(); for (int i = 0; i < tmp.length(); i++) { String a = tmp.substring(i) + tmp.substring(0, i); int m = Integer.parseInt(a); if (m > n && m <= B) { set.add(m); } } count += set.size(); } out.write(Integer.toString(count) + ""\n""); } out.close(); } }" B21945,"import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner r = new Scanner(System.in); int T = r.nextInt(); int caseNumber = 1; while(T-- > 0){ int A = r.nextInt(); int B = r.nextInt(); int ret = 0; for(int x = A; x <= B; x++){ HashSet S = new HashSet(); int curr = x; int L = (curr + """").length(); int L10 = 1; for(int i = 0; i < L - 1; i++) L10 *= 10; for(int itr = 0; itr < L; itr++){ if((curr + """").length() == L && !S.contains(curr) && curr <= B && curr >= A && curr < x){ ret++; } S.add(curr); curr = R(curr, L10); } } System.out.printf(""Case #%d: %d\n"", caseNumber++, ret); } } static int R(int x, int L){ int m = x % 10; return (x / 10) + (L * m); } } " B20216,"package qualifs; import gcj.Gcj; import java.util.HashSet; import java.util.Set; public class C { final private String file; C (String f) { file = f; } public void run() { Gcj gcj = new Gcj(file); gcj.readLine(); int ncase = gcj.iToken(); for (int cas=1 ; cas <= ncase ; cas++) { gcj.readLine(); String A = gcj.sToken(); String B = gcj.sToken(); int a = Integer.parseInt(A); int b = Integer.parseInt(B); int[] aa = gcj.breakdownNumber(A); int[] mm = gcj.breakdownNumber(A); int[] bb = gcj.breakdownNumber(B); int n = aa.length; int count = b-a; int rp = 0; Set dejavu = new HashSet(); if (n >= 2) while (count-- > 0) { for (int c=1 ; c mm[i]) rok = true; } if ( ! bok) { if (mm[p] > bb[i]) break; if (mm[p] < bb[i] || i == n-1) bok = true; } } // dejavu if (rok && bok) { String u="""",v=""""; for (int i=0 ; i=0 ; i--) { if (mm[i] == 9) mm[i] = 0; else { mm[i]++; break; } } } Gcj.outcase(cas, false); System.out.println(rp); } gcj.terminate(); } } " B20749,"package fixjava; import java.util.ArrayList; import java.util.HashMap; /** * Get the index of the given key if this key has been assigned an index before, and if not, allocate a new index for it by * incrementing a counter that starts at zero, and return the new index. */ public class UniqueIndexAllocator { private HashMap map = new HashMap(); private ArrayList orderedKeys = new ArrayList(); public UniqueIndexAllocator() { } /** Allocate unique indices for each item in the given collection. Read back the indices using the other methods. */ public UniqueIndexAllocator(Iterable collection) { for (T it : collection) getOrAllocateIndex(it); } /** Get the assigned index for a key, or assign it a new unique index if this key has not previously been assigned an index */ public int getOrAllocateIndex(T key) { Integer currIdx = map.get(key); if (currIdx == null) { map.put(key, currIdx = orderedKeys.size()); orderedKeys.add(key); } return currIdx; } /** Get all the keys as a list in their index order */ public ArrayList getOrderedKeys() { return orderedKeys; } /** Get all the keys as an array in their index order */ @SuppressWarnings(""unchecked"") public T[] getOrderedKeysAsArray() { return (T[]) orderedKeys.toArray(); } /** Get the mapping from key to index */ public HashMap getKeyToIndexMap() { return map; } /** Return the number of allocated indices, i.e. the number of unique keys */ public int numIndices() { return orderedKeys.size(); } } " B21831,"package qualification; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedList; import java.util.Scanner; public class C { public static void main(String[] Args) throws IOException { Scanner sc = new Scanner(new FileReader(""C-small.in"")); PrintWriter pw = new PrintWriter(new FileWriter(""output.txt"")); int caseCnt = sc.nextInt(); // int caseCnt=1; for (int caseNum=1; caseNum <= caseCnt; caseNum++) { System.out.println(caseNum); int A=sc.nextInt(); int B=sc.nextInt(); // int A = 1234567; // int B =1234567; HashMap> visited = new HashMap>(); long total=0; for(int i=A;i<=B;i++){ if(!visited.containsKey(i)) visited.put(i, new LinkedList()); String stringI=String.valueOf(i); for(int j=1;j=A && testInt<=B && testInt!=i){ if(!visited.containsKey(testInt)) visited.put(testInt, new LinkedList()); if(!visited.get(testInt).contains(i)) { total++; visited.get(testInt).add(i); visited.get(i).add(testInt); } } } } System.out.println(total); pw.println(""Case #"" + caseNum + "": "" + total); } pw.flush(); pw.close(); sc.close(); } } " B20375,"import java.util.*; public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int t = 1; t <= T; ++t) { int A = in.nextInt(); int B = in.nextInt(); HashSet set = new HashSet(); int ans = 0; for (int i = A; i <= B; ++i) { String val = Integer.toString(i); HashSet set2 = new HashSet(); for (int j = 0; j < val.length()-1; ++j) { val = val.charAt(val.length()-1) + val.substring(0, val.length()-1); if (set2.contains(Integer.parseInt(val))) continue; if (set.contains(Integer.parseInt(val))) ++ans; set2.add(Integer.parseInt(val)); } set.add(i); } System.out.printf(""Case #%d: %d\n"", t, ans); } } } /* 4 1 9 10 40 100 500 1111 2222 */ " B22240,"package problemc; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; public class ProblemC { public static void main(String args[]){ List inputs = readInput(); String n; String m; int count = 0; for(String input : inputs ){ count++; n = input.split("" "")[0]; m = input.split("" "")[1]; output(count, findRecycledNumbers(n,m)); } } private static int findRecycledNumbers(String n, String m){ int recycledNumbers = 0; n = n.trim(); m = m.trim(); int mFirst = Integer.parseInt(m.substring(0,1)); int nLong = Integer.parseInt(n); int mLong = Integer.parseInt(m); String nString = """"; for(int i = nLong; i0; j--){ // System.out.println(""nSTRING: "" + nString); String valueAt = nString.substring(j, j+1); //System.out.println(""VALUE AT: "" + valueAt); if(Integer.parseInt(valueAt) <= mFirst){ //System.out.println(""IN HERE""); String end = nString.substring(j); String remaining = nString.substring(0, j); String finalNum = end + remaining; if(Integer.parseInt(finalNum) <= mLong && Integer.parseInt(finalNum) > nLong){ recycledNumbers++; } } } } return recycledNumbers; } private static List readInput(){ List untranslatedStrings = new ArrayList(); try{ BufferedReader in = new BufferedReader(new FileReader(""input.txt"")); Long numTestCases = Long.parseLong(in.readLine()); for(int i=0; i set = new HashSet(); String prev = j + """"; for (int k = 0; k < number.length(); k++) { String nextS = getNext(prev); int next = Integer.parseInt(nextS); if(next == j){ continue; } if(set.contains(next)){ continue; } if(next >= start && next <= end){ map[next] = true; tmpCount++; set.add(next); } prev = nextS; } map[j] = true; if(tmpCount != 0){ count += (tmpCount*(tmpCount+1))/2; } } out.println(""Case #"" + (i+1) + "": "" + count); } out.close(); } } " B20949,"import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class C{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int caze, T; int A, B; void run(){ T=sc.nextInt(); for(caze=1; caze<=T; caze++){ A=sc.nextInt(); B=sc.nextInt(); solve(); } } void solve(){ int ans=0; for(int n=A; n<=B; n++){ int digit=(int)(log10(n)+EPS); int d=(int)pow(10, digit); // debug(""n"", n); for(int m=rot(n, d); m!=n; m=rot(m, d)){ // debug(""m"", m); if(n found = new ArrayList(); for(int n = min; n <= max; n++){ String num = n+""""; found.clear(); for(int d = 0; d n && value <= max && (value+"""").length() == num.length() && !found.contains(num)){ //System.out.println(n + "" "" + value); found.add(num); count++; } } } out.write(""Case #"" + (x+1) + "": "" + count + ""\n""); } in.close(); out.close(); } public static void main(String[] args) throws Exception{ new Main(); } } " B21319,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package probc; import java.io.*; import java.util.Scanner; import javax.swing.JOptionPane; /** * * @author nick */ public class ProbC { public static int numLines = 0; public static String[] dataLine; public static String[] outLine; public static void main(String[] args) throws UnsupportedEncodingException, IOException { // input //JOptionPane.showMessageDialog(null, ""This program provides a decrypter for Google's third CodeJam question: Recycled Numbers.""); getInput(); decode(); writeOutput(); } private static void getInput() throws FileNotFoundException { Scanner scanner = new Scanner(new FileInputStream(""input.txt"")); try { numLines = Integer.parseInt(scanner.nextLine()); dataLine = new String[numLines]; outLine = new String[numLines]; for (int i = 0; i < numLines; i++) { dataLine[i] = scanner.nextLine(); } } finally { scanner.close(); } } private static void writeOutput() throws UnsupportedEncodingException, FileNotFoundException, IOException { Writer out = new OutputStreamWriter(new FileOutputStream(""output.txt"")); try { String outText = """"; for (int i = 0; i < numLines; i++) { outText = outText + outLine[i] + ""\n""; } out.write(outText); } finally { out.close(); } } private static void decode() { for (int i = 0; i < numLines; i++) { Scanner sc = new Scanner(dataLine[i]); String numOneString = sc.next(); String numTwoString = sc.next(); sc.close(); int numOneInt = Integer.parseInt(numOneString); int numTwoInt = Integer.parseInt(numTwoString); int length = numOneString.length(); int setLength = numTwoInt - numOneInt; String tempString = """"; int tempInt = 0; int answer = 0; int[] answers = new int[numTwoInt]; tempInt = numOneInt; for (int ii = 0; ii < setLength; ii++) { tempString = """" + tempInt; for (int iii = 0; iii < length; iii++) { tempString = tempString.substring(1) + tempString.charAt(0); if (Integer.parseInt(tempString) >= tempInt & Integer.parseInt(tempString) <= numTwoInt) { if (Integer.parseInt(tempString) != tempInt) { answer++; } } } tempInt++; } outLine[i] = ""Case #"" + (i + 1) + "": "" + answer; } } } " B20874,"import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class c { public static void main(String[] args){ Scanner in = new Scanner(System.in); int numOfLines = new Integer(in.nextLine()); for (int i= 1; i<=numOfLines; i++) { int res =0; String [] lineValues = in.nextLine().split("" ""); int n = new Integer(lineValues[0]); int m = new Integer(lineValues[1]); for (Integer j = n; j parellesBones = new ArrayList(); for (int k = nS.length();k>=1;k--) { String endPart=nS.substring(k); String beginPart=nS.substring(0,k); Integer recycled = new Integer(endPart+beginPart); if (recycled >m) continue; if (recycled j) { parellesBones.add(recycled); res++; } } } System.out.format(""Case #%d: %d\n"", i, res); } return; } }" B20032,"import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class GoogleReplaced { static BufferedWriter bw = null; public static void main(String[] args) throws Exception { try { Scanner sc = new Scanner(new File(""C-large.in"")); bw = new BufferedWriter(new FileWriter(""output.txt"")); long totalCases = sc.nextLong(); for (int i = 1; i <= totalCases; i++) { int finalCount = 0; int i1 = sc.nextInt(); int i2 = sc.nextInt(); int tempNum1 = i1; for (; tempNum1 <= i2; tempNum1++) { String string = String.valueOf(tempNum1); List usedList = new ArrayList(); for (int j = 1; j < string.length(); j++) { String string1 = string.substring(string.length() - j, string .length()); String string2 = string.substring(0, string.length() - j); String newString = string1 + string2; int newIntValue = Integer.parseInt(newString); if ((i1 <= newIntValue) && ((i2 >= newIntValue))) { if (newIntValue > tempNum1) { if (!usedList.contains(newIntValue)) { usedList.add(newIntValue); finalCount = finalCount + 1; } } } } } bw.append(""Case #"" + i + "": ""); bw.append(String.valueOf(finalCount)); bw.append(""\n""); } } catch (Exception e) { e.printStackTrace(); } finally { bw.flush(); bw.close(); } } } " B21515,"import java.io.BufferedReader; import java.io.FileReader; import java.util.HashSet; import java.util.Set; public class ProblemB { public static void main(String[] args) { try { BufferedReader bufReader = new BufferedReader(new FileReader(args[0])); int numOfCases = Integer.parseInt(bufReader.readLine()); int a, b; for (int i = 0; i < numOfCases; i++) { // should change 2 to numOfCases!!! Set distinctRecycledPairs = new HashSet(); String line = bufReader.readLine(); a = Integer.parseInt(line.substring(0, line.indexOf(' '))); b = Integer.parseInt(line.substring(line.indexOf(' ') + 1, line.length())); //System.out.println(""A = "" + a + "" B = "" + b); for (int j = a; j <= b; j++) { String n = """" + j; for (int k = 1; k < n.length(); k++) { String possibleM = n.substring(k) + n.substring(0, k); if (Integer.parseInt(possibleM) > Integer.parseInt(n) && Integer.parseInt(possibleM) >= a && Integer.parseInt(possibleM) <= b) { // the pair (n,m) may repeat, so use a set // there should be a better way though distinctRecycledPairs.add(n + "" "" + possibleM); } } } System.out.println(""Case #"" + (i+1) + "": "" + distinctRecycledPairs.size()); } bufReader.close(); } catch (Exception e) { e.printStackTrace(); } } } " B21175,"import java.util.Scanner; public class ProblemC { public static int rotate(int x) { int y = x % 10; x /= 10; int cd = (x + """").length(); if (x == 0) { cd = 0; } y *= Math.pow(10, cd); y += x; return y; } public static String rotate(String x) { String r = x.substring(0, 1); if (x.length() > 1) { r = x.substring(1) + r; } return r; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int tt = 1; tt <= t; tt++) { int a = sc.nextInt(); int b = sc.nextInt(); int c = 0; for (int i = a; i <= b; i++) { String s = i + """"; while (true) { s = rotate(s); int x = Integer.parseInt(s); if (x == i) { break; } if (x > i && x >= a && x <= b) { // System.out.println(i + "" "" + x); c++; } } } System.out.println(""Case #"" + tt + "": "" + c); } } } " B21190,"package googlejam; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""inputC.txt"")); PrintWriter pw = new PrintWriter(""outputC.txt""); int T = sc.nextInt(); for (int t = 1; t <= T; t++) { int count = count(sc.nextInt(), sc.nextInt()); pw.println(""Case #"" + t + "": "" + count); } pw.flush(); pw.close(); } public static int count(int A, int B) { int res = 0; Set a = new HashSet(); for (int i = A; i < B; ++i) { a.clear(); String n = Integer.toString(i); for (int start = 1; start < n.length(); ++start) { if (n.charAt(start) == '0') { continue; } int m = 0; for (int d = 0; d < n.length(); ++d) { m *= 10; m += n.charAt((start + d) % n.length()) - '0'; } if (m > i && m <= B && !a.contains(m)) { a.add(m); ++res; } } } return res; } } " B21052,"import java.util.Scanner; import java.util.TreeMap; public class RecycledNumbers { public static void main(String[]args){ Scanner sc = new Scanner(System.in); //Read in the T int -- Test Cases int T = Integer.parseInt(sc.nextLine()); for (int t = 1; t <= T; t++) { int num = 0; //START OF CODE int a = sc.nextInt(); int b = sc.nextInt(); int focus = a; for (int i = 0; focus < b; i++) { String f = focus + """"; boolean distinct = true; /*all:for (int j = 0; j < f.length(); j++) { for (int j2 = j+1; j2 < f.length(); j2++) { if(f.charAt(j) == f.charAt(j2)){ distinct = false; break all; } } } distinct = true;*/ if(distinct){ for (int j = 0; j < f.length() - 1; j++) { f = f.charAt(f.length()-1) + f.substring(0,f.length()-1); int fs = Integer.parseInt(f); if(fs <= b && f.charAt(0) != '0' && fs > focus){ //System.out.println(focus+ "" ""+ f); num++; } } } focus++; } //END OF CODE //OUTPUT System.out.format(""Case #%d: %d\n"", t, num); } } } " B22134,"import java.util.Scanner; import java.io.*; public class Q3 { public static void main(String []args) throws IOException { int numT=0; Scanner kb=new Scanner(new File(""D:/sample.txt"")); numT = kb.nextInt(); int a[] = new int[numT]; int b[]=new int[numT]; for (int i = 0; i < numT; i++) { a[i] = kb.nextInt(); b[i]=kb.nextInt(); } for (int i = 0; i < numT; i++) { System.out.println(""Case #""+(i+1)+"":""+"" ""+cal(a[i],b[i])); } } public static int cal(int A,int B){ int score=0; for(int n=A;n<=B;n++){ String num = n + """"; int lastm = 0; for(int j=1;j= A && m != n && m > n && lastm != m) { lastm = m; score++; } } } return score; } }" B20957,"import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ProblemC { private void solve() { Scanner in = new Scanner(new BufferedInputStream(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int T = in.nextInt(); for (int i = 1; i <= T; i++) { long result = 0; int A = in.nextInt(); int B = in.nextInt(); int digits = digits(A); int m = (int)Math.pow(10, digits-1); for (int k = A; k <= B; k++) { Set used = new HashSet(); //used.add(k); int kk = k; for (int d = 1; d < digits; d++) { int r = kk % 10; kk /= 10; kk += r * m; if (kk > k && kk <= B && !used.contains(kk)) { result++; used.add(kk); } } } out.println(""Case #"" + i + "": "" + result); } out.flush(); out.close(); } private int digits(int a) { int d = 0; while (a > 0) { d++; a /= 10; } return d; } public static void main(String[] args) throws IOException { ProblemC solver = new ProblemC(); solver.solve(); } } " B21070,"package template; import java.util.ArrayList; import java.util.Set; import java.util.HashSet; public class TestCaseSolver implements Runnable { private ArrayList testCases; private int ref; public TestCaseSolver(ArrayList tcs, int ref) { testCases = tcs; this.ref = ref; } public TestCaseSolver(TestCase tc, int ref) { ArrayList tcs = new ArrayList<>(); tcs.add(tc); testCases = tcs; this.ref = ref; } public int getRef() { return ref; } @Override public void run() { for (TestCase tc : testCases) { long startTime = System.nanoTime(); solve(tc); long duration = System.nanoTime() - startTime; double secs = (double)duration / (1000000000d); tc.setTime(secs); System.out.println(""Thread "" + ref + "" solved testcase "" + tc.getRef() + "" in "" + String.format(""%.2f"", secs) + "" secs.""); } } private void solve(TestCase tc) { ArrayList a_b = tc.getIntegerList(""a_b""); int A = a_b.get(0); int B = a_b.get(1); int count = 0; for (int i = A; i <= B; i++) { ArrayList digs = Utils.splitToDigits(i); int l = digs.size(); Set solns = new HashSet<>(); for (int r = 1; r < l; r++) { int rec = recombine(digs, r); if (valid(digs, r) && rec <= B) { //System.out.println(digs + "" "" + r); solns.add(new Integer(rec)); } } count += solns.size(); } tc.setSolution(new Integer(count)); } private boolean valid(ArrayList digits, int startRotation) { if (digits.get(startRotation).intValue() == 0) {return false;} int len = digits.size(); for (int origLoc = 0; origLoc < len; origLoc++) { int rotLoc = (origLoc + startRotation) % len; int origDig = digits.get(origLoc); int rotDig = digits.get(rotLoc); if (rotDig > origDig) {return true;} if (rotDig < origDig) {return false;} } return false; } private int recombine(ArrayList digs, int start) { int tot = 0; for (int i = 0; i < digs.size(); i++) { int loc = (i + start) % digs.size(); tot += digs.get(loc).intValue() * (int)(Math.pow(10d, (double)(digs.size() - i - 1))); } return tot; } } " B20823,"package codejam.c; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; import codejam.TestCaseReader; public class Main { public static void main(String[] args) { TestCaseReader reader = new TestCaseReader(""in.txt"") { @Override protected int[] parseTestCase(String line) { String[] splitted = line.split(""\\s""); return new int[] { Integer.parseInt(splitted[0]), Integer.parseInt(splitted[1]) }; } }; BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(new File(""out.txt""))); } catch (IOException e) { e.printStackTrace(); } int testCases = reader.getTestCases(); int[] testCase = null; for (int i = 0; i < testCases; i++) { testCase = reader.getNextTestCase(); long result = Main.solveCase(testCase[0], testCase[1]); try { writer.write(""Case #"" + (i + 1) + "": "" + result); writer.newLine(); } catch (IOException e) { e.printStackTrace(); } } try { writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } private static long solveCase(int a, int b) { char[] bArray = Main.converToCharArray(b); Set counted = new HashSet(); for (int num = a; num <= b; num++) { char[] numArray = Main.converToCharArray(num); char[] numArrayPair = Main.converToCharArray(num); for (int i = 0; i < numArray.length - 1; i++) { Main.rotateCharArray(numArrayPair); if (Main.compare(numArrayPair, bArray) <= 0 && Main.compare(numArray, numArrayPair) < 0) { String pair = new String(numArray) + new String(numArrayPair); if (!counted.contains(pair)) { counted.add(pair); } } } } return counted.size(); } private static char[] converToCharArray(int num) { return new Integer(num).toString().toCharArray(); } private static void rotateCharArray(char[] array) { char tmp = array[array.length - 1]; for (int i = array.length - 1; i > 0; i--) { array[i] = array[i - 1]; } array[0] = tmp; } private static int compare(char[] a, char[] b) { for (int i = 0; i < a.length; i++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } return 0; } } " B20998,"import java.util.*; public class C { private int[] tens = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; public static void main(String[] args) { C c = new C(); c.solve(); } public void solve() { Scanner in = new Scanner(System.in); int t = in.nextInt(); for(int ii = 1; ii <= t; ++ii) { int a = in.nextInt(); int b = in.nextInt(); long total = 0; for(int check = a; check < b; ++check) { total += countRecycle(check, b); } System.out.printf(""Case #%d: %d\n"", ii, total); } } public int countRecycle(int num, int max) { int size = getSize(num); //12345, size = 4, 10000, size = 4, 9999, size = 3 HashSet valid = new HashSet(); for(int i = 1; tens[i] <= num; ++i) { int newNum = (num/tens[i]) + (num%tens[i])*(tens[size-i+1]); if(newNum <= max && newNum > num) valid.add(newNum); } return valid.size(); } public int getSize(int a) { int size = 0; while(tens[size] <= a) ++size; return size - 1; } }" B21873,"import java.io.*; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class RecycledNumbers { BufferedReader br; StringTokenizer st = new StringTokenizer(""""); private void solve() throws IOException { // final String IO_FILE = null; final String IO_FILE = ""./C/C-large""; final PrintWriter pw; if (IO_FILE == null) { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); } else { br = new BufferedReader(new FileReader(IO_FILE + "".in"")); pw = new PrintWriter(IO_FILE + "".out""); } int testCases = nextInt(); for (int ti = 1; ti <= testCases; ti++) { int a = nextInt(); int b = nextInt(); int ans = find(a, b); pw.println(""Case #"" + ti + "": "" + ans); } br.close(); pw.close(); } private int find(int a, int b) { int ans = 0; for (int n = a; n <= b; n++) { ans += check(n, b); } return ans; } private int check(final int n, final int b) { int length = 0, copy = n, pow10 = 1; while (copy > 0) { length++; copy /= 10; pow10 *= 10; } int firstDigitPow10 = pow10 / 10; int x = n; Set set = new HashSet(); for (int i = 0; i < length - 1; i++) { int lastDigit = x % 10; x /= 10; int m = lastDigit * firstDigitPow10 + x; if (lastDigit != 0 && n < m && m <= b) { set.add(m); } x = m; } return set.size(); } String nextString() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextString()); } public static void main(String[] args) throws IOException { new RecycledNumbers().solve(); } } " B20180,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Distincts { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(""input8.txt"")); BufferedWriter writer = new BufferedWriter(new FileWriter(""output1.txt"")); int cases = Integer.parseInt(reader.readLine()); for (int cs = 1; cs <= cases; cs++) { String line = reader.readLine(); String[] tokens = line.split("" ""); int count = 0; for (int i = Integer.parseInt(tokens[0]); i <= Integer.parseInt(tokens[1]); i++) { count += getGreaterRecycles(i, Integer.parseInt(tokens[1])); } writer.write(""Case #"" + cs + "": "" + count + ""\r\n""); } writer.close(); } static int getGreaterRecycles(int number, int max) { String ns = number + """"; Set result = new HashSet(); for (int i = 0; i < ns.length() - 1; i++) { ns = ns.substring(ns.length() - 1) + ns.substring(0, ns.length() - 1); int nr = Integer.parseInt(ns); if (nr > number && nr <= max) { result.add(nr); } } return result.size(); } } " B20793,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.falidae; import java.util.*; import java.io.*; /** * * @author LittleRock */ public class RecycledNumbers { public RecycledNumbers() { } public void init() { } public long solve(int a, int b) { Set valid = new HashSet(); long reval = 0l; for (int i = a; i <= b; i++) { String digits = Integer.toString(i); char last = digits.charAt(0); boolean allSame = true; for (int j = 1; j < digits.length(); j++) { if (digits.charAt(j) != last) { allSame = false; } } if (allSame) { continue; } int pow10a = 1; int pow10b = (int)Math.pow(10, digits.length()); valid.clear(); for (int j = 1; j < digits.length(); j++) { pow10a *= 10; pow10b /= 10; int front = i / pow10a; int back = i % pow10a; int shifted = back * pow10b + front; // System.out.println(""front "" + front + "", back "" + back); // System.out.println(""shifted "" + shifted); if (Integer.toString(shifted).length() == digits.length() && shifted <= b && shifted > i) { valid.add(shifted); } } // if (valid.size() > 0) { // System.out.println(i + "" cycle valid "" + valid.size()); // } reval += valid.size(); } return reval; } public static void main(String[] args) throws IOException { Scanner in = new Scanner(new FileReader(""in.txt"")); PrintWriter out = new PrintWriter(new FileWriter(""out.txt"")); RecycledNumbers solver = new RecycledNumbers(); int testCount = in.nextInt(); for (int i = 0; i < testCount; i++) { solver.init(); printIndex(i, out); out.print(solver.solve(in.nextInt(), in.nextInt())); out.println(); } in.close(); out.flush(); out.close(); } private static void printIndex(int i, PrintWriter out) { out.printf(""Case #%d: "", i + 1); } }" B20471,"package codejam.world2012.qualification.c; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class C { /** * @param args */ public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(""src/codejam/world2012/qualification/c/large.in"")); BufferedWriter out = new BufferedWriter(new FileWriter(""src/codejam/world2012/qualification/c/large.out"")); int T = 0; T = Integer.parseInt(in.readLine()); for (int t = 0; t < T; t++) { String[] line = in.readLine().split("" ""); Long answer = 0L; Long A = Long.parseLong(line[0]); Long B = Long.parseLong(line[1]); Set history = new HashSet(); for (Long n = A; n < B; n++) { String current = n.toString(); for (int i = current.length() -1; i> 0; i--) { StringBuilder recycled = new StringBuilder(); recycled.append(current.substring(i)); recycled.append(current.substring(0, i)); Long m = Long.parseLong(recycled.toString()); if ((m > n) && (B>= m)) { if (!history.contains(current +"":"" + recycled) && !history.contains(recycled +"":"" + current)) { answer++; history.add(current +"":"" + recycled); } } } } out.write(""Case #""+String.valueOf(t+1) +"": ""+answer.toString()); if (t < T-1) out.write(System.getProperty(""line.separator"")); } out.close(); } } " B20452,"import java.util.ArrayList; import java.io.IOException; public class exo2 { public static ArrayList listeCouple = new ArrayList() ; public static int T; public static int A ; public static int B ; public static int Result = 0 ; static int k ; static int l ; static int m ; static int n ; static int o ; static int p ; static int q ; public static void digit2(int A,int B,int D){ k = D%10 ; l = (D-k)/10 ; if((k*10+l)>=A && (k*10+l)<=B && (k*10+l)>D){ Result = Result + 1 ; } } public static void digit3(int A,int B,int D){ k = D%10 ; l = ((D-k)%100) /10; m = (D-l*10-k ) /100; if ((k*100+m*10+l)>=A &&(k*100+m*10+l)<=B && (k*100+m*10+l)>D ) { Result = Result + 1 ; } if ((l*100+k*10+m)>=A &&(l*100+k*10+m)<=B &&(l*100+k*10+m)>D ) { Result = Result + 1 ; } } public static void digit4(int A,int B,int D){ k = D%10 ; l = ((D-k)%100) /10; m = (D-l*10-k)%1000 /100 ; n = (D-m*100-l*10-k)/1000; if ((k*1000+n*100+m*10+l)>=A && (k*1000+n*100+m*10+l)<=B &&(k*1000+n*100+m*10+l)>D ){ Result = Result + 1 ; } if ((l*1000+k*100+n*10+m)>=A &&(l*1000+k*100+n*10+m)<=B &&(l*1000+k*100+n*10+m)>D ){ Result = Result + 1 ; } if ((m*1000+l*100+k*10+n)>=A &&(m*1000+l*100+k*10+n)<=B &&(m*1000+l*100+k*10+n)>D ){ Result = Result + 1 ; } } public static void digit5(int A,int B,int D){ k = D%10 ; l = ((D-k)%100) /10; m = (D-l*10-k)%1000 /100 ; n = ((D-m*100-l*10-k)%10000) / 1000; o = (D-n*1000-m*100-l*10-k)/10000 ; if ((k*10000+o*1000+n*100+m*10+l)>=A && (k*10000+o*1000+n*100+m*10+l)<=B && (k*10000+o*1000+n*100+m*10+l)>D) { Result = Result + 1 ; } if ((l*10000+k*1000+o*100+n*10+m)>=A && (l*10000+k*1000+o*100+n*10+m)<=B && (l*10000+k*1000+o*100+n*10+m)>D ) { Result = Result + 1 ; } if ((m*10000+l*1000*k*100+o*10+n)>=A && (m*10000+l*1000*k*100+o*10+n)<=B && (m*10000+l*1000*k*100+o*10+n)>D){ Result = Result + 1 ; } if ((n*10000+m*1000*l*100+k*10+o)>=A && (n*10000+m*1000*l*100+k*10+o)<=B && (n*10000+m*1000*l*100+k*10+o)>D){ Result = Result + 1 ; } } public static void digit6(int A,int B, int D){ k = D%10 ; l = ((D-k)%100) /10; m = (D-l*10-k)%1000 /100 ; n = ((D-m*100-l*10-k)%10000) / 1000; o = ((D-n*1000-m*100-l*10-k)%100000) /10000; p = (D-o*10000-n*1000-m*100-l*10-k)/100000 ; if ((k*100000+p*10000+p*1000+n*100+m*10+l)>=A && (k*100000+p*10000+p*1000+n*100+m*10+l)<=B && (k*100000+p*10000+p*1000+n*100+m*10+l)>D) { Result = Result + 1 ; } if ((l*100000+k*10000+p*1000+o*100+n*10+m)>=A && (l*100000+k*10000+p*1000+o*100+n*10+m)<=B && (l*100000+k*10000+p*1000+o*100+n*10+m)>D) { Result = Result + 1 ; } if ((m*100000+l*10000*k*1000+p*100+o*10+n)>=A && (m*100000+l*10000*k*1000+p*100+o*10+n)<=B && (m*100000+l*10000*k*1000+p*100+o*10+n)>D){ Result = Result + 1 ; } if ((n*100000+m*10000*l*1000+k*100+p*10+o)>=A && (n*100000+m*10000*l*1000+k*100+p*10+o)<=B && (n*100000+m*10000*l*1000+k*100+p*10+o)>D){ Result = Result + 1 ; } if ((o*100000+n*10000+m*1000*l*100+k*10+p)>=A && (o*100000+n*10000+m*1000*l*100+k*10+p)<=B && (o*100000+n*10000+m*1000*l*100+k*10+p)>D){ Result = Result + 1 ; } } public static void digit7(int A,int B,int D){ k = D%10 ; l = ((D-k)%100) /10; m = (D-l*10-k)%1000 /100 ; n = ((D-m*100-l*10-k)%10000) / 1000; o = ((D-n*1000-m*100-l*10-k)%100000) /10000; p = ((D-o*10000-n*1000-m*100-l*10-k)%1000000)/100000 ; q = (D-p*100000-o*10000-n*1000-m*100-l*10-k)/1000000 ; if ((k*1000000+q*100000+p*10000+o*1000+n*100+m*10+l)>=A && (k*1000000+q*100000+p*10000+o*1000+n*100+m*10+l)<=B && (k*1000000+q*100000+p*10000+o*1000+n*100+m*10+l)>D) { Result = Result + 1 ; } if ((l*1000000+k*100000+q*10000+p*1000+o*100+n*10+m)>=A && (l*1000000+k*100000+q*10000+p*1000+o*100+n*10+m)<=B && (l*1000000+k*100000+q*10000+p*1000+o*100+n*10+m)>D ) { Result = Result + 1 ; } if ((m*1000000+l*100000+k*10000+q*1000+p*100+o*10+n)>=A && (m*1000000+l*100000+k*10000+q*1000+p*100+o*10+n)<=B && (m*1000000+l*100000+k*10000+q*1000+p*100+o*10+n)>D){ Result = Result + 1 ; } if ((n*1000000+m*100000+l*10000+k*1000+q*100+p*10+o)>=A && (n*1000000+m*100000+l*10000+k*1000+q*100+p*10+o)<=B && (n*1000000+m*100000+l*10000+k*1000+q*100+p*10+o)>D){ Result = Result + 1 ; } if ((o*1000000+n*100000+m*10000+l*1000+k*100+q*10+p)>=A && (o*1000000+n*100000+m*10000+l*1000+k*100+q*10+p)<=B && (o*1000000+n*100000+m*10000+l*1000+k*100+q*10+p)>D){ Result = Result + 1 ; } if ((p*1000000+o*100000+n*10000+m*1000+l*100+k*10+q)>=A && (p*1000000+o*100000+n*10000+m*1000+l*100+k*10+q)<=B && (p*1000000+o*100000+n*10000+m*1000+l*100+k*10+q)>D){ Result = Result + 1 ; } } public static void traiter(int A,int B, int j) { int D = A ; if (B<10) { Result = 0 ; } else if (B<=100){ for (int i=0;i<(B-A);i++){ digit2(A,B,D+i); } } else if(B<1000){ for (int i=0;i<(B-A);i++){ digit3(A,B,D+i); } } else if(B<10000){ for (int i=0;i<(B-A);i++){ digit4(A,B,D+i); } } else if(B<100000){ for (int i=0;i<(B-A);i++){ digit5(A,B,A+i); } } else if(B<1000000){ for (int i=0;i<(B-A);i++){ digit6(A,B,A+i); } } else if(B<10000000){ for (int i=0;i<(B-A);i++){ digit7(A,B,A+i); } } } public static void read(String arg) throws java.io.IOException { java.util.Scanner lecteur ; java.io.File fichier = new java.io.File(arg); lecteur = new java.util.Scanner(fichier); T = lecteur.nextInt() ; for (int i=0;i<=T;i++){ if (lecteur.hasNextInt()){ A = lecteur.nextInt(); B = lecteur.nextInt() ; traiter(A,B,i); System.out.println(""Case #""+(i+1)+"": ""+Result); } Result = 0 ; listeCouple.removeAll(listeCouple) ; } } public static void main(String[] args) throws IOException{ String arg = null; arg = ""C-large.in"" ; read(arg) ; } }" B20360,"import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.Scanner; import java.util.TreeMap; /** * Created with IntelliJ IDEA. * User: akim * Date: 4/14/12 * Time: 7:45 PM * To change this template use File | Settings | File Templates. */ public class C { String makeHash(int a) { String t = Integer.toString(a); String ans = t; for (int i = 0; i < t.length(); ++i) { t = t.substring(1)+t.charAt(0); if (ans.compareTo(t) > 0) ans = t; } // System.out.println(a + "" - "" + ans); return ans; } void solve() throws FileNotFoundException { PrintWriter out = new PrintWriter(new FileOutputStream(""output.txt"")); Scanner in = new Scanner(new FileInputStream(""input.txt"")); int t = Integer.parseInt(in.nextLine()); System.err.println(t); TreeMap ans = new TreeMap(); for (int i = 0; i < t; ++i) { ans.clear(); int A = in.nextInt(); int B = in.nextInt(); for (int qqq = A; qqq <= B; ++qqq) { String hash = makeHash(qqq); if (!ans.containsKey(hash)) ans.put(hash, 0L); long tmp = ans.get(hash); ans.put(hash, tmp + 1); } long rrr = 0; /*for (int a = A; a <= B; ++a) for (int b = a + 1; b <= B; ++b) if (makeHash(a).equals(makeHash(b))) --rrr;*/ for (String h : ans.keySet()) { long tmp = ans.get(h); rrr += tmp * (tmp - 1) / 2; } out.println(""Case #"" + (i + 1) + "": "" + rrr); System.err.println((i + 1) + "" "" + rrr); } out.flush(); out.close(); } public static void main(String[] args) throws FileNotFoundException { new C().solve(); } } " B20414,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Number { public static void main(String[] args) throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(s.readLine()); for (int i = 1; i <= t; i++){ String[] a = s.readLine().split("" ""); int A = Integer.parseInt(a[0]); int B = Integer.parseInt(a[1]); int temp = 0; int result = 0; for (int j = A; j < B; j++) { String str = """" + j ; int n = str.length(); for (int k = 1; k < n; k++) { str = """" + str.charAt(n-1) + str.substring(0, n-1); temp = Integer.parseInt(str); if (temp > j && temp <= B) result++; } } System.out.println(""Case #""+ i + "": ""+ result); } } }" B20284,"import java.util.Scanner; public class Utils { public static int readIntegerLine(Scanner sc) { String s = readStringLine(sc); return Integer.parseInt(s); } public static String readStringLine(Scanner sc) { return sc.nextLine(); } public static int readInteger(Scanner sc) { return sc.nextInt(); } } " B20694,"package org.moriraaca.codejam.recyclednumbers; import org.moriraaca.codejam.AbstractTest; import org.moriraaca.codejam.TestConfiguration; @TestConfiguration(solverClass = RecycledNumbersSolver.class) public class RecycledNumbers extends AbstractTest { public RecycledNumbers(String fileName) { super(fileName); } } " B20267,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; public class C { /** * @param args */ static String n; static int count = 0; static String h; static int t ; static ArrayList memo = new ArrayList(); static ArrayList old = new ArrayList(); public static int solve(int s, int e){ count = 0 ; memo.clear(); old.clear(); for (int i = s; i <= e; i++) { n = i+""""; in:for (int j = 0; j < n.length(); j++) { h = n.substring(n.length()-j) + n.substring(0,n.length()-j); t = Integer.parseInt(h); if (t <= e && t>i ) { for (int k = 0; k < memo.size(); k++) { if (memo.get(k)==t && old.get(k)==i) continue in; } memo.add(t); old.add(i); count++; } } } return count; } static BitSet v1 = new BitSet(2000000); static int [] index = new int[2000000]; public static int solve2(int s, int e){ count = 0; v1.clear(); Arrays.fill(index, 0,0,e); for (int i = s; i <= e; i++) { n = i+""""; for (int j = 0; j <= n.length(); j++) { h = n.substring(n.length()-j) + n.substring(0,n.length()-j); t = Integer.parseInt(h); if (t <= e && t >i ) { if (v1.get(i) && index[i]==t) continue; count++; v1.set(i); index[i] = t ; } } } return count; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(""c.in"")); BufferedWriter bw = new BufferedWriter(new FileWriter(""c.out"")); int n; int t = Integer.parseInt(br.readLine().trim()); String ss[]; for (int i = 1; i <= t; i++) { ss= br.readLine().split("" ""); n = solve2(Integer.parseInt(ss[0]), Integer.parseInt(ss[1])); // System.out.println(""Case #""+i+"": ""+n); bw.write(""Case #""+i+"": ""+n); bw.newLine(); } bw.close(); } } " B22131,"package c; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { Set[] c = new HashSet[2000001]; public C() { Scanner s = new Scanner(System.in); int t = s.nextInt(); for(int i =0; i < t;i ++) { int a = s.nextInt(); int b = s.nextInt(); for(int j = a; j <=b; j++) { c[j]= new HashSet(); } int digits = (a+"""").toCharArray().length; for(int j = Math.min(a, b); j<=Math.max(a, b); j++) { int newJ = j; for(int k = 1; k < digits; k++) { int dig = newJ%10; newJ = newJ/10; newJ += dig*Math.pow(10, digits-1); if(newJ>=a && newJ<=b && newJ!=j) { int min = Math.min(newJ, j); int max = Math.max(newJ, j); c[min].add(max); //System.out.println(j+"" ""+min+"" ""+max); } } } long tot = 0; for(int j = a; j <=b; j++) { tot+=c[j].size(); } System.out.println(""Case #""+(i+1)+"": ""+tot); } } /** * @param args */ public static void main(String[] args) { new C(); } } " B20561,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int cases = Integer.parseInt(br.readLine().trim()); for(int t=1;t<=cases;t++){ String[] inp=br.readLine().trim().split("" ""); int start=Integer.parseInt(inp[0]); int end=Integer.parseInt(inp[1]); System.out.println(""Case #""+t+"": ""+getAns(start, end)); } } public static long getAns(int start, int end){ boolean[] visited=new boolean[end+1]; long total=0; int max=0; int digitCount=1; int mult=10; while(start/(mult) !=0){ digitCount++; mult*=10; } for(int n=start;n<=end;n++){ int count=1; if(visited[n]) continue; visited[n]=true; for(int s=1;s=start && o<=end && !visited[o]){ if(rem/(Math.pow(10,digitCount-s-1))>0){ if(o!=n){ count++; visited[o]=true; } } } } total+=count*(count-1)/2; } return total; } } " B20720,"package com.clausewitz.codejam.qr2012; import java.io.IOException; import java.util.StringTokenizer; import com.clausewitz.codejam.Solver; public class Recycled extends Solver { private int A = 0; private int B = 0; @Override public void readProblem() throws IOException { String line = fileIn.readLine(); StringTokenizer st = new StringTokenizer(line); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); } @Override public void algorithm(int idx) { int count = 0; for(int i=A;i<=B;++i) { String original = """" + i; String candidate = original; while(true) { candidate = rotate(candidate); if(candidate.equalsIgnoreCase(original)) break; int n = Integer.parseInt(candidate); if(n>=A && n<=B) ++count; } } answer[idx] = """" + count/2; } private String rotate(String s) { if(s.length()==1) return s; return s.substring(1, s.length()) + s.charAt(0); } } " B21421,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.TreeSet; public class prob2 { private static long oneTest(int a, int b){ boolean [] bool=new boolean[b+1]; long res=0; for(int i=a; i<=b; i++){ if(bool[i]) continue; res+=pairs(i, bool, a, b); } return res; } private static long pairs(int j, boolean []bool, int a, int b){ String str=Integer.toString(j); int len=str.length(); TreeSet set=new TreeSet(); for(int i=0; i<=str.length(); i++){ int c=Integer.parseInt(str); if(Integer.toString(c).length()!=len||(cb)) { str=str.substring(len-1)+str.substring(0,len-1); continue; } str=str.substring(len-1)+str.substring(0,len-1); bool[c]=true; set.add(c); } long res=set.size(); res*=(set.size()-1); res/=2; return res; } public static void main(String args[]) throws IOException{ PrintWriter out=new PrintWriter(new FileWriter(""result.txt"")); BufferedReader in=new BufferedReader(new FileReader(""C-large.in"")); //BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); // System.out.print(oneTest(10, 40)); int n=Integer.parseInt(in.readLine()); for(int i=1; i<=n; i++){ String str=in.readLine(); out.print(""Case #""+i+"": ""); StringTokenizer tok=new StringTokenizer(str); out.print(oneTest(Integer.parseInt(tok.nextToken()), Integer.parseInt(tok.nextToken()))); out.println(); System.out.println(i); } out.flush(); System.out.println(""over""); } } " B20231,"package qualification.c; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import common.ClockWatch; import common.ISolver; import common.QuestionHandler; public class RecycledNumbers implements ISolver { private int addCountSign(Set signatures, Set tmpSig, int val, int min, int max) { String valStr = String.valueOf(val); int len = valStr.length(); char[] chars = new char[len * 2]; for (int i = 0; i < len; ++i) { chars[i] = valStr.charAt(i); chars[i + len] = valStr.charAt(i); } int presentSigCount = 0; tmpSig.clear(); for (int i = 1; i < len; ++i) { if (chars[i] != '0') { Integer sig = Integer.valueOf(new String(chars, i, len)); if (sig >= min && sig <= max) { if (tmpSig.add(sig) && signatures.contains(sig)) { ++presentSigCount; } } } } signatures.add(val); return presentSigCount; } @Override public String solve(String problem) { Scanner scan = new Scanner(problem); int min = scan.nextInt(); int max = scan.nextInt(); Set signatures = new HashSet(); Set tmpSig = new HashSet(); int result = 0; for (int i = min; i <= max; ++i) { result += addCountSign(signatures, tmpSig, i, min, max); } return String.valueOf(result); } @Override public void addCase(String problem, String answer) { String myAnswer = solve(problem); if (!myAnswer.equals(answer)) { throw new RuntimeException(""Invalid prediction for '"" + problem + ""'. Expected '"" + answer + ""' got '"" + myAnswer + ""'""); } } public static void main(String[] args) { ClockWatch watch = new ClockWatch(); QuestionHandler questionHandler = new QuestionHandler( new RecycledNumbers()); questionHandler.addResource(""sample.in"", ""sample.out""); watch.tic(); // System.out.println(""Sample input:""); // questionHandler.solve(""sample.in"", ""sample.out""); // System.out.println(""\nSmall input:""); // questionHandler.solve(""small.in"", ""small.out""); System.out.println(""\nLarge input:""); questionHandler.solve(""large.in"", ""large.out""); watch.printTocSecs(); } } " B20876,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashMap; import java.util.LinkedList; class RecycledNumbers { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println(""Input? ""); String input = in.readLine(); if(!input.equals(""System.in"")) { in = new BufferedReader(new FileReader(new File(input))); } PrintStream out; out = new PrintStream(new File(""C.out"")); //out = System.out; int cases = Integer.parseInt(in.readLine()); for(int i = 1; i <= cases; i++) { String[] line = in.readLine().split("" ""); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); int recycledPairs = 0; HashMap> cache = new HashMap>(); for(int n = A; n < B; n++) { String nStr = Integer.toString(n); for(int wrap = 0; wrap < nStr.length(); wrap++) { String mStr = recycle(nStr, wrap); int m = Integer.parseInt(mStr); if(A <= n && n < m && m <= B) { //System.out.println(A + ""<="" + nStr + ""<"" + mStr + ""<="" + B); if(cache.get(n) == null) { cache.put(n, new LinkedList()); cache.get(n).add(m); recycledPairs++; } else if(!cache.get(n).contains(m)) { cache.get(n).add(m); recycledPairs++; } } } } out.print(""Case #"" + i + "": "" + recycledPairs); if(i != cases) out.println(); } if(out != System.out) out.close(); } public static String recycle(String number, int offset) { offset = offset > number.length() - 1 || offset < 0 ? offset % number.length() : offset; if(offset == 0) return number; char[] oldNumber = number.toCharArray(); char[] newNumber = new char[number.length()]; System.arraycopy(oldNumber, offset, newNumber, 0, number.length() - offset); System.arraycopy(oldNumber, 0, newNumber, number.length() - offset, offset); return new String(newNumber); } }" B22081,"package gcj; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; public abstract class SolverBase { public static final String TOKEN_SEPARATOR = "" ""; public static final String IMPOSSIBLE = ""IMPOSSIBLE""; public String problemName; public boolean verbose = false; public SolverBase(String problemName) { this.problemName = problemName; } public void solve(InputStream in, PrintStream out) throws Exception { InputStreamReader isr = new InputStreamReader(in); BufferedReader reader = new BufferedReader(isr); long N = Long.parseLong(reader.readLine()); for (long i = 1; i <= N; i++) { out.print(""Case #"" + i + "": ""); solveSingle(reader, out); } } public abstract void solveSingle(BufferedReader reader, PrintStream out) throws Exception; public long[] readSingleLineLongArray(BufferedReader reader) throws Exception { String[] longsAsStrings = readSingleLineStringArray(reader); long[] longs = new long[longsAsStrings.length]; for (int i = 0; i < longsAsStrings.length; i++) { longs[i] = Long.parseLong(longsAsStrings[i]); } return longs; } public int[] readSingleLineIntArray(BufferedReader reader) throws Exception { String[] intsAsStrings = readSingleLineStringArray(reader); int[] ints = new int[intsAsStrings.length]; for (int i = 0; i < intsAsStrings.length; i++) { ints[i] = Integer.parseInt(intsAsStrings[i]); } return ints; } public String[] readSingleLineStringArray(BufferedReader reader) throws Exception { String line = reader.readLine(); if (verbose) { System.out.println(""Reading line "" + line); } return line.split(TOKEN_SEPARATOR); // return StringUtils.split(line, TOKEN_SEPARATOR); } public String[][] readStringArrays(BufferedReader reader, int lines) throws Exception { String[][] arrays = new String[lines][]; for (int i = 0; i < lines; i++) { arrays[i] = readSingleLineStringArray(reader); } return arrays; } public char[][] readCharArrays(BufferedReader reader, int lines) throws Exception { char[][] arrays = new char[lines][]; for (int i = 0; i < lines; i++) { String line = reader.readLine(); arrays[i] = line.toCharArray(); } return arrays; } public long[][] readLongArrays(BufferedReader reader, int lines) throws Exception { long[][] arrays = new long[lines][]; for (int i = 0; i < lines; i++) { arrays[i] = readSingleLineLongArray(reader); } return arrays; } protected void check(boolean b) { if (!b) { throw new IllegalStateException(""Check failed""); } } } " B21299,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashSet; import java.util.Set; public class ProB { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub File infile = new File(""C-large.in""); File outfile = new File(""out.txt""); BufferedReader reader = null; BufferedWriter writer = null; try{ reader = new BufferedReader(new FileReader(infile)); writer = new BufferedWriter(new FileWriter(outfile)); String ss = reader.readLine(); String out; String []nums; int t = Integer.parseInt(ss),i,j,res; int a,b; for(i=1;i<=t;i++){ out = ""Case #"" + i + "": ""; ss = reader.readLine(); nums = ss.split("" ""); a = Integer.parseInt(nums[0]); b = Integer.parseInt(nums[1]); res = 0; for(j=a;j= 10){ head = p / base; tail = p % base; if(tail >= (base / 10)){ tail *= max / base; tail += head; if(tail > p && tail <=b) { if(!set.contains(tail)){ set.add(tail); res++; } } } base /= 10; } return res; } private static void sort(int []scores,int n) { int i,j,t,s; for(i=0;i s){ s = scores[j]; t = j; } } s = scores[i]; scores[i] = scores[t]; scores[t] = s; } } } " B22143,"import java.io.File; import java.util.ArrayList; import java.util.Formatter; import java.util.List; import java.util.Scanner; public class recycled { static int A; static int B; static int count=0; static int n; private static Scanner x; private static Formatter y; static String newline = System.getProperty(""line.separator""); static List words = new ArrayList(); static int testCases; public static void main(String args[]){ // open input file try{ x= new Scanner(new File(""C-large.in"")); }catch(Exception e){ System.out.println(""Could not find the file""); } while(x.hasNext()){ words.add(x.nextLine()); } testCases=Integer.parseInt(words.get(0)); words.remove(0); int cnt=0; // create output file try{ y= new Formatter(""recycled.ou""); //System.out.println(""sampleTongue.ou has been created""); }catch(Exception e){ System.out.println(""Could not create a file""); } //evaluate for(int k=0; kn && m<=B){ count++; System.out.println(n+"" ""+m); } //copying for(int j=0; j loadFromFile(String infile) { //inc checks on #lines, length of splits, etc. BufferedReader br = Utils.newBufferedReader(infile); ArrayList tcList = new ArrayList<>(); //first line is N, the number of test cases Integer N = Utils.readInteger(br); //cycle through N test cases for (int x = 0; x < N; x++) { TestCase tc = new TestCase(); tc.setRef(x + 1); /////////////////////////////////////////////////////////// //load properties - the bit to customise per problem ArrayList l = Utils.readIntegerList(br, 2); tc.setIntegerList(""a_b"", l); /////////////////////////////////////////////////////////// tcList.add(tc); } //confirm end of file if (Utils.readLn(br) != null) { Utils.die(""Unexpected text at end of infile""); } return tcList; } public static ArrayList mockUp() { ArrayList tcList = new ArrayList<>(); for (int i = 0; i < 10; i++) { TestCase tc = new TestCase(); tc.setRef(i); int[] xs = Utils.randomIntegerArray(100, -50, 50, i * 2); int[] ys = Utils.randomIntegerArray(100, -50, 50, i * 2 + 1); tc.setIntegerList(""xs"", Utils.arrayToArrayList(xs)); tc.setIntegerList(""ys"", Utils.arrayToArrayList(ys)); tcList.add(tc); } return tcList; } public static void writeSolutions(ArrayList tcList, String outfile) { BufferedWriter bw = Utils.newBufferedWriter(outfile, false); for (int i = 0; i < tcList.size(); i++) { TestCase tc = tcList.get(i); Object solution = tc.getSolution(); String line = ""Case #"" + (i + 1) + "": "" + solution.toString(); Utils.writeLn(bw, line); } Utils.closeBw(bw); } } " B21454,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import util.MyUtil; public class ProblemC { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws Exception { String title = ""C-small-attempt0.in""; BufferedReader reader = MyUtil.getReader(title); int caseNumber = Integer.parseInt(reader.readLine()); BufferedWriter writer = MyUtil.getWriter(title); for (int i = 0 ; i < caseNumber; i++){ String line = reader.readLine(); String result = subRoutine(line); writer.write(""Case #"" + (i + 1) + "": "" + result + ""\n""); System.out.println(""Case #"" + (i + 1) + "": "" + result); } writer.flush(); } private static String subRoutine(String line){ StringBuilder sb = new StringBuilder(); String[] elements = line.split("" ""); long A = Long.parseLong(elements[0]); long B = Long.parseLong(elements[1]); long count = 0; for (long n = A ; n < B ; n++){ Set ms = new HashSet(); String str = String.valueOf(Math.abs((long)n)); String newn = Long.toString(n); for (int i = 1; i < str.length(); i++){ newn = shift(newn); long m = Long.parseLong(newn); if (m > n && m <= B && m > A){ ms.add(m); //System.out.println(n + "" : "" + m); test(n,m); } } count += ms.size(); } sb.append(count); return sb.toString(); } public static boolean test(long n, long m){ String nstr = Long.toString(n); String mstr = Long.toString(m); for (int i = 0; i < nstr.length(); i++){ nstr = nstr.charAt(nstr.length() - 1) + nstr; nstr = nstr.substring(0, mstr.length()); if (nstr.equals(mstr)){ return true; } } return false; } private static String shift(String nstr){ long n = Long.parseLong(nstr); StringBuilder shifted = new StringBuilder(); long last = n % 10; shifted.append(last); for (int i = 0; i < nstr.length() - 1; i++){ shifted.append(nstr.charAt(i)); } return shifted.toString(); } } " B20511,"import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.*; public class main { static int numberPeriod(int n, int len) { if (len == 2 && n / 10 == n % 10) return 1; if (len == 4 && n % 100 == n / 100) return 2; if (len == 6 && n % 100 == n / 10000 && n % 100 == n / 100 % 100) return 2; if (len == 6 && n % 1000 == n / 1000) return 3; return len; } static int numberLength(int n) { int len = 0; while (n > 0) { n /= 10; len++; } return len; } public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File(""C-large.in"")); PrintWriter out = new PrintWriter(""result.txt""); int tests = sc.nextInt(); for (int t = 1; t <= tests; t++) { int a = sc.nextInt(), b = sc.nextInt(), length = numberLength(a), tt = (int) Math.pow(10, length - 1), res = 0; for (int j = a; j <= b; j++) { int cur = j; int val = j; int per = numberPeriod(j, length); for (int k = 0; k < per; k++) { int c = val % 10; val = val / 10 + c * tt; if (val > cur && val <= b) { res++; } } } out.printf(""Case #%d: %d\n"",t,res); } out.flush(); } }" B20202," package recyclednumbers; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; public class RecycledNumbers { public static void main(String[] args) { int result= 0 ,x,y,counter,num,count; String SoX,temp; int[] array = new int[7]; int cntarray=0; boolean flag = true; PrintWriter pw = null; Scanner sc = null; try { sc = new Scanner(new FileReader(""C:\\Users\\gad\\Downloads\\C-large(1).in"")); pw = new PrintWriter(new FileWriter(""D:\\mystudy\\RCLoutput.out"")); int cc=Integer.parseInt(sc.nextLine()); for(int cnt=0;cnt1) { temp = temp.substring(1,counter) + temp.charAt(0); num = Integer.parseInt(temp); for (int t=0;t=x&&jn && r<=B){ result++; } }while(r!=n); } } fw.write(""Case #""+i+"": ""+result+""\n""); } fw.close(); } private static String shiftLeft(String rStr){ char[] rChars = rStr.toCharArray(); char temp = rChars[0]; for(int i=0; i set = new HashSet(); public static void main(String[] args) { Cycle c = new Cycle(); c.start(args[0]); } private void start(String filename) { try { BufferedReader br = new BufferedReader(new FileReader(filename)); int N = Integer.parseInt(br.readLine()); int n = 1; while (n <= N) { StringTokenizer st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int COUNT = 0; set.clear(); for (int i = A; i <= B; i++) { String iNum = """" + i; int iDigitCount = iNum.length(); for (int j = 0; j < iDigitCount; j++) { iNum = getRecycled(iNum); int recycled = Integer.parseInt(iNum); int recycledDigitCount = iNum.length(); if ( (i < recycled) && (A <= i && recycled <= B) && (recycledDigitCount == iDigitCount) ) { String entry = String.format(""%d|%d"", i, recycled); if (!set.contains(entry)) { set.add(entry); COUNT++; //System.out.println(String.format(""%d | %d"", i, // recycled)); } //else // System.out.println(entry); } } } System.out.println(String.format(""Case #%d: %s"", n,COUNT)); n++; } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private String getRecycled(String i) { String s = new String(i + """"); String s2 = s.substring(s.length() - 1); s = s.substring(0, s.length()-1); s = s2 + s; return s; } } " B20403,"package boy0; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CodeJam_C_Small { public static void main(String[] args) throws IOException { String strLine; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); CodeJam_C_Small me = new CodeJam_C_Small(); // me.init(); strLine = br.readLine(); int T = Integer.parseInt(strLine); String[] as; char[] a, b; int y; for (int x = 1; x <= T; x++) { strLine = br.readLine(); as = strLine.split("" ""); a = as[0].toCharArray(); b = as[1].toCharArray(); y = me.get_num_recycled_pairs(a, b); System.out.println(""Case #"" + x + "": "" + y); } } // 1 ¡Â A ¡Â B ¡Â 2000000. max length = 7 private char[] recycled = new char[16]; // (max+1)*2 = 8*2 = 16 private int r_length = 0; private char[] b; private int b_length = 0; // A ¡Â n < m ¡Â B public int get_num_recycled_pairs(char[] a, char[] b_) { int y = 0; int a_length = a.length; b = b_; b_length = b.length; // r = a (&& a); r_length = a_length; for (int i = 0; i < a_length; i++) { recycled[i] = a[i]; recycled[i + r_length] = a[i]; } // while r <= b while (comp(recycled, 0, r_length, b, 0, b_length) <= 0) { // check each r-pair for (int i = 1; i < r_length; i++) { if (is_recycled_pair(i)) { y++; } } // r++; add_1_r(); } return y; } // < : -x , == : 0, > : +x private int comp(char[] c1, int c1_offset, int c1_length, char[] c2, int c2_offset, int c2_length) { int x = c1_length - c2_length; if (x == 0) { for (int i = 0; i < c2_length; i++) { x = c1[c1_offset + i] - c2[c2_offset + i]; if (x != 0) { break; } } } return x; } private boolean is_recycled_pair(int offset) { // n = r[0] , m = r[offset] // n >= m ? false if (comp(recycled, 0, r_length, recycled, offset, r_length) >= 0) { return false; } // m > b ? false if (comp(recycled, offset, r_length, b, 0, b_length) > 0) { return false; } // r[offset] == r[x] ? false (0 < x < offset) for (int x = 1; x < offset; x++) { if (comp(recycled, offset, r_length, recycled, x, r_length) == 0) { return false; } } // System.out.println(""r:"" + new String(recycled) + ""\t offset:"" + offset); return true; } // r++ private void add_1_r() { for (int i = r_length - 1; i >= 0; i--) { if (recycled[i] == '9') { recycled[i] = '0'; recycled[i + r_length] = recycled[i]; } else { recycled[i] = (char) (recycled[i] + 1); recycled[i + r_length] = recycled[i]; return; } } // here, length overflow r_length++; for (int i = r_length - 1; i >= 1; i--) { recycled[i] = recycled[i - 1]; recycled[i + r_length] = recycled[i]; } recycled[r_length] = recycled[0] = '1'; } } " B21523," import java.io.*; import java.util.*; public class Q3 { public static void main(String[] args) { Q3 q = new Q3(); //System.out.println(q.calculate(1090000, 1900000)); //q.test(); //q.answerSmall(); q.answerLarge(); } public void answerSmall(){ read(""C-small-attempt0.IN"", ""Q3_small_output.txt""); } public void answerLarge(){ read(""C-large.IN"", ""Q3_large_output.txt""); } public void test(){ read(""Test3_input.txt"", ""Test3_output.txt""); } public void read(String readFrom, String writeTo){ try{ Scanner in = new Scanner(new File(readFrom)); File f = new File(writeTo); FileWriter fw = new FileWriter(f); int T = Integer.parseInt(in.nextLine()); int A, B; String[] input; String answer; for(int i = 1; i <= T; i++) { input = in.nextLine().split("" ""); A = Integer.parseInt(input[0]); B = Integer.parseInt(input[1]); answer = """" + calculate(A, B); if(i + 1 <= T) answer += ""\r\n""; fw.write(""Case #"" + i + "": "" + answer); } fw.close(); }catch(Exception ex) { System.out.println(ex); } } public int calculate(int A, int B) { int num = 0, m; String hold; ArrayList distinct = new ArrayList(); for(int n = A; n <= B; n++) { if(n > 10) { hold = """" + n; distinct.clear(); for(int i = 1; i < hold.length(); i++) { m = Integer.parseInt((hold.substring(i) + hold.substring(0,i))); if(m <= B && n < m && !distinct.contains(m)) { distinct.add(m); num++; } } } } return num; } } " B21623," import java.util.HashSet; import java.util.Scanner; /** * @author Anil Kishore, India */ public class Qual_C { static int get(int x, int A, int B) { int r = 0; String s =""""+x; HashSet set = new HashSet(); for(int i=1;i s = new HashSet(); int x = i; for (int j = 0; j < n; ++j) { int y = x % 10 * m + x / 10; if (y > i && y <=b && !s.contains(y)) { r ++; s.add(y); } x = y; } } return r; } public static void main(String[] args) throws Exception { //InputStream in = System.in; InputStream in = new FileInputStream(""c:\\C-large.in""); Scanner scanner = new Scanner(in); //BufferedReader r = new BufferedReader(new InputStreamReader(in)); /* for (;;) { String l = r.readLine(); if (l == null) { break; } } */ int n; n = scanner.nextInt(); for (int i = 1; i <= n; ++i) { int a = scanner.nextInt(); int b = scanner.nextInt(); System.out.println(""Case #"" + i + "": "" + gao(a,b)); } } } " B21037,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.lang.reflect.Array; import java.util.ArrayList; public class C { private static ArrayList makeCycle(ArrayList digits) { if (digits.size() == 1) { return new ArrayList(digits); } ArrayList cycle = new ArrayList(); int tail = 0; while (tail < digits.size() && digits.get(tail) == 0) { ++tail; } cycle = new ArrayList(digits.subList(tail + 1, digits.size())); for (int i = 0;i <= tail; ++i) { cycle.add(digits.get(i)); } return cycle; } private static boolean sequenceEquals(ArrayList sec1, ArrayList sec2) { for (int i = 0;i < sec1.size(); ++i) { if (sec1.get(i) != sec2.get(i)) { return false; } } return true; } private static long value(ArrayList digits) { long val = 0; long pow = 1; for (int i = 0;i < digits.size(); ++i) { val += digits.get(i) * pow; pow *= 10; } return val; } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StreamTokenizer tokenizer = new StreamTokenizer(in); int tests; tokenizer.nextToken(); tests = (int)tokenizer.nval; int[] answers = new int[tests]; for (int i = 0;i < tests; ++i) { long A, B; tokenizer.nextToken(); A = (long)tokenizer.nval; tokenizer.nextToken(); B = (long)tokenizer.nval; for (long n = A; n <= B; ++n) { ArrayList digits = new ArrayList(); long v = n; while (v > 0) { digits.add(Byte.valueOf(Long.toString(v % 10))); v = v / 10; } ArrayList cycled = new ArrayList(digits); while (!sequenceEquals(cycled = makeCycle(new ArrayList(cycled)), digits)) { long val = value(cycled); if (val <= B && val > n) { ++answers[i]; } } } } for (int i = 0;i < tests; ++i) { System.out.println(""Case #"" + (i + 1) + "": "" + answers[i]); } } } " B20520,"import java.util.*; import java.io.*; public class c{ public static void main(String[] args)throws IOException{ Scanner br = new Scanner(new File(""c.in"")); PrintWriter out = new PrintWriter(new File(""c.out"")); int cases = br.nextInt(); for(int i = 0;i seen = new HashSet(); for(int k = 1;k b){ continue; } count++; } } } out.println(""Case #""+(i+1)+"": ""+count); } out.close(); } } " B20864,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; public class RecycledNumbers { HashSet rnumsPairs = new HashSet(); PrintWriter out = null; BufferedReader in = null; public RecycledNumbers() { try { out = new PrintWriter(new FileWriter(""B-small-practice.out"")); in = new BufferedReader(new FileReader(""C-large.in"")); } catch (IOException e) { e.printStackTrace(); } } public void getRecycleNumbers(int num, int A, int B) { String aux = num + """"; int an = 0; int len = aux.length(); String rnum = """"; int rn = 0; for (int i = 1; i < len; i++) { rnum = aux.substring(i) + aux.substring(0, i); rn = Integer.parseInt(rnum); an = Integer.parseInt(aux); if ((rn > A) && (rn <= B) && (an < rn)) { Pair p = new Pair(an, rn); rnumsPairs.add(p); } } } public void getCount(int A, int B) { for (int i = A; i <= B; i++) { getRecycleNumbers(i, A, B); } } /** * @param args */ public static void main(String[] args) { RecycledNumbers rn = new RecycledNumbers(); try { int nt = Integer.parseInt(rn.in.readLine()); String num[] = new String[2]; for (int i = 1; i <= nt; i++) { num = rn.in.readLine().split("" ""); int A = Integer.parseInt(num[0]); int B = Integer.parseInt(num[1]); rn.getCount(A, B); rn.out.println(""Case #"" + i + "": "" + rn.rnumsPairs.size()); rn.rnumsPairs.clear(); } } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } rn.out.close(); } } class Pair { int a = 0; int b = 0; public Pair(Integer a, Integer b) { this.a = a; this.b = b; } public boolean equals(Object o) { if (o == null) { return false; } if (!(o instanceof Pair)) return false; Pair p = (Pair) o; if (((p.a == a) && (p.b == b)) || ((p.a == b) && (p.b == a))) { return true; } return false; } public int hashCode() { int hcode = a + """".hashCode() + b + """".hashCode(); return hcode; } } " B20479,"package codejam2012.qualifier; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { private int noOfCases; private int currentCase; private BufferedReader reader; private BufferedWriter writer; String str; String a,b; long aLong, bLong; long noOfRecycledNumbers; public static void main(String[] args) throws Exception { // new RecycledNumbers().solveProblem(""input/2012Qualifier/C-small-attempt0.in.txt"", ""input/2012Qualifier/C-small-attempt0.out.txt""); new RecycledNumbers().solveProblem(""input/2012Qualifier/C-large.in.txt"", ""input/2012Qualifier/C-large.out.txt""); } private void solveProblem(String inputFileName, String outputFileName) throws Exception { reader = new BufferedReader(new FileReader(inputFileName)); writer = new BufferedWriter(new FileWriter(outputFileName)); try { String str = reader.readLine(); noOfCases = Integer.parseInt(str); currentCase = 0; for(int i=0;i recycled = new HashSet(); for(int index=1; index < length; index++) { boolean lowerLimitBreached = true; for(int i=0;i nChar) { lowerLimitBreached = false; break; } else if(mChar < nChar) { lowerLimitBreached = true; break; } } if(lowerLimitBreached) continue; boolean upperLimitBreached = false; for(int i=0;i mChar) { upperLimitBreached = false; break; } else if(bChar < mChar) { upperLimitBreached = true; break; } } if(upperLimitBreached) continue; StringBuilder strBuilder = new StringBuilder(); for(int i=0;i M = new LinkedList(); for (int i = 1; i < s.length(); i++) { boolean flag = false; String temp = """"; temp = s.substring(s.length() - i, s.length()) + s; int t = Integer.parseInt(temp.substring(0, s.length())); for (int k = 0; k < M.size(); k++) { if (t == M.get(k)) { flag = true; break; } } if (!flag) M.add(t); } int res[] = new int[M.size()]; for (int i = 0; i < M.size(); i++) { res[i] = M.get(i); } return res; } public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File(""C-large.in"")); // Scanner in = new Scanner(System.in); BufferedWriter out = null; try { FileWriter fstream = new FileWriter(""out.txt""); out = new BufferedWriter(fstream); int cases = in.nextInt(); int A; int B; for (int i = 0; i < cases; i++) { int result = 0; A = in.nextInt(); B = in.nextInt(); for (int j = A; j < B + 1; j++) { int[] Ms = getM(j); for (int k = 0; k < Ms.length; k++) { if (Ms[k] > j && Ms[k] <= B) { result++; } } } out.write(""Case #"" + (i + 1) + "": "" + result + ""\n""); System.out.println(""Case #"" + (i + 1) + "": "" + result); } out.close(); } catch (Exception e) {// Catch exception if any System.err.println(""Error: "" + e.getMessage()); } } } " B21871,"import java.io.FileNotFoundException; import java.io.FileReader; import java.util.HashSet; import java.util.Iterator; import java.util.Scanner; public class RecycledNumbers { public static int recycle(int source, int digits) { int pow = (int) Math.pow(10, digits - 1); int mod = source % 10; return pow * mod + source / 10; } public static class Range { public final int A; public final int B; public Range(int A, int B) { this.A = A; this.B = B; } } public static Iterator iterator(Readable input) { final Scanner scanner = new Scanner(input); return new Iterator() { private int cases = scanner.nextInt(); @Override public boolean hasNext() { return cases > 0; } @Override public Range next() { int A = scanner.nextInt(); int B = scanner.nextInt(); cases--; return new Range(A, B); } @Override public void remove() { throw new AbstractMethodError(); } }; } public static int recycledPairs(Range scores) { int digits = Integer.toString(scores.A).length(); HashSet pairs = new HashSet(); for (int i = scores.A; i <= scores.B; i++) { int recycled = recycle(i, digits); while (recycled != i) { if (recycled >= scores.A && recycled <= scores.B) { int first = i < recycled ? i : recycled; int second = i > recycled ? i : recycled; pairs.add(String.format(""%d%d"", first, second)); } recycled = recycle(recycled, digits); } } return pairs.size(); } public static void main(String[] args) throws FileNotFoundException { FileReader fileReader = new FileReader(args[0]); int caseId = 1; Iterator iterator = iterator(fileReader); while (iterator.hasNext()) { int result = recycledPairs(iterator.next()); System.out.format(""Case #%s: %s\n"", caseId, result); caseId++; } } } " B21864,"package gcj12; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class C { void solve() { Scanner scan = new Scanner(System.in); int tCase = scan.nextInt(); for (int i = 1; i <= tCase; i++) { int res = 0; int a = scan.nextInt(); int b = scan.nextInt(); for (int j = a; j <= b; j++) { int pow = 10; Map map = new HashMap(); while (j / pow > 0) { int tmp = Integer.valueOf((j % pow) + """" + (j / pow)); if (tmp > j && tmp <= b && map.get(tmp) == null) { map.put(tmp, tmp); res++; } pow *= 10; } } System.out.println(""Case #"" + i + "": "" + res); } } public static void main(String[] args) { new C().solve(); } } " B20789,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out =new PrintWriter(new FileWriter(""C-large.out"")); int T = Integer.parseInt(br.readLine()); for(int i = 0; i 0) { int first = k/b; int second = k%b; String res = Integer.toString(second)+Integer.toString(first); int ires = Integer.parseInt(res); if(ires != j&& ires>j && ires <=m ) { count++; } if(ires==j) break; b=b*10; } } out.println(""Case #""+(i+1)+"": "" +count); } br.close(); out.close(); } } " B20278,"import java.io.*; import java.util.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { static final int [] mul = {1, 10, 100, 1000, 10000, 100000, 1000000}; int getLen (int num) { int ret = 0; while (num > 0) { num /= 10; ret++; } return ret; } public void solve () throws Exception { int tt = nextInt(); for (int test = 1; test <= tt; test++) { int l = nextInt(); int r = nextInt(); long result = 0; int has [] = new int [r + 1]; for (int num = l; num <= r; num++) { int len = getLen(num); for (int j = 1; j <= len - 1; j++) { if ((num % mul[j]) / mul[j - 1] == 0) continue; int numto = num / mul [j] + (num % mul [j]) * mul [len - j]; if (numto > num && numto <= r) { if (has [numto] != num) result++; has[numto] = num; } } } out.println(""Case #""+test+"": ""+result); } } final String fname = """"; long stime = 0; BufferedReader in; PrintWriter out; StringTokenizer st; private String nextToken () throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } private int nextInt () throws Exception { return Integer.parseInt(nextToken()); } private long nextLong () throws Exception { return Long.parseLong(nextToken()); } private double nextDouble () throws Exception { return Double.parseDouble(nextToken()); } @Override public void run() { try { in = new BufferedReader(new FileReader(""input.txt"")); out = new PrintWriter(new FileWriter(""output.txt"")); solve (); } catch (Exception e) { throw new RuntimeException(e); } finally { out.close(); } } public static void main(String[] args) { new Thread(null, new Solution(), """", 1<<26).start(); } }" B20690,"import java.io.*; import java.util.LinkedList; import java.util.StringTokenizer; public class RecycledNumbers { public static void main(String[] args) { StringTokenizer st; BufferedReader br = null; try { FileWriter fstream = new FileWriter(""output.out""); BufferedWriter out = new BufferedWriter(fstream); String sCurrentLine; br = new BufferedReader(new FileReader(""C-small-attempt0.in"")); sCurrentLine = br.readLine();//no. of cases int i = 1; while ((sCurrentLine = br.readLine()) != null) { out.write(""Case #"" + i++ + "": ""); st = new StringTokenizer(sCurrentLine,"" ""); String n = st.nextToken(); int N = Integer.parseInt(n); int m = Integer.parseInt(st.nextToken()); int count = 0; for (int j = N; j < m; j++) { String recycled = Integer.toString(j); LinkedList possible_rotations = new LinkedList(); for (int k = 0; k < n.length(); k++) { recycled = recycled.substring(1)+recycled.charAt(0); if(!possible_rotations.contains(recycled) && Integer.parseInt(recycled) > j && Integer.parseInt(recycled) <= m) count++; possible_rotations.addLast(recycled); } } out.write(count + ""\n""); } out.close(); } catch (IOException e) { e.getMessage(); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.getMessage(); } } } } " B21637,"package google.codejam2012.awanish; import java.util.ArrayList; import java.util.Scanner; import java.util.StringTokenizer; public class RecycledNumbers { static long total = 0; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner inputScan = new Scanner(System.in); int noOfCases = Integer.parseInt(inputScan.nextLine()); long start; long end; for (int i = 1; i <= noOfCases; i++) { total = 0; String startend = inputScan.nextLine(); StringTokenizer st = new StringTokenizer(startend, "" ""); start = Integer.parseInt(st.nextToken()); end = Integer.parseInt(st.nextToken()); for (long j = start; j <= end; j++) { checkPair(j, start, end); } System.out.println(""Case #"" + i + "": "" + total/2); } } private static void checkPair(long j, long start, long end) { ArrayList a = new ArrayList(); String tocheck = String.valueOf(j); a.add(tocheck); for (int c = 0; c < tocheck.length(); c++) { tocheck = rotate(tocheck); if (!a.contains(tocheck) && !tocheck.substring(0, 1).equals(""0"") && start <= Integer.parseInt(tocheck) && Integer.parseInt(tocheck) <= end) { a.add(tocheck); total++; } } } private static String rotate(String tocheck) { // TODO Auto-generated method stub return tocheck.substring(tocheck.length() - 1, tocheck.length()) + tocheck.substring(0, tocheck.length() - 1); } } " B20751,"/** * */ package fixjava; public class ConcurrentCounter { private int count = 0; public synchronized int getAndIncrement() { return count++; } }" B20614,"package Test1; import java.io.BufferedReader; import java.io.InputStreamReader; public class Test1 { public static void main(String[] args) { String temp1 = null; String temp2 = null; int n,a,b; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ; try { String str = in.readLine(); int result; n = Integer.parseInt(str.trim()); for (int i = 1; i <= n; i++) { str = in.readLine(); String[] temp = str.split("" ""); a = Integer.parseInt(temp[0]); b = Integer.parseInt(temp[1]); result = 0; for (int j=a; j<=b;j++){ temp1 = (new Integer(j)).toString(); for (int k=1; k b) continue; //System.out.println(""Case #""+i+"": ""+j+"":""+currentnum+"";;;;;;;""+temp1.substring(0, k)+""=====""+temp1.substring(k)); result++; } } System.out.println(""Case #""+i+"": ""+result); //System.out.println(""""); } } catch (Exception e) { } } } " B20588,"package practice.GC2012; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class recycle { public static void main(String args[]) throws IOException { Scanner s = new Scanner(new File(""Z:\\junkyard\\practice\\resources\\input3.txt"")); FileWriter fo = new FileWriter(new File(""Z:\\junkyard\\practice\\resources\\output3.txt"")); int num = s.nextInt(); for(int i = 1; i<= num; i++) { fo.write(""Case #"" + i + "": ""); int a = s.nextInt(); int b = s.nextInt(); Set alreadyCounted = new HashSet(); for (int j = a;j<=b;j++) { StringBuffer n = new StringBuffer(String.valueOf(j)); for (int p = 0; p < n.length(); p++) { n.append(n.charAt(0)); n.deleteCharAt(0); if (j < Integer.parseInt(n.toString()) && Integer.parseInt(n.toString()) <= b) { alreadyCounted.add(String.valueOf(j) + n.toString()); } } } fo.write(alreadyCounted.size() + ""\n""); } fo.close(); s.close(); } } " B21422,"import java.io.*; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File(""c1.in"")); PrintStream outputStream = new PrintStream(new FileOutputStream(""c.out"")); // PrintStream outputStream = System.out; int n = scanner.nextInt(); // System.out.println(n); for (int i = 0; i < n; i++) { int a = scanner.nextInt(); int b = scanner.nextInt(); outputStream.println(""Case #"" + (i+1) + "": "" + ile(a, b)); } } private static int ile(int a, int b) { int para = 0; int ilenie = 0; int next = a; while (next <= b) { String now = String.valueOf(next); // if (!uzyte.contains(now)) { int przed = para; Set uzyte = new HashSet(); for (int i = 0; i < ilecyfr(next)-1; i++) { now = rotuj(now); int nowInt = Integer.valueOf(now); // if (ilecyfr(next) != ilecyfr(nowInt)) { // continue; // } if (nowInt >= a && nowInt <= b && nowInt != next && !uzyte.contains(now)) { // if (now > next) { // System.out.println(""hehe "" + now + "" "" + next); // } // System.out.println(next + "" "" + now); para++; uzyte.add(now); } } if (przed == para) { ilenie++; // System.out.println(next); } // } else { // System.out.println(now + "" used""); // } next++; } // System.out.println(ilenie); // return b - a - ilenie; return para / 2; } private static String rotuj(String n) { String s = String.valueOf(n); String substring = s.substring(1); return substring + s.charAt(0); // int len = ilecyfr(n); // int reszta = n %10; // n/=10; // return (int) (n + (reszta * Math.pow(10, len - 1))); } private static int ilecyfr(int n) { int ile = 0; while (n > 0) { ile++; n/=10; } return ile; } } " B22223,"// Google Code Jam 2011 // lid package Real; import java.io.*; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.InputMismatchException; import org.apache.commons.lang.ArrayUtils; @SuppressWarnings(""unused"") class T3 implements Runnable { // params // static String filePrefix = ""/jam/C-example""; static String filePrefix = ""/jam/C-large""; //static String filePrefix = ""/jam/A-large""; // I/O private InputReader in; //@SuppressWarnings(""unused"") private PrintWriter out; public static void main(String[] args) { new Thread(new T3()).start(); // init filestreams then start thread } // Init filestreams public T3() { try { System.setIn(new FileInputStream(filePrefix + "".in"")); System.setOut(new PrintStream(new FileOutputStream(filePrefix + "".out""))); } catch (FileNotFoundException e) { log(""Tried to open "" + filePrefix + "".in""); throw new RuntimeException(); } in = new InputReader(System.in); out = new PrintWriter(System.out); } // Start thread public void run() { // Keep track of time for efficiency (Zaphod) long startTime = System.currentTimeMillis(); logn(""Starting.""); int num_cases = in.readInt(); logn(""Num_cases: "" + num_cases); ArrayList list = new ArrayList(50); for (int case_num = 0; case_num < num_cases; case_num++) { // brute force that bitch int start = in.readInt(); int end = in.readInt(); int numOut = 0; int numOut2 = 0; for (Integer cur = start; cur <= end; cur++) { String curS = cur.toString(); list.clear(); for (int rotnum = 0; rotnum < curS.length(); rotnum++) { // String curSr = curS.substring(beginIndex) curS = curS.substring(curS.length()-1,curS.length()) + curS.substring(0,curS.length()-1); if (curS.charAt(0) == '0') continue; Integer rotInt = Integer.parseInt(curS); if (rotInt <= end && rotInt >= start && rotInt > cur) { if(!list.contains(rotInt)) list.add(rotInt); numOut++; // logn("""" + cur + "","" + curS); // break; } } numOut2 += list.size(); } fout(""Case #"" + (case_num + 1) + "": ""); fout("""" + numOut2); fout (""\n""); } logn(""Done.""); long stopTime = System.currentTimeMillis(); logn(""Time: "" + (stopTime - startTime) / 1000.0); } private static void fout (String msg) { System.out.print(msg); } private static void log (String msg) { System.err.print(msg); } private static void logn (String msg) { System.err.println(msg); } // readCharacter, readString, readInt, readLong, readLine, readDouble //@SuppressWarnings(""unused"") // from Egor Kulikov private static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } //@SuppressWarnings(""unused"") private static int getBit (int input, int pos) { input >>= pos; return input & 0x0001; } } " B21490,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; public class question3CodeJam { public int MAX=0; public int MIN=0; public int COUNTERVALS = 0; public int findInversions(){ for(int i=MIN;i<=MAX;i++){ if(i<10){ continue; } String finalizeVals = i+""""; String tmpString1 = i+""""; String tmpString2 = """"; //first string HashMap valFound = new HashMap(); for(int j=0;j= a) { if( t.length() % 2 == 0 ) { fp= t.substring(0,t.length()/2); lp = t.substring(t.length()/2); if( fp.equals(lp) ) { if(!memory.contains(Integer.parseInt(u)+"" ""+i)) { count++; memory += Integer.parseInt(u) + "" "" + i+""\n""; } } else { count++; } } else { count++; } /*if( memory.contains(Integer.parseInt(u)+"" ""+i) ) System.out.println(Integer.parseInt(u)+"" ""+i); else { count++; memory += Integer.parseInt(u) + "" "" + i+""\n""; }*/ } } } output += count; if( casen != no-1 ) output += ""\n""; casen++; } BufferedWriter bw = new BufferedWriter( new FileWriter(""E:\\result.txt"")); bw.write(output); bw.close(); br.close(); } catch( Exception e ) { e.printStackTrace(); } } }" B20372,"import java.io.*; import java.lang.*; import java.util.*; class GCJ { public static void main(String[] args) { try { PrintWriter out = new PrintWriter(new FileWriter(""1.txt"")); BufferedReader in = new BufferedReader(new FileReader(""1.in"")); in.readLine(); int counter = 1; while (in.ready()) { String s = in.readLine(); out.print(""Case #"" + Integer.toString(counter) + "": ""); counter++; String[] n = s.split("" ""); int A = Integer.parseInt(n[0]); int B = Integer.parseInt(n[1]); int D = B - ((B - A)/10); if(Integer.toString(D).length() > 2) D = B - (int) Math.pow(10, Integer.toString(D).length() - 2); else D = B; int number = 0; //System.out.println(D); for(int i=A; i list = new ArrayList(); for(int c=1;c= A && t <= B && t > i && !list.contains(t) ) { //out.print(i); //out.print("",""); //out.println(t); list.add(t); number++; } } } out.println(Integer.toString(number)); //System.out.println(Integer.toString(number)); } in.close(); out.close(); } catch (IOException e) { System.err.println(""Caught IOException: "" + e.getMessage()); } } }" B21025,"package qualification; import java.io.*; import java.util.*; public class C_RecycledNumbers { //-------------------------------------------------------------------------------- private static String ID=""C""; private static String NAME=""large""; private static boolean STANDARD_OUTPUT=false; //-------------------------------------------------------------------------------- public static void main(String[] args) throws Throwable { int[][] results=new int[2000001][]; for (int i=0; i B)) output.write(""0""); else { int count = 0; for(int j=A; j matches = new HashSet(); for(int k=1; kj) && (m<=B)) matches.add(m); } count += matches.size(); } output.write(String.valueOf(count)); } if(i9){ mo=mo*10; s=(a%mo+""""+a/mo); x=Integer.valueOf(s); } else continue; while(a!=x){ if(x>=A&&x<=B){ nr++; } mo=1; while((x/mo)%10==0){ mo=mo*10; } if(x/mo>9){ mo=mo*10; s=(x%mo+""""+x/mo); x=Integer.valueOf(s); } else break; } } System.out.println(nr/2); out.write(""Case #""+i+"": ""+nr/2); out.newLine(); } in.close(); fin.close(); out.close(); fout.close(); } catch(Exception e){} } } " B21398," import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { private Scanner in; private PrintWriter out; public long output; public int A; public int B; /** * main method */ public static void main(String args[]){ new RecycledNumbers(""C-large.in""); } /** * constructor */ public RecycledNumbers(String filename){ initIO(filename); int n = in.nextInt(); // long tmStart = System.currentTimeMillis(); for(int i=1;i<=n;i++){ A = in.nextInt(); B = in.nextInt(); output = 0; output=solve(); out.println(""Case #""+i+"": ""+output); } // System.out.println(System.currentTimeMillis() - tmStart); closeIO(); } public long solve(){ long op=0; Set s = new HashSet(); for(int i=A;i<=B;i++){ String stringI = Integer.toString(i); s.clear(); for(int ind=stringI.length()-1;ind>0;ind--){ if(stringI.substring(ind).charAt(0)!= '0'){ String stringTemp = stringI.substring(ind) + stringI.substring(0, ind); if(Integer.parseInt(stringTemp) > i && Integer.parseInt(stringTemp)<=B){ // System.out.println(stringI + "" ""+Integer.parseInt(stringTemp)); s.add(Integer.parseInt(stringTemp)); // op++; } } } op+=s.size(); } return op; } /** * Set up devices to do I/O */ public void initIO(String filename){ try { in = new Scanner(new FileReader(filename)); out = new PrintWriter(new FileWriter(filename+"".out"")); }catch (IOException except) { System.err.println(""File is missing!""); } } /** * Free memory used for I/O */ public void closeIO(){ in.close(); out.close(); } } " B22246,"import java.util.LinkedList; import java.util.Scanner; public class Recycle { private static int[] total(int r) { int i=1, t=10; while(r/t > 0) { i++; t*=10; } return new int[] {i,t/10}; } private static int pow(int c) { int t=1; while(c-->0) t*=10; return t; } private static int recycle(int r, int c /* peechhe se, 1 based*/) { int k = pow(c), t=total(r)[0]; int a = r/k; int b = (r%k) * pow(t-c); return a+b; } public static void main(String[] args) { Scanner c = new Scanner(System.in); int t = c.nextInt(); for(int w=1; w<=t; ++w) { System.out.print(""Case #""+w+"": ""); int cnt = 0; int A = c.nextInt(); int B = c.nextInt(); int tmp[] = total(A); int tot = tmp[0]; for(int i=Math.max(A, 10); i <=B; ++i ) { int in = i/tmp[1]; int pow = 1; LinkedList l = new LinkedList(); for(int j=1; j= in) { int r = recycle(i,j); if(r > i && r<=B && !l.contains(r)) { cnt++; l.add(r); //System.out.println(""(""+i+"",""+r+"")""); } } } } System.out.println(cnt); } } } " B20261,"import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class C { public final String INPUT_FILE_NAME = ""c_in""; public final String OUTPUT_FILE_NAME = ""c_out""; int kase = 1; int T = 0; int a,b; public void run() throws IOException{ Scanner s = new Scanner(new File(INPUT_FILE_NAME)); PrintWriter pw = new PrintWriter(new FileWriter(OUTPUT_FILE_NAME)); //PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); T = s.nextInt(); while (T-- > 0){ a = s.nextInt(); b = s.nextInt(); int len = ("""" + a).length(); int ans = 0; for (int i = a; i <=b ; i++) { String s1 = i + """"; String temp = """"; for (int k = 1; k < s1.length() ; k++) { temp = s1.substring(s1.length() - k) + s1.substring(0,s1.length()-k); int r1 = Integer.parseInt(temp); if (r1 > i && r1 <= b) ans++; } } pw.println(""Case #"" + kase + "": "" + ans); kase++; } pw.close(); s.close(); } public static void main(String[] args) throws IOException { (new C()).run(); } } " B20246,"import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map.Entry; import java.util.Scanner; public class G_3 { static int a, b; static HashMap map; static String change(int n) { String s = """" + n; int len = s.length(); int min = Integer.MAX_VALUE; int value; // String best = null; for (int i = 0; i < len; i++) { s = s.charAt(len - 1) + s.substring(0, len - 1); value = Integer.parseInt(s); if (min > value) { min = value; // best = s; } } return """" + min; } public static void main(String[] args) throws IOException { PrintWriter bw = new PrintWriter(new FileWriter(""1.txt"")); Scanner scan = new Scanner(System.in); int T = scan.nextInt(); map = new HashMap(); for (int i = 0; i < T; i++) { map.clear(); a = scan.nextInt(); b = scan.nextInt(); for (int j = a; j <= b; ++j) { String str = change(j); // System.out.println(str); if (map.containsKey(str)) { map.put(str, map.get(str) + 1); } else { map.put(str, 1); } } long sum = 0; for (Entry e : map.entrySet()) { int n = e.getValue(); sum += n * (n - 1) / 2; } System.out.println(String.format(""Case #%d: %d"", (i + 1), sum)); bw.write(String.format(""Case #%d: %d\n"", (i + 1), sum)); } bw.flush(); bw.close(); } } " B21384,"package recycledNumbers; import java.awt.font.NumericShaper; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Recycle { /** * @param args */ public static void main(String[] args) { List bLimits = null; BufferedReader br; // loading try { br = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]))); String line; int lCounter = 0; int numLines, low, upp; Limits ls; String[] bounds; while ((line = br.readLine()) != null) { if (lCounter == 0) { numLines = Integer.parseInt(line); bLimits = new ArrayList(numLines); lCounter++; } else { bounds = line.split("" ""); low = Integer.parseInt(bounds[0]); upp = Integer.parseInt(bounds[1]); ls = new Limits(low, upp); bLimits.add(ls); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // go int count = 1; for (Limits ls : bLimits) { calcRecycledPairs(ls.getLow(), ls.getUpp(), count); count++; } } private static void calcRecycledPairs(int low, int upp, int count) { Set recPairs = new HashSet(); for (int num = low; num <= upp; num++) { int numRotations = Integer.toString(num).length() - 1; int originalNum = num; // recNums.add(originalNum); String numS = Integer.toString(num); String rotNumS; int rotNum; while (numRotations > 0) { rotNumS = rotate(numS); // System.out.println(""["" + numS + "";"" + rotNumS + ""]""); rotNum = Integer.parseInt(rotNumS); if (!(originalNum == rotNum) && !numS.equals(rotNumS) && rotNum >= low && rotNum <= upp && !recPairs.contains(new RecycledPair(originalNum, rotNum))) { // System.out.println(""*** ("" + originalNum + "","" + rotNum + // "")""); recPairs.add(new RecycledPair(originalNum, rotNum)); } numS = rotNumS; numRotations--; } } System.out.println(""Case #"" + count + "": "" + recPairs.size()); } private static String rotate(String num) { String last = Character.toString(num.charAt(num.length() - 1)); char[] prefix = new char[num.length() - 1]; num.getChars(0, num.length() - 1, prefix, 0); String s = last + new String(prefix); return s; } } " B20262,"package QR_2012; import java.io.FileInputStream; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import Utils.IOStreams; public class C_Recycled_Numbers { public static void main(String[] args) throws IOException { IOStreams streams = new IOStreams(args[0]); System.setIn(new FileInputStream(args[0])); Scanner sc = new Scanner(System.in); sc.nextLine(); int caseNum = 1; while (sc.hasNextInt()) { int lowerBoundInt = sc.nextInt(); int upperBoundInt = sc.nextInt(); int hits = 0; for (int num1 = lowerBoundInt; num1 <= upperBoundInt; num1++) { char[] num1Str = ("""" + num1).toCharArray(); int length = num1Str.length; Set num2Duplicates = new HashSet(); for (int startingPoint = 0; startingPoint < length; startingPoint++) { int index = startingPoint; boolean init = true; StringBuffer num2Str = new StringBuffer(); while (init || index % length != startingPoint) { init = false; num2Str.append(num1Str[index % length]); index++; } Integer num2 = new Integer(num2Str.toString()); if (num1 < num2 && num2 <= upperBoundInt && !num2Duplicates.contains(num2)) { hits++; num2Duplicates.add(num2); } } } streams.printLine(""Case #"" + (caseNum++) + "": "" + hits + ""\n""); } streams.closeStreams(); } } " B20470,"import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { static String CASE = ""Case #""; static String N_L = System.getProperty(""line.separator""); static int T, A, B; public static void main(String[] args) { String input = ""file/C-large.in""; String output = ""file/C-large.txt""; run(input, output); } public static void run(String input, String output) { Scanner sc = null; Writer writer = null; StringBuilder result = new StringBuilder(); try { sc = new Scanner(new FileInputStream(input)); writer = new OutputStreamWriter(new FileOutputStream(output)); T = sc.nextInt(); int one = 10; int two = 100; int three = 1000; int four = 10000; int five = 100000; int six = 1000000; for(int i = 1; i <= T; i++) { A = sc.nextInt(); B = sc.nextInt(); Set set = new HashSet(); int total = 0; int mask = 1; if(A >= one) { if(A < two) { mask = one; } else if(A < three) { mask = two; } else if(A < four) { mask = three; } else if(A < five) { mask = four; } else if(A < six) { mask = five; } else { mask = six; } for(int j = A; j <= B; j++) { if(set.contains(j)) { continue; } set.add(j); int div = j / mask; int res = j - (mask * div); int target = res * 10 + div; while(j != target) { if(target >= A && target <= B && !set.contains(target)) { total++; } div = target / mask; res = target - (mask * div); target = res * 10 + div; } } } result.append(CASE).append(i).append("": "").append(total); if(i != T) { result.append(N_L); } writer.write(result.toString()); result.setLength(0); } writer.flush(); } catch(IOException e) { e.printStackTrace(); } finally { sc.close(); try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } " B20706,"package org.moriraaca.codejam; import java.io.File; import java.io.InputStream; import java.io.PrintStream; public abstract class AbstractSolver { protected final String RESOURCE_FOLDER = ""src/main/resources/""; /* Config */ protected final String defaultInputFileName; protected final OutputDestination outputDestination; protected final DebugOutputLevel debugOutputLevel; protected final Class dataParserClass; protected PrintStream output; protected PrintStream getOutput() { if (output == null) { try { switch (outputDestination) { case STDOUT: output = System.out; break; case FILE: output = new PrintStream(new File( defaultInputFileName.replaceAll(""\\.in"", ""\\.out""))); default: break; } } catch (Exception rethrow) { throw new Error(""Fatal error on initialization of output"", rethrow); } } return output; } public AbstractSolver() { try { SolverConfiguration config = getClass().getAnnotation( SolverConfiguration.class); debugOutputLevel = config.debugOutputLevel(); outputDestination = config.outputDestination(); defaultInputFileName = config.inputFileName(); dataParserClass = config.parser(); } catch (Exception log) { log.printStackTrace(); throw new Error(""Fatal error on initialization"", log); } } public void write(String msg, DebugOutputLevel level) { if (level.ordinal() <= debugOutputLevel.ordinal()) { getOutput().print(msg); } } public final String solve() { return solve(defaultInputFileName); } @SuppressWarnings(""unchecked"") public final String solve(String fileName) { try { AbstractDataParser dataParser = dataParserClass.getConstructor( InputStream.class).newInstance( getClass().getClassLoader().getResourceAsStream(fileName)); StringBuilder result = new StringBuilder(); for (int i = 0; i < dataParser.getTestCases().length; i++) { result.append(""Case #"") .append(i + 1) .append("": "") .append(solveTestCase((TC) dataParser.getTestCases()[i])) .append(""\n""); } return result.toString(); } catch (Exception e) { throw new Error(""Fatal error on solve"", e); } } public final void getSolution() { write(solve(), DebugOutputLevel.SOLUTION); } protected abstract String solveTestCase(TC testCase); } " B20286,"package br.com.feasoft.jam; import java.io.IOException; import java.util.*; /** * User: Homer * Date: 4/13/12 * Time: 9:30 PM */ public class Recycle { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); int numberOfCases = scanner.nextInt(); for (int i = 0; i < numberOfCases; i++) { int number1 = scanner.nextInt(); int number2 = scanner.nextInt(); int answer = 0; Map> pairs = new HashMap>(); for ( int j = number1; j <= number2; j++) { int size = Double.valueOf(Math.log10(j)).intValue(); for (int k = 1; k <= size; k++) { int number = shift(j, k); if(pairs.get(j) == null) { pairs.put(j, new HashSet()); } if (number != j && number >= number1 && number <= number2 && !pairs.get(j).contains(number)) { answer++; if(pairs.get(number) == null) { pairs.put(number, new HashSet()); } pairs.get(j).add(number); pairs.get(number).add(j); } } } System.out.printf(""Case #%d: %d\n"", i + 1, answer); } } public static int shift(int number, int quantity) { int digits = Double.valueOf(Math.log10(number)).intValue()+1; int lastDigitsGoingForward = Double.valueOf(number % Math.pow(10, quantity)).intValue(); int newFirstPart = Double.valueOf(lastDigitsGoingForward * Math.pow(10, digits-quantity)).intValue(); int firstDigitsGoingBack = Double.valueOf(number / Math.pow(10, quantity)).intValue(); return newFirstPart + firstDigitsGoingBack; } } " B21731,"package codejam.qual_2012; import java.io.File; import java.io.PrintStream; import java.util.Scanner; public class MainC { static boolean[] seen; public static void main(String[] args) throws Exception { String f = ""/home/floris/dev/java/Test/src/codejam/qual_2012/C-large.in""; Scanner sc = new Scanner(new File(f)); System.setOut(new PrintStream(new File(f+"".out""))); int T = sc.nextInt(); for (int i=1; T-- > 0; i++) { System.out.printf(""Case #%d: %d%n"", i, solve(sc.nextInt(), sc.nextInt())); } } private static long solve(int A, int B) { long result = 0; int pos = 1; int t = A/10; while (t != 0) {t/=10; pos++;} int cutoff = 1; for (int i = 1; i < pos; i++) cutoff *=10; seen = new boolean[cutoff*10]; fillSeen(); for (int i = A; i<=B; i++) { if (seen[i]) continue; result += roll(A, B, i, pos, cutoff); } return result; } private static long roll(int A, int B, int v, int pos, int cutoff) { pos--; pos--; int result = 0; if (A<=v && v <= B) result++; seen[v] = true; int n = (v%cutoff)* 10 + v/cutoff; switch (pos) { case 6: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; n = (n%cutoff)* 10 + n/cutoff; case 5: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; n = (n%cutoff)* 10 + n/cutoff; case 4: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; n = (n%cutoff)* 10 + n/cutoff; case 3: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; n = (n%cutoff)* 10 + n/cutoff; case 2: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; n = (n%cutoff)* 10 + n/cutoff; case 1: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; n = (n%cutoff)* 10 + n/cutoff; case 0: if (!seen[n ]&& A<=n && n <= B) result++; seen[n] = true; } return ((long)result)*(result-1)/2; } private static boolean allDigitsSame(int c) { int d = c%10; c /= 10; while (c != 0) { if (c%10 != d) return false; c /= 10; } return true; } private static void fillSeen() { seen[0] = true; for (int i = 1; i < 10; i++) { int j = i; while (j < seen.length) { seen[j]=true; j = j * 10 + i; } } } } " B20868,"import java.io.*; import java.util.*; /** * * @author kronenthaler */ public class C { public static void main(String arg[]){ try{ Scanner in = new Scanner(new FileInputStream(""c-large.in"")); System.setOut(new PrintStream(""c.out"")); int T = in.nextInt(); for(int cases=1;cases<=T;cases++){ int A = in.nextInt(); int B = in.nextInt(); int count = 0; for(int i=A;i> map = new HashSet>(); for(int j=1;j a = new ArrayList(); a.add(i); a.add(m); if(!map.contains(a)){ count++; map.add(a); } } } } System.out.printf(""Case #%d: %d\n"", cases, count); } }catch(Exception e){ e.printStackTrace(); } } } " B21306,"package main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecycledNumbers { public static void main(String... args) throws NumberFormatException, IOException { BufferedReader buffer = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]))); int qtd = Integer.parseInt(buffer.readLine()); List saida = new ArrayList(); for (int i = 1; i <= qtd; i++) { combinacoesFeitas = new HashSet(); saida.add(""Case #"" + i + "": "" + qtsTemNoIntervalo(buffer.readLine())); } buffer.close(); escrevaNoArquivoASaida(""output.txt"", saida); } private static void escrevaNoArquivoASaida(String nomeArquivo, List saida) throws IOException { BufferedWriter br = new BufferedWriter(new FileWriter(new File(nomeArquivo))); for (String string : saida) { br.write(string + ""\n""); } br.close(); } public static int qtsTemNoIntervalo(String linha) { String[] valores = linha.split("" ""); return qtsTemNoIntervalo(Integer.valueOf(valores[0]), Integer.valueOf(valores[1])); } static Set combinacoesFeitas = new HashSet(); public static int qtsTemNoIntervalo(int inicio, int fim) { int tamanhoString = String.valueOf(inicio).length(); int count = 0; for (int numeroAtual = inicio; numeroAtual <= fim; numeroAtual++) { String numeroAtualString = String.valueOf(numeroAtual); for(int indiceSubs = 1; indiceSubs < tamanhoString; indiceSubs++) { String rabo = numeroAtualString.substring(indiceSubs); String cabeca = numeroAtualString.substring(0, indiceSubs); String novoNumeroString = rabo + cabeca; int novoNumero = Integer.valueOf(novoNumeroString); novoNumeroString = String.valueOf(novoNumero); if (inicio <= novoNumero && numeroAtual < novoNumero && novoNumero <= fim && numeroAtualString.length() == novoNumeroString.length() && !combinacoesFeitas.contains(numeroAtual + novoNumeroString)) { count++; combinacoesFeitas.add(numeroAtual + novoNumeroString); } } } return count; } } " B20748,"package fixjava; import java.awt.Adjustable; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.RenderingHints; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollBar; @SuppressWarnings(""serial"") public class ZoomPanel extends JPanel { public static abstract class ZoomContent extends JPanel { // Width and height of canvas contents, in canvas coordinates private float contentWCanv, contentHCanv; // Width and height of canvas contents, in screen coordinates private int contentWScr, contentHScr; // Canvas scroll position, in screen coordinates private int contentXScr, contentYScr; // Current zoom protected float scale = 1.0f; // Initialize zoom etc. the first time canvas is painted private boolean firstPaint = true; // The scrollbar components in the parent ZoomPanel private JScrollBar hScrollBar; private JScrollBar vScrollBar; // --------------------------------------------------------------------------------------------------- public ZoomContent(float contentWidth, float contentHeight) { this.contentWCanv = contentWidth; this.contentHCanv = contentHeight; final ZoomContent canvas = this; final float[] mouseXY = new float[2]; this.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { canvas.mouseWheelMoved(e); } }); this.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseMoved(MouseEvent e) { canvas.mouseMoved(e, toCanvasCoords(e, mouseXY)); } @Override public void mouseDragged(MouseEvent e) { canvas.mouseDragged(e, toCanvasCoords(e, mouseXY)); } }); this.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { canvas.mouseReleased(e, toCanvasCoords(e, mouseXY)); } @Override public void mousePressed(MouseEvent e) { canvas.mousePressed(e, toCanvasCoords(e, mouseXY)); } @Override public void mouseExited(MouseEvent e) { canvas.mouseExited(e, toCanvasCoords(e, mouseXY)); } @Override public void mouseEntered(MouseEvent e) { canvas.mouseEntered(e, toCanvasCoords(e, mouseXY)); } @Override public void mouseClicked(MouseEvent e) { canvas.mouseClicked(e, toCanvasCoords(e, mouseXY)); } }); } // --------------------------------------------------------------------------------------------------- /** Called first time paint() is called, to set up zoom etc. */ private void zoomToFit() { int w = getWidth(), h = getHeight(); // Scale to fit scale = Math.min(w / (float) contentWCanv, h / (float) contentHCanv); // Center in window zoomBy(1.0, 0, 0); } private void resized() { // Center in window if needed zoomBy(1.0, 0, 0); } // --------------------------------------------------------------------------------------------------- /** Called by ZoomPanel after setting up scrollbars */ protected void addScrollBars(final JScrollBar hScrollBar, final JScrollBar vScrollBar) { this.hScrollBar = hScrollBar; this.vScrollBar = vScrollBar; hScrollBar.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { int hMax = hScrollBar.getMaximum(); float hScale = hMax == 0 ? 0.0f : 1.0f / hMax; scrollToX((hScrollBar.getValue() + hScrollBar.getVisibleAmount() / 2) * hScale); } }); vScrollBar.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { int vMax = vScrollBar.getMaximum(); float vScale = vMax == 0 ? 0.0f : 1.0f / vMax; scrollToY((vScrollBar.getValue() + vScrollBar.getVisibleAmount() / 2) * vScale); } }); } // --------------------------------------------------------------------------------------------------- // Override these methods as needed in subclasses. canvasXY is the x/y canvas coords of the mouse point. public void mouseMoved(MouseEvent e, float[] canvasXY) { } public void mouseDragged(MouseEvent e, float[] canvasXY) { } public void mouseClicked(MouseEvent e, float[] canvasXY) { } public void mousePressed(MouseEvent e, float[] canvasXY) { } public void mouseReleased(MouseEvent e, float[] canvasXY) { } public void mouseEntered(MouseEvent e, float[] canvasXY) { } public void mouseExited(MouseEvent e, float[] canvasXY) { } public void keyTyped(KeyEvent e) { if (e.getKeyChar() == '1') zoomToFit(); } public void mouseWheelMoved(MouseWheelEvent e) { double scrollAmt = e.getPreciseWheelRotation(); zoomBy(Math.pow(e.isControlDown() ? 1.2 : 1.05, -scrollAmt), e.getX(), e.getY()); } // ------------------------------------------------------------------------------------------------ protected void scrollToX(float scrollbarFracX) { int viewportWScr = getWidth(); contentXScr = (int) (viewportWScr / 2 - contentWScr * scrollbarFracX); repaint(); } protected void scrollToY(float scrollbarFracY) { int viewportHScr = getHeight(); contentYScr = (int) (viewportHScr / 2 - contentHScr * scrollbarFracY); repaint(); } // ------------------------------------------------------------------------------------------------ protected void zoomBy(double zoomFactor, int centerXScr, int centerYScr) { // Change scale scale *= zoomFactor; // Update size of contents in screen coordinates contentWScr = (int) Math.ceil(contentWCanv * scale); contentHScr = (int) Math.ceil(contentHCanv * scale); // Update scroll position in screen coordinates contentXScr = (int) Math.round((contentXScr - centerXScr) * zoomFactor + centerXScr); contentYScr = (int) Math.round((contentYScr - centerYScr) * zoomFactor + centerYScr); // Figure out size and position of scrollbars if (hScrollBar != null && vScrollBar != null) { int viewportWScr = getWidth(), viewportHScr = getHeight(); // Snap view to beginning or end of scroll region if we zoom off the end int viewPosX = -contentXScr, viewPosMaxX = contentWScr - viewportWScr; viewPosX = Math.max(Math.min(viewPosX, viewPosMaxX), 0); int viewPosY = -contentYScr, viewPosMaxY = contentHScr - viewportHScr; viewPosY = Math.max(Math.min(viewPosY, viewPosMaxY), 0); if (viewPosMaxX > 0) { // Canvas wider than viewport hScrollBar.setMaximum(contentWScr); hScrollBar.setValue(viewPosX); hScrollBar.setVisibleAmount(viewportWScr); hScrollBar.setBlockIncrement((int) Math.ceil(viewportWScr * 0.8f)); hScrollBar.setUnitIncrement((int) Math.ceil(viewportWScr * 0.08f)); hScrollBar.setEnabled(true); } else { // Canvas narrower than viewport, center it horizontally hScrollBar.setEnabled(false); contentXScr = (viewportWScr - contentWScr) / 2; } if (viewPosMaxY > 0) { // Canvas taller than viewport vScrollBar.setMaximum(contentHScr); vScrollBar.setValue(viewPosY); vScrollBar.setVisibleAmount(viewportHScr); vScrollBar.setBlockIncrement((int) Math.ceil(viewportHScr * 0.8f)); vScrollBar.setUnitIncrement((int) Math.ceil(viewportHScr * 0.08f)); vScrollBar.setEnabled(true); } else { // Canvas shorter than viewport, center it vertically vScrollBar.setEnabled(false); contentYScr = (viewportHScr - contentHScr) / 2; } } repaint(); } // ------------------------------------------------------------------------------------------------ protected float[] toCanvasCoords(int screenX, int screenY, float[] outXY) { outXY[0] = (screenX - contentXScr) / scale; outXY[1] = (screenY - contentYScr) / scale; return outXY; } protected float[] toCanvasCoords(int screenX, int screenY) { float[] outXY = new float[2]; toCanvasCoords(screenX, screenY, outXY); return outXY; } protected float[] toCanvasCoords(MouseEvent e) { return toCanvasCoords(e.getX(), e.getY()); } protected float[] toCanvasCoords(MouseEvent e, float[] outXY) { toCanvasCoords(e.getX(), e.getY(), outXY); return outXY; } // ------------------------------------------------------------------------------------------------ @Override public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; if (firstPaint) { zoomToFit(); firstPaint = false; } g2.drawRect(contentXScr, contentYScr, contentWScr, contentHScr); AffineTransform orig = g2.getTransform(); // Correctly center scaled canvas in viewport g2.translate(contentXScr, contentYScr); g2.scale(scale, scale); // Run user-provided code paintCanvas(g2); // Restore old transform g2.setTransform(orig); } /** Override this to draw your content */ public abstract void paintCanvas(Graphics2D g); } // ------------------------------------------------------------------------------------------------ /** A zoomable image */ public static class ZoomImageContent extends ZoomContent { protected BufferedImage img; public ZoomImageContent(BufferedImage img) { super(img.getWidth(), img.getHeight()); this.img = img; } @Override public void paintCanvas(Graphics2D g) { g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(img, 0, 0, null); } } // ------------------------------------------------------------------------------------------------ public ZoomPanel(final ZoomContent content) { // Set up layout this.setLayout(new GridBagLayout()); GridBagConstraints gridBagConstraints = new GridBagConstraints(); // Add content panel gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.fill = GridBagConstraints.BOTH; this.add(content, gridBagConstraints); JScrollBar hScrollBar = new JScrollBar(Adjustable.HORIZONTAL); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 0.0; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; //hScrollBar.addAdjustmentListener(scrollBarListener); this.add(hScrollBar, gridBagConstraints); JScrollBar vScrollBar = new JScrollBar(Adjustable.VERTICAL); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.weightx = 0.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.fill = GridBagConstraints.VERTICAL; //vScrollBar.addAdjustmentListener(scrollBarListener); this.add(vScrollBar, gridBagConstraints); // Create small spacer panel in corner between scrollbars JPanel cornerPanel = new JPanel(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.0; gridBagConstraints.weighty = 0.0; this.add(cornerPanel, gridBagConstraints); // Add scrollbar refs to ZoomContent content.addScrollBars(hScrollBar, vScrollBar); // Update scrollbar block increments when window size changes content.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent evt) { content.resized(); } }); } // ------------------------------------------------------------------------------------------------ /** Create new ZoomFrame. Calls System.exit(0) on window close. */ public static class ZoomFrame extends JFrame { protected ZoomContent content; @SuppressWarnings(""unused"") private ZoomFrame() { } public ZoomFrame(String title, int windowWidth, int windowHeight, final ZoomContent content) { // Set window title super(title); // Keep ref to content in case subclasses need it this.content = content; // Exit on window close this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); // Catch keystrokes this.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { content.keyTyped(e); } }); this.setSize(windowWidth, windowHeight); // Add ZoomPanel to ZoomFrame, and add ZoomContent to ZoomPanel this.add(new ZoomPanel(content)); this.setVisible(true); } } // ------------------------------------------------------------------------------------------------ // Demo usage public static void main(String[] args) { new ZoomFrame(""Zoom Panel"", 1024, 768, new ZoomContent(800, 600) { int x = 100, y = 100; @Override public void paintCanvas(Graphics2D g) { g.fillOval(x, y, 50, 50); } @Override public void mousePressed(MouseEvent e, float[] coords) { x = (int) coords[0] - 25; y = (int) coords[1] - 25; repaint(); } }); } } " B21495,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.File; import java.util.Map; import java.util.HashMap; public class GCJ_qr_c { /** * @param args */ public static void main(String[] args) { GCJReader in = new GCJReader(args[0]); GCJWriter out = new GCJWriter(args[1]); int numTestCases = Integer.parseInt(in.readLine()); HashMap map = new HashMap(); for(int i = 1; i <= numTestCases; i+=1) { String[] inLine = in.readLine().split("" ""); final int A = Integer.parseInt(inLine[0]); final int B = Integer.parseInt(inLine[1]); final int numDigits = inLine[0].length(); int count = 0; for(int j = A; j <= B; j += 1 ) { //start running through the numbers from A to B, looking for recycled numbers String n = Integer.toString(j); //start rearranging blocks of digits for(int k = 1; k < numDigits; k+=1) { //Get our n, as a String for rearranging //Get the block of digits to move to the front of n from String nBlock = n.substring(n.length() - k); //Get the ""remainder"" digits, the digits not being moved to the front String nFront = n.substring(0, n.length() - k); //Build m String m = nBlock + nFront; //check if the (n, m) pair is recycled int mVal = Integer.parseInt(m); int nVal = Integer.parseInt(n); if(!(mVal < A || mVal > B || mVal <= nVal || map.containsKey(mVal))) { map.put(mVal, nVal); count++; } } map.clear(); } String outLine = """" + count; out.writeLine(String.format(""Case #%d: %s"", i, outLine)); } } private static class GCJWriter { private String outFile = null; private BufferedWriter out = null; public GCJWriter(String outFile) { this.outFile = outFile; try { out = new BufferedWriter(new FileWriter(outFile)); } catch (Exception e) { throw new RuntimeException(e); } } public void writeLine(String output) { try { out.write(output + ""\n""); out.flush(); } catch (Exception e) { throw new RuntimeException(e); } } } private static class GCJReader { private String inFile = null; private BufferedReader in = null; public GCJReader(String inFile) { this.inFile = inFile; try { in = new BufferedReader(new FileReader(inFile)); } catch (Exception e) { throw new RuntimeException(e); } } public String readLine() { try { return in.readLine(); } catch (Exception e) { throw new RuntimeException(e); } } } }" B22229,"import java.io.*; import java.util.*; public class RecycledNumbers { //static Set seen = new Set(); static int min, max; static int count; public static void main (String[] args) throws IOException { Scanner in = new Scanner(new File(""C-small.txt"")); int cases; cases = in.nextInt(); for (int n = 0; n < cases; n++) { //seen = new LinkedList(); min = in.nextInt(); max = in.nextInt(); count = 0; for (int i = min; i < max; i++) { findPairs(i); } System.out.println(""Case #"" + (n+1) + "": "" + count); } } public static void findPairs(int num) { String n = """" + num; int result; for (int i = 1; i < n.length(); i++) { result = Integer.parseInt(n.substring(i) + n.substring(0, i)); if (result > num && result <= max) { count ++; } } } }" B20880,"package Jam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; public class ProblemC { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ProblemC p = new ProblemC(); p.readAndOutput(); } public int cmp(byte[] s1,int start,byte[]s2) { int tmp = 0; for( int i = 0;i hm; public void print(byte[] tmp,int st) { StringBuffer sb = new StringBuffer(); for( int i = 0;i= tmp.length ) { if( st == -1 ) return 0; if( cmp(tmp,0,min) >=0 && cmp(tmp,0,max) <=0 && cmp(tmp,st,min) >=0 && cmp(tmp,st,max) <=0 ) { print(tmp,st); return 1; }else { return 0; } } int sum = 0; byte k; if( st == -1 ) { k = (byte) (tmp[0] + 1); for(;k<=max[0];k++) { tmp[pos] = k; sum += l_cal(tmp,pos+1,pos); } } for( k = '0'; k <= '9'; k++ ) { tmp[pos] = k; sum += l_cal(tmp,pos+1,st); } return sum; } public int m_cal(byte[] tmp,int pos,int st) { if( pos >= tmp.length ) { if( st == -1 ) return 0; if( cmp(tmp,st,tmp) > 0 && cmp(tmp,0,min) >=0 && cmp(tmp,0,max) <=0 && cmp(tmp,st,min) >=0 && cmp(tmp,st,max) <=0 ) { print(tmp,st); return 1; }else { return 0; } } int sum = 0; byte k; if( st == -1 ) { tmp[pos] = tmp[0]; sum += m_cal(tmp,pos+1,pos); } for( k = '0'; k <= '9'; k++ ) { tmp[pos] = k; sum += m_cal(tmp,pos+1,st); } return sum; } public int cal() { int sum = 0; byte tmp[] = new byte[min.length]; int range = max[0] - min[0] + 1; int len = min.length; hm = new HashMap(); for( int i = 0; i numRecycled(int B) { String s = num + """"; HashSet recycleds = new HashSet(); int numeroCasas = s.length(); // System.out.print(num + ""(""); for (int i = 1; i < numeroCasas; i++) { String novoNum = s.substring(s.length() - i, s.length()) + s.substring(0, s.length() - i); int aux = Integer.parseInt(novoNum); if (aux <= B && aux > num) { recycleds.add(aux); // System.out.print("" "" + aux); } } // System.out.print("")\n""); return recycleds; } public int quantNumRecycled(int B) { return numRecycled(B).size(); } } " B22066,"import java.util.Scanner; public class RecycledNum { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int i=0; i= 2 get numRot C 2 if(numRot > 1) numPairs += (numRot - 1) * numRot / 2; } } System.out.println(""Case #"" + (i+1) + "": "" + numPairs); } } } " B21096,"import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.BitSet; public class ProbC { public static long solve(int A, int B) { int[] basePower = new int[8]; basePower[0] =1; for(int i=1; i<8; i++) basePower[i] = basePower[i-1] * 10; long count = 0; BitSet mask = new BitSet(B+1); int[] digits = new int[8]; for(int i=A; i<=B; i++) { if(mask.get(i)) continue; mask.set(i); int candidate = i; int nCandidates = 1; int size = 0; while(candidate > 0) { digits[size] = candidate % 10; candidate /= 10; size++; } if(size > 1) { for(int j=0; j=0; k--) { part1 = part1 * 10 + digits[k]; } for(int k=size-1; k>j; k--) { part2 = part2 * 10 + digits[k]; } if(part1 != 0) { int value = part1 * basePower[size-1-j] + part2; if(value >= A && value <=B && !mask.get(value)) { nCandidates++; mask.set(value); } } } count += (nCandidates-1) * nCandidates/2; } } return count; } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader(""C-large.in"")); PrintWriter out = new PrintWriter(new FileWriter(""C-large.out"")); String line = in.readLine(); int T = Integer.parseInt(line); for(int i=1; i<=T; i++) { line = in.readLine(); String[] comp = line.split(""\\s+""); int A = Integer.parseInt(comp[0]); int B = Integer.parseInt(comp[1]); out.print(""Case #"" + i+ "": ""); out.println(solve(A, B)); } out.flush(); in.close(); out.close(); } } " B22128,"package CD; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.sql.SQLException; import java.util.Hashtable; public class RC{ private int first; private int second; public RC(int i,int i_s){ this.first=i; this.second=i_s; } public static int dist(int mi,int mx){ Hashtable numbers = new Hashtable(); if (mx<10){ return 0; } for(int i=mi;i<=mx;i++){ String s=Integer.toString(i); for(int e=s.length()-1;e>0;e--){ String new_s=s.substring(e, s.length())+s.substring(0, e); int i_s=Integer.parseInt(new_s); if (i_s<=mx && i_s!=i && i_s>=mi){ String c=Integer.toString(i_s)+Integer.toString(i); String b=Integer.toString(i)+Integer.toString(i_s); if (!(has(numbers,c)) && !(has(numbers,b))){ numbers.put(c, 0); } } } } return numbers.size(); } public static boolean has(Hashtable numbers,String c){ if (numbers.get(c)==null){ return false; } return true; } public static void main(String[] args) throws IOException{ int a=dist(1111,3333); System.out.println(Integer.toString(a)); } }" B21909," import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Chamika */ public class GRecycle { public static void main(String[] args) { Scanner s = new Scanner(System.in); int cases = s.nextInt(); HashSet al = new HashSet<>(); for(int i = 0;i < cases;i++){ int x = s.nextInt(); int y = s.nextInt(); int res = 0; for(int j = x;j <= y;j++){ int z = Integer.toString(j).length(); int a = j; al.clear(); for(int k = 0;k < z;k++){ a = (a%(10))*(int)Math.pow(10,z - 1) + a/10; res = (a > j && a <= y && !al.contains(a)) ? res + 1 : res; al.add((a > j && a <= y) ? a : 0); } } System.out.println(""Case #"" + (i + 1) + "": "" + res); } } } " B20911,"import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; public class prob3 { /** * @param args */ static BufferedReader openRead(String fileName){ BufferedReader in = null; try { in = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { System.err.println(""Error Opening the input file""); e.printStackTrace(); } return in; } static int countRecyclyed(int n, int A, int B, int len){ int result = 0; int l = 10; int t = 1; for (int i = 1; i < len; i++) t = t*10; for (int i = 1; i < len; i++){ int m = n / l + (n % l)*t; l = l*10; t = t /10; if (m > A && m <=B && m >n){ result ++; // System.out.format(""(%d , %d)\n"", n, m); } } return result; } static void processLine( String line , int k, PrintStream ps){ ps.format(""Case #%d: "", k); String[] lineItems = line.split("" ""); int A = Integer.parseInt(lineItems[0]); int B = Integer.parseInt(lineItems[1]); int len = lineItems[0].length(); System.out.println(len); int n = 0; for (int i = A ; i < B; i++){ n += countRecyclyed(i, A, B, len); } ps.format(""%d\n"", n); } public static void main(String[] args) throws IOException { if (args.length < 1){ System.err.println(""not suffucient args""); System.exit(-1); } BufferedReader in = openRead(args[0]); PrintStream ps = new PrintStream(new File(args[1])); // read size int T = 0; String TStr = in.readLine(); T = Integer.parseInt(TStr); if ( T < 1 || T > 100) System.exit(-1); // read contents String line; for (int i = 0; i < T && (line = in.readLine())!= null; i++){ processLine( line, i+1, ps); } System.out.println(""Done!""); } } " B20097,"import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class main2 { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader m = new BufferedReader(new InputStreamReader(System.in)); PrintWriter ou = new PrintWriter(""file.txt""); int n = Integer.parseInt(m.readLine()); for (int i = 0; i < n; i++) { String cas = m.readLine(); String [] a = cas.split("" ""); int base = Integer.parseInt(a[0]); int count = 0; int count1=0; if(a[0].length()==1){ System.out.print(""Case #""+(i+1)+"": ""+count); System.out.print(""\n""); }else{ Boolean con = false;; int cass = Integer.parseInt(a[0]); do { // con = false;; // String newcase = a[0].charAt(0)+""""; // for(int j=0 ;j= 0; numdigits++); HashSet done = new HashSet(); int n = A; int possiblem; answers[c] = 0; while (n <= B) { possiblem = n; int possiblemsthisround = 0; for (int i = 0; i <= numdigits; i++) { if ((possiblem%10) != 0) { possiblem = (possiblem%10)*((int)Math.pow(10,numdigits-1)) + (possiblem-(possiblem%10))/10; if ((possiblem <= B) && (possiblem > n)) { if (done.contains(possiblem) == false) { done.add(possiblem); possiblemsthisround++; } done.add(possiblem); } } else possiblem = (possiblem%10)*((int)Math.pow(10,numdigits-1)) + (possiblem-(possiblem%10))/10; } if (possiblemsthisround > 0) answers[c] += possiblemsthisround*(possiblemsthisround + 1)/2; n++; } } for (int i = 0; i < T; i++) { int j = i+1; System.out.println(""Case #""+j+"": ""+answers[i]); } } } " B20871,"package codejam; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.PrintStream; import java.util.HashSet; public class _Q_C { public static void main(String[] args) throws Exception { String input_file = ""C-large.in""; String output_file = ""_Q_C_large_out.txt""; BufferedReader in = new BufferedReader(new FileReader(input_file)); PrintStream out = new PrintStream(new FileOutputStream(output_file)); in.readLine(); String line; int case_num = 1; while ((line=in.readLine()) != null) { String[] line_str = line.split("" ""); int a = Integer.parseInt(line_str[0]); int b = Integer.parseInt(line_str[1]); HashSet hs = new HashSet(); for (Integer n = a; n <= b; ++n) { String n_str = n.toString(); int len = n_str.length(); for (int r = 1; r < len; ++r) { String rotated_n_str = n_str.substring(len - r) + n_str.substring(0, len - r); if (isValidPair(a, b, n_str, rotated_n_str)) { String check_str = removeLeadingZero(n_str) + ""_"" + removeLeadingZero(rotated_n_str); String check_str_rev = removeLeadingZero(rotated_n_str) + ""_"" + removeLeadingZero(n_str); if (!hs.contains(check_str) && !hs.contains(check_str_rev)) { int rotated_n = Integer.parseInt(rotated_n_str); if (n <= rotated_n) hs.add(check_str); else hs.add(check_str_rev); } } } } //System.out.println(""Case #"" + case_num + "": "" + hs.size() + ""\n"" + hs.toString()); out.println(""Case #"" + case_num + "": "" + hs.size()); ++case_num; } } private static boolean isValidPair(int a, int b, String n_str, String m_str) { Integer n = Integer.parseInt(n_str); Integer m = Integer.parseInt(m_str); String n_str_strip = n.toString(); String m_str_strip = m.toString(); return (n_str_strip.length() == m_str_strip.length() && a <= n && n < m && m <= b); } private static String removeLeadingZero(String s) { int i = 0; for (; i < s.length(); ++i) { if (s.charAt(i) != '0') break; } return s.substring(i); } } " B21630,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.*; import java.util.*; /** * * @author Alex */ public class ReduceReuseButDont { public static void main(String sArgs[]) throws IOException { Scanner oScan = new Scanner(new File(""C-large.in"")); int sets = Integer.parseInt(oScan.nextLine().trim()); int count = 0; while(sets-->0) { count++; int a = oScan.nextInt(); int b = oScan.nextInt(); int rec = 0; /* for(int i = a; i set=new HashSet(); for(int j=1;j { /** Return at most n items from the beginning of the Iterable. */ public static ArrayList head(Iterable collection, int n) { ArrayList head = new ArrayList(); int count = n; if (n > 0) for (T item : collection) { head.add(item); if (--count == 0) break; } return head; } /** Return at most n items from the end of the List. */ public static ArrayList tail(List list, int n) { ArrayList tail = new ArrayList(); for (int len = list.size(), i = Math.max(len - n, 0); i < len; i++) tail.add(list.get(i)); return tail; } } " B22044,"package google.problems; import google.loader.Challenge; public abstract class AbstractChallenge implements Challenge{ private final int problemNumber; private String result; public AbstractChallenge(int i) { this.problemNumber = i; } protected void setResult(String result){ this.result = result; } @Override public String getResult() { return ""Case #""+problemNumber+"": ""+result+""\n""; } protected int getInt(int pos, String[] tokens) { return Integer.parseInt(tokens[pos]); } } " B20467,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * * @author malte */ public class RecycledNumbers { static int caseNum = 0; static BufferedReader reader; static BufferedWriter writer; public static void main(String[] args) throws FileNotFoundException, IOException { reader = new BufferedReader(new InputStreamReader(new FileInputStream(""./in""))); new File(""./out"").createNewFile(); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(""./out""))); reader.readLine(); // Skip numberofcases String input; while ((input = reader.readLine()) != null) { input = input.trim(); String[] numbers = input.split("" ""); write(getPairCount(numbers[0], numbers[1])); } } static int getPairCount(String aStr, String bStr) { int a = Integer.parseInt(aStr); int b = Integer.parseInt(bStr); if (a < 10 || a == b) { return 0; } HashMap> pairs = new HashMap>(); for (int i = a; i <= b; i++) { String iStr = Integer.toString(i); for (int swaplength = 1; swaplength < iStr.length(); swaplength++) { int indexToSwap = iStr.length() - swaplength; if (iStr.charAt(indexToSwap) != '0' && Integer.parseInt("""" + iStr.charAt(indexToSwap)) <= Integer.parseInt("""" + bStr.charAt(0))) { String newString = iStr.substring(indexToSwap) + iStr.substring(0, indexToSwap); int newInt = Integer.parseInt(newString); if (newInt <= b && newInt > i) { if (pairs.containsKey(newInt)) { if (pairs.get(newInt).contains(i)) { continue; } } Set values = pairs.get(i); if (values == null) { values = new HashSet(); pairs.put(i, values); } values.add(newInt); /*boolean alreadyFound = false; for (int[] pair: pairs) { if ((pair[0] == newInt || pair[1] == newInt) && (pair[0] == i || pair[1] == i)) { alreadyFound = true; break; } } if (!alreadyFound) { pairs.add(new int[]{i, newInt}); count++; }*/ } } } } return countEntries(pairs); } public static int countEntries(Map> map) { int count = 0; for (Set set: map.values()) { count += set.size(); } return count; } public static void write(Object out) throws IOException { caseNum += 1; writer.write(String.format(""Case #%s: %s%n"", caseNum, out)); writer.flush(); } } " B21572,"import java.util.*; public class C { public static void main (String [] arg) { int [][] store = new int [2000010][7]; for (int i = 1; i i) store[i][ptr++] = j; j = rotate(j); } } Scanner sc = new Scanner(System.in); int T = Integer.parseInt(sc.nextLine()); for (int ii = 1; ii<=T; ++ii) { //Something int A = sc.nextInt(); int B = sc.nextInt(); int count = 0; for (int a = A; a 0; ++i) if (store[a][i] <= B) count++; int ans = count; System.out.printf(""Case #%d: %s\n"",ii,ans); } } public static int rotate(int a) { String s = Integer.toString(a); do { s = s.substring(1) + s.charAt(0); } while (s.charAt(0) == '0'); return Integer.parseInt(s); } }" B22165,"package phase1.problemC; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { RecycledNumbers s = new RecycledNumbers(); try { s.doIt(); } catch (Exception e) { e.printStackTrace(); } } private void doIt() throws Exception { Scanner s = new Scanner(new File(""C:\\Andre\\GCJInputs\\fase1\\p3\\C-large.in"")); int T = Integer.valueOf(s.nextLine()); int cont=1; Writer out = new OutputStreamWriter(new FileOutputStream(""C:\\Andre\\GCJInputs\\fase1\\p3\\C-large.out"")); while (cont<=T) { out.write(""Case #""+cont+"": ""); String[] values = s.nextLine().split("" ""); out.write(String.valueOf(calculate(values[0], values[1]))); out.write(""\n""); cont++; } out.flush(); out.close(); } private int calculate(String A, String B) { int r = 0; String c = A; if (c.length()==1) { return r; } int cont = Integer.parseInt(c)-1; int fim = Integer.parseInt(B); while (cont++ linhas = new HashSet(); while (qd++ Integer.parseInt(B)) continue; if (Integer.parseInt(n) < Integer.parseInt(m)) { linhas.add(linha); } linha=""""; } resp=linhas.size(); return resp; } private boolean numerosIguais(String s) { int cont=10; cont = cont + s.indexOf('0') + s.indexOf('1') + s.indexOf('2') + s.indexOf('3') + s.indexOf('4') + s.indexOf('5') + s.indexOf('6') + s.indexOf('7') + s.indexOf('8') + s.indexOf('9'); if (cont>2) return false; return true; } } " B21679," import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Akash Agrawal */ public class RN { public static boolean check(int n , int []arr) { for(int i=0;ii && C<=B && check(C,ar)) { count++; //System.out.println(i+"" ""+C); ar[ind++]=C; } } } System.out.println(""Case #""+cas+++"": ""+count); } } } " B20837,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication11; import java.io.*; import java.util.ArrayList; import java.util.HashMap; /** * * @author karthik */ public class JavaApplication11 { /** * @param args the command line arguments */ public static int isrotate(String c,int n) { String c1=new String(); for(int i=c.length()-n;i h=new HashMap(); FileInputStream f=new FileInputStream(""large""); DataInputStream dis=new DataInputStream(f); BufferedReader br=new BufferedReader(new InputStreamReader(dis)); ArrayList al=new ArrayList(); int n=Integer.parseInt(br.readLine()); int a,b,count=0; String s[]; int temp,temp1; for(int i=0;i h=new HashMap(); for(int k=1;k { private final L left; private final R right; public R getRight() { return right; } public L getLeft() { return left; } public Pair(final L left, final R right) { this.left = left; this.right = right; } /** Convenience method so type params of pair don't have to be specified: just do Pair.make(l, r) */ public static Pair make(L left, R right) { return new Pair(left, right); } // --------------------------------------------------------------------------------------------------- private static final boolean objEquals(Object p1, Object p2) { if (p1 == null) return p2 == null; return p1.equals(p2); } @Override public final boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } else { final Pair other = (Pair) o; return objEquals(getLeft(), other.getLeft()) && objEquals(getRight(), other.getRight()); } } @Override public int hashCode() { int hl = getLeft() == null ? 0 : getLeft().hashCode(); int hr = getRight() == null ? 0 : getRight().hashCode(); return (hl + (127 * hr)) ^ (hr << 1); } // --------------------------------------------------------------------------------------------------- @Override public String toString() { return ""("" + getLeft() + "", "" + getRight() + "")""; } // --------------------------------------------------------------------------------------------------- public static ArrayList getAllLefts(Iterable> list) { ArrayList result = new ArrayList(); for (Pair pair : list) result.add(pair.getLeft()); return result; } public static ArrayList getAllRights(Iterable> list) { ArrayList result = new ArrayList(); for (Pair pair : list) result.add(pair.getRight()); return result; } // --------------------------------------------------------------------------------------------------- public static , B> Comparator> comparatorOnLeft(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Pair o1, Pair o2) { return o1.getLeft().compareTo(o2.getLeft()); } }; } public static , B> Comparator> comparatorOnLeftRev(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Pair o1, Pair o2) { return -o1.getLeft().compareTo(o2.getLeft()); } }; } public static > Comparator> comparatorOnRight(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Pair o1, Pair o2) { return o1.getRight().compareTo(o2.getRight()); } }; } public static > Comparator> comparatorOnRightRev(Collection> tupleCollection) { return new Comparator>() { @Override public int compare(Pair o1, Pair o2) { return -o1.getRight().compareTo(o2.getRight()); } }; } static , B> Comparator> comparatorOnLeft(Collection> tupleCollection, final boolean ascending) { return new Comparator>() { final int weight = ascending ? 1 : -1; @Override public int compare(Pair o1, Pair o2) { return o1.getLeft().compareTo(o2.getLeft()) * weight; } }; } static > Comparator> comparatorOnRight(Collection> tupleCollection, final boolean ascending) { return new Comparator>() { final int weight = ascending ? 1 : -1; @Override public int compare(Pair o1, Pair o2) { return o1.getRight().compareTo(o2.getRight()) * weight; } }; } // --------------------------------------------------------------------------------------------------- /** Sort a List> in-place into order of increasing or decreasing K */ public static , V> void sortPairsByLeft(List> list, boolean ascending) { Collections.sort(list, comparatorOnLeft(list, ascending)); } /** Sort a List> in-place into order of increasing K */ public static , V> void sortPairsByLeft(List> list) { Collections.sort(list, comparatorOnLeft(list, true)); } /** Sort a List> in-place into order of increasing or decreasing V */ public static > void sortPairsByRight(List> list, boolean ascending) { Collections.sort(list, comparatorOnRight(list, ascending)); } /** Sort a List> in-place into order of increasing V */ public static > void sortPairsByRight(List> list) { Collections.sort(list, comparatorOnRight(list)); } /** Convert a map into a list of Pair, final order unspecified */ public static ArrayList> mapToList(HashMap map) { ArrayList> list = new ArrayList>(); for (Entry ent : map.entrySet()) list.add(new Pair(ent.getKey(), ent.getValue())); return list; } } " B21913,"import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public abstract class FileWrapper { protected static final String CASE = ""Case #""; protected static final String OUTPUT = ""result.out""; protected int caseNum = 0; protected String output[] = null; private FileReader fr = null; private BufferedReader br = null; private FileWriter fw = null; private BufferedWriter bw = null; protected void openReadFile(String fileName) throws Exception { this.fr = new FileReader(fileName); this.br = new BufferedReader(this.fr); } protected void closeReadFile() throws Exception { this.br.close(); this.fr.close(); } protected String readLine() throws Exception { return this.br.readLine(); } protected boolean isFileReady() throws Exception { return this.br.ready(); } protected abstract void processInput(String fileName); private void openWriteFile(String fileName) throws Exception { this.fw = new FileWriter(fileName); this.bw = new BufferedWriter(this.fw); } private void closeWriteFile() throws Exception { this.bw.close(); this.fw.close(); } private void writeLine(String line) throws Exception { this.bw.write(line); this.bw.newLine(); } protected void processOutput(String fileName) { try{ this.openWriteFile(fileName); for (int i=0; i j && number <= B) { count++; } number = recycle(number); } } // do case things here System.out.format(""Case #%d: %d\n"", i, count); } } private static int recycle(int n) { int temp = n; int max = 1; while (temp >= 10) { max *= 10; temp /= 10; } int m = n / 10 + (max * (n % 10)); temp = n; while (temp % 10 == 0) { temp = m; m = m / 10 + (max * (m % 10)); } return m; } } " B20742,"package fixjava; import java.util.Iterator; /** * Create an iterator that keeps track of the current index into the Iterable. * * Usage: * * public static void main(String[] args) { // Iterate over a list: ArrayList list = new ArrayList(); list.add(""apple""); list.add(""banana""); list.add(""pear""); for (IndexedItem it : IndexedItem.iterate(list)) System.out.println(it.getIndex() + "": "" + it.getItem()); // Iterate over an array: String[] arr = new String[] {""a"", ""b"", ""c""}; for (IndexedItem it : IndexedItem.iterate(arr)) System.out.println(it.getIndex() + "": "" + it.getItem()); } * * @author (c) Luke Hutchison 2010. Covered under the BSD license. * * @param * The type of the Iterable. */ public class IndexedItem { private T item; private int index = -1; /** Get the current item in the iteration. */ public T getItem() { return item; } /** Get the index of the current item (zero-indexed). */ public int getIndex() { return index; } private static class IndexedIterator implements Iterable>, Iterator> { private final Iterator collectionIter; private final IndexedItem currItem = new IndexedItem(); public IndexedIterator(Iterable collection) { this.collectionIter = collection.iterator(); } public IndexedIterator(final U[] array) { collectionIter = new Iterator() { U[] arr = array; IndexedItem it = currItem; @Override public boolean hasNext() { return it.index + 1 < arr.length; } @Override public U next() { return arr[it.index + 1]; } @Override public void remove() { for (int i = it.index + 2; i < arr.length; i++) arr[i] = arr[i + 1]; } }; } @Override public Iterator> iterator() { return this; } @Override public boolean hasNext() { return collectionIter.hasNext(); } @Override public IndexedItem next() { currItem.item = collectionIter.next(); currItem.index++; return currItem; } @Override public void remove() throws UnsupportedOperationException, IllegalStateException { collectionIter.remove(); currItem.index--; currItem.item = null; } } /** Iterate over an Iterable and keep track of the index */ public static Iterable> iterate(Iterable collection) { return new IndexedIterator(collection); } /** Iterate over an array T[] and keep track of the index */ public static Iterable> iterate(T[] array) { return new IndexedIterator(array); } } " B20388,"import java.util.*; import java.io.*; public class Tester { public static void main(String[]args) throws IOException { Scanner sc = new Scanner(new File(""C-large.in"")); int intNum = sc.nextInt(); sc.nextLine(); String[] first = new String[intNum]; String[] second =new String[intNum]; for(int i =0;ij) { //If it is greater than the first number recycle++;recycled.add(append); } } } } } System.out.println(""Case #"" + (i+1) + "": "" + recycle); } } } " B20883,"package com.google.codejam; public class CodeJamTest { public static void main(String[] args){ Utils.run(RecycledNumbers.class); } } " B21356,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Qualification; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author abdallah gaber */ public class RecycledNumbers { ///////////////////////////variables//////////////// public static void main(String[] args) { int res= 0 ,A,B,counter,number; String sA,sB,temp; int[] array = new int[7]; int cntarray=0; boolean flag = true; PrintWriter pw = null; Scanner sc = null; try { sc = new Scanner(new FileReader(""C:\\Users\\abdallah gaber\\Documents\\NetBeansProjects\\CodeJam2012\\src\\Qualification\\Clargeinput.in"")); pw = new PrintWriter(new FileWriter(""C:\\Users\\abdallah gaber\\Documents\\NetBeansProjects\\CodeJam2012\\src\\Qualification\\Clargeoutput.out"")); int casCnt=Integer.parseInt(sc.nextLine()); for(int cnt=0;cnt1) { //System.out.println(sA.substring(((counter-count)+1), (counter))+"" ""+sA.substring((counter-count))); temp = temp.substring(1,counter) + temp.charAt(0); number = Integer.parseInt(temp); for (int t=0;t=A&&j 1) { result *= i; i--; } return result; } } " B21694,"import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException { //variable initialization String inFile = args[0]; String outFile = inFile.split(""\\."")[0] + "".out""; //file reading... BufferedReader reader = new BufferedReader(new FileReader(inFile)); PrintWriter writer = new PrintWriter(new FileWriter(outFile)); //get input data int T = Integer.valueOf(reader.readLine()); for (int t = 0; t < T; t++) { String[] str_nums = reader.readLine().split("" ""); int A = Integer.valueOf(str_nums[0]); int B = Integer.valueOf(str_nums[1]); int count = 0; // for (int i = 1; i < 5; i++) { // for (int j = i+1; j < 5; j++) { // for (int k = 0; k < 10; k++) { // if (k == i || k == j) continue; // int shift = 1; // int n = i*100 + k*10 + j; // int m = n % (int)Math.pow(10, shift) * (int)Math.pow(10, 3 - shift) // + n / (int)Math.pow(10, shift); // count++; // System.out.print(n + ""->"" + m + "", ""); // shift = 2; // n = i*100 + j*10 + k; // m = n % (int)Math.pow(10, shift) * (int)Math.pow(10, 3 - shift) // + n / (int)Math.pow(10, shift); // count++; // System.out.print(n + ""->"" + m + "", ""); // // } // System.out.println(); // } // } int digits = String.valueOf(A).length(); for(int i = A; i < B; i++) { //Set chars = new HashSet(); //for (char c : String.valueOf(i).toCharArray()) chars.add(c); //if (chars.size() != digits) continue; Set olds = new HashSet(); for (int shift = 1; shift < digits; shift++) { int n = i; int m = n % (int)Math.pow(10, shift) * (int)Math.pow(10, digits - shift) + n / (int)Math.pow(10, shift); if (m < A || m > B || n >= m) continue; if (olds.contains(m)) continue; olds.add(m); count++; // if (t == 3) System.out.print(n + ""->"" + m + "", ""); } } String result = ""Case #"" + (t+1) + "": "" + count; writer.println(result); System.out.println(result); } reader.close(); writer.close(); } } " B21835,"import java.io.*; import java.util.*; public class C_RecycledNumbers { static String name = ""C-large""; static boolean been[]; static int f(int a, int b) { //System.out.println(a + "" "" + b); been[a] = true; int c = a; int num = 1, k = -1, ans = 1; while (c != 0) { c /= 10; num *= 10; k++; } num /= 10; c = a; for (int i = 0; i < k; i++) { int rem = a % 10; a /= 10; a += rem * num; if (a <= b && a >= c) { if (been[a]) continue; // System.out.println(a+"" ""+c); been[a] = true; ans++; } } return ans * (ans - 1) / 2; } public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader(new FileReader(name + "".in"")); PrintWriter out = new PrintWriter(name + "".out""); int t = Integer.parseInt(in.readLine()), caseN = 1; been = new boolean[10000000]; while (caseN <= t) { long ans = 0; StringTokenizer tok = new StringTokenizer(in.readLine()); int a = Integer.parseInt(tok.nextToken()), b = Integer.parseInt(tok .nextToken()); for (int i = a; i <= b; i++) { ans += f(i, b); } Arrays.fill(been, a, b + 10, false); out.print(""Case #""); out.print(caseN++); out.print("": ""); out.println(ans); } out.flush(); } } " B20039,"/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package google.code.jam.recycled.numbers; import java.io.*; import java.util.ArrayList; /** * * @author Lucas */ public class Utils { public ArrayList parse(String file) { BufferedReader in = null; ArrayList list = new ArrayList(); int size; try { in = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(file)))); size = Integer.parseInt(in.readLine()); for (int n = 0; n < size; n++) { String[] stringCases = in.readLine().split(""\\s+""); Integer[] cases = new Integer[2]; cases[0] = Integer.parseInt(stringCases[0]); cases[1] = Integer.parseInt(stringCases[1]); list.add(cases); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } return list; } public void write(ArrayList output, String file) { BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(file)); for (int n = 0; n < output.size() - 1; n++) { out.write(""Case #"" + (n + 1) + "": "" + output.get(n)); out.newLine(); } out.write(""Case #"" + output.size() + "": "" + output.get(output.size() - 1)); } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) { out.flush(); out.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } } " B21787,"import java.io.*; import java.util.*; import java.lang.Math.*; public class gcj3 { public static void main(String args[])throws Exception { //Scanner in=new Scanner(System.in); //BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //BufferedReader br = new BufferedReader(new FileReader(""gcj3.in"")); //PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(""gcj3.out""))); //PrintWriter pw = new PrintWriter(System.out); StringTokenizer st; BufferedReader br = new BufferedReader(new FileReader(""C:\\Users\\rahul\\Desktop\\gcj3.in"")); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(""C:\\Users\\rahul\\Desktop\\gcj3.out""))); int t=Integer.parseInt(br.readLine()); int ctr=0; while(t>0) { int total=0; t--;ctr++; st=new StringTokenizer(br.readLine()); int A=Integer.parseInt(st.nextToken()); int B=Integer.parseInt(st.nextToken()); int i,j,k,l; int ctr1=0,ctr2=0; for(i=A;i<=B;i++) { String s=Integer.toString(i); l=s.length(); String s1=s; int a[]=new int[l+1]; a[0]=-1; for(j=0;ji && a[j]!=a[j-1]) { ctr1++; } } pw.println(""Case #""+ctr+"": ""+ctr1); } pw.flush(); pw.close(); } }" B21099,"package recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class SimpleWriter { private BufferedWriter bw; private int line; public SimpleWriter() { String filename = prompt(); setWriter(filename); } public SimpleWriter(String filename) { setWriter(filename); } private String prompt() { System.out.println(""Output file: ""); BufferedReader bufr = new BufferedReader( new InputStreamReader(System.in)); String filename = null; try { filename = bufr.readLine(); } catch (IOException e) { System.err.println(""At prompt: "" + e.getMessage()); } return filename; } private void setWriter(String filename) { try { bw = new BufferedWriter(new FileWriter(filename)); } catch (IOException e) { System.err.println(e.getMessage()); } } public void writeLine(String str) { try { line++; bw.write(str + ""\n""); } catch (IOException e) { System.err.println(""Line "" + (line - 1) + "": "" + e.getMessage()); } } public void writeLine(int i) { writeLine(i + """"); } public void writeLine(int[] arr) { String line = """"; for (int i : arr) { line = line + i + "" ""; } line = line.trim(); writeLine(line); } public void flush() { try { bw.flush(); } catch (IOException e) { System.err.println(""At flush: "" + e.getMessage()); } } } " B21184,"import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class RecycledNumbers { /** * Input 4 1 9 10 40 100 500 1111 2222 * * Output * * Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // Reading the input file Scanner in = new Scanner(new File(""C-large.in"")); // writting the input file FileOutputStream fos = new FileOutputStream(""C-large.out""); PrintStream out = new PrintStream(fos); // Close the output stream int testCase = in.nextInt(); for (int i = 0; i < testCase; i++) { // System.out.println(""Case #"" + (i + 1) + "":\t""); out.print(""Case #"" + (i + 1) + "":\t""); long A = in.nextInt(); long B = in.nextInt(); long small; long large; if (A < B) { small = A; large = B; } else { small = B; large = A; } long numberOfDistinctDigit = 0; /* Start The Problem */ while (small <= large) { // count the digit String convert = String.valueOf(small); // System.out.println(convert); String src; String dest; String result; ArrayList firstRecord = new ArrayList<>(); for (int q = 0; q <= convert.length() - 1; q++) { if ((convert.length() == q) || (convert.length() == 1)) { dest = ""\t""; src = convert.substring(0, q + 1); result = dest + src; } else { dest = convert.substring(q + 1); src = convert.substring(0, q + 1); result = dest + src; } result = result.trim(); long resultlong = Integer.parseInt(result); if (result.length() == 1) { // System.out.println(""Single Digit Number""); } else { if ((resultlong <= large) && (resultlong > small) && (result.length() == convert.length()) && (Integer.parseInt(convert) != resultlong) && (!firstRecord.contains(resultlong))) { numberOfDistinctDigit++; firstRecord.add(resultlong); // System.out.println(""Result "" + resultlong + // "" Result "" + numberOfDistinctDigit); if (i == 3) { System.out.println(resultlong); } } } } small++; // System.out.println(""\n""); }// while out.print(numberOfDistinctDigit); out.print(""\n""); }// for in.close(); out.close(); fos.close(); // System.out.println(""________________________END___________________""); } public static String reverse(String s) { return new StringBuffer(s).reverse().toString(); } } " B22146,"import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashMap; public class Recycled { public static void main(String args[]) { try { BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(""c:\\gcj\\CL\\C-large.in""))); String line=br.readLine(); PrintStream ps=new PrintStream(""c:\\gcj\\CL\\C-large.out""); int n=Integer.parseInt(line); for(int i=1;i<=n;i++) { line=br.readLine(); String[] nums=line.split("" ""); long A=Long.parseLong(nums[0]); long B=Long.parseLong(nums[1]); ps.println(""Case #""+i+"": ""+getCount(A,B)); } } catch(Exception e) { e.printStackTrace(); } //System.out.print(""""+getCount(105279,1957139)); } public static long getCount(long A, long B) { long count=0; for(long i=A;i<=B;i++) { //for(long j=i+1;j<=B;j++) /*{ if(j>i && isRecycled(i,j)) { //hm.put(i, j); count++; System.out.println(""C:""+count); } }*/ count+=getRecycled(i, B); } return count; } static long getRecycled(long n,long limit) { long temp=n; int numDigits=String.valueOf(n).length(); long count=0; long denom=(long)Math.pow(10, numDigits-1); temp=n; // int digit=firstDigit; long sub=0; do { int firstDigit=(int)(temp/denom); sub=denom*firstDigit; //int digit=(int)temp%10; temp=temp-sub; temp=temp*10+firstDigit; if(temp>n && temp<=limit) { count++; } } while(temp!=n); /* String strN=String.valueOf(n); StringBuilder strM=new StringBuilder(String.valueOf(m)); for(int i=0;i 0) { digit++; baseAndMask *= 10; } long i; for (i = A; i < B; i++) { int k = digit; long recycled = i * baseAndMask + i; while (k-- > 0) { long j = recycled % baseAndMask; if (j <= B && j > i) { result++; } recycled = recycled / 10; } } output.printf(""Case #%d: %d\n"", testcase, result); } output.close(); } } " B22221,"package tr0llhoehle.cakemix.googleCodeJam.recycledNumbers; import java.io.IOException; import java.text.ParseException; import tr0llhoehle.cakemix.utility.googleCodeJam.IOManager; public class Main { /** * @param args */ public static void main(String[] args) { if (args.length >= 1) { IOManager io = new IOManager( new RNSolver(), (Class) new RNProblem().getClass()); try { io.start(args[0]); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } " B21181,"import java.io.*; import java.util.ArrayList; public class inpOutHandler { public testCase readInput(String fname, int linesInTestCase){ testCase allCases; ArrayList lineList = new ArrayList(); BufferedReader rd = null; try { rd = new BufferedReader(new FileReader(fname)); while (true) { String line = rd.readLine(); if (line == null) break; lineList.add(line); } rd.close(); } catch (IOException ex) { System.out.println(""Can't open that file.""); } //for(int i=0;i""); int N = Integer.parseInt(lineList.get(0)); //int N=100; allCases = new testCase(N); int index=1; for(int i=0;i set = new HashSet(); // System.out.println(""------------ ""); String in = reader.readLine(); int A = Integer.parseInt(in.split("" "")[0]); int B = Integer.parseInt(in.split("" "")[1]); //System.out.println(""A = "" + A); //System.out.println(""B = "" + B); int cyfr = 1+ (int) Math.log10(A); //System.out.println(""cyfr = "" + cyfr); int out = 0; for(int j = A; j<=B; j++){ // System.out.println(""j = "" + j); for(int k =1 ; k=A) && (nowa <=B) ){ set.add(""""+nowa+""_""+j); } } } System.out.println(""Case #""+(i+1)+"": ""+set.size()); writer.write(""Case #""+(i+1)+"": ""+set.size()); writer.newLine(); } writer.close(); } } " B21124,"import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Scanner; public class leadingZero { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader read = new BufferedReader(new InputStreamReader( System.in)); String ll; ll = read.readLine(); int a = Integer.parseInt(ll); for (int k = 0; k < a; k++) { Scanner scn=new Scanner(read.readLine()); int A = scn.nextInt(); int B = scn.nextInt(); int[] s = new int[20000000]; for (int i = A; i <= B; i++) { String r = i + """"; int l = i; LinkedListlist=new LinkedList(); for (int j = 0; j < r.length() - 1; j++) { int b = l % 10; l = l / 10 + (int) Math.pow(10, r.length() - 1) * b; if (l > i && !list.contains(l)) { s[l]++; list.add(l); } } } int sum = 0; for (int i = A; i <= B; i++) { if (s[i] > 0) { sum += s[i]; //System.out.println(i+"" .. ""+s[i]); } } System.out.println(""Case #""+(k+1)+"": ""+sum); } } } " B21859,"import java.io.*; import java.util.*; public class Revn{ static int bt[]={0,10,100,1000,10000,100000,1000000},gl[]=new int[2000001];; public static void main(String args[])throws Exception{ BufferedReader br=new BufferedReader(new FileReader(""ginp.txt"")); PrintWriter pr=new PrintWriter(""Revn.txt""); int i=0,j=0,k=0,a=0,b=0,tc=Integer.parseInt(br.readLine());long co=0; StringTokenizer st=null; for(k=1;k<=tc;k++) {st=new StringTokenizer(br.readLine()); a=Integer.parseInt(st.nextToken()); b=Integer.parseInt(st.nextToken()); co=0; for(i=a;ix&&ty<=y&&gl[ty]==0?ry+1:ry; if(ty 0){ output = ""Case #"" + (totalround - round + 1) + "": ""; read = in.readLine(); split = read.split("" ""); integerA = Integer.parseInt(split[0]); integerB = Integer.parseInt(split[1]); total = 0; //try every possibility for(int i = integerA; i < integerB; i++){ String num = Integer.toString(i); ArrayList array = new ArrayList(); //try to move digits from back to front for(int j = 1; j < num.length(); j++){ String front = num.substring(0, j); String back = num.substring(j); back += front; int compare = Integer.parseInt(back); //check if the digit after moved falls in range if((!array.contains(compare)) && (compare > i) && (compare <= integerB)){ array.add(compare); total++; } } } output += total; //write output to file out.write(output); if(round != 1) out.newLine(); round--; } in.close(); out.close(); }catch(Exception e){ System.err.print(e); } } } " B21467,"package com.renoux.gael.codejam.cj2012.qc; import java.util.HashSet; import java.util.Set; import com.renoux.gael.codejam.fwk.Solver; import com.renoux.gael.codejam.utils.ArrayUtils; import com.renoux.gael.codejam.utils.Input; import com.renoux.gael.codejam.utils.Output; public class QC extends Solver { public static void main(String... args) throws Exception { new QC().run(); } @Override protected void solveCase(Input in, Output out) { System.out.println(); int[] line = ArrayUtils.parseInts(in.readLine().split("" "")); int a = line[0]; int b = line[1]; Set pairs = new HashSet(); for (int i = a; i < b; i++) { String number = Integer.toString(i); for (int k = 1; k < number.length(); k++) { String modified = number.substring(k) + number.substring(0, k); int value = Integer.parseInt(modified); if (i < value && value <= b) { // System.out.println(i + "" "" + value); Pair p = new Pair(i, value); if (!pairs.add(p)) { // System.out.println(""Duplicata !!!""); } } } } out.writeLine(pairs.size()); } @Override protected String getProblemName() { return ""QC""; } @Override protected boolean disableSample() { return true; } @Override protected boolean disableLarge() { return true; } public static class Pair { public int m, n; public Pair(int m, int n) { this.m = m; this.n = n; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + m; result = prime * result + n; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (m != other.m) return false; if (n != other.n) return false; return true; } } } " B21586,"/************************************************************************* * Compilation: javac In.java * Execution: java In * * Reads in data of various types from: stdin, file, URL. * * % java In * * Remarks * ------- * - isEmpty() returns true if there is no more input or * it is all whitespace. This might lead to surprising behavior * when used with readChar() * *************************************************************************/ import java.net.URLConnection; import java.net.URL; import java.net.Socket; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.BufferedInputStream; import java.util.Scanner; import java.util.Locale; /** * Input. This class provides methods for reading strings * and numbers from standard input, file input, URL, and socket. *