F1
stringlengths
6
6
F2
stringlengths
6
6
label
stringclasses
2 values
text_1
stringlengths
149
20.2k
text_2
stringlengths
48
42.7k
A12846
A12396
0
/* * 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<List<String>> loadInputsExcludes(String fileName) { List<List<String>> result = new ArrayList<List<String>>(); List<String> 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<String> dataList = new ArrayList<String>(); 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<List<String>> loadInputs(String fileName) { List<List<String>> result = new ArrayList<List<String>>(); List<String> lines = FileUtil.readLines(FILE_ROOT + fileName); for (String line : lines) { List<String> dataList = new ArrayList<String>(); 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<String> loadInputLines(String fileName) { return FileUtil.readLines(FILE_ROOT + fileName); } public static void writeOutputs(String fileName, List<String> lines) { FileUtil.writeLines(FILE_ROOT + fileName, lines); } }
public class possible { int Anom; int High; int count = 0; possible(int anom, int high){ Anom = anom; High = high; } public void canDo(int score){ int Score = score; if(High > 0 && Score - High - (2 * (High- 1 )) >= 0){ ++count; }else if( Anom > 0 && High > 1 && Score - High - (2 * (High- 2 )) >= 0 ){ ++count; --Anom; }else if( High == 0){ ++count; } } }
B22190
B20319
0
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<Long> used = new HashSet<Long>(); 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(); } }
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;i<s.length;i++){ count[i]=RecyclePairs(Integer.parseInt(s[i][0]),Integer.parseInt(s[i][1])); System.out.println("Case #"+(i+1)+": "+count[i]); } } public static int RecyclePairs(int A, int B) { int totalCount=-1; String sA=A+""; String sB=B+""; char c1[]=sA.toCharArray(); char c2[]=sB.toCharArray(); for(int i=0; i<sA.length();i++) { for(int j=i;j<sA.length();j++) { if(c1[i] != c1[j] || c2[i]!=c2[j]) { totalCount=0; break; } } } if(sA.length() == 1) totalCount=0; for(int n=A;n<=B;n++) { totalCount+=getAllCycleNumbers(n, A, B); } return totalCount; } public static int getAllCycleNumbers(int n, int A, int B) { String sN=n+""; int count =0; int m; for(int i=1;i<=sN.length()-1;i++){ m=crossOver(sN, i); // System.out.println("The crossover "+m); if(m>n && 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<cuttingPoint;i++) s1+=c[i]; for(int i=cuttingPoint;i<s.length();i++) s2+=c[i]; result=s2+s1; r=Integer.parseInt(result); return r; } public static String[][] TextLines(String FileName){ int NumberOfLines; String [] testCases=null; String [] [] tokens=null; 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; NumberOfLines=Integer.parseInt(br.readLine()); testCases=new String[NumberOfLines]; tokens =new String [NumberOfLines][2]; int i=0; //Read File Line By Line StringTokenizer stk; while (i<NumberOfLines) { testCases[i]=br.readLine(); stk=new StringTokenizer(testCases[i]," "); while(stk.hasMoreTokens()) { tokens[i][0]=stk.nextToken(); tokens[i][1]=stk.nextToken(); } i++; } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } return tokens; } }
A11277
A11256
0
package googlers; import java.util.Scanner; import java.util.PriorityQueue; import java.util.Comparator; public class Googlers { public static void main(String[] args) { int n,s,p,count=0,t; Scanner sin=new Scanner(System.in); t=Integer.parseInt(sin.nextLine()); int result[]=new int[t]; int j=0; if(t>=1 && t<=100) { for (int k = 0; k < t; k++) { count=0; String ip = sin.nextLine(); String[]tokens=ip.split(" "); n=Integer.parseInt(tokens[0]); s=Integer.parseInt(tokens[1]); p=Integer.parseInt(tokens[2]); if( (s>=0 && s<=n) && (p>=0 && p<=10) ) { int[] total=new int[n]; for (int i = 0; i < n; i++) { total[i] = Integer.parseInt(tokens[i+3]); } Comparator comparator=new PointComparator(); PriorityQueue pq=new PriorityQueue<Point>(1, comparator); for (int i = 0; i < n; i++) { int x=total[i]/3; int r=total[i]%3; if(x>=p) count++; else if(x<(p-2)) continue; else { //System.out.println("enter "+x+" "+(p-2)); if(p-x==1) { Point temp=new Point(); temp.q=x; temp.r=r; pq.add(temp); } else // p-x=2 { if(r==0) continue; else { Point temp=new Point(); temp.q=x; temp.r=r; pq.add(temp); } } } //System.out.println("hi "+pq.size()); } while(pq.size()!=0) { Point temp=(Point)pq.remove(); if(p-temp.q==1 && temp.q!=0) { if(temp.r>=1) count++; else { if(s!=0) { s--; count++; } } } else if(p-temp.q==2) { if(s!=0 && (temp.q+temp.r)>=p) { s--; count++; } } } //System.out.println(p); result[j++]=count; } } for (int i = 0; i < t; i++) { System.out.println("Case #"+(i+1)+": "+result[i]); } } } /*Point x=new Point(); x.q=8; Point y=new Point(); y.q=6; Point z=new Point(); z.q=7; pq.add(x); pq.add(y); pq.add(z); */ } class PointComparator implements Comparator<Point> { @Override public int compare(Point x, Point y) { // Assume neither string is null. Real code should // probably be more robust if (x.q < y.q) { return 1; } if (x.q > y.q) { return -1; } return 0; } } class Point { int q,r; public int getQ() { return q; } public void setQ(int q) { this.q = q; } public int getR() { return r; } public void setR(int r) { this.r = r; } }
package codeJam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Dance { public static void main(String[] args) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { FileWriter fstream = new FileWriter("Dance.txt"); BufferedWriter out = new BufferedWriter(fstream); int noTestCases = Integer.parseInt(in.readLine()); for (int i = 1; i <= noTestCases; i++) { out.write("\nCase #" + i + ": "); String[] inputs = in.readLine().split(" "); int surprise = Integer.parseInt(inputs[1]); int minMark = Integer.parseInt(inputs[2]); int result = 0; List<Integer> lessmarks = new ArrayList<Integer>(); for (int j = 3; j < inputs.length; j++) { int div = Integer.parseInt(inputs[j]) / 3; int mod = Integer.parseInt(inputs[j]) % 3; if (mod > 0) { div++; } if (div >= minMark) { result++; } else if (Integer.parseInt(inputs[j]) > 0) { lessmarks.add(Integer.parseInt(inputs[j])); } } if (surprise > 0 && !lessmarks.isEmpty()) { int ite = 0; for (int z = 0; z < lessmarks.size() && surprise > 0; z++) { ite++; if (ite > lessmarks.size() * 3 && surprise == Integer.parseInt(inputs[1])) { break; } int mark = lessmarks.get(z); int div = mark / 3; int mod = mark % 3; if (mod > 0) div++; if (minMark - div > 2) continue; div++; if (div >= minMark) { result++; lessmarks.remove(z); } surprise--; if (z + 1 == lessmarks.size() && surprise > 0) { z = 0; } } } out.write(Integer.toString(result)); } out.close(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
A12846
A11090
0
/* * 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<List<String>> loadInputsExcludes(String fileName) { List<List<String>> result = new ArrayList<List<String>>(); List<String> 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<String> dataList = new ArrayList<String>(); 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<List<String>> loadInputs(String fileName) { List<List<String>> result = new ArrayList<List<String>>(); List<String> lines = FileUtil.readLines(FILE_ROOT + fileName); for (String line : lines) { List<String> dataList = new ArrayList<String>(); 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<String> loadInputLines(String fileName) { return FileUtil.readLines(FILE_ROOT + fileName); } public static void writeOutputs(String fileName, List<String> lines) { FileUtil.writeLines(FILE_ROOT + fileName, lines); } }
package DancingWithTheGooglers; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.Collections; import java.util.Scanner; import java.util.ArrayList; public class DancingWithTheGooglers { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new FileInputStream("input.txt")); PrintWriter out = new PrintWriter(new FileOutputStream("output.txt")); int lines = in.nextInt(); in.nextLine(); int counter = 0; for (;counter<lines;counter++) { out.write("Case #" + (counter+1) + ": "); int n = in.nextInt(); int s = in.nextInt(); int p = in.nextInt(); int finalCount = 0; ArrayList<Integer> scores = new ArrayList<Integer>(); for (int i = 0; i<n; i++) { scores.add(in.nextInt()); } Collections.sort(scores); for (int i: scores) { if (i<p) continue; else if ((((i-2)/3)+2)<p) continue; else if ((((i-1)/3)+1)>=p) finalCount++; else if (s>0) { s--; finalCount++; } } out.write(finalCount + "\n"); } in.close(); out.close(); } }
B12762
B10225
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.File; import java.io.FileInputStream; import java.util.Scanner; /** * * @author imgps */ public class C { public static void main(String args[]) throws Exception{ int A,B; int ctr = 0; int testCases; Scanner sc = new Scanner(new FileInputStream("C-small-attempt0.in ")); testCases = sc.nextInt(); int input[][] = new int[testCases][2]; for(int i=0;i<testCases;i++) { // System.out.print("Enter input A B: "); input[i][0] = sc.nextInt(); input[i][1] = sc.nextInt(); } for(int k=0;k<testCases;k++){ ctr = 0; A = input[k][0]; B = input[k][1]; for(int i = A;i<=B;i++){ int num = i; int nMul = 1; int mul = 1; int tnum = num/10; while(tnum > 0){ mul = mul *10; tnum= tnum/10; } tnum = num; int n = 0; while(tnum > 0 && mul >= 10){ nMul = nMul * 10; n = (num % nMul) * mul + (num / nMul); mul = mul / 10; tnum = tnum / 10; for(int m=num;m<=B;m++){ if(n == m && m > num){ ctr++; } } } } System.out.println("Case #"+(k+1)+": "+ctr); } } }
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-small-attempt0.in", "out/C-small.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<Pair> pairs = new TreeSet<Pair>(); 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<Pair> 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; } }
B21207
B21058
0
/* * 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 <marco.lackovic@gmail.com> * @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; } }
/** * 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<Integer,Integer> table = new HashMap<Integer,Integer>(); for(int l=1; l<number.length(); l++) { String reverse = moveFromEndToFront(number,l); int numberVal = Integer.valueOf(number); int reverseVal = Integer.valueOf(reverse); if( (reverseVal <= max) && (numberVal < reverseVal) ) table.put(reverseVal, numberVal); } cpt += table.size(); } System.out.println("Case #" + i + ": " + cpt); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block System.out.println("File not found"); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
A21010
A22673
0
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<Integer, Integer>(index, value). Array must * have at least one value. */ public static Pair<Integer, Integer> 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<Integer, Integer>(argMin, min); } /** * ArgMax returned as a Pair<Integer, Integer>(index, value). Array must * have at least one value. */ public static Pair<Integer, Integer> 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<Integer, Integer>(argMax, max); } }
/* ID: 14vikra1 LANG: JAVA TASK: dancescore */ import java.io.*; import java.util.*; class dancescore { public static void main (String [] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("dancescore.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("dancescore.out"))); int T = Integer.parseInt(br.readLine()); for (int i = 0; i < T; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int S = Integer.parseInt(st.nextToken()); int p = Integer.parseInt(st.nextToken()); int surprise = 0; int work = 0; for (int j = 0; j < N; j++) { int current = Integer.parseInt(st.nextToken()); if (current%3 != 0 && current >= 2) { if (Math.ceil(current/3) + 1 >= p) { work++; } else if (Math.ceil(current/3) + 2 >= p) { surprise++; } } else if (current >= 2) { if (Math.ceil(current/3) >= p) { work++; } else if (Math.ceil(current/3) + 1 >= p) { surprise++; } } else { if (current == 1 && p <= 1) { work++; } else if (current == 1 && p == 2) { surprise++; } else if (current == 0 && p == 0) { work++; } } } int answer = work + Math.min(S, surprise); out.println("Case #" + (i+1) + ": " + answer); } out.close(); System.exit(0); } }
A21396
A20391
0
import java.util.*; public class Test { public static void main(String[] args){ Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int i = 1; i<=T; i++) { int n = in.nextInt(); int s = in.nextInt(); int p = in.nextInt(); int result = 0; for(int j = 0; j<n; j++){ int x = canAddUp(in.nextInt(), p); if(x == 0) { result++; } else if (x==1 && s > 0) { result++; s--; } } System.out.println("Case #"+i+": "+result); } } public static int canAddUp(int sum, int limit) { boolean flag = false; for(int i = 0; i<=sum; i++) { for(int j = 0; i+j <= sum; j++) { int k = sum-(i+j); int a = Math.abs(i-j); int b = Math.abs(i-k); int c = Math.abs(j-k); if(a > 2 || b > 2 || c> 2){ continue; } if (i>=limit || j>=limit || k>=limit) { if(a < 2 && b < 2 && c < 2) { return 0; }else{ flag = true; } } } } return (flag) ? 1 : 2; } }
package codejam2012; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; /** * * @author devashish */ public class ProblemB { public static void main(String[] args) { StringTokenizer st = null; BufferedReader in; PrintWriter out = null; try { in = new BufferedReader(new FileReader(new File("E:/b.in"))); out = new PrintWriter(new FileWriter(new File("E:/b.out"))); while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } int t = Integer.parseInt(st.nextToken()); for (int i = 1; i <= t; i++) { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } int N = Integer.parseInt(st.nextToken()); int S = Integer.parseInt(st.nextToken()); int p = Integer.parseInt(st.nextToken()); int[] T = new int[N]; for (int j = 0; j < N; j++) { T[j] = Integer.parseInt(st.nextToken()); } int outputLine = maxGooglers(N, S, p, T); out.print("Case #" + i + ": " + outputLine + "\n"); } } catch (IOException e) { } out.flush(); } private static int maxGooglers(int N, int S, int p, int[] T) { int output = 0; int surprisingMinScore = Math.max(3 * p - 4, 0) ; int nonSurprisingMinScore = Math.max(3 * p - 2, 0); int countSurprise = 0; // System.out.println(surprisingMinScore); // System.out.println(nonSurprisingMinScore); for (int i = 0; i < T.length; i++) { // System.out.println(T[i]); // System.out.println("T[i]: " + T[i]); if (T[i] < surprisingMinScore) { continue; } else if (T[i] >= surprisingMinScore && T[i] < nonSurprisingMinScore) { //either surprising or low scores //countSurprise += findPossibleSurprisingScoresWithBestResult(T[i], p); if (S > 0 && T[i] >= 2) { countSurprise += findPossibleSurprisingScoresWithBestResult(T[i], p); // System.out.println("#countSurprise: " + countSurprise); //output += findPossibleSurprisingScoresWithBestResult(T[i], p); } } else if (T[i] >= nonSurprisingMinScore) { //Non surprising score //System.out.println("non surprising score."); output++; } } //System.out.println("#output: " + output); //System.out.println((countSurprise < S ? countSurprise : S)); return output + (countSurprise < S ? countSurprise : S); } private static int findPossibleSurprisingScoresWithBestResult(int t, int p) { int count = 0; int a = t/3; int b = ((t + 4)/3); if (p >= a && p <=b) { count++; } //System.out.println("#count:" + count); return count; } }
B20023
B21278
0
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<Integer> db=new HashSet<Integer>(); for (int j=1; j<e1.length();j++){ String e2=e1.substring(j)+e1.substring(0,j); Integer k=Integer.parseInt(e2); if (k>i && 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;i<tnum;i++) { // while loop begins here thisLine=br.readLine(); System.out.println(thisLine); System.out.println("Case #"+(i+1)+": "+a.szamol(thisLine)+"\n"); bw.write("Case #"+(i+1)+": "+a.szamol(thisLine)+"\n"); } // end while // end try br.close(); bw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
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)); } }
B21207
B20852
0
/* * 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 <marco.lackovic@gmail.com> * @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; } }
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); } } }
A12113
A11649
0
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class B { static int[][] memo; static int[] nums; static int p; public static void main(String[] args)throws IOException { Scanner br=new Scanner(new File("B-small-attempt0.in")); PrintWriter out=new PrintWriter(new File("b.out")); int cases=br.nextInt(); for(int c=1;c<=cases;c++) { int n=br.nextInt(),s=br.nextInt(); p=br.nextInt(); nums=new int[n]; for(int i=0;i<n;i++) nums[i]=br.nextInt(); memo=new int[n][s+1]; for(int[] a:memo) Arrays.fill(a,-1); out.printf("Case #%d: %d\n",c,go(0,s)); } out.close(); } public static int go(int index,int s) { if(index>=nums.length) return 0; if(memo[index][s]!=-1) return memo[index][s]; int best=0; for(int i=0;i<=10;i++) { int max=i; for(int j=0;j<=10;j++) { if(Math.abs(i-j)>2) continue; max=Math.max(i,j); thisone: for(int k=0;k<=10;k++) { int ret=0; if(Math.abs(i-k)>2||Math.abs(j-k)>2) continue; max=Math.max(max,k); int count=0; if(Math.abs(i-k)==2) count++; if(Math.abs(i-j)==2) count++; if(Math.abs(j-k)==2) count++; if(i+j+k==nums[index]) { boolean surp=(count>=1); if(surp&&s>0) { if(max>=p) ret++; ret+=go(index+1,s-1); } else if(!surp) { if(max>=p) ret++; ret+=go(index+1,s); } best=Math.max(best,ret); } else if(i+j+k>nums[index]) break thisone; } } } return memo[index][s]=best; } }
/* * 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<String> loadFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); String in; ArrayList<String> lines = new ArrayList<String>(); while ((in = br.readLine()) != null) { lines.add(in); } return lines; } }
B10231
B10566
0
import java.io.*; class code1 { public static void main(String args[]) throws Exception { File ii = new File ("C-small-attempt1.in"); FileInputStream fis = new FileInputStream(ii); BufferedReader br = new BufferedReader(new InputStreamReader (fis)); int cases = Integer.parseInt(br.readLine()); FileOutputStream fout = new FileOutputStream ("output.txt"); DataOutputStream dout = new DataOutputStream (fout); int total=0; for(int i=0;i<cases;i++){ String temp = br.readLine(); String parts [] = temp.split(" "); int lower = Integer.parseInt(parts[0]); int upper = Integer.parseInt(parts[1]); System.out.println(lower+" "+upper); for(int j=lower;j<=upper;j++) { int abc = j;int length=0; if(j<10)continue; while (abc!=0){abc/=10;length++;} abc=j; for(int m=0;m<length-1;m++){ int shift = abc%10; abc=abc/10; System.out.println("hi "+j); abc=abc+shift*power(10,length-1); if(abc<=upper&&shift!=0&&abc>j)total++; System.out.println(total); } } dout.writeBytes("Case #"+(i+1)+ ": "+total+"\n"); total=0; }//for close } private static int power(int i, int j) { int no=1; for(int a=0;a<j;a++){no=10*no;} return no; } }
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; } }
B21207
B20040
0
/* * 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 <marco.lackovic@gmail.com> * @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; } }
/* * 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"); } }
A20382
A20391
0
package dancinggooglers; import java.io.File; import java.util.Scanner; public class DanceScoreCalculator { 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 <filename>"); 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(); DanceScoreCase danceCase = new DanceScoreCase(googleDancerLine); System.out.println(String.format("Case #%d: %d", i, danceCase.maxDancersThatCouldPass())); } } catch (Exception e) { e.printStackTrace(); } } }
package codejam2012; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; /** * * @author devashish */ public class ProblemB { public static void main(String[] args) { StringTokenizer st = null; BufferedReader in; PrintWriter out = null; try { in = new BufferedReader(new FileReader(new File("E:/b.in"))); out = new PrintWriter(new FileWriter(new File("E:/b.out"))); while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } int t = Integer.parseInt(st.nextToken()); for (int i = 1; i <= t; i++) { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } int N = Integer.parseInt(st.nextToken()); int S = Integer.parseInt(st.nextToken()); int p = Integer.parseInt(st.nextToken()); int[] T = new int[N]; for (int j = 0; j < N; j++) { T[j] = Integer.parseInt(st.nextToken()); } int outputLine = maxGooglers(N, S, p, T); out.print("Case #" + i + ": " + outputLine + "\n"); } } catch (IOException e) { } out.flush(); } private static int maxGooglers(int N, int S, int p, int[] T) { int output = 0; int surprisingMinScore = Math.max(3 * p - 4, 0) ; int nonSurprisingMinScore = Math.max(3 * p - 2, 0); int countSurprise = 0; // System.out.println(surprisingMinScore); // System.out.println(nonSurprisingMinScore); for (int i = 0; i < T.length; i++) { // System.out.println(T[i]); // System.out.println("T[i]: " + T[i]); if (T[i] < surprisingMinScore) { continue; } else if (T[i] >= surprisingMinScore && T[i] < nonSurprisingMinScore) { //either surprising or low scores //countSurprise += findPossibleSurprisingScoresWithBestResult(T[i], p); if (S > 0 && T[i] >= 2) { countSurprise += findPossibleSurprisingScoresWithBestResult(T[i], p); // System.out.println("#countSurprise: " + countSurprise); //output += findPossibleSurprisingScoresWithBestResult(T[i], p); } } else if (T[i] >= nonSurprisingMinScore) { //Non surprising score //System.out.println("non surprising score."); output++; } } //System.out.println("#output: " + output); //System.out.println((countSurprise < S ? countSurprise : S)); return output + (countSurprise < S ? countSurprise : S); } private static int findPossibleSurprisingScoresWithBestResult(int t, int p) { int count = 0; int a = t/3; int b = ((t + 4)/3); if (p >= a && p <=b) { count++; } //System.out.println("#count:" + count); return count; } }
A10699
A13194
0
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; public class Dancing { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // read input file File file = new File("B-small-attempt4.in"); //File file = new File("input.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String ln = ""; int count = Integer.parseInt(br.readLine()); // write output file File out = new File("outB.txt"); BufferedWriter bw = new BufferedWriter(new FileWriter(out)); int y = 0; for (int i=0; i < count; i++){ ln = br.readLine(); y = getY(ln); bw.write("Case #" + (i+1) + ": " + y); bw.newLine(); } bw.close(); } private static int getY(String str) { String[] data = str.split(" "); int n = Integer.parseInt(data[0]); int s = Integer.parseInt(data[1]); int p = Integer.parseInt(data[2]); int[] t = new int[n]; for (int i=0; i < n; i++){ t[i] = Integer.parseInt(data[i+3]); } int y = 0; int base = 0; for(int j=0; j < t.length; j++){ base = t[j] / 3; if(base >= p) { y++; } else if(base == p-1){ if(t[j] - (base+p) > base-1 && t[j] > 0){ y++; } else if(s>0 && t[j] - (base+p) > base-2 && t[j] > 0){ s -= 1; y++; } } else if(base == p-2){ if(s > 0 && t[j] - (base+p) > base-1 && t[j] > 0){ s -= 1; y++; } } } return y; } }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class ProblemB { 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<numTestCases; testCase++){ split=reader.readLine().split("\\s+"); int n=Integer.parseInt(split[0]); int s=Integer.parseInt(split[1]); int p=Integer.parseInt(split[2]); int a, b; int curr; int res=0; for (int i=0; i<n; i++){ curr=Integer.parseInt(split[i+3]); a=(curr+2)/3; if (curr<2||curr>28) b=-1; else b=(curr+4)/3; if (a>=p) res++; else if (s>0&&b>=p){ res++; s--; } } System.out.println("Case #"+(testCase+1)+": "+res); } } }
B10702
B10541
0
import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class Recycle { private static HashMap<Integer, HashSet<Integer>> map = new HashMap<Integer, HashSet<Integer>>(); private static HashSet<Integer> toSkip = new HashSet<Integer>(); /** * @param args */ public static void main(String[] args) { Scanner reader = new Scanner(System.in); int T = reader.nextInt(); for (int tc = 1; tc <= T; tc++) { int a = reader.nextInt(); int b = reader.nextInt(); long before = System.currentTimeMillis(); int res = doit(a, b); System.out.printf("Case #%d: %d\n", tc, res); long after = System.currentTimeMillis(); // System.out.println("time taken: " + (after - before)); } } private static int doit(int a, int b) { int count = 0; HashSet<Integer> skip = new HashSet<Integer>(toSkip); for (int i = a; i <= b; i++) { if (skip.contains(i)) continue; HashSet<Integer> arr = generate(i); // if(arr.size() > 1) { // map.put(i, arr); // } // System.out.println(i + " --> " + // Arrays.deepToString(arr.toArray())); int temp = 0; if (arr.size() > 1) { for (int x : arr) { if (x >= a && x <= b) { temp++; skip.add(x); } } count += temp * (temp - 1) / 2; } // System.out.println("not skipping " + i + " gen: " + arr.size()+ " " + (temp * (temp - 1) / 2)); } return count; } private static HashSet<Integer> generate(int num) { if(map.containsKey(num)) { HashSet<Integer> list = map.get(num); return list; } HashSet<Integer> list = new HashSet<Integer>(); String s = "" + num; list.add(num); int len = s.length(); for (int i = 1; i < len; i++) { String temp = s.substring(i) + s.substring(0, i); // System.out.println("temp: " + temp); if (temp.charAt(0) == '0') continue; int x = Integer.parseInt(temp); if( x <= 2000000) { list.add(x); } } if(list.size() > 1) { map.put(num, list); } else { toSkip.add(num); } return list; } }
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; } }
B10155
B11209
0
/* * 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-small-attempt0", 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); } } } }
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<T; i++) { int A = in.nextInt(); int B = in.nextInt(); long res = 0; for (int X=A; X<B; X++) { int D = digits(X); HashSet<Integer> set = new HashSet<Integer>(); for (int j=1; j<D; j++) { int C = moveLast(X, j); if (C > 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<digits; i++) p *= 10; last = X % p; while ((p2*10)<=X) p2 *= 10; return last*(p2/p)*10 + (X / p); } public static int digits(int X) { int k = 0; while (X > 0) { X /= 10; k++; } return k; } }
B12570
B10523
0
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)); } } }
package gcj2012qr; import java.io.*; import java.util.*; import java.util.concurrent.*; import com.google.*; /** * @author Roman Kosenko <madkite@gmail.com> */ public class RecycledNumbers extends SingleThreadSolution<Object> { public static void main(String[] args) throws Exception { solve(new SolutionFactory<Object>() { public Callable<Object> 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-small-attempt0.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); } }
A20490
A20204
0
/** * */ 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<input folder>:\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<output folder>:\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); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.util.*; import java.io.*; public class DancingWithGooglers { public static void main(String[] args) throws Exception { Scanner input = new Scanner(new File("C:\\temp\\B-large.in")); int A = input.nextInt(); for (int c = 1; c <= A; c++) { int N = input.nextInt(); int S = input.nextInt(); int p = input.nextInt(); double[] t = new double[N]; for (int n = 0; n < N; n++) { t[n] = input.nextInt(); } int a = 0; for (int i = 0; i < t.length; i++) { for (int j = p; j <= 10; j++) { if (p == 0 && t[i] == 0) { a++; break; } else if (j >= p && j*3-t[i] <= 2 && t[i] > j) { a++; break; } else if (j >= p && j*3-t[i] <=4 && t[i] > j && S>0) { S--; a++; break; } } } System.out.println("Case #" + c + ": " + a); } } }
B10245
B11194
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.util.HashSet; /** * * @author vandit */ public class RecycleNumbers { private HashSet<String> numbers = new HashSet<String>(); private HashSet<String> initialTempNumbers = new HashSet<String>(); private HashSet<String> finalTempNumbers = new HashSet<String>(); HashSet<Pair> numberPairs = new HashSet<Pair>(); private void findRecycledNumbers(int start, int end, int places) { for (int i = start; i <= end; i++) { String initialNumber = Integer.toString(i); //if (!(numbers.contains(initialNumber) || finalTempNumbers.contains(initialNumber))) { StringBuffer tempNumber = new StringBuffer(initialNumber); int len = tempNumber.length(); int startIndexToMove = len - places; String tempString = tempNumber.substring(startIndexToMove); if ((places == 1 && tempString.equals("0")) || tempString.charAt(0) == '0') { continue; } tempNumber.delete(startIndexToMove, len); String finalTempNumber = tempString + tempNumber.toString(); if (! (finalTempNumber.equals(initialNumber) || Integer.parseInt(finalTempNumber) > end || Integer.parseInt(finalTempNumber) < Integer.parseInt(initialNumber))) { numbers.add(initialNumber); finalTempNumbers.add(finalTempNumber); Pair pair = new Pair(finalTempNumber,initialNumber); numberPairs.add(pair); } } } public HashSet<Pair> findAllRecycledNumbers(int start, int end) { int length = Integer.toString(start).length(); for (int i = 1; i < length; i++) { findRecycledNumbers(start, end, i); } return numberPairs; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication18; /** * * @author USER-1 */ import java.io.*; public class Main { /** * @param args the command line arguments */ public static boolean check_recycled(int m,int n) { int rem=0,div=m; Integer k=new Integer(m); Integer k1=new Integer(n); String g=k.toString(); String g1=k1.toString(); int c=0,l=g.length(),l1=g1.length(); while(c<l) { int w=0,ml=0; String temp="",temp1=""; while(w<=c) { temp=String.valueOf(g.charAt(l-w-1))+temp; w++; } while(ml<=(l-w-1)) { temp1=temp1+String.valueOf(g.charAt(ml)); ml++; } //System.out.println(temp1); if((temp+temp1).equals(g1)) { return true; } c++; } return false; } public static void main(String[] args) { // TODO code application logic here try { BufferedReader br=new BufferedReader(new FileReader("a1.in.txt")); PrintWriter out=new PrintWriter(new FileWriter("out.txt")); int t=Integer.parseInt(br.readLine()); int q=0; while(q<t) { String h[]= br.readLine().split(" "); int a=Integer.parseInt(h[0]); int b=Integer.parseInt(h[1]),n=0,m=0,p=0; //out.println(check_recycled(12345,34512)); for(int i=a;i<b;i++) { n=i; for(int j=a+1;j<=b;j++) { m=j; if(m>n) { if(check_recycled(n,m)) { p++; } } } } out.println("Case #"+(q+1)+":"+" "+p); q++; } out.flush(); } catch(Exception e) { System.out.print(e.toString()); } } }
A22992
A22796
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package IO; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; /** * * @author dannocz */ public class InputReader { public static Input readFile(String filename){ try { /* Sets up a file reader to read the file passed on the command 77 line one character at a time */ FileReader input = new FileReader(filename); /* Filter FileReader through a Buffered read to read a line at a time */ BufferedReader bufRead = new BufferedReader(input); String line; // String that holds current file line int count = 0; // Line number of count ArrayList<String> cases= new ArrayList<String>(); // Read first line line = bufRead.readLine(); int noTestCases=Integer.parseInt(line); count++; // Read through file one line at time. Print line # and line while (count<=noTestCases){ //System.out.println("Reading. "+count+": "+line); line = bufRead.readLine(); cases.add(line); count++; } bufRead.close(); return new Input(noTestCases,cases); }catch (ArrayIndexOutOfBoundsException e){ /* If no file was passed on the command line, this expception is generated. A message indicating how to the class should be called is displayed */ e.printStackTrace(); }catch (IOException e){ // If another exception is generated, print a stack trace e.printStackTrace(); } return null; }// end main }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Dance { private static final int[] maxBestResult = { 0, 1, 2 }; private static final int[] maxBestResultSurprise = { 0, 1, 2 }; private static final int[] minBestResult = { 0, 1, 2 }; private static final int[] minBestResultSurprise = { 0, 1, 2 }; 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 idx = 0; int n = Integer.parseInt(ss[idx++]); // number of Googlers int s = Integer.parseInt(ss[idx++]); // number of Surprises int p = Integer.parseInt(ss[idx++]); // minimum score int[] sums = new int[n]; for (int j = 0; j < n; j++) { sums[j] = Integer.parseInt(ss[idx++]); } int result = compute(sums, s, p); out.println("Case #" + i + ": " + result); System.out.println("Case #" + i + ": " + result); } out.close(); System.out.println("time: " + (System.currentTimeMillis() - t0)); } private static int compute(int[] sums, int s, int p) { if (p == 0) return sums.length; int pointsRequiredWithOutSurprise = Math.max(1, (p * 3) - 2); // p, p-1, p-1 int pointsRequiredWithSurprise = Math.max(2, (p * 3) - 4); // p, p-2, p-2 int result = 0; for (int i = 0; i < sums.length; i++) { int sum = sums[i]; if (sum >= pointsRequiredWithOutSurprise) { result++; // splitStd(sum); } else if (s > 0 && sum >= pointsRequiredWithSurprise) { s--; result++; // splitSurprise(sum); } else { // failed // splitStd(sum); } } return result; } private static void splitStd(int sum) { switch (sum % 3) { case 0: System.out.println(sum + ": " + sum / 3 + "," + sum / 3 + "," + sum / 3); break; case 1: System.out.println(sum + ": " + (1 + sum / 3) + "," + sum / 3 + "," + sum / 3); break; case 2: System.out.println(sum + ": " + (1 + sum / 3) + "," + (1 + sum / 3) + "," + sum / 3); break; } } private static void splitSurprise(int sum) { switch (sum % 3) { case 0: System.out.println(sum + ": " + (1 + sum / 3) + "," + sum / 3 + "," + (sum / 3 - 1)); break; case 1: System.out.println(sum + ": " + (1 + sum / 3) + "," + (sum / 3 - 1) + "," + (sum / 3 - 1)); break; case 2: System.out.println(sum + ": " + (2 + sum / 3) + "," + (sum / 3) + "," + sum / 3); break; } } }
A20490
A21986
0
/** * */ 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<input folder>:\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<output folder>:\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); } }
package dancers; 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 Dancers { public static int SURPRISE = 0; public static int ATENDEE = 0; public static int BESTRESULT = 0; public static int[] SCORES; public static int[] RESULTS; public static String[] inputLines; 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 int countResult() { int result = 0; int mayResult = 0; for(int score:SCORES){ if(score>=(BESTRESULT+(Math.max(0, 2*(BESTRESULT-1))))) result++; else if(score>=BESTRESULT+(Math.max(0,2*(BESTRESULT-2)))) mayResult++; } mayResult = Math.min(mayResult, SURPRISE); return result+mayResult; } public static void readIo() throws Exception { DataInputStream in = new DataInputStream(new FileInputStream("B2.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(" "); ATENDEE = Integer.parseInt(tokens[0]); SURPRISE = Integer.parseInt(tokens[1]); BESTRESULT = Integer.parseInt(tokens[2]); SCORES = new int[ATENDEE]; for(int i = 3; i<tokens.length; i++) SCORES[i-3] = Integer.parseInt(tokens[i]); } public static void solveProblemsFromLine() { for(int inp=0; inp<inputLines.length;inp++) { parse(inputLines[inp]); RESULTS[inp] = countResult(); System.out.println(RESULTS[inp]); } } public static void saveOutputFile() throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter("result.txt")); for(int i=0; i<RESULTS.length; i++) { out.write("Case #"+(i+1)+": "+ RESULTS[i]); out.newLine(); } out.flush(); out.close(); } }
B20006
B21015
0
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; } }
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<Integer> h = new HashSet<Integer>(); 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); } } }
A12211
A12039
0
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 Dancing_improved { static int f_Superan_limites(String params){ int superan_limite=0; String[] parametros=params.split(" "); int n_participantes= Integer.parseInt(parametros[0]); int n_sorprendidos= Integer.parseInt(parametros[1]); int nota_limite= Integer.parseInt(parametros[2]); int suma_notas, resto, nota_juego; for(int i=3;i<parametros.length;i++){ // Recorro las sumas de los participantes suma_notas=Integer.parseInt(parametros[i]); resto=suma_notas%3; if(resto==0){ // el resto es el número triplicado! nota_juego=suma_notas/3; if(nota_juego>=nota_limite){ superan_limite++; }else if(nota_juego-1>=0 && n_sorprendidos>0 && ((nota_juego+1)>=nota_limite || (nota_juego+2)>=nota_limite)){ // no supera el límite pero podría hacerlo si quedan sorprendidos n_sorprendidos--; superan_limite++; } }else if((suma_notas+1)%3==0){ // Tendré que jugar con el valor en +-1 nota_juego=(suma_notas+1)/3; if(nota_juego-1>=0 && nota_juego>=nota_limite){ superan_limite++; }else if(nota_juego-1>=0 && n_sorprendidos>0 && (nota_juego+1)>=nota_limite){ n_sorprendidos--; superan_limite++; } }else if((suma_notas+2)%3==0){ // Tendré que jugar con el valor en +-2 nota_juego=(suma_notas+2)/3; if(nota_juego-1>=0 && nota_juego>=nota_limite){ superan_limite++; } } } return superan_limite; } public static void main(String[] args) throws IOException { FileReader fr = new FileReader(args[0]); BufferedReader bf = new BufferedReader(fr); int ntest=0; FileWriter fstream = new FileWriter("out.txt"); BufferedWriter out = new BufferedWriter(fstream); String lines = bf.readLine(); String liner, linew; int lines_r=0; String[] numbers; int total; while((liner = bf.readLine())!=null && lines_r<=Integer.parseInt(lines)) { ntest++; numbers=liner.split(" "); total=f_Superan_limites(liner); linew="Case #"+ntest+": "+total+"\n"; out.write(linew); lines_r++; } out.close(); fr.close(); } }
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; } }
B13196
B10168
0
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.Iterator; import java.util.List; public class Q3M { public static void main(String[] args) throws Exception { compute(); } private static void compute() throws Exception { BufferedReader br = new BufferedReader(new FileReader(new File( "C:\\work\\Q3\\C-small-attempt0.in"))); String line = null; int i = Integer.parseInt(br.readLine()); List l = new ArrayList(); for (int j = 0; j < i; j++) { line = br.readLine(); String[] nums = line.split(" "); l.add(calculate(nums)); } writeOutput(l); } private static int calculate(String[] nums) { int min = Integer.parseInt(nums[0]); int max = Integer.parseInt(nums[1]); int count = 0; List l = new ArrayList(); for (int i = min; i <= max; i++) { for (int times = 1; times < countDigits(i); times++) { int res = shiftNum(i, times); if (res <= max && i < res) { if ((!l.contains((i + ":" + res)))) { l.add(i + ":" + res); l.add(res + ":" + i); count++; } } } } return count; } private static boolean checkZeros(int temp, int res) { if (temp % 10 == 0 || res % 10 == 0) return false; return true; } private static int shiftNum(int n, int times) { int base = (int) Math.pow(10, times); int temp2 = n / base; int placeHolder = (int) Math.pow((double) 10, (double) countDigits(temp2)); int res = placeHolder * (n % base) + temp2; if (countDigits(res) == countDigits(n)) { return res; } else { return 2000001; } } public static int countDigits(int x) { if (x < 10) return 1; else { return 1 + countDigits(x / 10); } } private static void writeOutput(List l) throws Exception { StringBuffer b = new StringBuffer(); int i = 1; BufferedWriter br = new BufferedWriter(new FileWriter(new File( "C:\\work\\Q3\\ans.txt"))); for (Iterator iterator = l.iterator(); iterator.hasNext();) { br.write("Case #" + i++ + ": " + iterator.next()); br.newLine(); } br.close(); } }
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 <input-file> <output-file>"); 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<String> distinct = new HashSet<String>(); 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; } }
A11201
A11191
0
package CodeJam.c2012.clasificacion; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * Problem * * You're watching a show where Googlers (employees of Google) dance, and then * each dancer is given a triplet of scores by three judges. Each triplet of * scores consists of three integer scores from 0 to 10 inclusive. The judges * have very similar standards, so it's surprising if a triplet of scores * contains two scores that are 2 apart. No triplet of scores contains scores * that are more than 2 apart. * * For example: (8, 8, 8) and (7, 8, 7) are not surprising. (6, 7, 8) and (6, 8, * 8) are surprising. (7, 6, 9) will never happen. * * The total points for a Googler is the sum of the three scores in that * Googler's triplet of scores. The best result for a Googler is the maximum of * the three scores in that Googler's triplet of scores. Given the total points * for each Googler, as well as the number of surprising triplets of scores, * what is the maximum number of Googlers that could have had a best result of * at least p? * * For example, suppose there were 6 Googlers, and they had the following total * points: 29, 20, 8, 18, 18, 21. You remember that there were 2 surprising * triplets of scores, and you want to know how many Googlers could have gotten * a best result of 8 or better. * * With those total points, and knowing that two of the triplets were * surprising, the triplets of scores could have been: * * 10 9 10 6 6 8 (*) 2 3 3 6 6 6 6 6 6 6 7 8 (*) * * The cases marked with a (*) are the surprising cases. This gives us 3 * Googlers who got at least one score of 8 or better. There's no series of * triplets of scores that would give us a higher number than 3, so the answer * is 3. * * 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 integers * separated by single spaces. The first integer will be N, the number of * Googlers, and the second integer will be S, the number of surprising triplets * of scores. The third integer will be p, as described above. Next will be N * integers ti: the total points of the Googlers. * * 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 maximum number of Googlers who * could have had a best result of greater than or equal to p. * * Limits * * 1 ≤ T ≤ 100. 0 ≤ S ≤ N. 0 ≤ p ≤ 10. 0 ≤ ti ≤ 30. At least S of the ti values * will be between 2 and 28, inclusive. * * Small dataset * * 1 ≤ N ≤ 3. * * Large dataset * * 1 ≤ N ≤ 100. * * Sample * * Input Output 4 Case #1: 3 3 1 5 15 13 11 Case #2: 2 3 0 8 23 22 21 Case #3: 1 * 2 1 1 8 0 Case #4: 3 6 2 8 29 20 8 18 18 21 * * @author Leandro Baena Torres */ public class B { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader("B.in")); String linea; int numCasos, N, S, p, t[], y, minSurprise, minNoSurprise; linea = br.readLine(); numCasos = Integer.parseInt(linea); for (int i = 0; i < numCasos; i++) { linea = br.readLine(); String[] aux = linea.split(" "); N = Integer.parseInt(aux[0]); S = Integer.parseInt(aux[1]); p = Integer.parseInt(aux[2]); t = new int[N]; y = 0; minSurprise = p + ((p - 2) >= 0 ? (p - 2) : 0) + ((p - 2) >= 0 ? (p - 2) : 0); minNoSurprise = p + ((p - 1) >= 0 ? (p - 1) : 0) + ((p - 1) >= 0 ? (p - 1) : 0); for (int j = 0; j < N; j++) { t[j] = Integer.parseInt(aux[3 + j]); if (t[j] >= minNoSurprise) { y++; } else { if (t[j] >= minSurprise) { if (S > 0) { y++; S--; } } } } System.out.println("Case #" + (i + 1) + ": " + y); } } }
import java.util.*; import java.io.*; public class B { public static void main(String[]args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(in.readLine()); for(int x=1;x<T+1;x++) { StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int s = Integer.parseInt(st.nextToken()); int p = Integer.parseInt(st.nextToken()); int[] scores = new int[n]; for(int i=0;i<n;i++) scores[i]=Integer.parseInt(st.nextToken()); int cases = 0; for(int score : scores) { int base = score/3; switch(score%3) { case 0: if(base>=p) { cases++; } else if (s > 0 && base > 0 && base + 1 >= p) { cases++; s--; } break; case 1: if(base+1>=p) { cases++; } else if (s > 0 && base + 1 >= p) { cases++; s--; } break; case 2: if(base+1>=p) { cases++; } else if (s > 0 && base + 2 >= p) { cases++; s--; } break; } } System.out.println("Case #"+x+": "+cases); } } }
A10793
A12280
0
import java.io.*; import java.math.*; import java.util.*; import java.text.*; public class b { public static void main(String[] args) { Scanner sc = new Scanner(new BufferedInputStream(System.in)); int T = sc.nextInt(); for (int casenumber = 1; casenumber <= T; ++casenumber) { int n = sc.nextInt(); int s = sc.nextInt(); int p = sc.nextInt(); int[] ts = new int[n]; for (int i = 0; i < n; ++i) ts[i] = sc.nextInt(); int thresh1 = (p == 1 ? 1 : (3 * p - 4)); int thresh2 = (3 * p - 2); int count1 = 0, count2 = 0; for (int i = 0; i < n; ++i) { if (ts[i] >= thresh2) { ++count2; continue; } if (ts[i] >= thresh1) { ++count1; } } if (count1 > s) { count1 = s; } System.out.format("Case #%d: %d%n", casenumber, count1 + count2); } } }
package com.mademoisellegeek.googlecodejam; import com.mademoisellegeek.googlecodejam.y2012.qualround.DancingWithTheGooglers; import com.mademoisellegeek.googlecodejam.y2012.qualround.SpeakingInTongues; public class GoogleCodeJam { public static void main(String[] args) { new Thread(new DancingWithTheGooglers()).start(); } }
B11318
B12135
0
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); int casos=1, a, b, n, m, cont; while(t!=0){ a=sc.nextInt(); b=sc.nextInt(); if(a>b){ int aux=a; a=b; b=aux; } System.out.printf("Case #%d: ",casos++); if(a==b){ System.out.printf("%d\n",0); }else{ cont=0; for(n=a;n<b;n++){ for(m=n+1;m<=b;m++){ if(isRecycled(n,m)) cont++; } } System.out.printf("%d\n",cont); } t--; } } public static boolean isRecycled(int n1, int n2){ String s1, s2, aux; s1 = String.valueOf( n1 ); s2 = String.valueOf( n2 ); boolean r = false; for(int i=0;i<s1.length();i++){ aux=""; aux=s1.substring(i,s1.length())+s1.substring(0,i); // System.out.println(aux); if(aux.equals(s2)){ r=true; break; } } return r; } }
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 { private int numCase; public void calc() throws FileNotFoundException, IOException { FileReader reader = new FileReader("D:/C-small-attempt0.in"); BufferedReader bf = new BufferedReader(reader); FileWriter writer = new FileWriter("D:/output.txt"); BufferedWriter bw = new BufferedWriter(writer); numCase = Integer.parseInt(bf.readLine()); int n, m; for (int all = 1; all <= numCase; all++) { String[] inp = bf.readLine().split(" "); n = Integer.parseInt(inp[0]); m = Integer.parseInt(inp[1]); int count = 0; if (n < 10) { count = 0; } else if (n < 100) { for (int i = n; i <= m; i++) { String temp = i + ""; String rv = temp.charAt(1) + "" + temp.charAt(0); if (Integer.parseInt(rv) >= n && Integer.parseInt(rv) <= m && Integer.parseInt(rv) != i) { // System.out.println("I : " + i + " RV : " + rv); count++; } } } else if (n >= 100 && n <= 999) { for (int i = n; i <= m; i++) { String temp = i + ""; String rv = temp.charAt(2) + "" + temp.charAt(0) + "" + temp.charAt(1); if (Integer.parseInt(rv) >= n && Integer.parseInt(rv) <= m && Integer.parseInt(rv) != i) { // System.out.println("I : " + i + " RV : " + rv); count++; } rv = temp.charAt(1) + "" + temp.charAt(2) + "" + temp.charAt(0); if (Integer.parseInt(rv) >= n && Integer.parseInt(rv) <= m && Integer.parseInt(rv) != i) { // System.out.println("I : " + i + " RV : " + rv); count++; } } } else if (n >= 1000 & n <= 9999) { for (int i = n; i <= m; i++) { String temp = i + ""; String rv = temp.charAt(1) + "" + temp.charAt(2) + "" + temp.charAt(3) + "" + temp.charAt(0); if (Integer.parseInt(rv) >= n && Integer.parseInt(rv) <= m && Integer.parseInt(rv) != i) { // System.out.println("I : " + i + " RV : " + rv); count++; } rv = temp.charAt(2) + "" + temp.charAt(3) + "" + temp.charAt(0) + "" + temp.charAt(1); if (Integer.parseInt(rv) >= n && Integer.parseInt(rv) <= m && Integer.parseInt(rv) != i) { // System.out.println("I : " + i + " RV : " + rv); count++; } rv = temp.charAt(3) + "" + temp.charAt(0) + "" + temp.charAt(1) + "" + temp.charAt(2); if (Integer.parseInt(rv) >= n && Integer.parseInt(rv) <= m && Integer.parseInt(rv) != i) { // System.out.println("I : " + i + " RV : " + rv); count++; } } } System.out.println("Case #" + all + ": " + count / 2); bw.write("Case #" + all + ": " + count / 2+"\r\n"); } bw.close(); writer.close(); bf.close(); reader.close(); } public static void main(String[] args) throws FileNotFoundException, IOException { RecycledNumber rn = new RecycledNumber(); rn.calc(); } }
B13196
B11310
0
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.Iterator; import java.util.List; public class Q3M { public static void main(String[] args) throws Exception { compute(); } private static void compute() throws Exception { BufferedReader br = new BufferedReader(new FileReader(new File( "C:\\work\\Q3\\C-small-attempt0.in"))); String line = null; int i = Integer.parseInt(br.readLine()); List l = new ArrayList(); for (int j = 0; j < i; j++) { line = br.readLine(); String[] nums = line.split(" "); l.add(calculate(nums)); } writeOutput(l); } private static int calculate(String[] nums) { int min = Integer.parseInt(nums[0]); int max = Integer.parseInt(nums[1]); int count = 0; List l = new ArrayList(); for (int i = min; i <= max; i++) { for (int times = 1; times < countDigits(i); times++) { int res = shiftNum(i, times); if (res <= max && i < res) { if ((!l.contains((i + ":" + res)))) { l.add(i + ":" + res); l.add(res + ":" + i); count++; } } } } return count; } private static boolean checkZeros(int temp, int res) { if (temp % 10 == 0 || res % 10 == 0) return false; return true; } private static int shiftNum(int n, int times) { int base = (int) Math.pow(10, times); int temp2 = n / base; int placeHolder = (int) Math.pow((double) 10, (double) countDigits(temp2)); int res = placeHolder * (n % base) + temp2; if (countDigits(res) == countDigits(n)) { return res; } else { return 2000001; } } public static int countDigits(int x) { if (x < 10) return 1; else { return 1 + countDigits(x / 10); } } private static void writeOutput(List l) throws Exception { StringBuffer b = new StringBuffer(); int i = 1; BufferedWriter br = new BufferedWriter(new FileWriter(new File( "C:\\work\\Q3\\ans.txt"))); for (Iterator iterator = l.iterator(); iterator.hasNext();) { br.write("Case #" + i++ + ": " + iterator.next()); br.newLine(); } br.close(); } }
/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; public class Utils { private static final String FILE_IN_EXTENSION = ".in"; private static final String FILE_OUT_EXTENSION = ".out"; private static final String OUT_DATE_FORMAT = "_yyyy-MM-dd_HH-mm-ss"; public static <T> void solve(String filePath, String fileName, InputConverter<T> inputConverter, SolverBase<T> 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<T> reader = null; SolutionWriter writer = null; try { reader = new InputReader<T>(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; } }
B20856
B22091
0
/* * 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<Integer> mm = new LinkedList<Integer>(); //mm.add(new LinkedList<Integer>()); //int[][] mm; //for(int ii=0;ii<mm.length;ii++){ // mm[0][ii] = 1; //} for(int i=0;i<T;i++){ String[] line = in.readLine().split(" "); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); //System.out.print(" A = "+A+"\n"); //System.out.print(" B = "+B+"\n"); int ans = 0; for(int j=A;j<B;j++){ int n=j; if(n>=10){ String N = Integer.toString(n); int nlen = N.length(); List<Integer> oks = new ArrayList<Integer>(); for(int k=0;k<nlen-1;k++){ String M = ""; for(int kk=1;kk<=nlen;kk++){ M = M + N.charAt((k+kk)%nlen); } int m = Integer.parseInt(M); //System.out.print(" N = "+N+"\n"); //System.out.print(" M = "+M+"\n"); if(m>n && m<=B) { boolean isNewOne = true; for(int kkk=0;kkk<oks.size();kkk++){ //System.out.print(" KKK = "+oks.get(kkk)+"\n"); if(m==oks.get(kkk)){ isNewOne = false; } } if(isNewOne){ //System.out.print(" N = "+N+"\n"); //System.out.print(" M = "+M+"\n"); oks.add(m); ans++; } } } } } out.write("Case #"+(i+1)+": "+ans+"\n"); System.out.print("Case #"+(i+1)+": "+ans+"\n"); } in.close(); out.close(); }catch(Exception e){ e.printStackTrace(); try{ in.close(); out.close(); }catch(Exception e1){ e1.printStackTrace(); } } System.out.print("YES!\n"); } }
/* * 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; n<B;n++) { tmp = String.valueOf(n); for (int j=0;j<tmp.length();j++) { subB = tmp.substring(0,j); subE = tmp.substring(j); recycled = subE+subB; m = Integer.parseInt(recycled); if ((m>n) && (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(""); } } } }
B20291
B20569
0
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<X; i++) { String[] S = br.readLine().split(" "); int A = Integer.parseInt(S[0]); int B = Integer.parseInt(S[1]); int R = 0; int x = 1; int n = 0; while(A/x > 0) { n++; x *= 10; } for(int j=A; j<B; j++) { Set<Integer> seen = new HashSet<Integer>(); for(int k=1; k<n; k++) { int p1 = j % (int)Math.pow(10, k); int p2 = (int) Math.pow(10, n-k); int p3 = j / (int)Math.pow(10, k); int y = p1*p2 + p3; if(j < y && !seen.contains(y) && y <= B) { seen.add(y); R++; } } } pw.printf("Case #%d: %d\n", i+1, R); pw.flush(); } } catch(Exception e) { e.printStackTrace(); } } }
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)<a||Integer.parseInt(str)>b); return Integer.parseInt(str); } }
B11361
B10606
0
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<m&&m<=B){ ans++; } } } answer(ans+""); } int rot(int n, int d){ return n/10+n%10*d; } void answer(String s){ println("Case #"+caze+": "+s); } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(deepToString(os)); } public static void main(String[] args){ try{ System.setIn(new FileInputStream("dat/C-small.in")); System.setOut(new PrintStream(new FileOutputStream("dat/C-small.out"))); }catch(Exception e){} new C().run(); System.out.flush(); System.out.close(); } }
import java.io.*; import java.util.*; public class Prob3 { public static void main (String[] args) throws IOException { BufferedReader in = new BufferedReader (new FileReader ("C-small-attempt0.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 (); } }
A11201
A11535
0
package CodeJam.c2012.clasificacion; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * Problem * * You're watching a show where Googlers (employees of Google) dance, and then * each dancer is given a triplet of scores by three judges. Each triplet of * scores consists of three integer scores from 0 to 10 inclusive. The judges * have very similar standards, so it's surprising if a triplet of scores * contains two scores that are 2 apart. No triplet of scores contains scores * that are more than 2 apart. * * For example: (8, 8, 8) and (7, 8, 7) are not surprising. (6, 7, 8) and (6, 8, * 8) are surprising. (7, 6, 9) will never happen. * * The total points for a Googler is the sum of the three scores in that * Googler's triplet of scores. The best result for a Googler is the maximum of * the three scores in that Googler's triplet of scores. Given the total points * for each Googler, as well as the number of surprising triplets of scores, * what is the maximum number of Googlers that could have had a best result of * at least p? * * For example, suppose there were 6 Googlers, and they had the following total * points: 29, 20, 8, 18, 18, 21. You remember that there were 2 surprising * triplets of scores, and you want to know how many Googlers could have gotten * a best result of 8 or better. * * With those total points, and knowing that two of the triplets were * surprising, the triplets of scores could have been: * * 10 9 10 6 6 8 (*) 2 3 3 6 6 6 6 6 6 6 7 8 (*) * * The cases marked with a (*) are the surprising cases. This gives us 3 * Googlers who got at least one score of 8 or better. There's no series of * triplets of scores that would give us a higher number than 3, so the answer * is 3. * * 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 integers * separated by single spaces. The first integer will be N, the number of * Googlers, and the second integer will be S, the number of surprising triplets * of scores. The third integer will be p, as described above. Next will be N * integers ti: the total points of the Googlers. * * 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 maximum number of Googlers who * could have had a best result of greater than or equal to p. * * Limits * * 1 ≤ T ≤ 100. 0 ≤ S ≤ N. 0 ≤ p ≤ 10. 0 ≤ ti ≤ 30. At least S of the ti values * will be between 2 and 28, inclusive. * * Small dataset * * 1 ≤ N ≤ 3. * * Large dataset * * 1 ≤ N ≤ 100. * * Sample * * Input Output 4 Case #1: 3 3 1 5 15 13 11 Case #2: 2 3 0 8 23 22 21 Case #3: 1 * 2 1 1 8 0 Case #4: 3 6 2 8 29 20 8 18 18 21 * * @author Leandro Baena Torres */ public class B { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader("B.in")); String linea; int numCasos, N, S, p, t[], y, minSurprise, minNoSurprise; linea = br.readLine(); numCasos = Integer.parseInt(linea); for (int i = 0; i < numCasos; i++) { linea = br.readLine(); String[] aux = linea.split(" "); N = Integer.parseInt(aux[0]); S = Integer.parseInt(aux[1]); p = Integer.parseInt(aux[2]); t = new int[N]; y = 0; minSurprise = p + ((p - 2) >= 0 ? (p - 2) : 0) + ((p - 2) >= 0 ? (p - 2) : 0); minNoSurprise = p + ((p - 1) >= 0 ? (p - 1) : 0) + ((p - 1) >= 0 ? (p - 1) : 0); for (int j = 0; j < N; j++) { t[j] = Integer.parseInt(aux[3 + j]); if (t[j] >= minNoSurprise) { y++; } else { if (t[j] >= minSurprise) { if (S > 0) { y++; S--; } } } } System.out.println("Case #" + (i + 1) + ": " + y); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj_b; /** * * @author kay */ public class Gcj_B { /** * @param args the command line arguments */ public static void main(String[] args) { Generate app = new Generate(); app.do_processing("G:/my.txt"); // TODO code application logic here } }
B21790
B21601
0
import java.io.*; import java.util.*; public class C { void solve() throws IOException { in("C-large.in"); out("C-large.out"); long tm = System.currentTimeMillis(); boolean[] mask = new boolean[2000000]; int[] r = new int[10]; int t = readInt(); for (int cs = 1; cs <= t; ++cs) { int a = readInt(); int b = readInt(); int ans = 0; for (int m = a + 1; m <= b; ++m) { char[] d = String.valueOf(m).toCharArray(); int c = 0; for (int i = 1; i < d.length; ++i) { if (d[i] != '0' && d[i] <= d[0]) { int n = 0; for (int j = 0; j < d.length; ++j) { int jj = i + j; if (jj >= 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(); } }
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)&&(j<num1)&&(num1<=B)) { found++; }} }while(cnt>0); } 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(); } } }
B12085
B10959
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Scanner; /** * * @author daniele */ public class GCJ_C { public static void main(String[] args) throws Exception{ Scanner in = new Scanner(new File(args[0])); FileWriter out = new FileWriter("/home/daniele/Scrivania/Output"); int prove=in.nextInt(); int min,max; int cifre; int cifreaus; String temp; int aus; int count=0; ArrayList<Integer> vals = new ArrayList<Integer>(); int jcount=0; ArrayList<Integer> perm = new ArrayList<Integer>(); out.write(""); out.flush(); for(int i=1;i<=prove;i++){ out.append("Case #" +i+": ");out.flush(); min=in.nextInt(); max=in.nextInt(); for(int j=min;j<=max;j++){ if(!vals.contains(j)){ temp=""+j; cifre=temp.length(); aus=j; perm.add(j); for(int k=1;k<cifre;k++){ aus=rotateOnce(aus); temp=""+aus; cifreaus=temp.length();//elusione zeri iniziali if(aus>=min && aus<=max && aus!=j && cifreaus==cifre && nobody(vals,perm)){ perm.add(aus); jcount ++; } } while(jcount>0){count+=jcount; jcount--;} vals.addAll(perm); perm= new ArrayList<Integer>(); } } out.append(count+"\n");out.flush(); count=0; vals= new ArrayList<Integer>(); } } static public int rotateOnce(int n){ String s=""+n; if(s.length()>1){ s=s.charAt(s.length()-1) + s.substring(0,s.length()-1); n=Integer.parseInt(s); } return n; } static public boolean nobody(ArrayList<Integer> v,ArrayList<Integer> a){; for(int i=0;i<a.size();i++) if(v.contains(a.get(i))) return false; return true; } }
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<cases;tt++){ StringTokenizer cmd=new StringTokenizer(in.nextLine()); int low=Integer.parseInt(cmd.nextToken()); int high=Integer.parseInt(cmd.nextToken()); int pair=0; for(int i=low;i<high;i++){ if(arr[i]){ continue; } int count=0; int j=back(i); while(i!=j){ if(j<=high&&j>=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; } }
B11318
B11552
0
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); int casos=1, a, b, n, m, cont; while(t!=0){ a=sc.nextInt(); b=sc.nextInt(); if(a>b){ int aux=a; a=b; b=aux; } System.out.printf("Case #%d: ",casos++); if(a==b){ System.out.printf("%d\n",0); }else{ cont=0; for(n=a;n<b;n++){ for(m=n+1;m<=b;m++){ if(isRecycled(n,m)) cont++; } } System.out.printf("%d\n",cont); } t--; } } public static boolean isRecycled(int n1, int n2){ String s1, s2, aux; s1 = String.valueOf( n1 ); s2 = String.valueOf( n2 ); boolean r = false; for(int i=0;i<s1.length();i++){ aux=""; aux=s1.substring(i,s1.length())+s1.substring(0,i); // System.out.println(aux); if(aux.equals(s2)){ r=true; break; } } return r; } }
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<Integer> recycledSet = new HashSet<Integer>(); 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; } }
A22992
A20386
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package IO; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; /** * * @author dannocz */ public class InputReader { public static Input readFile(String filename){ try { /* Sets up a file reader to read the file passed on the command 77 line one character at a time */ FileReader input = new FileReader(filename); /* Filter FileReader through a Buffered read to read a line at a time */ BufferedReader bufRead = new BufferedReader(input); String line; // String that holds current file line int count = 0; // Line number of count ArrayList<String> cases= new ArrayList<String>(); // Read first line line = bufRead.readLine(); int noTestCases=Integer.parseInt(line); count++; // Read through file one line at time. Print line # and line while (count<=noTestCases){ //System.out.println("Reading. "+count+": "+line); line = bufRead.readLine(); cases.add(line); count++; } bufRead.close(); return new Input(noTestCases,cases); }catch (ArrayIndexOutOfBoundsException e){ /* If no file was passed on the command line, this expception is generated. A message indicating how to the class should be called is displayed */ e.printStackTrace(); }catch (IOException e){ // If another exception is generated, print a stack trace e.printStackTrace(); } return null; }// end main }
import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; public class B { public static void main(String ... args) throws Exception{ Scanner in = new Scanner(new File("B-large.in")); PrintStream out = new PrintStream(new File("B-large.out")); int[] max1 = new int[31]; int[] max2 = new int[31]; max1[0] = 0; max2[0] = 0; max1[1] = 1; max2[1] = 1; max1[2] = 1; max2[2] = 2; max1[3] = 1; max2[3] = 2; max1[4] = 2; max2[4] = 2; max1[5] = 2; max2[5] = 3; max1[6] = 2; max2[6] = 3; max1[7] = 3; max2[7] = 3; max1[8] = 3; max2[8] = 4; max1[9] = 3; max2[9] = 4; max1[10] = 4; max2[10] = 4; max1[11] = 4; max2[11] = 5; max1[12] = 4; max2[12] = 5; max1[13] = 5; max2[13] = 5; max1[14] = 5; max2[14] = 6; max1[15] = 5; max2[15] = 6; max1[16] = 6; max2[16] = 6; max1[17] = 6; max2[17] = 7; max1[18] = 6; max2[18] = 7; max1[19] = 7; max2[19] = 7; max1[20] = 7; max2[20] = 8; max1[21] = 7; max2[21] = 8; max1[22] = 8; max2[22] = 8; max1[23] = 8; max2[23] = 9; max1[24] = 8; max2[24] = 9; max1[25] = 9; max2[25] = 9; max1[26] = 9; max2[26] = 10; max1[27] = 9; max2[27] = 10; max1[28] = 10; max2[28] = 10; max1[29] = 10; max2[29] = 10; max1[30] = 10; max2[30] = 10; int T = in.nextInt(); in.nextLine(); for(int t=0;t<T;t++){ int N=in.nextInt(); int S=in.nextInt(); int p=in.nextInt(); int cnt1 = 0; int cnt2 = 0; for(int n=0;n<N;n++){ int num = in.nextInt(); cnt1+= max1[num]>=p?1:0; cnt2+= max2[num]>=p?1:0; } cnt1 += Math.min(cnt2-cnt1, S); out.println("Case #" + (t+1) + ": " + cnt1); } } }
B21790
B20836
0
import java.io.*; import java.util.*; public class C { void solve() throws IOException { in("C-large.in"); out("C-large.out"); long tm = System.currentTimeMillis(); boolean[] mask = new boolean[2000000]; int[] r = new int[10]; int t = readInt(); for (int cs = 1; cs <= t; ++cs) { int a = readInt(); int b = readInt(); int ans = 0; for (int m = a + 1; m <= b; ++m) { char[] d = String.valueOf(m).toCharArray(); int c = 0; for (int i = 1; i < d.length; ++i) { if (d[i] != '0' && d[i] <= d[0]) { int n = 0; for (int j = 0; j < d.length; ++j) { int jj = i + j; if (jj >= 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(); } }
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<T; i++) { int A = in.nextInt(); int B = in.nextInt(); long res = 0; for (int X=A; X<B; X++) { int D = digits(X); HashSet<Integer> set = new HashSet<Integer>(); for (int j=1; j<D; j++) { int C = moveLast(X, j); if (C > 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<digits; i++) p *= 10; last = X % p; while ((p2*10)<=X) p2 *= 10; return last*(p2/p)*10 + (X / p); } public static int digits(int X) { int k = 0; while (X > 0) { X /= 10; k++; } return k; } }
B20566
B21468
0
import java.util.Scanner; import java.io.*; import java.lang.Math; public class C{ public static int recycle(String str){ String[] numbers = str.split(" "); int min = Integer.parseInt(numbers[0]); int max = Integer.parseInt(numbers[1]); int ret = 0; for(int i = min; i < max; i++){ String num = i + ""; int len = num.length(); int k = i; for(int j = 1; j < len; j++){ k = (k/10) + (int)java.lang.Math.pow(10.0,(double)(len-1))*(k%10); if (k > 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){} } }
package com.renoux.gael.codejam.fwk; import java.io.File; import com.renoux.gael.codejam.utils.FluxUtils; import com.renoux.gael.codejam.utils.Input; import com.renoux.gael.codejam.utils.Output; import com.renoux.gael.codejam.utils.Timer; public abstract class Solver { public void run() { Timer.start(); if (!disableSample()) runOnce(getSampleInput(), getSampleOutput()); System.out.println(Timer.check()); Timer.start(); if (!disableSmall()) runOnce(getSmallInput(), getSmallOutput()); System.out.println(Timer.check()); Timer.start(); if (!disableLarge()) runOnce(getLargeInput(), getLargeOutput()); System.out.println(Timer.check()); } public void runOnce(String pathIn, String pathOut) { Input in = null; Output out = null; try { in = Input.open(getFile(pathIn)); out = Output.open(getFile(pathOut)); int countCases = Integer.parseInt(in.readLine()); for (int k = 1; k <= countCases; k++) { out.write("Case #", k, ": "); solveCase(in, out); } } catch (RuntimeException e) { e.printStackTrace(); } finally { FluxUtils.closeCloseables(in, out); } } private File getFile(String path) { return new File(path); } protected abstract void solveCase(Input in, Output out); private String getFullPath(boolean input, String type) { if (input) return "D:\\Downloads\\CodeJam\\" + getProblemName() + "\\" + getProblemName() + "_input_" + type + ".txt"; else return "D:\\Downloads\\CodeJam\\" + getProblemName() + "\\" + getProblemName() + "_output_" + type + ".txt"; } protected String getSampleInput() { return getFullPath(true, "sample"); } protected String getSmallInput() { return getFullPath(true, "small"); } protected String getLargeInput() { return getFullPath(true, "large"); } protected String getSampleOutput() { return getFullPath(false, "sample"); } protected String getSmallOutput() { return getFullPath(false, "small"); } protected String getLargeOutput() { return getFullPath(false, "large"); } protected boolean disableSample() { return disable()[0]; } protected boolean disableSmall() { return disable()[1]; } protected boolean disableLarge() { return disable()[2]; } protected boolean[] disable() { return new boolean[] { false, false, false }; } protected abstract String getProblemName(); }
A10699
A11135
0
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; public class Dancing { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // read input file File file = new File("B-small-attempt4.in"); //File file = new File("input.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String ln = ""; int count = Integer.parseInt(br.readLine()); // write output file File out = new File("outB.txt"); BufferedWriter bw = new BufferedWriter(new FileWriter(out)); int y = 0; for (int i=0; i < count; i++){ ln = br.readLine(); y = getY(ln); bw.write("Case #" + (i+1) + ": " + y); bw.newLine(); } bw.close(); } private static int getY(String str) { String[] data = str.split(" "); int n = Integer.parseInt(data[0]); int s = Integer.parseInt(data[1]); int p = Integer.parseInt(data[2]); int[] t = new int[n]; for (int i=0; i < n; i++){ t[i] = Integer.parseInt(data[i+3]); } int y = 0; int base = 0; for(int j=0; j < t.length; j++){ base = t[j] / 3; if(base >= p) { y++; } else if(base == p-1){ if(t[j] - (base+p) > base-1 && t[j] > 0){ y++; } else if(s>0 && t[j] - (base+p) > base-2 && t[j] > 0){ s -= 1; y++; } } else if(base == p-2){ if(s > 0 && t[j] - (base+p) > base-1 && t[j] > 0){ s -= 1; y++; } } } return y; } }
/** * 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.zip.Inflater; public class SRM { public static void main(String[] args) throws IOException { //TestSRMLib.run(); codeJam1.main(); return; } } class codeJam1 { 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(" "); int N = Integer.parseInt(words[0]); int S = Integer.parseInt(words[1]); int p = Integer.parseInt(words[2]); int n = 0; int res = 0; for (int j = 3; j < words.length; ++j) { if (p == 0) { res++; continue; } int t = Integer.parseInt(words[j]); if (p == 1) { if (t > 0) res++; continue; } if (t >= 3 * p - 2) res++; else if (t >= 3 * p - 4) n++; } res += Math.min(n, S); output.write("Case #" + i + ": " + res); output.newLine(); } input.close(); output.close(); } }
A11201
A11848
0
package CodeJam.c2012.clasificacion; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * Problem * * You're watching a show where Googlers (employees of Google) dance, and then * each dancer is given a triplet of scores by three judges. Each triplet of * scores consists of three integer scores from 0 to 10 inclusive. The judges * have very similar standards, so it's surprising if a triplet of scores * contains two scores that are 2 apart. No triplet of scores contains scores * that are more than 2 apart. * * For example: (8, 8, 8) and (7, 8, 7) are not surprising. (6, 7, 8) and (6, 8, * 8) are surprising. (7, 6, 9) will never happen. * * The total points for a Googler is the sum of the three scores in that * Googler's triplet of scores. The best result for a Googler is the maximum of * the three scores in that Googler's triplet of scores. Given the total points * for each Googler, as well as the number of surprising triplets of scores, * what is the maximum number of Googlers that could have had a best result of * at least p? * * For example, suppose there were 6 Googlers, and they had the following total * points: 29, 20, 8, 18, 18, 21. You remember that there were 2 surprising * triplets of scores, and you want to know how many Googlers could have gotten * a best result of 8 or better. * * With those total points, and knowing that two of the triplets were * surprising, the triplets of scores could have been: * * 10 9 10 6 6 8 (*) 2 3 3 6 6 6 6 6 6 6 7 8 (*) * * The cases marked with a (*) are the surprising cases. This gives us 3 * Googlers who got at least one score of 8 or better. There's no series of * triplets of scores that would give us a higher number than 3, so the answer * is 3. * * 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 integers * separated by single spaces. The first integer will be N, the number of * Googlers, and the second integer will be S, the number of surprising triplets * of scores. The third integer will be p, as described above. Next will be N * integers ti: the total points of the Googlers. * * 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 maximum number of Googlers who * could have had a best result of greater than or equal to p. * * Limits * * 1 ≤ T ≤ 100. 0 ≤ S ≤ N. 0 ≤ p ≤ 10. 0 ≤ ti ≤ 30. At least S of the ti values * will be between 2 and 28, inclusive. * * Small dataset * * 1 ≤ N ≤ 3. * * Large dataset * * 1 ≤ N ≤ 100. * * Sample * * Input Output 4 Case #1: 3 3 1 5 15 13 11 Case #2: 2 3 0 8 23 22 21 Case #3: 1 * 2 1 1 8 0 Case #4: 3 6 2 8 29 20 8 18 18 21 * * @author Leandro Baena Torres */ public class B { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader("B.in")); String linea; int numCasos, N, S, p, t[], y, minSurprise, minNoSurprise; linea = br.readLine(); numCasos = Integer.parseInt(linea); for (int i = 0; i < numCasos; i++) { linea = br.readLine(); String[] aux = linea.split(" "); N = Integer.parseInt(aux[0]); S = Integer.parseInt(aux[1]); p = Integer.parseInt(aux[2]); t = new int[N]; y = 0; minSurprise = p + ((p - 2) >= 0 ? (p - 2) : 0) + ((p - 2) >= 0 ? (p - 2) : 0); minNoSurprise = p + ((p - 1) >= 0 ? (p - 1) : 0) + ((p - 1) >= 0 ? (p - 1) : 0); for (int j = 0; j < N; j++) { t[j] = Integer.parseInt(aux[3 + j]); if (t[j] >= minNoSurprise) { y++; } else { if (t[j] >= minSurprise) { if (S > 0) { y++; S--; } } } } System.out.println("Case #" + (i + 1) + ": " + y); } } }
import java.util.Scanner; public abstract class ProgrammingProblem { protected static final Scanner sc = new Scanner(System.in); protected static boolean DEBUG = false; protected abstract void print(); protected abstract void readInput(); protected abstract String execute(); protected static void main(@SuppressWarnings("rawtypes") Class myclass) throws InstantiationException, IllegalAccessException { int T = sc.nextInt(); for (int i = 0; i < T; i++) { ProgrammingProblem m = (ProgrammingProblem) myclass.newInstance(); m.readInput(); if (DEBUG) { m.print(); } System.out.println("Case #" + (i+1) + ": " + m.execute()); } } protected static ProgrammingProblem getTestCase() { return null; } public ProgrammingProblem() { super(); } }
A22771
A22159
0
package com.menzus.gcj._2012.qualification.b; import com.menzus.gcj.common.InputBlockParser; import com.menzus.gcj.common.OutputProducer; import com.menzus.gcj.common.impl.AbstractProcessorFactory; public class BProcessorFactory extends AbstractProcessorFactory<BInput, BOutputEntry> { public BProcessorFactory(String inputFileName) { super(inputFileName); } @Override protected InputBlockParser<BInput> createInputBlockParser() { return new BInputBlockParser(); } @Override protected OutputProducer<BInput, BOutputEntry> createOutputProducer() { return new BOutputProducer(); } }
/** * Created by IntelliJ IDEA. * User: SONY * Date: 19.02.12 * Time: 13:12 * To change this template use File | Settings | File Templates. */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main extends Thread { public Main(String inputFileName, String outputFileName) { try { this.input = new BufferedReader(new FileReader(inputFileName)); this.output = new PrintWriter(outputFileName); this.setPriority(Thread.MAX_PRIORITY); } catch (Throwable e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(666); } } final int doit2() throws Throwable { int N = nextInt(), S = nextInt(), p = nextInt(); int t[] = new int[N]; for (int i = 0; i < N; ++i) t[i] = nextInt(); int[][] dp = new int[N + 1][S + 2]; for (int i = 0; i < N; ++i) { for (int j = 0; j <= Math.min(S, i); ++j) { int act = t[i]; if (act >= 3 * p - 2) { dp[i + 1][j] = Math.max(dp[i + 1][j], dp[i][j] + 1); } else { dp[i + 1][j] = Math.max(dp[i + 1][j], dp[i][j]); } if (act >= 2 && act <= 28) { dp[i + 1][j + 1] = Math.max(dp[i + 1][j + 1], dp[i][j]); if (act >= Math.max(p, 3 * p - 4)) { dp[i + 1][j + 1] = Math.max(dp[i + 1][j + 1], dp[i][j] + 1); } } } } return dp[N][S]; } 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; }
B11421
B10332
0
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 Recycled { public static void main(String[] args) throws Exception{ String inputFile = "C-small-attempt0.in"; BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output"))); long num_cases = Long.parseLong(input.readLine()); int current_case = 0; while (current_case < num_cases){ current_case++; String[] fields = input.readLine().split(" "); int A = Integer.parseInt(fields[0]); int B = Integer.parseInt(fields[1]); int total = 0; for (int n = A; n < B; n++){ for (int m = n+1; m <= B; m++){ if (isRecycled(n,m)) total++; } } System.out.println("Case #" + current_case + ": " + total); output.write("Case #" + current_case + ": " + total + "\n"); } output.close(); } private static boolean isRecycled(int n, int m) { String sn = ""+n; String sm = ""+m; if (sn.length() != sm.length()) return false; int totaln = 0, totalm = 0; for (int i = 0; i < sn.length(); i++){ totaln += sn.charAt(i); totalm += sm.charAt(i); } if (totaln != totalm) return false; for (int i = 0; i < sn.length()-1; i++){ sm = sm.charAt(sm.length() - 1) + sm.substring(0, sm.length() - 1); if (sm.equals(sn)) return true; } return false; } }
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<Integer> set = new HashSet<Integer>(); 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(); int n = 0; for (int x = A; x < B; x++) { n += f(x, A, B); } System.out.println("Case #" + t + ": " + n); } } }
A22992
A20000
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package IO; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; /** * * @author dannocz */ public class InputReader { public static Input readFile(String filename){ try { /* Sets up a file reader to read the file passed on the command 77 line one character at a time */ FileReader input = new FileReader(filename); /* Filter FileReader through a Buffered read to read a line at a time */ BufferedReader bufRead = new BufferedReader(input); String line; // String that holds current file line int count = 0; // Line number of count ArrayList<String> cases= new ArrayList<String>(); // Read first line line = bufRead.readLine(); int noTestCases=Integer.parseInt(line); count++; // Read through file one line at time. Print line # and line while (count<=noTestCases){ //System.out.println("Reading. "+count+": "+line); line = bufRead.readLine(); cases.add(line); count++; } bufRead.close(); return new Input(noTestCases,cases); }catch (ArrayIndexOutOfBoundsException e){ /* If no file was passed on the command line, this expception is generated. A message indicating how to the class should be called is displayed */ e.printStackTrace(); }catch (IOException e){ // If another exception is generated, print a stack trace e.printStackTrace(); } return null; }// end main }
import java.io.*; class goodance { static int wc; static int best; public static void main(String args[]) throws IOException { FileReader fin=new FileReader("B-large.in"); BufferedReader bin=new BufferedReader(fin); FileWriter fout=new FileWriter("Output.txt"); BufferedWriter bout=new BufferedWriter(fout); PrintWriter pout=new PrintWriter(bout); int T=Integer.parseInt(bin.readLine()); String s[]=new String[T]; int omk1,omk2=3,parsm=4; int i=0,dummy=10,r=0,test=0; boolean flag,count; while(i<T) { s[i]=bin.readLine(); int l=s[i].length(); int sp1=s[i].indexOf(' '); int N=Integer.parseInt(s[i].substring(0,sp1)); int arr[]=new int[N]; s[i]=s[i].substring(sp1+1); int sp2=s[i].indexOf(' '); int S=Integer.parseInt(s[i].substring(0,sp2)); wc=S; s[i]=s[i].substring(sp2+1); int sp3=s[i].indexOf(' '); int P=Integer.parseInt(s[i].substring(0,sp3)); best=P; s[i]=s[i].substring(sp3+1); for(int h=0;h<N;h++) { int sp=s[i].indexOf(' '); if(sp==-1) arr[h]=Integer.parseInt(s[i].substring(0)); else arr[h]=Integer.parseInt(s[i].substring(0,sp)); s[i]=s[i].substring(sp+1); } for(int k=0;k<N;k++) { for(int a=0;a<=10;a++) { for(int b=0;b<=10;b++) { for(int c=0;c<=10;c++) { if(arr[k]==a+b+c) { if(flag=minmax(a,b,c)) { if(count=f(a,b,c)) { int d=def(a,b,c); omk1=d; if(omk1<omk2) { parsm=omk1; } if(omk2>omk1) omk2=omk1; } } } } } } r+=pav(parsm); omk2=3; parsm=-1; } pout.println("Case #"+(i+1)+": "+r); r=0; i++; omk2=3; } bin.close(); pout.close(); bout.close(); fout.close(); } static boolean minmax(int n1,int n3,int n2) { int max,min; max=(n1>n2?(n1>n3?n1:n3):(n2>n3?n2:n3)); min=(n1<n2?(n1<n3?n1:n3):(n2<n3?n2:n3)); if(max-min>2) return false; else return true; } static boolean f(int z,int m,int o) { if(z>=best||m>=best||o>=best) return true; else return false; } static int def(int n1,int n2,int n3) { int max,min; max=(n1>n2?(n1>n3?n1:n3):(n2>n3?n2:n3)); min=(n1<n2?(n1<n3?n1:n3):(n2<n3?n2:n3)); int diff=max-min; return diff; } static int pav(int t) { int royal=0; if(t==2) { if(wc>0) {royal=1; wc--; } } else if(t==1||t==0) royal=1; else {royal=0; } return royal; } }
B20424
B21856
0
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { // static int MAX = 10000; static int MAX = 2000000; static Object[] All = new Object[MAX+1]; static int size( int x ) { if(x>999999) 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<Integer> result = new ArrayList<Integer>(); 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; i<s; i++) { if(V[i]!=0){ rot=0; for(int j=0,ii=i;j<s; j++,ii=(ii+1)%s){ rot=rot*10+V[ii]; } if(rot>value && !result.contains(rot)) result.add(rot); } } if( result.isEmpty() ) return null; int[] r = new int[result.size()]; for(int i=0; i<r.length; i++) r[i]=result.get(i); return r; } static void precalculate() { for(int i=1; i<=MAX; i++){ All[i] = rotate(i); } } static int solve( Scanner in ) { int A, B, sol=0; A = in.nextInt(); B = in.nextInt(); for( int i=A; i<=B; i++) { // List<Integer> 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); } } }
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<Integer> h = new HashSet<Integer>(); 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(); } }
A11135
A10309
0
/** * 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.zip.Inflater; public class SRM { public static void main(String[] args) throws IOException { //TestSRMLib.run(); codeJam1.main(); return; } } class codeJam1 { 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(" "); int N = Integer.parseInt(words[0]); int S = Integer.parseInt(words[1]); int p = Integer.parseInt(words[2]); int n = 0; int res = 0; for (int j = 3; j < words.length; ++j) { if (p == 0) { res++; continue; } int t = Integer.parseInt(words[j]); if (p == 1) { if (t > 0) res++; continue; } if (t >= 3 * p - 2) res++; else if (t >= 3 * p - 4) n++; } res += Math.min(n, S); output.write("Case #" + i + ": " + res); output.newLine(); } input.close(); output.close(); } }
package org.cb.projectb.dancingwiththegooglers; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.StringTokenizer; public class Contest { public static void main(String[] args) throws FileNotFoundException { File input = new File(System.getProperty("user.dir") + "/" + "resources/projectB/B-small-attempt0.in"); Scanner sc = new Scanner(input); List<DanceOff> contests = new ArrayList<DanceOff>(); if (sc.hasNext()) { Integer.parseInt(sc.nextLine()); // number of cases - ignored while (sc.hasNext()) { String contestString = sc.nextLine(); StringTokenizer contestTokenizer = new StringTokenizer(contestString); int contestants = Integer.parseInt(contestTokenizer.nextToken()); int surprisingTriplets = Integer.parseInt(contestTokenizer.nextToken()); int scoreWeCareAbout = Integer.parseInt(contestTokenizer.nextToken()); List<Integer> scores = new ArrayList<Integer>(); for(int i = 0; i < contestants; i ++) { scores.add(Integer.parseInt(contestTokenizer.nextToken())); } contests.add(new DanceOff(contestants, surprisingTriplets, scoreWeCareAbout, scores)); } } for(int i = 1; i <= contests.size(); i ++) { DanceOff danceoff = contests.get(i-1); System.out.println("Case #" + i + ": " + danceoff.getNumberAllowedToBeImportant()); } } private static class DanceOff { private final int contestants; private final int surprisingTriplets; private final int scoreWeCareAbout; private final List<Integer> contestantScores; private final int numberAllowedToBeImportant; public DanceOff(int contestants, int surprisingTriplets, int scoreWeCareAbout, List<Integer> contestantScores) { this.contestants = contestants; this.surprisingTriplets = surprisingTriplets; this.scoreWeCareAbout = scoreWeCareAbout; this.contestantScores = contestantScores; this.numberAllowedToBeImportant = fillInDetails(); } private int fillInDetails() { int importantScores = 0; List<Integer[]> allProbableScores = new ArrayList<Integer[]>(); for(Integer score: contestantScores) { // System.out.print(score + " - "); int baseScore = score / 3; int remaining = score % 3; Integer[] scoresArray = new Integer[]{baseScore, baseScore, baseScore}; for(int i = 0; i < remaining; i++) { scoresArray[i] = scoresArray[i] + 1; } // System.out.print("Probable tripplet: ["); // for(int i = 0; i < scoresArray.length; i++) { // System.out.print(scoresArray[i] + " "); // } // System.out.println("]"); allProbableScores.add(scoresArray); } int freebeeImportantScores = 0; int ableToBeImportantIfSurprising = 0; for (Integer[] scoresList : allProbableScores) { // count how many in scores array are already important boolean isImportant = false; boolean canBeSurprising = false; for (Integer integer : scoresList) { if(integer >= this.scoreWeCareAbout) { isImportant = true; break; } } if(isImportant) { freebeeImportantScores++; } else { // see how many i can make 'surprising' to then care about if(scoresList[0] + 1 >= this.scoreWeCareAbout) { if(scoresList[0] == scoresList[1] && scoresList[0] != 0) { canBeSurprising = true; } } if(canBeSurprising) { ableToBeImportantIfSurprising++; } } } // take min of allowed surprising & how many could be surprised int numToMakeSpecial = Math.min(ableToBeImportantIfSurprising, this.surprisingTriplets); // add min to current important scores importantScores = freebeeImportantScores + numToMakeSpecial; // System.out.println("Freebee important: " + freebeeImportantScores); // System.out.println("Can be Made Important with surprising Score: " + ableToBeImportantIfSurprising); // System.out.println("Num Of Scores we are making surprising: " + numToMakeSpecial); // System.out.println("Max Special Scores: " + importantScores); // System.out.println(); return importantScores; } public int getNumberAllowedToBeImportant() { return numberAllowedToBeImportant; } @Override public String toString() { return "DanceOff [contestants = " + contestants + ", surprisingTriplets = " + surprisingTriplets + ", scoreWeCareAbout = " + scoreWeCareAbout + ", contestantScores = " + contestantScores + "]"; } } }
B12115
B13036
0
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; } }
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; } }
B10231
B10986
0
import java.io.*; class code1 { public static void main(String args[]) throws Exception { File ii = new File ("C-small-attempt1.in"); FileInputStream fis = new FileInputStream(ii); BufferedReader br = new BufferedReader(new InputStreamReader (fis)); int cases = Integer.parseInt(br.readLine()); FileOutputStream fout = new FileOutputStream ("output.txt"); DataOutputStream dout = new DataOutputStream (fout); int total=0; for(int i=0;i<cases;i++){ String temp = br.readLine(); String parts [] = temp.split(" "); int lower = Integer.parseInt(parts[0]); int upper = Integer.parseInt(parts[1]); System.out.println(lower+" "+upper); for(int j=lower;j<=upper;j++) { int abc = j;int length=0; if(j<10)continue; while (abc!=0){abc/=10;length++;} abc=j; for(int m=0;m<length-1;m++){ int shift = abc%10; abc=abc/10; System.out.println("hi "+j); abc=abc+shift*power(10,length-1); if(abc<=upper&&shift!=0&&abc>j)total++; System.out.println(total); } } dout.writeBytes("Case #"+(i+1)+ ": "+total+"\n"); total=0; }//for close } private static int power(int i, int j) { int no=1; for(int a=0;a<j;a++){no=10*no;} return no; } }
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 ProbC { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new FileReader("C-small-attempt0.in")); BufferedWriter bw = new BufferedWriter(new FileWriter("C-small-attempt0.out")); String line = br.readLine(); int T = Integer.parseInt(line); for(int i = 0; i < T; i++) { line = br.readLine(); String[] tokens = line.split(" "); int A = Integer.parseInt(tokens[0]); int B = Integer.parseInt(tokens[1]); int cnt = 0; for(int j = A; j < B; j++) { for(int k = j + 1; k <= B; k++) { String nstr = "" + j; String mstr = "" + k; if(nstr.length() != mstr.length()) { if(mstr.length() > nstr.length()) break; else continue; } String tstr = nstr + nstr; if(tstr.contains(mstr)) cnt++; } } String outputline = "Case #" + (i + 1) + ": " + cnt; System.out.println(outputline); bw.write(outputline + "\n"); } br.close(); bw.close(); } }
A11277
A10843
0
package googlers; import java.util.Scanner; import java.util.PriorityQueue; import java.util.Comparator; public class Googlers { public static void main(String[] args) { int n,s,p,count=0,t; Scanner sin=new Scanner(System.in); t=Integer.parseInt(sin.nextLine()); int result[]=new int[t]; int j=0; if(t>=1 && t<=100) { for (int k = 0; k < t; k++) { count=0; String ip = sin.nextLine(); String[]tokens=ip.split(" "); n=Integer.parseInt(tokens[0]); s=Integer.parseInt(tokens[1]); p=Integer.parseInt(tokens[2]); if( (s>=0 && s<=n) && (p>=0 && p<=10) ) { int[] total=new int[n]; for (int i = 0; i < n; i++) { total[i] = Integer.parseInt(tokens[i+3]); } Comparator comparator=new PointComparator(); PriorityQueue pq=new PriorityQueue<Point>(1, comparator); for (int i = 0; i < n; i++) { int x=total[i]/3; int r=total[i]%3; if(x>=p) count++; else if(x<(p-2)) continue; else { //System.out.println("enter "+x+" "+(p-2)); if(p-x==1) { Point temp=new Point(); temp.q=x; temp.r=r; pq.add(temp); } else // p-x=2 { if(r==0) continue; else { Point temp=new Point(); temp.q=x; temp.r=r; pq.add(temp); } } } //System.out.println("hi "+pq.size()); } while(pq.size()!=0) { Point temp=(Point)pq.remove(); if(p-temp.q==1 && temp.q!=0) { if(temp.r>=1) count++; else { if(s!=0) { s--; count++; } } } else if(p-temp.q==2) { if(s!=0 && (temp.q+temp.r)>=p) { s--; count++; } } } //System.out.println(p); result[j++]=count; } } for (int i = 0; i < t; i++) { System.out.println("Case #"+(i+1)+": "+result[i]); } } } /*Point x=new Point(); x.q=8; Point y=new Point(); y.q=6; Point z=new Point(); z.q=7; pq.add(x); pq.add(y); pq.add(z); */ } class PointComparator implements Comparator<Point> { @Override public int compare(Point x, Point y) { // Assume neither string is null. Real code should // probably be more robust if (x.q < y.q) { return 1; } if (x.q > y.q) { return -1; } return 0; } } class Point { int q,r; public int getQ() { return q; } public void setQ(int q) { this.q = q; } public int getR() { return r; } public void setR(int r) { this.r = r; } }
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 ProblemB { private String line = ""; private String fileContents = ""; private String delim = "\r\n"; private String fileName = "B-small-attempt3.in"; // private String fileName = "B-small-practice.in"; public void solve() { StringTokenizer st = new StringTokenizer(fileContents, delim); StringTokenizer lineToken = null; int count = 1; int testCases = 0; int googlers = 0; int surTripler = 0; int p = 0; int y = 0; ArrayList<Integer> numbersList = new ArrayList<Integer>(); 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, " "); googlers = Integer.parseInt(lineToken.nextToken()); surTripler = Integer.parseInt(lineToken.nextToken()); p = Integer.parseInt(lineToken.nextToken()); numbersList.clear(); for (int i = 0; i < googlers; i++) { numbersList.add(Integer.parseInt(lineToken.nextToken())); } y = 0; for (Integer number : numbersList) { // // if (number == 0) // continue; // // if (p == 0) { // y++; // continue; // } int mid = number / 3; int rem = number % 3; // int prem = number % p; switch (rem) { case 0: if (mid >= p) { y++; } else { if (surTripler > 0 && mid > 0 && mid + 1 >= p) { y++; surTripler--; } } break; case 1: if (mid >= p || mid + 1 >= p) { y++; } else { if (surTripler > 0 && mid + 1 >= p) { y++; surTripler--; } } break; case 2: if (mid + 1 >= p || mid >= p) { y++; } else { if (surTripler > 0 && mid + 2 >= p) { y++; surTripler--; } } break; } // if(prem == 0 && p*3 >= number) { // y++; // } // else if(mid >= p) { // y++; // } // else if(mid + rem >= p) { // y++; // } // else if(rem == 1) { // if(mid + rem >= p) { // y++; // } // } // else if(rem == 2) { // if(mid + rem >= p) { // y++; // } // } // else if(mid + rem + 2 >= p && surTripler > 0 && mid > 2 && // rem != 0) { // y++; // } // else if((prem + 1 >= (p - 1)) && surTripler == 0) { // y++; // } // else if((mid + 2 >= (p - 1) && surTripler > 0)) { // y++; // surTripler--; // } // else if((mid + 2 >= (p - 2) && surTripler > 0)) { // y++; // surTripler--; // } // else if(mid + 2 >= p && surTripler-- > 0 ) { // y++; // } // else if(rem == 2) { // System.out.print(mid + 1); // System.out.print(mid + 1); // System.out.print(mid); // } // else { // System.out.print(mid+rem); // System.out.print(mid); // System.out.print(mid); // } } System.out.println(y); } } public void readFile() { 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; StringBuilder sb = new StringBuilder(); // Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console sb.append(strLine); sb.append(delim); } // Close the input stream in.close(); fileContents = sb.toString(); } catch (Exception e) {// Catch exception if any System.err.println("Error: " + e.getMessage()); } } }
A10699
A10614
0
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; public class Dancing { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // read input file File file = new File("B-small-attempt4.in"); //File file = new File("input.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String ln = ""; int count = Integer.parseInt(br.readLine()); // write output file File out = new File("outB.txt"); BufferedWriter bw = new BufferedWriter(new FileWriter(out)); int y = 0; for (int i=0; i < count; i++){ ln = br.readLine(); y = getY(ln); bw.write("Case #" + (i+1) + ": " + y); bw.newLine(); } bw.close(); } private static int getY(String str) { String[] data = str.split(" "); int n = Integer.parseInt(data[0]); int s = Integer.parseInt(data[1]); int p = Integer.parseInt(data[2]); int[] t = new int[n]; for (int i=0; i < n; i++){ t[i] = Integer.parseInt(data[i+3]); } int y = 0; int base = 0; for(int j=0; j < t.length; j++){ base = t[j] / 3; if(base >= p) { y++; } else if(base == p-1){ if(t[j] - (base+p) > base-1 && t[j] > 0){ y++; } else if(s>0 && t[j] - (base+p) > base-2 && t[j] > 0){ s -= 1; y++; } } else if(base == p-2){ if(s > 0 && t[j] - (base+p) > base-1 && t[j] > 0){ s -= 1; y++; } } } return y; } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class GCJ2 { public GCJ2() { } public static void main(String[] args) { GCJ2 gcj = new GCJ2(); 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<lineNum; i++) { String line = br.readLine(); String[] segs = line.split(" "); int googlerNum = Integer.parseInt(segs[0]); int surpriseNum = Integer.parseInt(segs[1]); int maxScore = Integer.parseInt(segs[2]); int[] scores = new int[googlerNum]; for (int j=0; j<googlerNum; j++) { int s = Integer.parseInt(segs[3+j]); scores[j] = s; } int result = 0; for (int j=0; j<googlerNum; j++) { int s = scores[j]; int min = (maxScore-1) >= 0 ? (maxScore-1) : 0; if (s >= min + min + maxScore) { result++; } else if (surpriseNum > 0) { min = (maxScore-2) >= 0 ? (maxScore-2) : 0; if (s >= min + min + maxScore) { result++; surpriseNum--; } } } bw.write("Case #" + (i+1) + ": " + result); if (i != (lineNum-1)) bw.newLine(); } bw.flush(); bw.close(); } catch (Exception e) { e.printStackTrace(); } } }
B22190
B21007
0
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<Long> used = new HashSet<Long>(); 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(); } }
/* * 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++; } } } }
A13029
A10255
0
import java.util.List; public class Case implements Runnable { private int id; private String output; private int n; private int s; private int p; private List<Integer> g; public Case(int id) { this.id = id; } public Case(int id, int n, int s, int p, List<Integer> g) { super(); this.id = id; this.n = n; this.s = s; this.p = p; this.g = g; } public String solve() { int res = 0; for (int googler : g) { int b = googler / 3; boolean div = googler % 3 == 0; if (b >= p) { res++; continue; } if (p == b+1) { if (div && s > 0 && b > 0) { res++; s--; continue; } if (!div) { res++; continue; } } if (p == b+2) { if (3*b+2 == googler && s > 0) { res++; s--; } } } return String.valueOf(res); } @Override public void run() { output = solve(); } @Override public String toString() { return "Case #" + id + ": " + output; } }
import java.util.Scanner; /** * Google Code Jam 2012 * * @author 7henick */ public class ProblemB { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); sc.nextLine(); for (int i = 0; i < T; i++) { int N = sc.nextInt(); int S = sc.nextInt(); int p = sc.nextInt(); int result = 0; for (int j = 0; j < N; j++) { int g = sc.nextInt(); int min = g / 3; int best = g - min * 2; if (best - min == 0) { if (best >= p) { result++; } else { if (best + 1 >= p && min - 1 >= 0 && S > 0) { result++; S--; } } } else if (best - min == 1) { if (best >= p) { result++; } } else if (best - min == 2) { if (best - 1 >= p) { result++; } else { if (best >= p && S > 0) { result++; S--; } } } else { throw new Exception(); } } System.out.println("Case #" + (i + 1) + ": " + result); sc.nextLine(); } } }
B21207
B21945
0
/* * 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 <marco.lackovic@gmail.com> * @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; } }
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<Integer> S = new HashSet<Integer>(); 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); } }
A20261
A20628
0
package com.gcj.parser; public class MaxPoints { public static int normal(int value){ int toReturn = 0; switch (value) { case 0 : toReturn = 0 ; break; case 1 : toReturn = 1 ; break; case 2 : toReturn = 1 ; break; case 3 : toReturn = 1 ; break; case 4 : toReturn = 2 ; break; case 5 : toReturn = 2 ; break; case 6 : toReturn = 2 ; break; case 7 : toReturn = 3 ; break; case 8 : toReturn = 3 ; break; case 9 : toReturn = 3 ; break; case 10 : toReturn = 4 ; break; case 11 : toReturn = 4 ; break; case 12 : toReturn = 4 ; break; case 13 : toReturn = 5 ; break; case 14 : toReturn = 5 ; break; case 15 : toReturn = 5 ; break; case 16 : toReturn = 6 ; break; case 17 : toReturn = 6 ; break; case 18 : toReturn = 6 ; break; case 19 : toReturn = 7 ; break; case 20 : toReturn = 7 ; break; case 21 : toReturn = 7 ; break; case 22 : toReturn = 8 ; break; case 23 : toReturn = 8 ; break; case 24 : toReturn = 8 ; break; case 25 : toReturn = 9 ; break; case 26 : toReturn = 9 ; break; case 27 : toReturn = 9 ; break; case 28 : toReturn = 10 ; break; case 29 : toReturn = 10 ; break; case 30 : toReturn = 10 ; break; } return toReturn; } public static int surprising(int value){ int toReturn = 0; switch (value) { case 0 : toReturn = 0 ; break; case 1 : toReturn = 1 ; break; case 2 : toReturn = 2 ; break; case 3 : toReturn = 2 ; break; case 4 : toReturn = 2 ; break; case 5 : toReturn = 3 ; break; case 6 : toReturn = 3 ; break; case 7 : toReturn = 3 ; break; case 8 : toReturn = 4 ; break; case 9 : toReturn = 4 ; break; case 10 : toReturn = 4 ; break; case 11 : toReturn = 5 ; break; case 12 : toReturn = 5 ; break; case 13 : toReturn = 5 ; break; case 14 : toReturn = 6 ; break; case 15 : toReturn = 6 ; break; case 16 : toReturn = 6 ; break; case 17 : toReturn = 7 ; break; case 18 : toReturn = 7 ; break; case 19 : toReturn = 7 ; break; case 20 : toReturn = 8 ; break; case 21 : toReturn = 8 ; break; case 22 : toReturn = 8 ; break; case 23 : toReturn = 9 ; break; case 24 : toReturn = 9 ; break; case 25 : toReturn = 9 ; break; case 26 : toReturn = 10 ; break; case 27 : toReturn = 10 ; break; case 28 : toReturn = 10 ; break; case 29 : toReturn = 10 ; break; case 30 : toReturn = 10 ; break; } return toReturn; } }
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;t<T;t++) { st=new StringTokenizer(f.readLine()); int N=Integer.parseInt(st.nextToken()); int S=Integer.parseInt(st.nextToken()); int p=Integer.parseInt(st.nextToken()); int[] scores=new int[N]; for(int i=0;i<N;i++) { scores[i]=Integer.parseInt(st.nextToken()); } int res=0; int minScoreWithSurprise=p+2*(p-2); int minScoreWithoutSurprise=p+2*(p-1); for(int i=0;i<N;i++) { if(scores[i]==0) { if(p==0) res++; } else if(scores[i]==1) { if(p==1||p==2) res++; } else if(minScoreWithoutSurprise<=scores[i]) res++; else if(minScoreWithSurprise<=scores[i]&&S>0) { res++; S--; } } out.println("Case #"+(t+1)+": "+res); } out.close(); System.exit(0); } }
B12941
B13194
0
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<CInput, COutputEntry> { public CProcessorFactory(String inputFileName) { super(inputFileName); } @Override protected InputBlockParser<CInput> createInputBlockParser() { return new CInputBlockParser(); } @Override protected OutputProducer<CInput, COutputEntry> createOutputProducer() { return new COutputProducer(); } }
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<Triplet> 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++<testCases){ a = read.nextInt(); b = read.nextInt(); //read.nextLine(); output = "Case #"+cn+": "+ solve(a,b);//WRITE ANS TO DIFFERENT FILE ANS += output +" \n"; System.out.println(ANS); } writeToFile("numbers.out",ANS); } catch(FileNotFoundException e){//if file is not found System.err.println("data file \'"+path+"\' was not found\nPress <enter> 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; } }
B11327
B11818
0
package recycledNumbers; public class OutputData { private int[] Steps; public int[] getSteps() { return Steps; } public OutputData(int [] Steps){ this.Steps = Steps; for(int i=0;i<this.Steps.length;i++){ System.out.println("Test "+(i+1)+": "+Steps[i]); } } }
/** * Google CodeJam 2012 * General framework that takes care of the similar and repetitive tasks for all the problems. * E.g. managing case input and output. * * By Üllar Soon <positivew@gmail.com> */ package eu.positivew.codejam.framework; /** * CodeJam input case (string). * * @author Üllar Soon <positivew@gmail.com> */ public class CodeJamStringCase implements CodeJamInputCase { private String value = ""; public CodeJamStringCase(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String getType() { return "String"; } }
B20734
B21174
0
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(); } }
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<Integer> seen = new HashSet<Integer>(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(); } }
A22992
A20804
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package IO; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; /** * * @author dannocz */ public class InputReader { public static Input readFile(String filename){ try { /* Sets up a file reader to read the file passed on the command 77 line one character at a time */ FileReader input = new FileReader(filename); /* Filter FileReader through a Buffered read to read a line at a time */ BufferedReader bufRead = new BufferedReader(input); String line; // String that holds current file line int count = 0; // Line number of count ArrayList<String> cases= new ArrayList<String>(); // Read first line line = bufRead.readLine(); int noTestCases=Integer.parseInt(line); count++; // Read through file one line at time. Print line # and line while (count<=noTestCases){ //System.out.println("Reading. "+count+": "+line); line = bufRead.readLine(); cases.add(line); count++; } bufRead.close(); return new Input(noTestCases,cases); }catch (ArrayIndexOutOfBoundsException e){ /* If no file was passed on the command line, this expception is generated. A message indicating how to the class should be called is displayed */ e.printStackTrace(); }catch (IOException e){ // If another exception is generated, print a stack trace e.printStackTrace(); } return null; }// end main }
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; } }
B12074
B10928
0
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 ); } }
/* * 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<Character, Character> mapToGoogleres; private HashMap<Character, Character> mapToEnglish; public SpeakingInTongues(String filename) { super(filename); mapToEnglish = new HashMap<Character, Character>(); // mapToGoogleres = new HashMap<Character, Character>(); 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(); } } }
A12273
A12323
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Dancing * Jason Bradley Nel * 16287398 */ import java.io.*; public class Dancing { public static void main(String[] args) { In input = new In("input.txt"); int T = Integer.parseInt(input.readLine()); for (int i = 0; i < T; i++) { System.out.printf("Case #%d: ", i + 1); int N = input.readInt(); int s = input.readInt(); int p = input.readInt(); int c = 0;//counter for >=p cases //System.out.printf("N: %d, S: %d, P: %d, R: ", N, s, p); for (int j = 0; j < N; j++) { int score = input.readInt(); int q = score / 3; int m = score % 3; //System.out.printf("%2d (%d, %d) ", scores[j], q, m); switch (m) { case 0: if (q >= p) { c++; } else if (((q + 1) == p) && (s > 0) && (q != 0)) { c++; s--; } break; case 1: if (q >= p) { c++; } else if ((q + 1) == p) { c++; } break; case 2: if (q >= p) { c++; } else if ((q + 1) == p) { c++; } else if (((q + 2) == p) && (s > 0)) { c++; s--; } break; } } //System.out.printf("Best result of %d or higher: ", p); System.out.println(c); } } }
package com.wonyoung.codejam.qualificationround; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; public class DancingWithTheGooglers { private Integer testCasesT; private DancingWithTheGooglersData [] data; class DancingWithTheGooglersData { Integer googlersN; Integer surprisingS; Integer p; String[] totalPoints; public DancingWithTheGooglersData() { } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(googlersN.toString()); sb.append(" " + surprisingS.toString()); sb.append(" " + p.toString()); int count = 0; while ( count < googlersN ) { sb.append(" " + totalPoints[count].toString()); count++; } return sb.toString(); } } public DancingWithTheGooglers(String filename) throws IOException { BufferedReader br = new BufferedReader(new FileReader(filename)); String line; testCasesT = Integer.valueOf(br.readLine()); data = new DancingWithTheGooglersData[testCasesT]; int count = 0; while ( count < testCasesT) { line= br.readLine(); String [] words = line.split(" "); data[count] = new DancingWithTheGooglersData(); data[count].googlersN = Integer.valueOf(words[0]); data[count].surprisingS = Integer.valueOf(words[1]); data[count].p = Integer.valueOf(words[2]); data[count].totalPoints = Arrays.copyOfRange(words, 3, 3 + data[count].googlersN); count++; } br.close(); } public String result(int i) { return "Case #"+ (i+1) +": "+ greaterOrEqualsThanP(i); } private Integer greaterOrEqualsThanP(int i) { int result = 0; int surprisingCards = data[i].surprisingS; if (data[i].p <= 0) return data[i].googlersN; int baseScore = data[i].p*3 - 3; for ( String points : data[i].totalPoints) { Integer n = Integer.valueOf(points); if (baseScore < n) { result++; System.out.print("+"); } else if (data[i].p < n && baseScore < n+2 && surprisingCards > 0) { surprisingCards--; result++; System.out.print("s"); } else System.out.print("-"); } System.out.println(); return result; } public void print(String filename) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(filename)); int count = 0; while (count < testCasesT) { bw.write(result(count)); bw.newLine(); count++; } bw.close(); } public static void main(String args[]) throws IOException { DancingWithTheGooglers dwg = new DancingWithTheGooglers("B-small-attempt1.in"); dwg.print("B-small-attempt1.out"); } }
A10996
A12737
0
import java.util.Scanner; import java.io.*; class dance { public static void main (String[] args) throws IOException { File inputData = new File("B-small-attempt0.in"); File outputData= new File("Boutput.txt"); Scanner scan = new Scanner( inputData ); PrintStream print= new PrintStream(outputData); int t; int n,s,p,pi; t= scan.nextInt(); for(int i=1;i<=t;i++) { n=scan.nextInt(); s=scan.nextInt(); p=scan.nextInt(); int supTrip=0, notsupTrip=0; for(int j=0;j<n;j++) { pi=scan.nextInt(); if(pi>(3*p-3)) notsupTrip++; else if((pi>=(3*p-4))&&(pi<=(3*p-3))&&(pi>p)) supTrip++; } if(s<=supTrip) notsupTrip=notsupTrip+s; else if(s>supTrip) notsupTrip= notsupTrip+supTrip; print.println("Case #"+i+": "+notsupTrip); } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class BMain { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int casesCnt = Integer.parseInt(reader.readLine()); for (int i = 0; i < casesCnt; i++) { String line = reader.readLine(); solve(i + 1, line); } // int[] sIdx = {0,1,2}; // int[] sIdx = {0,3,4}; // int[] sIdx = {}; // int size = 5; // System.out.println(Arrays.toString(sIdx)); // for (int i = 0; i < 16; i++) { // boolean ok = nextSurprises(sIdx, size); // if (!ok) break; // System.out.println(Arrays.toString(sIdx)); // } } private static void solve(int caseN, String line) { final StringTokenizer tokens = new StringTokenizer(line); final int nGooglers = Integer.parseInt(tokens.nextToken()); final int surprises = Integer.parseInt(tokens.nextToken()); final int pMinScore = Integer.parseInt(tokens.nextToken()); final int[] scores = new int[nGooglers]; for (int i = 0; i < scores.length; i++) { scores[i] = Integer.parseInt(tokens.nextToken()); } int result = 0; int[] suprIdx = initSurprises(surprises, nGooglers); mainloop: do { int resultTmp = 0; boolean[] isSurprise = new boolean[nGooglers]; for (int i : suprIdx) { isSurprise[i] = true; if (scores[i]<2) continue mainloop; } for (int i = 0; i < scores.length; i++) { for (int best = pMinScore; best <= 10; best++) { int tripleBest = 3 * best; if (isSurprise[i]) { // if surprise .. -2,-3,-4 if (scores[i] <= tripleBest - 2 && scores[i] >= tripleBest - 4) { resultTmp++; } } else { // if !surprise .. sum = 3*best -0,-1,-2 if (scores[i] <= tripleBest && scores[i] >= tripleBest - 2) { resultTmp++; } } } } if (resultTmp > result) result = resultTmp; } while (nextSurprises(suprIdx, nGooglers)); System.out.printf("Case #%d: %d%n", caseN, result); } private static int[] initSurprises(int surprCnt, int googlers) { int [] result = new int[surprCnt]; for (int i = 1; i < result.length; i++) { result[i] = result[i-1] + 1; } return result; } private static boolean nextSurprises(int[] sIdx, int googlers) { int i = sIdx.length - 1; boolean overflow = true; while (i >= 0 && overflow) { if (sIdx[i] >= googlers - 1 - (sIdx.length - i - 1)) { // overflow i--; } else { // no overflow overflow = false; //inc idx sIdx[i]++; // fix remaining indexes for (int y = i + 1; y < sIdx.length; y++) { sIdx[y] = sIdx[y - 1] + 1; } return true; } } return false; } }
B12082
B10233
0
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 ); } }
import java.io.*; import java.util.*; public class PracticeC { /* ‚±‚±‚©‚ç•ÒW */ private static final String fname = "C-small-attempt3.in"; // “ü—Í—p‚̃tƒ@ƒCƒ‹–¼ // private static final int N = 10000; // private static void search(int v) // { // if (v < 21) // return; // String in = Integer.toString(v); // for (int i = 0; i < in.length(); i++) // { // String vs = ""; // for (int j = 0; j < in.length(); j++) // { // char n = in.charAt((i + j + 1) % in.length()); // if (vs.equals("") && n == '0') // break; // vs += n; // } // // System.out.println(v2); // if (vs.equals("")) // continue; // int v2 = Integer.valueOf(vs); // if (v > v2) val[v]++; // } // } private static void search(int v, int A, int B) { use = new boolean[B+1]; String in = Integer.toString(v); for (int i = 0; i < in.length(); i++) { String vs = ""; for (int j = 0; j < in.length(); j++) { char n = in.charAt((i + j + 1) % in.length()); if (vs.equals("") && n == '0') break; vs += n; } // System.out.println(v2); if (vs.equals("")) continue; int v2 = Integer.valueOf(vs); if (v2 >= A && v > v2 && !use[v2]) { use[v2] = true; val[v]++; } } } public static int val[]; public static boolean use[]; public static void solve() { int T = sc.nextInt(); // for (int i = 21; i < val.length; i++) search(i); // for (int i = 0; i < 100; i++) if(val[i] != 0) // System.out.println(i+":"+val[i]); for (int i = 1; i <= T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); val = new int[B+1]; for (int j = A; j <= B; j++) search(j, A, B); int cnt = 0; for (int j = A; j <= B; j++) { // if(val[j] != 0) System.out.println(j+":"+val[j]); cnt += val[j]; } // System. out.println("Case #" + i + ": " + (cnt)); } } /* ‚±‚±‚Ü‚Å */ private static Scanner sc; private static PrintWriter out; public static void main(String args[]) { try { sc = new Scanner(new File(fname)); // sc = new Scanner(System.in); out = new PrintWriter(new BufferedWriter(new FileWriter(new File(fname + "_out.dat")))); } catch (Exception e) { e.printStackTrace(); } solve(); out.close(); } }
B20291
B20069
0
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<X; i++) { String[] S = br.readLine().split(" "); int A = Integer.parseInt(S[0]); int B = Integer.parseInt(S[1]); int R = 0; int x = 1; int n = 0; while(A/x > 0) { n++; x *= 10; } for(int j=A; j<B; j++) { Set<Integer> seen = new HashSet<Integer>(); for(int k=1; k<n; k++) { int p1 = j % (int)Math.pow(10, k); int p2 = (int) Math.pow(10, n-k); int p3 = j / (int)Math.pow(10, k); int y = p1*p2 + p3; if(j < y && !seen.contains(y) && y <= B) { seen.add(y); R++; } } } pw.printf("Case #%d: %d\n", i+1, R); pw.flush(); } } catch(Exception e) { e.printStackTrace(); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Recycle; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; /** * * @author hemal */ public class Main { public static void main(String[] args) { try { BufferedReader bf = new BufferedReader(new FileReader(System.getProperty("user.dir") + "/src/Recycle/" + "input.in")); String s = bf.readLine(); int t = Integer.parseInt(s); // for (int i = 1; i <= t; i++) { // int count = 0; // String s1 = bf.readLine(); // String s2[] = s1.split(" "); // int a = Integer.parseInt(s2[0]); // int b = Integer.parseInt(s2[1]); // int size = s2[0].length(); // System.out.println("size " + size); // for (int j = a; i <= b; j++) { //// for(int k=0;k<size;k++){ //// String m=String.valueOf(j).charAt(k) //// } //// System.out.println(a + " " + b); //// for (int k = 1; k <= size; k++) { // int m = (int) (((j % (Math.pow(10, 1))) * Math.pow(10, size - 1)) + j / Math.pow(10, 1)); // System.out.println(m); // m = (int) (((j % (Math.pow(10, 2))) * Math.pow(10, size - 2)) + j / Math.pow(10, 2)); // System.out.println(m); //// m = (int) (((j % (Math.pow(10, 3))) * Math.pow(10, size - 3)) + j / Math.pow(10, 3)); //// System.out.println(m); //// m = (int) (((j % (Math.pow(10, 4))) * Math.pow(10, size - 4)) + j / Math.pow(10, 4)); //// System.out.println(m); //// if (m > 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(); } } }
B12074
B12408
0
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 ); } }
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()); } }
A22992
A20044
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package IO; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; /** * * @author dannocz */ public class InputReader { public static Input readFile(String filename){ try { /* Sets up a file reader to read the file passed on the command 77 line one character at a time */ FileReader input = new FileReader(filename); /* Filter FileReader through a Buffered read to read a line at a time */ BufferedReader bufRead = new BufferedReader(input); String line; // String that holds current file line int count = 0; // Line number of count ArrayList<String> cases= new ArrayList<String>(); // Read first line line = bufRead.readLine(); int noTestCases=Integer.parseInt(line); count++; // Read through file one line at time. Print line # and line while (count<=noTestCases){ //System.out.println("Reading. "+count+": "+line); line = bufRead.readLine(); cases.add(line); count++; } bufRead.close(); return new Input(noTestCases,cases); }catch (ArrayIndexOutOfBoundsException e){ /* If no file was passed on the command line, this expception is generated. A message indicating how to the class should be called is displayed */ e.printStackTrace(); }catch (IOException e){ // If another exception is generated, print a stack trace e.printStackTrace(); } return null; }// end main }
import java.util.Scanner; import java.util.ArrayList; public class dancing { public static void main(String [] args){ Scanner Keyboard = new Scanner(System.in); int testCases; ArrayList<String> input = new ArrayList<String>(); ArrayList<Integer> totalPoints = new ArrayList<Integer>(); int whitespaceNumber = 1; int previousWhitespace = 0; int numberOfGooglers = 0; int surprisingTriplet = 0; int bestResult = 0; int k = 0; int [] triplet = {0, 0, 0}; int numberOfBestResults = 0; testCases = Keyboard.nextInt(); Keyboard.nextLine(); for (int i = 0; i < testCases; i++){ input.add(Keyboard.nextLine()); } for (int i = 0; i < testCases; i++){ for (int j = 0; j < input.get(i).length(); j++){ if (input.get(i).charAt(j) == ' '){ if (whitespaceNumber == 1){ numberOfGooglers = Integer.parseInt(input.get(i).substring(0, j)); whitespaceNumber++; previousWhitespace = j; } else if (whitespaceNumber == 2){ surprisingTriplet = Integer.parseInt(input.get(i).substring(previousWhitespace+1, j)); whitespaceNumber++; previousWhitespace = j; } else if (whitespaceNumber == 3){ bestResult = Integer.parseInt(input.get(i).substring(previousWhitespace+1, j)); whitespaceNumber++; previousWhitespace = j; } else if (whitespaceNumber >= 4){ totalPoints.add(Integer.parseInt(input.get(i).substring(previousWhitespace+1, j))); whitespaceNumber++; previousWhitespace = j; } } } totalPoints.add(Integer.parseInt(input.get(i).substring(previousWhitespace+1, input.get(i).length()))); for (int b = 0; b < numberOfGooglers; b++){ while(true){ if (k + k + k < totalPoints.get(b)){ k++; } else if (k + k + k > totalPoints.get(b)){ if (k + k + (k-1) == totalPoints.get(b)){ triplet[0] = k; triplet[1] = k; triplet[2] = k-1; break; } else if (k + (k-1) + (k-1) == totalPoints.get(b)){ triplet[0] = k; triplet[1] = k-1; triplet[2] = k-1; break; } } else if (k + k + k == totalPoints.get(b)){ triplet[0] = k; triplet[1] = k; triplet[2] = k; break; } } if (triplet[0] < bestResult && triplet[1] < bestResult && triplet[2] < bestResult && surprisingTriplet > 0){ while (k < bestResult){ k++; } if (k + k + (k-2) == totalPoints.get(b) && k >= bestResult && (k-2)>=0){ triplet[0] = k; triplet[1] = k; triplet[2] = k-2; surprisingTriplet--; } else if (k + (k-1) + (k-2) == totalPoints.get(b) && k >= bestResult && (k-2)>=0){ triplet[0] = k; triplet[1] = k-1; triplet[2] = k-2; surprisingTriplet--; } else if (k + (k-2) + (k-2) == totalPoints.get(b) && k >= bestResult && (k-2)>=0){ triplet[0] = k; triplet[1] = k-2; triplet[2] = k-2; surprisingTriplet--; } } if (triplet[0] >= bestResult || triplet[1] >= bestResult || triplet[2] >= bestResult){ numberOfBestResults++; } k = 0; } System.out.println("Case #" + (i+1) + ": " + numberOfBestResults); whitespaceNumber = 1; previousWhitespace = 0; numberOfGooglers = 0; surprisingTriplet = 0; bestResult = 0; numberOfBestResults = 0; totalPoints.clear(); } } }
A12273
A12092
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Dancing * Jason Bradley Nel * 16287398 */ import java.io.*; public class Dancing { public static void main(String[] args) { In input = new In("input.txt"); int T = Integer.parseInt(input.readLine()); for (int i = 0; i < T; i++) { System.out.printf("Case #%d: ", i + 1); int N = input.readInt(); int s = input.readInt(); int p = input.readInt(); int c = 0;//counter for >=p cases //System.out.printf("N: %d, S: %d, P: %d, R: ", N, s, p); for (int j = 0; j < N; j++) { int score = input.readInt(); int q = score / 3; int m = score % 3; //System.out.printf("%2d (%d, %d) ", scores[j], q, m); switch (m) { case 0: if (q >= p) { c++; } else if (((q + 1) == p) && (s > 0) && (q != 0)) { c++; s--; } break; case 1: if (q >= p) { c++; } else if ((q + 1) == p) { c++; } break; case 2: if (q >= p) { c++; } else if ((q + 1) == p) { c++; } else if (((q + 2) == p) && (s > 0)) { c++; s--; } break; } } //System.out.printf("Best result of %d or higher: ", p); System.out.println(c); } } }
import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Dancing { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(new File("dancing.in")); System.setOut(new PrintStream(new File("dancing.out"))); ArrayList<Googler> changeAble = new ArrayList<Googler>(100); int t = sc.nextInt(); for(int i=1; i<=t; i++){ changeAble.clear(); int n = sc.nextInt();//number of googlers int s = sc.nextInt();//number of surprises int p = sc.nextInt();//target int y = 0;//number that match for(int j=0; j<n; j++){ Googler temp = new Googler(sc.nextInt(),p); if(temp.distAway < 1) y++; else if(temp.changeAble){ changeAble.add(temp); } } Collections.sort(changeAble); for(int j=0; j<s && j<changeAble.size(); j++){ Googler temp = changeAble.get(j); if(temp.maxScore+1 < p) break; y++; } System.out.println("Case #"+i+": "+y); } } } class Googler implements Comparable<Googler>{ int distAway; boolean changeAble = false; int maxScore; int sScore; int score; int t; public Googler(int score, int target){ t = target; this.score=score; int i = score/3; if(i*3==score){ maxScore = i; changeAble = true; } else if(i*2+i+1 == score) maxScore = i+1; else if(i+(i+1)*2==score){ maxScore = i+1; changeAble = true; } if(maxScore==0) changeAble = false; distAway = target-maxScore; } public int compareTo(Googler g){ return distAway-g.distAway; } public String toString(){ return score+""; } }
B10858
B12250
0
package be.mokarea.gcj.common; public abstract class TestCaseReader<T extends TestCase> { public abstract T nextCase() throws Exception; public abstract int getMaxCaseNumber(); }
import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.util.Arrays; import java.util.Scanner; public class Read { int noOfTestCases; int []nums; public void Read(String name) { File file = new File(name); try { Scanner scanner = new Scanner(file); String line = scanner.nextLine(); noOfTestCases = Integer.parseInt(line); nums = new int[noOfTestCases*2]; int i=0; while(i<noOfTestCases){ line = scanner.nextLine(); String []numS = line.split(" "); nums[2*i]=Integer.parseInt(numS[0]); nums[2*i+1]=Integer.parseInt(numS[1]); i++; } } catch (FileNotFoundException e) { } } public void write(String fname,String data) { try{ // Create file FileWriter fstream = new FileWriter(fname); BufferedWriter out = new BufferedWriter(fstream); out.write(data); //Close the output stream out.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } public static void main(String[] args) { Read r = new Read(); r.Read("test"); } }
B12115
B13049
0
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; } }
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-small-attempt3.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<String> line = new ArrayList<String>(); String[] s = strLine.split(" "); int i =0; for(;i<s.length;){ line.add(s[i++]); } int n1 = Integer.parseInt(line.get(0)); int n2 = Integer.parseInt(line.get(1)); int nr = 0; for(int k = n1; k<=n2; k++) { int temp1=k,temp2,nr_temp=0; int nr_sh = (int)Math.log10(k); do{ if((temp1>=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()); } } }
A22191
A22429
0
package com.example; import java.io.IOException; import java.util.List; public class ProblemB { enum Result { INSUFFICIENT, SUFFICIENT, SUFFICIENT_WHEN_SURPRISING } public static void main(String[] a) throws IOException { List<String> lines = FileUtil.getLines("/B-large.in"); int cases = Integer.valueOf(lines.get(0)); for(int c=0; c<cases; c++) { String[] tokens = lines.get(c+1).split(" "); int n = Integer.valueOf(tokens[0]); // N = number of Googlers int s = Integer.valueOf(tokens[1]); // S = number of surprising triplets int p = Integer.valueOf(tokens[2]); // P = __at least__ a score of P int sumSufficient = 0; int sumSufficientSurprising = 0; for(int i=0; i<n; i++) { int points = Integer.valueOf(tokens[3+i]); switch(test(points, p)) { case SUFFICIENT: sumSufficient++; break; case SUFFICIENT_WHEN_SURPRISING: sumSufficientSurprising++; break; } // uSystem.out.println("points "+ points +" ? "+ p +" => "+ result); } System.out.println("Case #"+ (c+1) +": "+ (sumSufficient + Math.min(s, sumSufficientSurprising))); // System.out.println(); // System.out.println("N="+ n +", S="+ s +", P="+ p); // System.out.println(); } } private static Result test(int n, int p) { int fac = n / 3; int rem = n % 3; if(rem == 0) { // int triplet0[] = { fac, fac, fac }; // print(n, triplet0); if(fac >= p) { return Result.SUFFICIENT; } if(fac > 0 && fac < 10) { if(fac+1 >= p) { return Result.SUFFICIENT_WHEN_SURPRISING; } // int triplet1[] = { fac+1, fac, fac-1 }; // surprising // print(n, triplet1); } } else if(rem == 1) { // int triplet0[] = { fac+1, fac, fac }; // print(n, triplet0); if(fac+1 >= p) { return Result.SUFFICIENT; } // if(fac > 0 && fac < 10) { // int triplet1[] = { fac+1, fac+1, fac-1 }; // print(n, triplet1); // } } else if(rem == 2) { // int triplet0[] = { fac+1, fac+1, fac }; // print(n, triplet0); if(fac+1 >= p) { return Result.SUFFICIENT; } if(fac < 9) { // int triplet1[] = { fac+2, fac, fac }; // surprising // print(n, triplet1); if(fac+2 >= p) { return Result.SUFFICIENT_WHEN_SURPRISING; } } } else { throw new RuntimeException("error"); } return Result.INSUFFICIENT; // System.out.println(); // System.out.println(n +" => "+ div3 +" ("+ rem +")"); } // private static void print(int n, int[] triplet) { // System.out.println("n="+ n +" ("+ (n/3) +","+ (n%3) +") => ["+ triplet[0] +","+ triplet[1] +","+ triplet[2] +"]" + (triplet[0]-triplet[2] > 1 ? " *" : "")); // } }
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; public class Solver { public static String PROBLEM_NUMBER="B"; 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 nGooglers; public int nSurprising; public int desiredScore; public int[]scores; public StringBuffer outputString; public void solve(){ outputString=new StringBuffer("Case #"+nCase+": "); int nSurprisingLeft=nSurprising; int nResult=0; for(int score:scores){ boolean surprisingFound=false; boolean normalFound=false; for(int i=10;i>=0;i--){ int score1=i; int score2=i; int score3=i; int aux=score-i; if(aux>=0){ if(aux%2==0){ score2=aux/2; score3=score2; }else{ score2=aux/2; score3=score2+1; } if(score1>=desiredScore||score2>=desiredScore||score3>=desiredScore){ if( (Math.abs(score1-score2))<2 && (Math.abs(score1-score3)) <2 ){ //System.out.println("Posible score for "+score+" is ("+score1+","+score2+","+score3 +")"); normalFound=true; }else if( (Math.abs(score1-score2))<=2 && (Math.abs(score1-score3)) <=2 ){ //System.out.println("Posible surprising score for "+score+" is ("+score1+","+score2+","+score3 +")"); surprisingFound=true; } } } } if(normalFound){ nResult++; }else if(surprisingFound&&nSurprisingLeft>0){ nSurprisingLeft--; nResult++; } } outputString.append(nResult); } } //Boring IO handling public static void main(String[]args){ try{ String output=PATH_TO_OUPUT_FILE_LARGE; if(SMALL){ output=PATH_TO_OUPUT_FILE_SMALL; } File file=new File(output); file.createNewFile(); BufferedWriter bw=new BufferedWriter(new FileWriter(file)); String input=PATH_TO_INPUT_FILE_LARGE; if(SMALL){ input=PATH_TO_INPUT_FILE_SMALL; } FileInputStream fstream = new FileInputStream(input); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line int nCases=0; int nCase=1; Problem problem=new Problem(); for (int i=0;(strLine = br.readLine()) != null;i++) { // Print the content on the console //System.out.println (strLine); if(i== 0){ nCases=Integer.parseInt(strLine); }else{ int nParam=(i-1)%1; switch(nParam){ case 0: problem.nCase=nCase; String[]tokens=strLine.split(" "); problem.nGooglers=Integer.parseInt(tokens[0]); problem.nSurprising=Integer.parseInt(tokens[1]); problem.desiredScore=Integer.parseInt(tokens[2]); problem.scores=new int[problem.nGooglers]; for(int j=0,z=3;j<problem.nGooglers;j++,z++){ problem.scores[j]=Integer.parseInt(tokens[z]); } problem.solve(); System.out.println(problem.outputString); bw.append(problem.outputString); bw.newLine(); problem=new Problem(); nCase++; break; default: throw new Exception("Error Parsing"); } } } //Close the input stream in.close(); bw.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }
B22190
B21843
0
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<Long> used = new HashSet<Long>(); 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(); } }
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<String> newNumbers = new HashSet<String>(); 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); } } }
A22771
A20340
0
package com.menzus.gcj._2012.qualification.b; import com.menzus.gcj.common.InputBlockParser; import com.menzus.gcj.common.OutputProducer; import com.menzus.gcj.common.impl.AbstractProcessorFactory; public class BProcessorFactory extends AbstractProcessorFactory<BInput, BOutputEntry> { public BProcessorFactory(String inputFileName) { super(inputFileName); } @Override protected InputBlockParser<BInput> createInputBlockParser() { return new BInputBlockParser(); } @Override protected OutputProducer<BInput, BOutputEntry> createOutputProducer() { return new BOutputProducer(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam2012; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; /** * * @author acer */ public class B { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here FileInputStream input = new FileInputStream("input.txt"); DataInputStream in = new DataInputStream(input); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileOutputStream output = new FileOutputStream("output.txt"); int T = Integer.parseInt(br.readLine()); for (int i = 0; i < T; i++) { String[] temp = br.readLine().split(" "); int N = Integer.parseInt(temp[0]); int S = Integer.parseInt(temp[1]); int P = Integer.parseInt(temp[2]); int[] points = new int[N]; int count = 0, scount = 0; for (int j = 0; j < N; j++) { points[j] = Integer.parseInt(temp[j + 3]); int avg = points[j] / 3; if (points[j] % 3 == 0) { if (avg >= P) { count++; } else if ((avg + 1) == P && avg != 0 && avg != 10) { scount++; } } else if (points[j] % 3 == 1) { if ((avg+1) >= P) { count++; } } else if (points[j] % 3 == 2) { if ((avg + 1) >= P) { count++; } else if ((avg + 2) == P && avg != 9) { scount++; } } } if (S >= scount) { output.write(("Case #" + (i + 1) + ": " + (count + scount) + "\n").getBytes()); } else { output.write(("Case #" + (i + 1) + ": " + (count + S) + "\n").getBytes()); } } } }
B10899
B10822
0
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<String> readData = new ArrayList<String>(); 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<String> 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<String> dupC = new HashSet<String>(); for (int i = a; i <= b; i++) { int n = i; List<String> 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<String> findPerm(int num) { String numString = String.valueOf(num); List<String> value = new ArrayList<String>(); 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; } }
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-small-attempt4"; 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<Integer,List> m = new HashMap<Integer,List>(); 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<Integer> 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<Integer> rr = new HashSet<Integer>(); for(int i=0;i<tt.length();i++) { if(i!=0) { tt = tt.substring(1) + tt.charAt(0); if(tt.startsWith("0")) continue; t = Integer.parseInt(tt); } if(t>=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<Integer, List> 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<Integer>(); m.put(b, target); } target.add(i); } public static Map<Integer,Boolean> dedup = new HashMap<Integer,Boolean>(); private boolean dedup(int t) { String tt = ""+t; for(int i=0;i<tt.length();i++) { if(i!=0) { tt = tt.substring(1) + tt.charAt(0); if(tt.startsWith("0")) continue; t = Integer.parseInt(tt); } if(dedup.get(t) != null) return false; } return true; } }
B20856
B20884
0
/* * 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<Integer> mm = new LinkedList<Integer>(); //mm.add(new LinkedList<Integer>()); //int[][] mm; //for(int ii=0;ii<mm.length;ii++){ // mm[0][ii] = 1; //} for(int i=0;i<T;i++){ String[] line = in.readLine().split(" "); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); //System.out.print(" A = "+A+"\n"); //System.out.print(" B = "+B+"\n"); int ans = 0; for(int j=A;j<B;j++){ int n=j; if(n>=10){ String N = Integer.toString(n); int nlen = N.length(); List<Integer> oks = new ArrayList<Integer>(); for(int k=0;k<nlen-1;k++){ String M = ""; for(int kk=1;kk<=nlen;kk++){ M = M + N.charAt((k+kk)%nlen); } int m = Integer.parseInt(M); //System.out.print(" N = "+N+"\n"); //System.out.print(" M = "+M+"\n"); if(m>n && m<=B) { boolean isNewOne = true; for(int kkk=0;kkk<oks.size();kkk++){ //System.out.print(" KKK = "+oks.get(kkk)+"\n"); if(m==oks.get(kkk)){ isNewOne = false; } } if(isNewOne){ //System.out.print(" N = "+N+"\n"); //System.out.print(" M = "+M+"\n"); oks.add(m); ans++; } } } } } out.write("Case #"+(i+1)+": "+ans+"\n"); System.out.print("Case #"+(i+1)+": "+ans+"\n"); } in.close(); out.close(); }catch(Exception e){ e.printStackTrace(); try{ in.close(); out.close(); }catch(Exception e1){ e1.printStackTrace(); } } System.out.print("YES!\n"); } }
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; } }
B12082
B11119
0
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 ); } }
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<Integer> recs = new TreeSet<Integer>(); 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(); } }
A21010
A20366
0
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<Integer, Integer>(index, value). Array must * have at least one value. */ public static Pair<Integer, Integer> 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<Integer, Integer>(argMin, min); } /** * ArgMax returned as a Pair<Integer, Integer>(index, value). Array must * have at least one value. */ public static Pair<Integer, Integer> 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<Integer, Integer>(argMax, max); } }
import java.io.*; import java.util.*; public class DancingWithTheGooglers { /** * @param args */ public static void main(String[] args) { try { FileReader fileReader = new FileReader("B-large.in.txt"); FileWriter fileWriter = new FileWriter("out.txt"); BufferedReader reader = new BufferedReader(fileReader); BufferedWriter writer = new BufferedWriter(fileWriter); String inputString; inputString = reader.readLine(); int cases = Integer.parseInt(inputString); for (int caseCount = 0; caseCount < cases; caseCount++) { inputString = reader.readLine(); String output = "Case #" + (caseCount+1) + ": "; String a[] = inputString.split(" "); int n = Integer.parseInt(a[0]); int s = Integer.parseInt(a[1]); int p = Integer.parseInt(a[2]); int ans = 0; int score[] = new int[n]; for (int i = 0; i < n; i++) score[i] = Integer.parseInt(a[i + 3]); Arrays.sort(score); for (int i = 0; i < n; i++) { if ((score[i] + 2) / 3 >= p) ans ++; else { if (s > 0 && score[i] >= 2 && ((score[i] + 4) / 3 >= p)) { s--; ans++; } } } output += ans; output += '\n'; writer.write(output); } reader.close(); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
A22642
A20970
0
import java.util.*; import java.io.*; public class DancingWithTheGooglers { public DancingWithTheGooglers() { Scanner inFile = null; try { inFile = new Scanner(new File("inputB.txt")); } catch(Exception e) { System.out.println("Problem opening input file. Exiting..."); System.exit(0); } int t = inFile.nextInt(); int [] results = new int [t]; DancingWithTheGooglersMax [] rnc = new DancingWithTheGooglersMax[t]; int i, j; int [] scores; int s, p; for(i = 0; i < t; i++) { scores = new int [inFile.nextInt()]; s = inFile.nextInt(); p = inFile.nextInt(); for(j = 0; j < scores.length; j++) scores[j] = inFile.nextInt(); rnc[i] = new DancingWithTheGooglersMax(i, scores, s, p, 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("outputB.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 DancingWithTheGooglers(); } private class DancingWithTheGooglersMax extends Thread { int id; int s, p; int [] results, scores; public DancingWithTheGooglersMax(int i, int [] aScores, int aS, int aP,int [] res) { id = i; s = aS; p = aP; results = res; scores = aScores; } public void run() { int a = 0, b = 0; if(p == 0) results[id] = scores.length; else if(p == 1) { int y; y = 3*p - 3; for(int i = 0; i < scores.length; i++) if(scores[i] > y) a++; else if(scores[i] > 0) b++; b = Math.min(b, s); results[id] = a+b; } else { int y, z; y = 3*p - 3; z = 3*p - 5; for(int i = 0; i < scores.length; i++) if(scores[i] > y) a++; else if(scores[i] > z) b++; b = Math.min(b, s); results[id] = a+b; } } } }
/* ID: t.lam1 LANG: JAVA TASK: codejam */ import java.io.*; import java.util.*; import java.text.*; import static java.lang.System.*; import static java.lang.Integer.*; import static java.lang.Double.*; import static java.lang.Character.*; import static java.util.Collections.*; import static java.lang.Math.*; import static java.util.Arrays.*; class codejam { public static void main (String [] args) throws IOException{ codejam a=new codejam(); a.run(); } public void run()throws IOException { dancing(); } public void recycle()throws IOException{ Scanner file = new Scanner(new File("codejam.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("codejam.out"))); int cases = file.nextInt(); file.nextLine(); ArrayList<String> done = new ArrayList<String>(); for(int x =0; x<cases; x++){ out.print("Case #"+(x+1)+": "); int a = file.nextInt(), b = file.nextInt(), c = 0; for(int n = a; n<=b; n++){ for(int m = n+1; m<=b; m++){ if(n<10||m<10)continue; else if(done.contains(""+n+m)){ } else{ String nn = ""+n, mm=""+m, temp = mm; mm = mm.substring(mm.length()-1)+mm.substring(0,mm.length()-1); while(!mm.equals(temp)){ if(mm.equals(nn)){ c++; done.add(""+n+m); break; } mm = mm.substring(mm.length()-1)+mm.substring(0,mm.length()-1); } } } } out.println(c); } out.close(); } public void dancing()throws IOException{ Scanner file = new Scanner(new File("codejam.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("codejam.out"))); int cases = file.nextInt(); file.nextLine(); for(int x =0; x<cases; x++){ out.print("Case #"+(x+1)+": "); Scanner chop = new Scanner(file.nextLine()); int N = chop.nextInt(), S = chop.nextInt(), P = chop.nextInt(), nums = 0; ArrayList<Integer> googlers = new ArrayList<Integer>(); for(int y = 0; y<N; y++){ googlers.add(chop.nextInt()); } //System.out.print(N+" "+S+" "+P+" "); for(Integer a: googlers){ //System.out.println(); //System.out.println(a+" "); int temp = a/3; int temp2 = a; if(S>0){ //System.out.println("bye"); if(P-(temp2-P)/2==2){ S--; nums++; } if(temp2-2*temp>=P&&(temp2-2*temp)-temp<2)nums++; else{ temp++; if((temp2-2*temp>=P||temp==P)&&temp-(temp2-2*temp)<2)nums++; } } else{ //System.out.println("hi"); if(temp2-2*temp>=P&&(temp2-2*temp)-temp<2)nums++; else{ //System.out.println("else"); temp++; if((temp2-2*temp>=P||temp==P)&&temp-(temp2-2*temp)<2)nums++; } } } //System.out.println("nums: "+nums); out.println(nums); } out.close(); } public void googleRese()throws IOException{ Scanner file = new Scanner(new File("codejam.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("codejam.out"))); int x = file.nextInt(); file.nextLine(); //ArrayList<String> cases = new ArrayList<String>(); Map<Character,Character> remap = new TreeMap<Character,Character>(); remap.put('a','y'); remap.put('b','h'); remap.put('c','e'); remap.put('d','s'); remap.put('e', 'o'); remap.put('f', 'c'); remap.put('g', 'v'); remap.put('h', 'x'); remap.put('i', 'd'); remap.put('j', 'u'); remap.put('k', 'i'); remap.put('l', 'g'); remap.put('m', 'l'); remap.put('n', 'b'); remap.put('o', 'k'); remap.put('p', 'r'); remap.put('r', 't'); remap.put('s', 'n'); remap.put('t', 'w'); remap.put('u', 'j'); remap.put('v', 'p'); remap.put('w', 'f'); remap.put('x', 'm'); remap.put('y','a'); remap.put('z','q'); remap.put('q','z'); remap.put(' ',' '); for(int y = 1; y<=x; y++){ String temp = file.nextLine(); out.print("Case #"+y+": "); for(Character a: temp.toCharArray()){ if(remap.get(a)==null)System.out.println(a); out.print(remap.get(a)); } out.println(); } out.close(); } }
A20119
A20743
0
package code12.qualification; import java.io.File; import java.io.FileWriter; import java.util.Scanner; public class B { public static String solve(int N, int S, int p, int[] t) { // 3a -> (a, a, a), *(a - 1, a, a + 1) // 3a + 1 -> (a, a, a + 1), *(a - 1, a + 1, a + 1) // 3a + 2 -> (a, a + 1, a + 1), *(a, a, a + 2) int numPNoS = 0; int numPWithS = 0; for (int i = 0; i < N; i++) { int a = (int)Math.floor(t[i] / 3); int r = t[i] % 3; switch (r) { case 0: if (a >= p) { numPNoS++; } else if (a + 1 >= p && a - 1 >= 0) { numPWithS++; } break; case 1: if (a >= p || a + 1 >= p) { numPNoS++; } break; case 2: if (a >= p || a + 1 >= p) { numPNoS++; } else if (a + 2 >= p) { numPWithS++; } break; } } return "" + (numPNoS + Math.min(S, numPWithS)); } public static void main(String[] args) throws Exception { // file name //String fileName = "Sample"; //String fileName = "B-small"; String fileName = "B-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 N, S, p; int[] t; // get total case totalCase = scanner.nextInt(); for (int caseIndex = 1; caseIndex <= totalCase; caseIndex++) { // get input N = scanner.nextInt(); S = scanner.nextInt(); p = scanner.nextInt(); t = new int[N]; for (int i = 0; i < N; i++) { t[i] = scanner.nextInt(); } String output = "Case #" + caseIndex + ": " + solve(N, S, p, t); System.out.println(output); writer.write(output + "\n"); } scanner.close(); writer.close(); } }
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; public class Qual2 { 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(200); int n = nums[0]; int surprises = nums[1]; int desiredScore = nums[2] * 3; int numWithDesiredScore = 0; for(int i = 0; i < n; i++) { int score = nums[3+i]; if (score < 2 && desiredScore > 1) { continue; } if(score + 2 >= desiredScore) { numWithDesiredScore++; } else if (score + 4 >= desiredScore && surprises > 0) { numWithDesiredScore++; surprises--; } } out.print(numWithDesiredScore); } 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); } }
B12669
B11667
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package year_2012.qualification; 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.HashSet; import java.util.Set; /** * * @author paul * @date 14 Apr 2012 */ public class QuestionC { private static Set<Integer> getCycle(int x) { String s = Integer.toString(x); Set<Integer> set = new HashSet<Integer>(); 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<Integer> mask(Set<Integer> set, int a, int b) { Set<Integer> result = new HashSet<Integer>(); 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<Integer> 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(); } }
import java.io.*; public class Recycled{ public static void main(String args[]) { try{ File myFile = new File("C-small-attempt0.in"); FileReader fileReader = new FileReader(myFile); BufferedReader reader = new BufferedReader(fileReader); FileWriter fileWriter = new FileWriter("C-small-attempt0.out"); BufferedWriter writer = new BufferedWriter(fileWriter); String line = null; line = reader.readLine(); int numLines = Integer.parseInt(line); //writer.write("hello"); for(int i=0;i<numLines;i++) { int recyclecount = 0; line = reader.readLine(); String AB[] = line.split(" "); int a = Integer.parseInt(AB[0]); int b = Integer.parseInt(AB[1]); int length = AB[0].length(); //the initial value of n for(int n=a;n<b;n++) { System.out.println("N: " + n); //writer.write("N " + n+"\r\n"); //recycle the value by taking the last digit forward and check with the range,and then the last two digits,etc for(int j=1;j<length;j++){ if(length!=1){ int tail = n%(int)Math.pow(10,j); int head = n/(int)Math.pow(10,j); //concatenate the head and tail and form a new number int newNumber = Integer.parseInt(tail +""+head); if((newNumber+"").length() == length){ System.out.println(newNumber); //writer.write("new " + newNumber+"\r\n"); //compare with the range n<m<=B if(newNumber<=b && newNumber>n) { recyclecount++; System.out.println("RC " + recyclecount); //writer.write("RC " + recyclecount+"\r\n"); } } } } } String out = "Case #" + (i+1) +": "+recyclecount+"\r\n"; writer.write(out); System.out.println(out); } reader.close(); writer.close(); }catch(Exception ex){ ex.printStackTrace(); } } }
A21010
A21501
0
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<Integer, Integer>(index, value). Array must * have at least one value. */ public static Pair<Integer, Integer> 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<Integer, Integer>(argMin, min); } /** * ArgMax returned as a Pair<Integer, Integer>(index, value). Array must * have at least one value. */ public static Pair<Integer, Integer> 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<Integer, Integer>(argMax, max); } }
package qualificationRound; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.Scanner; public class B { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int ncases = sc.nextInt(); StringBuilder sb = new StringBuilder(); for ( int ncase = 1; ncase <= ncases; ncase++ ) { int nGooglers = sc.nextInt(); int nSuprising = sc.nextInt(); int p = sc.nextInt(); int surprises = 0; int count = 0; for (int i = 0; i < nGooglers; i++) { int s = sc.nextInt(); int q = s/3; int rm = s%3; int pq = p-q; if ( s < p) continue; if ( q >= p ) { count++; } else if ( pq <= 2 ){ if ( rm == 0 ) { if ( pq == 1 && surprises < nSuprising ) { count++; surprises++; } } else { if ( pq == 1 ) count++; else if ( rm == 2 && surprises < nSuprising ) { count++; surprises++; } } } } sb.append("Case #"+ ncase +": " + count + "\n"); } BufferedOutputStream bos = null; bos= new BufferedOutputStream(new FileOutputStream(new File("C:\\Users\\Christian\\workspaceCPDI\\CodeJam2012\\src\\qualificationRound\\res.txt"))); bos.write(sb.toString().getBytes()); bos.close(); } }
A11201
A11985
0
package CodeJam.c2012.clasificacion; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * Problem * * You're watching a show where Googlers (employees of Google) dance, and then * each dancer is given a triplet of scores by three judges. Each triplet of * scores consists of three integer scores from 0 to 10 inclusive. The judges * have very similar standards, so it's surprising if a triplet of scores * contains two scores that are 2 apart. No triplet of scores contains scores * that are more than 2 apart. * * For example: (8, 8, 8) and (7, 8, 7) are not surprising. (6, 7, 8) and (6, 8, * 8) are surprising. (7, 6, 9) will never happen. * * The total points for a Googler is the sum of the three scores in that * Googler's triplet of scores. The best result for a Googler is the maximum of * the three scores in that Googler's triplet of scores. Given the total points * for each Googler, as well as the number of surprising triplets of scores, * what is the maximum number of Googlers that could have had a best result of * at least p? * * For example, suppose there were 6 Googlers, and they had the following total * points: 29, 20, 8, 18, 18, 21. You remember that there were 2 surprising * triplets of scores, and you want to know how many Googlers could have gotten * a best result of 8 or better. * * With those total points, and knowing that two of the triplets were * surprising, the triplets of scores could have been: * * 10 9 10 6 6 8 (*) 2 3 3 6 6 6 6 6 6 6 7 8 (*) * * The cases marked with a (*) are the surprising cases. This gives us 3 * Googlers who got at least one score of 8 or better. There's no series of * triplets of scores that would give us a higher number than 3, so the answer * is 3. * * 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 integers * separated by single spaces. The first integer will be N, the number of * Googlers, and the second integer will be S, the number of surprising triplets * of scores. The third integer will be p, as described above. Next will be N * integers ti: the total points of the Googlers. * * 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 maximum number of Googlers who * could have had a best result of greater than or equal to p. * * Limits * * 1 ≤ T ≤ 100. 0 ≤ S ≤ N. 0 ≤ p ≤ 10. 0 ≤ ti ≤ 30. At least S of the ti values * will be between 2 and 28, inclusive. * * Small dataset * * 1 ≤ N ≤ 3. * * Large dataset * * 1 ≤ N ≤ 100. * * Sample * * Input Output 4 Case #1: 3 3 1 5 15 13 11 Case #2: 2 3 0 8 23 22 21 Case #3: 1 * 2 1 1 8 0 Case #4: 3 6 2 8 29 20 8 18 18 21 * * @author Leandro Baena Torres */ public class B { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader("B.in")); String linea; int numCasos, N, S, p, t[], y, minSurprise, minNoSurprise; linea = br.readLine(); numCasos = Integer.parseInt(linea); for (int i = 0; i < numCasos; i++) { linea = br.readLine(); String[] aux = linea.split(" "); N = Integer.parseInt(aux[0]); S = Integer.parseInt(aux[1]); p = Integer.parseInt(aux[2]); t = new int[N]; y = 0; minSurprise = p + ((p - 2) >= 0 ? (p - 2) : 0) + ((p - 2) >= 0 ? (p - 2) : 0); minNoSurprise = p + ((p - 1) >= 0 ? (p - 1) : 0) + ((p - 1) >= 0 ? (p - 1) : 0); for (int j = 0; j < N; j++) { t[j] = Integer.parseInt(aux[3 + j]); if (t[j] >= minNoSurprise) { y++; } else { if (t[j] >= minSurprise) { if (S > 0) { y++; S--; } } } } System.out.println("Case #" + (i + 1) + ": " + y); } } }
import java.io.File; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Scanner; public class CodejamB { public static final String TEST = "test.in", SMALL = "B-small-attempt0.in", LARGE = "B-large.in"; public static final String OUTPUT = "out.txt"; public static Map<Integer, List<Triplet>> triplets; public static void main(String[] args) throws Exception { solve(SMALL); } public static void makeAllTriplets() { triplets = new HashMap<Integer, List<Triplet>>(); for(int i =0; i <= 10; i++) { for(int j = 0; j <= 10; j++) { for(int k = 0; k <= 10; k++) { Triplet trip = new Triplet(i, j, k); if(trip.legal()) { int sum = i + j + k; if(!triplets.containsKey(sum)) triplets.put(sum, new LinkedList<Triplet>()); triplets.get(sum).add(trip); } } } } } public static void solve(String filename) throws Exception { makeAllTriplets(); 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 N = in.nextInt(); int S = in.nextInt(); int p = in.nextInt(); int result = 0; int[] googlers = new int[N]; for(int i =0; i < N; i++) { boolean unsurprised = false; boolean valid = false; int sum = in.nextInt(); List<Triplet> poss = triplets.get(sum); for(Triplet t: poss) { if(t.best() >= p && !t.surprising()) { unsurprised = true; valid = true; System.out.println("UNSURPRISING " + Arrays.toString(t.scores) + "= " + sum); } else if(t.best() >= p) { valid = true; } } if(!unsurprised && S > 0 && valid) { S--; result++; } else if(unsurprised) { result++; } } in.nextLine(); out.println("Case #"+num+": "+result); System.out.println("Case #"+num+": "+result); } out.close(); } } class Triplet { int[] scores; public Triplet(int a, int b, int c) { scores = new int[]{a,b,c}; Arrays.sort(scores); } public int best() { return scores[2]; } public boolean legal() { return Math.abs(scores[2] - scores[0]) <= 2; } public boolean surprising() { return Math.abs(scores[2] - scores[0]) == 2; } }
B21207
B20921
0
/* * 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 <marco.lackovic@gmail.com> * @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; } }
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<b+1;i++){ ArrayList<Integer> number = new ArrayList<Integer>(); ArrayList<Integer> numbers = new ArrayList<Integer>(); int temp = i; while(temp/10>0){ number.add(temp%10); temp = temp/10; } number.add(temp%10); for(int j=0;j<number.size();j++){ numbers.clear(); for(int k=0;k<number.size();k++){ numbers.add(number.get(k)); } ArrayList<Integer> part = new ArrayList<Integer>(); for(int k=0;k<j;k++){ int temp1 = numbers.remove(0); part.add(temp1); } numbers.addAll(part); int newint = 0; for(int k=0;k<numbers.size();k++){ newint += numbers.get(k)*pow(10,k); } //System.out.println(i+" "+newint+" "+j); if(i<newint && newint<=b){ System.out.println(i+" "+newint+" "+j); result++; } } //System.exit(0); } System.out.println(result); } private static int pow(int i, int k) { // TODO Auto-generated method stub if(k==0){ return 1; }else{ return pow(i, k-1)*i; } } }
A12113
A11365
0
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class B { static int[][] memo; static int[] nums; static int p; public static void main(String[] args)throws IOException { Scanner br=new Scanner(new File("B-small-attempt0.in")); PrintWriter out=new PrintWriter(new File("b.out")); int cases=br.nextInt(); for(int c=1;c<=cases;c++) { int n=br.nextInt(),s=br.nextInt(); p=br.nextInt(); nums=new int[n]; for(int i=0;i<n;i++) nums[i]=br.nextInt(); memo=new int[n][s+1]; for(int[] a:memo) Arrays.fill(a,-1); out.printf("Case #%d: %d\n",c,go(0,s)); } out.close(); } public static int go(int index,int s) { if(index>=nums.length) return 0; if(memo[index][s]!=-1) return memo[index][s]; int best=0; for(int i=0;i<=10;i++) { int max=i; for(int j=0;j<=10;j++) { if(Math.abs(i-j)>2) continue; max=Math.max(i,j); thisone: for(int k=0;k<=10;k++) { int ret=0; if(Math.abs(i-k)>2||Math.abs(j-k)>2) continue; max=Math.max(max,k); int count=0; if(Math.abs(i-k)==2) count++; if(Math.abs(i-j)==2) count++; if(Math.abs(j-k)==2) count++; if(i+j+k==nums[index]) { boolean surp=(count>=1); if(surp&&s>0) { if(max>=p) ret++; ret+=go(index+1,s-1); } else if(!surp) { if(max>=p) ret++; ret+=go(index+1,s); } best=Math.max(best,ret); } else if(i+j+k>nums[index]) break thisone; } } } return memo[index][s]=best; } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashMap; public class Googlers { public static void main(String[] args) throws Exception{ String inputFile = "B-small-attempt0.in"; BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output"))); long num_cases = Long.parseLong(input.readLine()); int current_case = 0; while (current_case < num_cases){ current_case++; String[] fields = input.readLine().split(" "); int N = Integer.parseInt(fields[0]); int S = Integer.parseInt(fields[1]); int p = Integer.parseInt(fields[2]); int max = 0; int sc = 0; for (int i = 0; i < N; i++){ int v = Integer.parseInt(fields[3+i]); double d = Math.ceil(v/3.0); if (d >= p){ max++; } else { if (d != 0 && d == p-1){ if (sc < S){ max++; sc++; } } } } System.out.println("Case #" + current_case + ": " + max); output.write("Case #" + current_case + ": " + max + "\n"); } output.close(); } }
B21227
B20099
0
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); } } } }
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; int A,B; void execute() throws IOException { totalCases = ni(); for(testNum = 1; testNum <= totalCases; testNum++) { if(!input()) break; solve(); } } void solve() throws IOException { int count = 0; for(int i = A;i<=B;i++) { HashSet<Integer> hs = new HashSet<Integer>(); String s = String.valueOf(i); int k = s.length(); for(int j = 0;j<k;j++) { String x = s.substring(j,k) + s.substring(0,j); int no = Integer.parseInt(x); if(no>i && 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; } }
B10155
B10262
0
/* * 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-small-attempt0", 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); } } } }
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 !"); } } }
B10149
B12117
0
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<Integer> set = new TreeSet<Integer>(); 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)); } }
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 QuestionC { //final static String FNAME = "C:\\CodeJam\\RecycledNumbers"; final static String FNAME = "C:\\CodeJam\\C-small-attempt0"; //final static String FNAME = "C:\\CodeJam\\A-large-practice"; public static Scanner in; public static PrintWriter out; static void open() throws IOException { Locale.setDefault( Locale.US ); in = new Scanner( new File( FNAME + ".in" ) ); out = new PrintWriter( new File( FNAME + ".out" ) ); } static void close() throws IOException { out.close(); } public static void main(String[] args)throws IOException { open(); int N = in.nextInt(); //int T = Integer.parseInt(in.nextLine()); /* -------- Main code ---------- */ for(int i = 0 ; i < N ; i++){ int A = in.nextInt(); int B = in.nextInt(); //System.out.println(A + "----" + B); int absMinFirstDigit = Character.digit(Integer.toString(A).toCharArray()[0],10); int absMaxFirstDigit = Character.digit(Integer.toString(B).toCharArray()[0],10); //System.out.println(absMinFirstDigit + "----" + absMaxFirstDigit); long count = 0; if(A>=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<Integer> checkDupSet = new HashSet<Integer>(); for(int j = 1 ; j <= maxLen-1 ; j++){ int numAtJIindex = Character.digit(numChars[j], 10); if ( (numAtJIindex<absMinFirstDigit) || (numAtJIindex>absMaxFirstDigit) || (numAtJIindex<firstDigitOfNum ) ) continue; //Generate m int m = 0; for(int k = 0 , rot = j; k < maxLen ; k++, rot = (rot + 1)%maxLen ){ m = m * 10 + Character.digit(numChars[rot],10); //System.out.println("Number generated : "+ m); } if(m>n && 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(); } }
B11696
B10310
0
/* * 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-small-attempt0.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<String> solutions = new TreeSet<String>(); for (int k=1;k<values[1].length();k++){ String m = circshift(n,k); int mVal = Integer.parseInt(m); if(mVal<=B && mVal!=n && mVal> 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; } }
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) { //System.out.print("TEST:"+line); int r = 0; int a,b; String[] sp = line.split(" "); a = Integer.valueOf(sp[0]); b = Integer.valueOf(sp[1]); //if (b < 10) return 0; //else if (a == b) return 0; //else { //if (a <= 10) {a = 11;} 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) { //System.out.println("X:"+x+"T"+re); 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()); } }
B11318
B12976
0
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); int casos=1, a, b, n, m, cont; while(t!=0){ a=sc.nextInt(); b=sc.nextInt(); if(a>b){ int aux=a; a=b; b=aux; } System.out.printf("Case #%d: ",casos++); if(a==b){ System.out.printf("%d\n",0); }else{ cont=0; for(n=a;n<b;n++){ for(m=n+1;m<=b;m++){ if(isRecycled(n,m)) cont++; } } System.out.printf("%d\n",cont); } t--; } } public static boolean isRecycled(int n1, int n2){ String s1, s2, aux; s1 = String.valueOf( n1 ); s2 = String.valueOf( n2 ); boolean r = false; for(int i=0;i<s1.length();i++){ aux=""; aux=s1.substring(i,s1.length())+s1.substring(0,i); // System.out.println(aux); if(aux.equals(s2)){ r=true; break; } } return r; } }
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<Integer> set = new HashSet<Integer>() ; 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") ; } }
B12115
B10287
0
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; } }
import java.io.*; import java.util.Scanner; public class jam3Rec { public static void main(String args[]) throws java.lang.Exception { int a,b,n,m, cnt=0,len=0; //a=1111;b=2222; int t,cas=1; //System.out.println(); //Scanner scan=new Scanner(System.in); //Scanner scan=new Scanner(new FileReader("input3" + ".in")); Scanner scan=new Scanner(new FileReader("C-small-attempt2" + ".in")); PrintWriter out=new PrintWriter("SmallOutput5" + ".out"); //PrintWriter out=new PrintWriter("LocalOutput3" + ".out"); //FileReader("A-small-attempt1" + ".in") t=scan.nextInt(); while(t!=0) { t--; cnt=0; a=scan.nextInt(); b=scan.nextInt(); //a=100;b=500; String str1,tstr1; for(int i=a;i<=b;i++) { str1=Integer.toString(i); for(int j=a;j<=b;j++) { if(i!=j && i<j) { len=str1.length(); for(int k=1;k<len;k++) { tstr1=str1.substring(0,len-k); tstr1=str1.substring(len-k)+tstr1 ; if(tstr1.equals(Integer.toString(j))) { k=len; //System.out.println(i+" "+" "+j+" "+tstr1); cnt++; } } } } } //cnt=cnt/2; System.out.println("Case #"+cas+": "+cnt); out.println("Case #"+cas+": "+cnt); cas++; } //in.close(); out.close(); } }
B20856
B22095
0
/* * 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<Integer> mm = new LinkedList<Integer>(); //mm.add(new LinkedList<Integer>()); //int[][] mm; //for(int ii=0;ii<mm.length;ii++){ // mm[0][ii] = 1; //} for(int i=0;i<T;i++){ String[] line = in.readLine().split(" "); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); //System.out.print(" A = "+A+"\n"); //System.out.print(" B = "+B+"\n"); int ans = 0; for(int j=A;j<B;j++){ int n=j; if(n>=10){ String N = Integer.toString(n); int nlen = N.length(); List<Integer> oks = new ArrayList<Integer>(); for(int k=0;k<nlen-1;k++){ String M = ""; for(int kk=1;kk<=nlen;kk++){ M = M + N.charAt((k+kk)%nlen); } int m = Integer.parseInt(M); //System.out.print(" N = "+N+"\n"); //System.out.print(" M = "+M+"\n"); if(m>n && m<=B) { boolean isNewOne = true; for(int kkk=0;kkk<oks.size();kkk++){ //System.out.print(" KKK = "+oks.get(kkk)+"\n"); if(m==oks.get(kkk)){ isNewOne = false; } } if(isNewOne){ //System.out.print(" N = "+N+"\n"); //System.out.print(" M = "+M+"\n"); oks.add(m); ans++; } } } } } out.write("Case #"+(i+1)+": "+ans+"\n"); System.out.print("Case #"+(i+1)+": "+ans+"\n"); } in.close(); out.close(); }catch(Exception e){ e.printStackTrace(); try{ in.close(); out.close(); }catch(Exception e1){ e1.printStackTrace(); } } System.out.print("YES!\n"); } }
package qualification.q3; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Created by IntelliJ IDEA. * User: ofer * Date: 14/04/12 * Time: 20:31 * To change this template use File | Settings | File Templates. */ public class Q3Solver { private Set<String> mapping; public Q3Solver(){ mapping = new HashSet<String>(); } 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; } }
A20119
A20443
0
package code12.qualification; import java.io.File; import java.io.FileWriter; import java.util.Scanner; public class B { public static String solve(int N, int S, int p, int[] t) { // 3a -> (a, a, a), *(a - 1, a, a + 1) // 3a + 1 -> (a, a, a + 1), *(a - 1, a + 1, a + 1) // 3a + 2 -> (a, a + 1, a + 1), *(a, a, a + 2) int numPNoS = 0; int numPWithS = 0; for (int i = 0; i < N; i++) { int a = (int)Math.floor(t[i] / 3); int r = t[i] % 3; switch (r) { case 0: if (a >= p) { numPNoS++; } else if (a + 1 >= p && a - 1 >= 0) { numPWithS++; } break; case 1: if (a >= p || a + 1 >= p) { numPNoS++; } break; case 2: if (a >= p || a + 1 >= p) { numPNoS++; } else if (a + 2 >= p) { numPWithS++; } break; } } return "" + (numPNoS + Math.min(S, numPWithS)); } public static void main(String[] args) throws Exception { // file name //String fileName = "Sample"; //String fileName = "B-small"; String fileName = "B-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 N, S, p; int[] t; // get total case totalCase = scanner.nextInt(); for (int caseIndex = 1; caseIndex <= totalCase; caseIndex++) { // get input N = scanner.nextInt(); S = scanner.nextInt(); p = scanner.nextInt(); t = new int[N]; for (int i = 0; i < N; i++) { t[i] = scanner.nextInt(); } String output = "Case #" + caseIndex + ": " + solve(N, S, p, t); System.out.println(output); writer.write(output + "\n"); } scanner.close(); writer.close(); } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class DancingWithTheGooglers { static int surprise; public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new FileReader("small-B.in")); BufferedWriter out = new BufferedWriter(new FileWriter("small-B.out")); int n = Integer.parseInt(in.readLine()); for(int i = 1; i <= n; i++){ String [] nums = in.readLine().split(" "); int m = Integer.parseInt(nums[0]); surprise = Integer.parseInt(nums[1]); int best = Integer.parseInt(nums[2]); int total = 0; for(int j = 0; j < m; j++) if(check(Integer.parseInt(nums[j + 3]), best)) total++; out.write("Case #" + i + ": " + total); if(i < n) out.write("\n"); } in.close(); out.close(); } static boolean check(int score, int max){ int third = score / 3; int rem = score % 3; if(third >= max) return true; if(third == max - 2) if(rem == 2){ if(surprise > 0){ surprise --; return true; } return false; } else return false; if(third == max - 1) if(rem > 0) return true; else if(surprise > 0 && third > 0){ surprise --; return true; } return false; } }
B12570
B10090
0
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)); } } }
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<temp.length(); k++) { String test = temp.substring(k)+temp.substring(0,k); int check = Integer.parseInt(test); if(check>=lowerBound && check<=upperBound && check!=num && check>num) { cases++; } } } System.out.println("Case #" + i + ": " + cases); } } }
B12115
B13066
0
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; } }
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<Integer> 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<Integer> results = new ArrayList<Integer>(); 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); } }
B10485
B12592
0
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<Integer> 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<Integer> possibles = getPermutations(n); int count = 0; for(Integer i : possibles) if(i > n && i <= B) count++; return count; } public static Set<Integer> getPermutations(int n) { Set<Integer> perms = new TreeSet<Integer>(); 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; } }
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;z<x;z++){ line[z]=br.readLine(); tranform(line[z]); } }catch(Exception e){ e.printStackTrace(); } } private void tranform(String string) { String A[]; int count=0; int z=0; A=string.split(" "); int a=Integer.parseInt(A[0]); int b=Integer.parseInt(A[1]); //System.out.println(a+ " " +b); int len=new Integer(a).toString().length(); for(int x=a;x<=b;x++){ String test=new String(x+""); String temp=test; for(int y=0;y<len-1;y++){ temp=temp.charAt(len-1)+temp.substring(0,len-1); int testn=Integer.parseInt(temp); //System.out.println(testn); if(testn==x)continue; if(testn<a||testn>b) 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(); } }
B20006
B21743
0
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; } }
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<Integer> set = new HashSet<Integer>(); 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)); } } }
B20006
B22246
0
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; } }
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<Integer> l = new LinkedList<Integer>(); for(int j=1; j<tot; ++j, pow*=10) { int cth = (i/pow)%10; if(cth >= 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); } } }
B20424
B21085
0
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { // static int MAX = 10000; static int MAX = 2000000; static Object[] All = new Object[MAX+1]; static int size( int x ) { if(x>999999) 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<Integer> result = new ArrayList<Integer>(); 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; i<s; i++) { if(V[i]!=0){ rot=0; for(int j=0,ii=i;j<s; j++,ii=(ii+1)%s){ rot=rot*10+V[ii]; } if(rot>value && !result.contains(rot)) result.add(rot); } } if( result.isEmpty() ) return null; int[] r = new int[result.size()]; for(int i=0; i<r.length; i++) r[i]=result.get(i); return r; } static void precalculate() { for(int i=1; i<=MAX; i++){ All[i] = rotate(i); } } static int solve( Scanner in ) { int A, B, sol=0; A = in.nextInt(); B = in.nextInt(); for( int i=A; i<=B; i++) { // List<Integer> 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); } } }
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<Integer> visited = new HashSet<Integer>(); for(int k=1;k<num.length();k++) { String rot_s = num.substring(k) + num.substring(0,k); int rot = Integer.parseInt( rot_s ); if(rot > 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)); } }
B21227
B21668
0
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); } } } }
import java.io.*; import java.util.*; /** * * @author Hilos */ public class ProblemC { public static BufferedWriter bw; public static BufferedReader br; public static void main(String[] args) { try { String filename = "C-large"; br = new BufferedReader(new FileReader("E:\\Downloads\\" + filename + ".in")); bw = new BufferedWriter(new FileWriter("E:\\Downloads\\" + filename + ".out")); int caseCount = Integer.parseInt(br.readLine()); for (int c = 0; c < caseCount; c++) { String[] lineParts = br.readLine().split(" "); int A = Integer.parseInt(lineParts[0]); int B = Integer.parseInt(lineParts[1]); SolveCase(c + 1, A, B); } } catch (Exception exc) { System.out.println(exc.toString()); } } public static void SolveCase(int caseNumber, int A, int B) throws Exception { int totalRecycledPairs = 0; HashSet uniqueNumbers = new HashSet(); for (int i = A; i <= B; i++) { String strVal = String.valueOf(i); if (!uniqueNumbers.contains(i)) { int recycles = 0; String nextStr = strVal; do { nextStr = leftShift(nextStr); int nextInt = Integer.parseInt(nextStr); if (A <= nextInt && nextInt <= B) { uniqueNumbers.add(nextInt); recycles++; } } while (!nextStr.equals(strVal)); totalRecycledPairs += NchooseK(recycles, 2); } } bw.write("Case #" + caseNumber + ": " + totalRecycledPairs + "\n"); bw.flush(); } public static String leftShift(String str) { return str.substring(1) + str.charAt(0); } public static int NchooseK(int n, int k) { return factorial(n) / (factorial(k) * factorial(n - k)); } public static int factorial(int i) { int result = 1; while (i > 1) { result *= i; i--; } return result; } }
A22191
A22872
0
package com.example; import java.io.IOException; import java.util.List; public class ProblemB { enum Result { INSUFFICIENT, SUFFICIENT, SUFFICIENT_WHEN_SURPRISING } public static void main(String[] a) throws IOException { List<String> lines = FileUtil.getLines("/B-large.in"); int cases = Integer.valueOf(lines.get(0)); for(int c=0; c<cases; c++) { String[] tokens = lines.get(c+1).split(" "); int n = Integer.valueOf(tokens[0]); // N = number of Googlers int s = Integer.valueOf(tokens[1]); // S = number of surprising triplets int p = Integer.valueOf(tokens[2]); // P = __at least__ a score of P int sumSufficient = 0; int sumSufficientSurprising = 0; for(int i=0; i<n; i++) { int points = Integer.valueOf(tokens[3+i]); switch(test(points, p)) { case SUFFICIENT: sumSufficient++; break; case SUFFICIENT_WHEN_SURPRISING: sumSufficientSurprising++; break; } // uSystem.out.println("points "+ points +" ? "+ p +" => "+ result); } System.out.println("Case #"+ (c+1) +": "+ (sumSufficient + Math.min(s, sumSufficientSurprising))); // System.out.println(); // System.out.println("N="+ n +", S="+ s +", P="+ p); // System.out.println(); } } private static Result test(int n, int p) { int fac = n / 3; int rem = n % 3; if(rem == 0) { // int triplet0[] = { fac, fac, fac }; // print(n, triplet0); if(fac >= p) { return Result.SUFFICIENT; } if(fac > 0 && fac < 10) { if(fac+1 >= p) { return Result.SUFFICIENT_WHEN_SURPRISING; } // int triplet1[] = { fac+1, fac, fac-1 }; // surprising // print(n, triplet1); } } else if(rem == 1) { // int triplet0[] = { fac+1, fac, fac }; // print(n, triplet0); if(fac+1 >= p) { return Result.SUFFICIENT; } // if(fac > 0 && fac < 10) { // int triplet1[] = { fac+1, fac+1, fac-1 }; // print(n, triplet1); // } } else if(rem == 2) { // int triplet0[] = { fac+1, fac+1, fac }; // print(n, triplet0); if(fac+1 >= p) { return Result.SUFFICIENT; } if(fac < 9) { // int triplet1[] = { fac+2, fac, fac }; // surprising // print(n, triplet1); if(fac+2 >= p) { return Result.SUFFICIENT_WHEN_SURPRISING; } } } else { throw new RuntimeException("error"); } return Result.INSUFFICIENT; // System.out.println(); // System.out.println(n +" => "+ div3 +" ("+ rem +")"); } // private static void print(int n, int[] triplet) { // System.out.println("n="+ n +" ("+ (n/3) +","+ (n%3) +") => ["+ triplet[0] +","+ triplet[1] +","+ triplet[2] +"]" + (triplet[0]-triplet[2] > 1 ? " *" : "")); // } }
package googlejam; import java.util.Scanner; public class ProblemB { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int numberOfCases = sc.nextInt(); for (int i = 0; i <= numberOfCases; i++) { int googlers = sc.nextInt(); int suprisingTriplets = sc.nextInt(); int p = sc.nextInt(); int sum = 0; for (int j = 0; j < googlers; j++) { int points = sc.nextInt(); if (p == 0) { sum++; } else if (p == 1) { if (points >= 1) sum++; else continue; } else if (points >= p * 3) { sum++; } else if ((p * 3 - points) <= 2) { sum++; } else if ((p * 3 - points) <= 4 && suprisingTriplets > 0) { sum++; suprisingTriplets--; } } System.out.println(String.format("Case #%d: %d", i + 1, sum)); } } }
A22771
A23011
0
package com.menzus.gcj._2012.qualification.b; import com.menzus.gcj.common.InputBlockParser; import com.menzus.gcj.common.OutputProducer; import com.menzus.gcj.common.impl.AbstractProcessorFactory; public class BProcessorFactory extends AbstractProcessorFactory<BInput, BOutputEntry> { public BProcessorFactory(String inputFileName) { super(inputFileName); } @Override protected InputBlockParser<BInput> createInputBlockParser() { return new BInputBlockParser(); } @Override protected OutputProducer<BInput, BOutputEntry> createOutputProducer() { return new BOutputProducer(); } }
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 Dancers{ public static ArrayList<Triplet> 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="", test; int diff; try{ Scanner read = new Scanner(new File(path)); int testCases = Integer.parseInt(read.nextLine()); int cn=0; String tongue; while(cn++<testCases){ test = read.nextLine(); output = "Case #"+cn+": "+ solve(test);//WRITE ANS TO DIFFERENT FILE ANS += output +" \n"; System.out.println(ANS); } writeToFile("dancers.out",ANS); } catch(FileNotFoundException e){//if file is not found System.err.println("data file \'"+path+"\' was not found\nPress <enter> 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(String test){ String temp[] = test.split(" "); ArrayList<Triplet> tempList = new ArrayList<Triplet>(); Triplet[] scores; int dancerNo, surpriseNo, bestResult; dancerNo = Integer.parseInt(temp[0]); surpriseNo = Integer.parseInt(temp[1]); bestResult = Integer.parseInt(temp[2]); int counter = 0; while(counter < dancerNo){ tempList.add(new Triplet(temp[3+counter])); counter++; } scores = tempList.toArray(new Triplet[tempList.size()]); Arrays.sort(scores); scores = doTheSurprises(scores,surpriseNo, bestResult); System.out.println(Arrays.toString(scores)); return count(scores, bestResult); } public static Triplet[] doTheSurprises(Triplet sc[], int surprise, int max){ Triplet temp; int sNo=0; for(int i=sc.length-1; i>=0; i--){ if(sNo==surprise){ break; } if(sc[i].scores[2]<max){ if(sc[i].doSurprise()){ sNo++; } } } return sc; } public static int count(Triplet sc[], int max){ int temp=0; for(int i=0; i<sc.length; i++){ if(sc[i].scores[2]>=max){ temp++; } } return temp;} } class Triplet implements Comparable<Triplet>{ public int scores[] = new int[3]; public Triplet(int x, int y, int z){ scores[0]=x; scores[1]=y; scores[2]=z; } public Triplet(String x){setThrees(Integer.parseInt(x));} public Triplet(int x){setThrees(x);} public void setThrees(int numb){ this.scores[0] =numb/3; this.scores[1] = (numb-scores[0])/2; this.scores[2] = numb - scores[0] - scores[1]; } public int compareTo(Triplet x){ if(scores[2]<x.scores[2]){ return -1; } else if(scores[2]>x.scores[2]){ return 1; } else{ return 0; } } public boolean doSurprise(){ int s1 = scores[1], s2 = scores[2]; if(s1 == s2){ s1--; s2++; if(s1>=0 && s2<=10){ scores[1] = s1; scores[2] = s2; return true; } } return false; } public String toString(){ return Arrays.toString(scores); } }
A12211
A12298
0
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 Dancing_improved { static int f_Superan_limites(String params){ int superan_limite=0; String[] parametros=params.split(" "); int n_participantes= Integer.parseInt(parametros[0]); int n_sorprendidos= Integer.parseInt(parametros[1]); int nota_limite= Integer.parseInt(parametros[2]); int suma_notas, resto, nota_juego; for(int i=3;i<parametros.length;i++){ // Recorro las sumas de los participantes suma_notas=Integer.parseInt(parametros[i]); resto=suma_notas%3; if(resto==0){ // el resto es el número triplicado! nota_juego=suma_notas/3; if(nota_juego>=nota_limite){ superan_limite++; }else if(nota_juego-1>=0 && n_sorprendidos>0 && ((nota_juego+1)>=nota_limite || (nota_juego+2)>=nota_limite)){ // no supera el límite pero podría hacerlo si quedan sorprendidos n_sorprendidos--; superan_limite++; } }else if((suma_notas+1)%3==0){ // Tendré que jugar con el valor en +-1 nota_juego=(suma_notas+1)/3; if(nota_juego-1>=0 && nota_juego>=nota_limite){ superan_limite++; }else if(nota_juego-1>=0 && n_sorprendidos>0 && (nota_juego+1)>=nota_limite){ n_sorprendidos--; superan_limite++; } }else if((suma_notas+2)%3==0){ // Tendré que jugar con el valor en +-2 nota_juego=(suma_notas+2)/3; if(nota_juego-1>=0 && nota_juego>=nota_limite){ superan_limite++; } } } return superan_limite; } public static void main(String[] args) throws IOException { FileReader fr = new FileReader(args[0]); BufferedReader bf = new BufferedReader(fr); int ntest=0; FileWriter fstream = new FileWriter("out.txt"); BufferedWriter out = new BufferedWriter(fstream); String lines = bf.readLine(); String liner, linew; int lines_r=0; String[] numbers; int total; while((liner = bf.readLine())!=null && lines_r<=Integer.parseInt(lines)) { ntest++; numbers=liner.split(" "); total=f_Superan_limites(liner); linew="Case #"+ntest+": "+total+"\n"; out.write(linew); lines_r++; } out.close(); fr.close(); } }
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.lang.Math; import java.util.Arrays; public class DancingWithTheGooglers { public static int testSize = 0; public static int[] convertString2Nums(int n, String str) { int[] result = new int[n]; int begIndex = 0; int endIndex = 0; for(int i = 0; i < n - 1; i++) { endIndex = str.indexOf(' ', begIndex); result[i] = Integer.parseInt(str.substring(begIndex, endIndex)); begIndex = endIndex + 1; } result[n - 1] = Integer.parseInt(str.substring(begIndex, str.length())); return result; } public static boolean isPossibleScore(int score, int P) { if(0 == P) return true; if(score < P) return false; int remain = (score - P) >> 1; if(P - remain > 1) return false; return true; } public static boolean isSurprisePossible(int score, int P) { if(0 == P) return true; if(score < P) return false; int remain = (score - P) >> 1; if(P - remain > 2) return false; return true; } public static int maxDancers(String input) { int result = 0; String[] params = input.split(" "); int N = Integer.parseInt(params[0]); int S = Integer.parseInt(params[1]); int P = Integer.parseInt(params[2]); int[] a = new int[N]; int numOfSurprise = 0; for(int i = 0; i < N; i++) { a[i] = Integer.parseInt(params[i + 3]); } Arrays.sort(a); for(int i = N - 1; i >= 0 ; i--) { if(isPossibleScore(a[i], P)) { result++; } else { if(numOfSurprise < S && isSurprisePossible(a[i], P)) { result++; numOfSurprise++; } } } /* int i = 0; while(a[i] < P ) { i++; if(i >= N) break; } if(i == N) return 0; int j = 0; for(j = 0; j < S && j + i < N; j++) { result ++; } if(j + i < N) { for(int k = j + i; k < N; k++) { if(isPossibleScore(a[k], P)) result++; } } */ return result; } public static void Output(String inPath, String outPath) { try { FileInputStream fstream = new FileInputStream(inPath); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); File of = new File(outPath); of.delete(); BufferedWriter bw = new BufferedWriter(new FileWriter(new File(outPath), true)); String line = br.readLine(); int[] parameters = convertString2Nums(1, line); int numOfTest = parameters[0]; String str = new String(); for(int i = 0; i < numOfTest; i ++) { line = br.readLine(); str = new String("Case #" + (i+1) + ": " + maxDancers(line)); System.out.println(str); bw.write(str); bw.newLine(); } in.close(); bw.close(); } catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } //public static /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String inFile = new String(); String outFile = new String(); testSize = 1; switch(testSize) { case 0: inFile = new String("./B-test.in"); outFile = new String("./B-test.out"); break; case 1: inFile = new String("./B-small-attempt1.in"); outFile = new String("./B-small-attempt1.out"); break; case 2: inFile = new String("./A-large-practice.in"); outFile = new String("./A-large-practice.out"); break; default: break; } Output(inFile, outFile); } }