F1
stringlengths
6
6
F2
stringlengths
6
6
label
stringclasses
2 values
text_1
stringlengths
149
20.2k
text_2
stringlengths
48
42.7k
B12085
B12221
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.*; import java.io.*; public class QR_Csmall { public static void main(String[] args) throws Exception{ // Scanner sc = new Scanner(System.in); // PrintWriter pw = new PrintWriter(System.out); // Scanner sc = new Scanner(new FileReader("input.in")); // PrintWriter pw = new PrintWriter(new FileWriter("output.out")); Scanner sc = new Scanner(new FileReader("C-small-attempt0.in")); PrintWriter pw = new PrintWriter(new FileWriter("C-small-attempt0.out")); int T; int A, B; int n, m; int ncnt; int cnt; int[] check = new int[3]; boolean ok; T = sc.nextInt(); for(int times = 1; times <= T; times++){ A = sc.nextInt(); B = sc.nextInt(); cnt = 0; for(int i = A; i < B; i++){ n = i; m = 0; ncnt = 0; for(int k = 0; k < check.length; k++){ check[k] = -1; } while(n > 0){ n /= 10; ncnt++; } for(int j = 1; j < ncnt; j++){ ok = true; m = 0; m = (i / (int)Math.pow(10, j)) + ((i % (int)Math.pow(10, j)) * (int)Math.pow(10, ncnt-j)); if(i < m && m <= B){ check[j - 1] = m; for(int l = 0; l < j - 1; l++){ if(check[l] == m){ ok = false; break; } } if(ok) cnt++; } } } System.out.print("Case #" + times + ": "); System.out.print(cnt); System.out.println(); pw.print("Case #" + times + ": "); pw.print(cnt); pw.println(); } sc.close(); pw.close(); } }
A12846
A10667
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); } }
import java.util.*; import java.io.*; import java.lang.*; class DancingGooglers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = Integer.parseInt(sc.nextLine()); for (int i=0; i<T; i++) { String[] dat = sc.nextLine().split(" "); int N = Integer.parseInt(dat[0]); // number of googlers int S = Integer.parseInt(dat[1]); // number of surprising triplets int p = Integer.parseInt(dat[2]); // required at least int count = 0; List<Googler> g = new ArrayList<Googler>(); for (int j=0; j<N; j++) { int score = Integer.parseInt(dat[3+j]); // Possible scores int bestNonSurprising = 0; int bestSurprising = 0; for (int a=0; a<=10; a++) { for (int b=0; b<=10; b++) { int c = score - a - b; if (c < 0 || c > 10) continue; if (Math.abs(a-b) > 2 || Math.abs(b-c) > 2 || Math.abs(a-c) > 2) continue; if (Math.abs(a-b) == 2 || Math.abs(b-c) == 2 || Math.abs(a-c) == 2) { // surprising bestSurprising = Math.max(bestSurprising, Math.max(a, Math.max(b, c))); } else { // no bestNonSurprising = Math.max(bestNonSurprising, Math.max(a, Math.max(b, c))); } } } g.add(new Googler(bestNonSurprising, bestSurprising)); } Collections.sort(g); //for (int k=0; k<g.size(); k++) System.out.println(g.get(k).bns+" "+g.get(k).bs); boolean[] taken = new boolean[N]; for (int k=0; k<g.size(); k++) { if (g.get(k).bns >= p) { taken[k] = true; count++; } } int countsurprise = 0; for (int k=0; k<g.size(); k++) { if (countsurprise == S) break; if (!taken[k]) { if (g.get(k).bs >= p) { taken[k] = true; count++; countsurprise++; } } } System.out.println("Case #" + (i+1) + ": " + count); } } } class Googler implements Comparable<Googler> { int bns = 0, bs = 0; // Best Non, Best Surprising Googler(int a, int b) { bns = a; bs = b; } public int compareTo(Googler g) { if (this.bs != g.bs) return g.bs - this.bs; return this.bns - g.bns; } }
B12669
B11562
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(); } }
package codejam.is; /** * Created with IntelliJ IDEA. * User: ofer * Date: 4/13/12 * Time: 8:47 PM * To change this template use File | Settings | File Templates. */ public interface Test { /** Runs the test on the given input */ public void run(String input); /** Returns the output of the test */ public String getOutput(int testNum); }
B20006
B21712
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.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; public class CodeJamSolverRecycle { public static HashMap<Integer,ArrayList<Integer>> valueToIndexMap=new HashMap<Integer,ArrayList<Integer>>(); public static void main(String[] args) { int numTestCases=0; int numLinePerTestCase=1; int currentCase=0; String inputFileName="C-large.in"; //String inputFileName="input.in"; BufferedReader br=null; StringBuilder solutionString=new StringBuilder(); int lineCount=0; try{ String line; br=new BufferedReader(new FileReader(inputFileName)); while((line=br.readLine())!=null){ lineCount++; if(lineCount==1){ numTestCases=Integer.parseInt(line); continue; } String[] splittedLine=line.split("\\s+"); long a=Long.parseLong(splittedLine[0]); long b=Long.parseLong(splittedLine[1]); String solution=getSolution(a,b); System.out.println(solution); currentCase++; solutionString.append("Case #"+currentCase+": "+solution+"\n"); } br.close(); writeTextToFile(inputFileName.replace(".in", ".out"), solutionString.toString().trim()); } catch(IOException ex){ System.out.println("Unable to read from file!"); ex.printStackTrace(); } } private static String getSolution(long a, long b) { HashSet<String> resultSet=new HashSet<String>(); for(long n=a;n<=b;n++){ String nString=Long.toString(n); for(int i=1;i<nString.length();i++){ String firstPart=nString.substring(0,nString.length()-i); String secondPart=nString.substring(nString.length()-i,nString.length()); String mString=secondPart+firstPart; long m=Long.parseLong(mString); if(nString.length()!=Long.toString(m).length()) continue; if(a<=n && n<m && m<=b){ resultSet.add(Long.toString(n)+","+Long.toString(m)); } } } return resultSet.size()+""; } private static int[] getIntArrayFromStringLine(String line) { String[] stringArray=line.split("\\s+"); int length=stringArray.length; int intArray[]=new int[length]; valueToIndexMap=new HashMap<Integer,ArrayList<Integer>>(); for(int i=0;i<length;i++){ intArray[i]=Integer.parseInt(stringArray[i]); ArrayList<Integer> indicesList=new ArrayList<Integer>(); if(valueToIndexMap.containsKey(intArray[i])){ indicesList=valueToIndexMap.get(intArray[i]); } indicesList.add(i); valueToIndexMap.put(intArray[i], indicesList); } return intArray; } public static void writeTextToFile(String fileName, String textToWrite){ try{ BufferedWriter bw= new BufferedWriter( new FileWriter(fileName)); bw.write(textToWrite); bw.close(); } catch(IOException ex){ System.out.println("Unable to write to file!"); ex.printStackTrace(); } } }
A11502
A12153
0
package template; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class TestCase { private boolean isSolved; private Object solution; private Map<String, Integer> intProperties; private Map<String, ArrayList<Integer>> intArrayProperties; private Map<String, ArrayList<ArrayList<Integer>>> intArray2DProperties; private Map<String, Double> doubleProperties; private Map<String, ArrayList<Double>> doubleArrayProperties; private Map<String, ArrayList<ArrayList<Double>>> doubleArray2DProperties; private Map<String, String> stringProperties; private Map<String, ArrayList<String>> stringArrayProperties; private Map<String, ArrayList<ArrayList<String>>> stringArray2DProperties; private Map<String, Boolean> booleanProperties; private Map<String, ArrayList<Boolean>> booleanArrayProperties; private Map<String, ArrayList<ArrayList<Boolean>>> booleanArray2DProperties; private Map<String, Long> longProperties; private Map<String, ArrayList<Long>> longArrayProperties; private Map<String, ArrayList<ArrayList<Long>>> longArray2DProperties; private int ref; private double time; public TestCase() { initialise(); } private void initialise() { isSolved = false; intProperties = new HashMap<>(); intArrayProperties = new HashMap<>(); intArray2DProperties = new HashMap<>(); doubleProperties = new HashMap<>(); doubleArrayProperties = new HashMap<>(); doubleArray2DProperties = new HashMap<>(); stringProperties = new HashMap<>(); stringArrayProperties = new HashMap<>(); stringArray2DProperties = new HashMap<>(); booleanProperties = new HashMap<>(); booleanArrayProperties = new HashMap<>(); booleanArray2DProperties = new HashMap<>(); longProperties = new HashMap<>(); longArrayProperties = new HashMap<>(); longArray2DProperties = new HashMap<>(); ref = 0; } public void setSolution(Object o) { solution = o; isSolved = true; } public Object getSolution() { if (!isSolved) { Utils.die("getSolution on unsolved testcase"); } return solution; } public void setRef(int i) { ref = i; } public int getRef() { return ref; } public void setTime(double d) { time = d; } public double getTime() { return time; } public void setInteger(String s, Integer i) { intProperties.put(s, i); } public Integer getInteger(String s) { return intProperties.get(s); } public void setIntegerList(String s, ArrayList<Integer> l) { intArrayProperties.put(s, l); } public void setIntegerMatrix(String s, ArrayList<ArrayList<Integer>> l) { intArray2DProperties.put(s, l); } public ArrayList<Integer> getIntegerList(String s) { return intArrayProperties.get(s); } public Integer getIntegerListItem(String s, int i) { return intArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Integer>> getIntegerMatrix(String s) { return intArray2DProperties.get(s); } public ArrayList<Integer> getIntegerMatrixRow(String s, int row) { return intArray2DProperties.get(s).get(row); } public Integer getIntegerMatrixItem(String s, int row, int column) { return intArray2DProperties.get(s).get(row).get(column); } public ArrayList<Integer> getIntegerMatrixColumn(String s, int column) { ArrayList<Integer> out = new ArrayList(); for(ArrayList<Integer> row : intArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setDouble(String s, Double i) { doubleProperties.put(s, i); } public Double getDouble(String s) { return doubleProperties.get(s); } public void setDoubleList(String s, ArrayList<Double> l) { doubleArrayProperties.put(s, l); } public void setDoubleMatrix(String s, ArrayList<ArrayList<Double>> l) { doubleArray2DProperties.put(s, l); } public ArrayList<Double> getDoubleList(String s) { return doubleArrayProperties.get(s); } public Double getDoubleListItem(String s, int i) { return doubleArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Double>> getDoubleMatrix(String s) { return doubleArray2DProperties.get(s); } public ArrayList<Double> getDoubleMatrixRow(String s, int row) { return doubleArray2DProperties.get(s).get(row); } public Double getDoubleMatrixItem(String s, int row, int column) { return doubleArray2DProperties.get(s).get(row).get(column); } public ArrayList<Double> getDoubleMatrixColumn(String s, int column) { ArrayList<Double> out = new ArrayList(); for(ArrayList<Double> row : doubleArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setString(String s, String t) { stringProperties.put(s, t); } public String getString(String s) { return stringProperties.get(s); } public void setStringList(String s, ArrayList<String> l) { stringArrayProperties.put(s, l); } public void setStringMatrix(String s, ArrayList<ArrayList<String>> l) { stringArray2DProperties.put(s, l); } public ArrayList<String> getStringList(String s) { return stringArrayProperties.get(s); } public String getStringListItem(String s, int i) { return stringArrayProperties.get(s).get(i); } public ArrayList<ArrayList<String>> getStringMatrix(String s) { return stringArray2DProperties.get(s); } public ArrayList<String> getStringMatrixRow(String s, int row) { return stringArray2DProperties.get(s).get(row); } public String getStringMatrixItem(String s, int row, int column) { return stringArray2DProperties.get(s).get(row).get(column); } public ArrayList<String> getStringMatrixColumn(String s, int column) { ArrayList<String> out = new ArrayList(); for(ArrayList<String> row : stringArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setBoolean(String s, Boolean b) { booleanProperties.put(s, b); } public Boolean getBoolean(String s) { return booleanProperties.get(s); } public void setBooleanList(String s, ArrayList<Boolean> l) { booleanArrayProperties.put(s, l); } public void setBooleanMatrix(String s, ArrayList<ArrayList<Boolean>> l) { booleanArray2DProperties.put(s, l); } public ArrayList<Boolean> getBooleanList(String s) { return booleanArrayProperties.get(s); } public Boolean getBooleanListItem(String s, int i) { return booleanArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Boolean>> getBooleanMatrix(String s) { return booleanArray2DProperties.get(s); } public ArrayList<Boolean> getBooleanMatrixRow(String s, int row) { return booleanArray2DProperties.get(s).get(row); } public Boolean getBooleanMatrixItem(String s, int row, int column) { return booleanArray2DProperties.get(s).get(row).get(column); } public ArrayList<Boolean> getBooleanMatrixColumn(String s, int column) { ArrayList<Boolean> out = new ArrayList(); for(ArrayList<Boolean> row : booleanArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setLong(String s, Long b) { longProperties.put(s, b); } public Long getLong(String s) { return longProperties.get(s); } public void setLongList(String s, ArrayList<Long> l) { longArrayProperties.put(s, l); } public void setLongMatrix(String s, ArrayList<ArrayList<Long>> l) { longArray2DProperties.put(s, l); } public ArrayList<Long> getLongList(String s) { return longArrayProperties.get(s); } public Long getLongListItem(String s, int i) { return longArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Long>> getLongMatrix(String s) { return longArray2DProperties.get(s); } public ArrayList<Long> getLongMatrixRow(String s, int row) { return longArray2DProperties.get(s).get(row); } public Long getLongMatrixItem(String s, int row, int column) { return longArray2DProperties.get(s).get(row).get(column); } public ArrayList<Long> getLongMatrixColumn(String s, int column) { ArrayList<Long> out = new ArrayList(); for(ArrayList<Long> row : longArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class DancingWithTheGooglers { ArrayList<String> result = new ArrayList<>(); public void solve(int N, int S, int p, int[] ts){ int max = 0; if(p==0){ max = ts.length; result.add(""+max); return; } //Filter of those how cannot have p based on total score ArrayList<Integer> totals = new ArrayList<>(); for(int i=0;i<ts.length;i++){ if(ts[i]>=3*p-4&&ts[i]>0){ totals.add(ts[i]); } } //Count those that must have a score above p without surprise ArrayList<Integer> needSurprise = new ArrayList<>(); for(int i=0;i<totals.size();i++){ int val = totals.get(i); if(val>=3*p-2){ max++; }else{ needSurprise.add(val); } } if(S>=needSurprise.size()){ max += needSurprise.size(); }else{ max += S; } result.add(""+max); } public void saveResults(String file){ try { FileWriter fstream = new FileWriter(file); BufferedWriter out = new BufferedWriter(fstream); int count = 1; for(int i=0;i<result.size();i++){ String s = "Case #" + count++ + ": " + result.get(i) + "\n"; out.write(s); } out.close(); } catch (Exception e) { // TODO: handle exception } } public static void main(String[] args) { DancingWithTheGooglers dwtg = new DancingWithTheGooglers(); String file = args[0]; try{ BufferedReader br = new BufferedReader(new FileReader(new File(file))); String line = br.readLine(); int numRows = Integer.parseInt(line); while((line=br.readLine())!=null){ String[] ss = line.split(" "); int N = Integer.parseInt(ss[0]); int S = Integer.parseInt(ss[1]); int p = Integer.parseInt(ss[2]); int[] ts = new int[N]; for(int i=0;i<N;i++){ ts[i] = Integer.parseInt(ss[3+i]); } dwtg.solve(N,S,p,ts); } }catch (Exception e) { System.out.println(e.getMessage()); } dwtg.saveResults(args[1]); } }
B10245
B11509
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; } }
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class RecycledNumbers { private PrintWriter out; private Scanner in; private void init() { } private void solve() { int A = in.nextInt(); int B = in.nextInt(); int r = 0; for (int i = A; i <= B; i++) { int j = rotate(i); while (i != j) { if (i < j && j <= B) { r++; } j = rotate(j); } } out.println(r); } private int rotate(int number) { int pos = 1; while (number % 10 == 0) { pos *= 10; number /= 10; } int rest = number % 10; number /= 10; int numberCopy = number; while (numberCopy > 0) { pos *= 10; numberCopy /= 10; } return rest * pos + number; } private void runTests() { init(); int T = Integer.parseInt(in.nextLine()); for (int i = 0; i < T; i++) { out.print("Case #" + (i + 1) + ": "); solve(); } } private void run() { try { runTests(); } finally { close(); } } private void close() { out.close(); in.close(); } public RecycledNumbers() throws FileNotFoundException { this.in = new Scanner(new File("C-small-attempt0.in")); this.out = new PrintWriter(new File("C-small-attempt0.out")); } public static void main(String[] args) throws FileNotFoundException { new RecycledNumbers().run(); } }
A21010
A21800
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.util.Scanner; public class DancingWithTheGooglers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String line = scanner.nextLine().trim(); int totalCase = Integer.parseInt(line); for (int i = 1; i <= totalCase; i++) { line = scanner.nextLine().trim(); String parts[] = line.split(" +"); int numOfGooglers = Integer.parseInt(parts[0]); int numOfSuprises = Integer.parseInt(parts[1]); int bestResult = Integer.parseInt(parts[2]); String output = "Case #" + i + ": "; int possible = 0; int impoosible = 0; for (int count = 0; count < numOfGooglers; count++) { int index = 3+count; int totalPoints = Integer.parseInt(parts[index]); if (totalPoints < bestResult) { impoosible++; continue; } int sumOfTwo = totalPoints - bestResult; float avgOfTwo = sumOfTwo / 2.0f; int num2 = (int)Math.floor(avgOfTwo); int num3 = (int)Math.ceil(avgOfTwo); int diff1 = bestResult - num2; int diff2 = bestResult - num3; if (diff1 <= 1 && diff2 <= 1) { possible++; } else if (diff1 >= 3 || diff2 >= 3) { impoosible++; } } int googlersLeft = numOfGooglers - possible; int possibleGooglers = (googlersLeft - impoosible > numOfSuprises ? numOfSuprises : googlersLeft - impoosible); int p = possible + possibleGooglers; output += p; System.out.println(output); } System.exit(0); } }
B10149
B11613
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.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.Integer; import java.util.ArrayList; class jamc { public static void main(String[] args) { BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); try { String s = bufferRead.readLine(); int testCases=Integer.parseInt(s); ArrayList<String> sars = new ArrayList<String>(); for(int i=0; i< testCases; i++){ s = bufferRead.readLine(); sars.add(s); } System.out.println("\n"); for(int j=0; j<sars.size(); j++){ String [] split=sars.get(j).split(" "); int num1=Integer.parseInt(split[0]); int num2=Integer.parseInt(split[1]); System.out.println("Case #"+(j+1)+": " + recycleCt(num1, num2)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static int recycleCt(int num1, int num2){ int ret=0; String num1Str=String.valueOf(num1); String num2Str=String.valueOf(num2); if(num1Str.length()!=num2Str.length()){ return 0; } for(int j=num2; j>=num1; j--) for(int i=num1; i<=num2; i++){ if(i<j) if(isRecycled(i, j)) ret++; } return ret; } public static boolean isRecycled(int num1, int num2){ String num1Str=String.valueOf(num1); String num2Str=String.valueOf(num2); for(int i=0; i < num1Str.length(); i++){ String tempStr=num1Str.substring(i, num1Str.length()) +num1Str.substring(0, i); if(tempStr.compareToIgnoreCase(num2Str)==0) return true; } return false; } }
A10568
A13159
0
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class DancingWithTheGooglers { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader (new FileReader("B-small.in")); PrintWriter out = new PrintWriter(new FileWriter("B-small.out")); int t = Integer.parseInt(f.readLine()); for (int i = 0; i < t; i++){ int c = 0; StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); int[] ti = new int[n]; int s = Integer.parseInt(st.nextToken()); int p = Integer.parseInt(st.nextToken()); for (int j = 0; j < n; j ++){ ti[j] = Integer.parseInt(st.nextToken()); if (ti[j] % 3 == 0){ if (ti[j] / 3 >= p) c++; else if (ti[j] / 3 == (p-1) && s > 0 && ti[j] >= 2){ s--; c++; } } else if (ti[j] % 3 == 1){ if ((ti[j] / 3) + 1 >= p) c++; } else{ if (ti[j] / 3 >= p-1) c++; else if (ti[j] / 3 == (p-2) && s > 0){ s--; c++; } } } out.println("Case #" + (i+1) + ": " + c); } out.close(); System.exit(0); } }
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); } }
B12082
B11039
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 qual2012; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); //PrintWriter out = new PrintWriter(System.out); PrintWriter out = new PrintWriter(new FileWriter("C.out")); for (int t = in.nextInt(), cs = 1; t > 0; t--, cs++) { out.print("Case #" + cs + ": "); int a = in.nextInt(), b = in.nextInt(); long ans = 0; for (int i = a; i <= b; i++) { ans += go(i, a); } out.println(ans); } out.flush(); } static long go(int x, int low) { String s = x + ""; Set<Integer> set = new HashSet<Integer>(); for (int i = 1; i < s.length(); i++) { String w = s.substring(i) + s.substring(0, i); if (w.startsWith("0")) continue; int y = Integer.valueOf(w); if (low <= y && y < x) set.add(y); } return set.size(); } }
B12074
B12909
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 ); } }
import java.util.*; import java.io.*; public class Main { public static boolean recycledNumber(int n, int m) { String N = String.valueOf(n); String M = String.valueOf(m); for(int i = 0; i < N.length(); i++) { String firstPart = N.substring(0, i); String endPart = N.substring(i, N.length()); String combined = endPart + firstPart; if(M.equals(combined)) return true; } return false; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("testcase.in")); int testcases = sc.nextInt(); sc.nextLine(); for(int testcase = 1; testcase <= testcases; testcase++) { int A = sc.nextInt(); int B = sc.nextInt(); int recycledPairs = 0; for(int n = A; n < B; n++) { for(int m = n+1; m <= B; m++) { if(recycledNumber(n, m)) recycledPairs++; } } System.out.printf("Case #%d: %d\n", testcase, recycledPairs); } } }
A20119
A20832
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(); } }
package dancing; import java.io.*; public class DancingG { private int N; private String[] InputStringArray; private String[] OutputStringArray; public static void main(String[] args) { try{ DancingG dg = new DancingG(); if (dg.GetDataFromInputFile()) if (dg.ProcestestData()) dg.WriteDatatoOutputFile(); else System.out.println("Error while writing to outputfile"); else System.out.println("Error while getting the input data"); }catch(IOException ex){ System.out.println("IO Error"); } } private boolean GetDataFromInputFile() throws IOException{ int casecount=0; FileInputStream in = new FileInputStream("E:\\Study\\Google Code jam\\2012\\DancingG" + "\\Input\\A-small-attempt0.in"); DataInputStream di = new DataInputStream(in); BufferedReader br = new BufferedReader(new InputStreamReader(di)); String line; if ((line = br.readLine())!= null) { casecount = Integer.parseInt(line); InputStringArray = new String[casecount]; OutputStringArray = new String[casecount]; } for (int i=0; i<casecount; i++){ if ((line = br.readLine())!= null) InputStringArray[i]=line; } return true; } private void WriteDatatoOutputFile() throws IOException{ FileOutputStream out = new FileOutputStream("E:\\Study\\Google Code jam\\2012\\DancingG\\Output\\output.txt"); DataOutputStream dout = new DataOutputStream(out); BufferedWriter br = new BufferedWriter(new OutputStreamWriter(dout)); for (int i=1; i<=OutputStringArray.length;i++){ br.write("Case #"+i+": "+OutputStringArray[i-1]+"\r\n"); } br.close(); dout.close(); out.close(); System.out.println("Done"); } private boolean ProcestestData(){ for (int i=0; i<(InputStringArray.length);i++){ String CurrentString = InputStringArray[i]; OutputStringArray[i] = ProcessString(CurrentString); } return true; } private String ProcessString(String aString){ int N,S,p; String outputString=""; int spacepos=0; int count=0; String[] parameters = aString.split(" "); N=Integer.parseInt(parameters[0]); S=Integer.parseInt(parameters[1]); p=Integer.parseInt(parameters[2]); int normallimit = 28-(10-p)*3; int surprisinglimit = normallimit-2; if (surprisinglimit<2) surprisinglimit = 2; int surprisinglimtcount =0; for (int i=3; i<parameters.length;i++){ if (Integer.parseInt(parameters[i])>=normallimit) count++; else if (Integer.parseInt(parameters[i])>=surprisinglimit) surprisinglimtcount++; } if (surprisinglimtcount>S) surprisinglimtcount=S; count = count + surprisinglimtcount; return String.valueOf(count); } }
A11277
A11866
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.util.Scanner; import java.io.*; import java.util.ArrayList; public class Main2 { public static void main(String[] args) throws IOException { String line = " "; String line2 = " "; String line3 = " "; FileReader reader = new FileReader("B-small-attempt2.in"); Scanner in = new Scanner(reader); ArrayList<String> list = new ArrayList<String>(); ArrayList<String> list2 = new ArrayList<String>(); int number = 0; int numb = 0; int index = 0; int c; int N; int nprob; int hnum; int calc; boolean suc; int p; int[] num = new int[103]; int count = in.nextInt(); in.nextLine(); for(int i = 0; i < count; i++) { line = in.nextLine(); list.add(line); } while(count > 0) { p = 0; line2 = list.get(numb); number = 0; while(line2.length() > 0) { index = line2.indexOf(' '); if(index > 0) { line = line2.substring(0,index); num[number] = Integer.parseInt(line); line2 = line2.substring(index); line2 = line2.trim(); } else if(index == -1) { num[number] = Integer.parseInt(line2); line2 = ""; } number++; } N = num[0]; nprob = num[1]; hnum = num[2]; suc = false; for(int j = 0; j < N; j++) { c = 3; calc = num[j+3]; while(c > 0) { calc -= hnum; c--; } if(calc >= 0) suc = true; else if(calc == -1) suc = true; else if(calc == -2) suc = true; else if(nprob > 0 && calc == -3 && num[j+3] > 0) { suc = true; nprob--; } else if(nprob > 0 && calc == -4 && num[j+3] > 0) { suc = true; nprob--; } else suc = false; if(suc) p++; } line3 = "Case #" + (numb+1) + ": " + p; list2.add(line3); count--; numb++; } for(String a : list2) System.out.println(a); } }
B21270
B21254
0
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; public class CopyOfCopyOfMain { static int ndigits(int n) { return (int) (Math.log10(n) + 1); } static int rot(int n, int dig) { return (int) ((n % 10) * Math.pow(10, dig - 1)) + (int) (n / 10); } public static void main(String[] args) throws FileNotFoundException { String file = "C-large"; Scanner in = new Scanner(new File(file + ".in")); PrintWriter out = new PrintWriter(new File(file + ".out")); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int A = in.nextInt(); int B = in.nextInt(); int c = 0; int[] list = new int[ndigits(B)]; numbers: for (int i = A; i <= B; i++) { int digs = ndigits(i); int rot = i; int pairs = 0; Arrays.fill(list, -1); list[0] = i; digits: for (int j = 1; j <= digs + 1; j++) { rot = rot(rot, digs); if(rot < i) continue; if (A <= rot && rot <= B) { for (int k = 0; k < j; k++) { if (list[k] == rot) { continue digits; } } pairs++; list[j] = rot; } } //c += pairs * (pairs + 1) / 2; c += pairs ; // c+=digs; } out.println("Case #" + t + ": " + c); } in.close(); out.close(); } }
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class ProblemC_Qual_2012 implements Runnable{ BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ in = new BufferedReader(new FileReader("C-large.in")); out = new PrintWriter("output.txt"); } String readString() throws IOException{ while(!tok.hasMoreTokens()){ try{ tok = new StringTokenizer(in.readLine()); }catch (Exception e){ return null; } } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new Thread(null, new ProblemC_Qual_2012(), "", 256 * (1L << 20)).start(); } long timeBegin, timeEnd; void time(){ timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory(){ memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } void debug(Object... objects){ if (DEBUG){ for (Object o: objects){ System.err.println(o.toString()); } } } public void run(){ try{ timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); time(); memory(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } boolean DEBUG = false; void solve() throws IOException{ int t = readInt(); for (int it = 1; it <= t; it++){ out.print("Case #" + it + ": "); int a = readInt(); int b = readInt(); boolean[] used = new boolean[b+1]; int x = a; int pow = 1; while (x >= 10){ x /= 10; pow *= 10; } long res = 0; for (int i = a; i <= b; i++){ if (used[i]) continue; x = i; long count = 0; do{ if (x / pow != 0 && x >= a && x <= b){ used[x] = true; count++; } x = x % pow * 10 + (x / pow); }while (x != i); used[i] = true; res += (count - 1) * count / 2; } out.println(res); } } }
B10149
B10821
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.math.*; import java.io.*; import java.util.*; public class Recycle { public static void main(String[] args) { Recycle r = new Recycle(); writeOutput(r.countRecycleds(readInput())); } // Count all recycleds for all the inputs public String countRecycleds(ArrayList<String> lines) { String line; StringBuffer out = new StringBuffer(); for (int i = 1; i < lines.size(); i++) { line = lines.get(i); String[] args = line.split(" "); out.append("Case #" + i + ": "); out.append(countRecycleds(Integer.parseInt(args[0]), Integer.parseInt(args[1]))); out.append("\n"); } return out.toString(); } // Count all recycleds between A and B public int countRecycleds(int A, int B) { int count = 0; for (int n = A; n <= B; n++) { count += countRecycledsForN(n, B); } return count; } // Count recycleds for one n (ie, number of ms) public int countRecycledsForN(int n, int B) { int digits = countDigits(n); int count = 0; Map<Integer,Boolean> used = new HashMap<Integer, Boolean>(); // For each number of digits we're swapping for(int swap = 1; swap < digits; swap++) { // The base 10 number to swap int swapper = (int)Math.pow(10, swap); // The digits being swapped int swappedDigits = n % swapper; // n without the digits being swapped int swappedN = n / swapper; int m = (swappedDigits * (int)Math.pow(10, digits - swap)) + swappedN; // If m is valid, count it if (n < m && m <= B && !used.containsKey(m)) { count++; used.put(m, true); } } return count; } // Count the number of digits in n (base 10) public int countDigits(int n) { return (int)Math.log10(n) + 1; } public static void writeOutput(String s) { try{ BufferedWriter out = new BufferedWriter(new FileWriter("./Output.txt")); out.write(s); out.close(); }catch (Exception e){ System.out.println(s); throw new RuntimeException("Oops, couldn't write"); } } public static ArrayList<String> readInput() { ArrayList<String> lines = new ArrayList<String>(); try { FileInputStream fstream = new FileInputStream("./Input.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String str; while ((str = br.readLine()) != null) { lines.add(str); } br.close(); return lines; } catch (Exception e) { throw new RuntimeException("Couldn't read"); } } }
A11135
A12499
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(); } }
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class CodeJam { // public static final String INPUT_FILE_PATH = "D://CodeJamInput.txt"; public static final String INPUT_FILE_PATH = "D://B-small-attempt0.in"; public static final String OUTPUT_FILE_PATH = "D://CodeJamOutput.txt"; public static List<String> readInput() { List<String> list = new ArrayList<String>(); try { BufferedReader input = new BufferedReader(new FileReader( INPUT_FILE_PATH)); try { String line = null; while ((line = input.readLine()) != null) { list.add(line); } } finally { input.close(); } } catch (IOException ex) { ex.printStackTrace(); } return list; } public static void writeOutput(List<String> output) { PrintWriter writer = null; try { writer = new PrintWriter(new FileWriter(OUTPUT_FILE_PATH)); for (String line : output) { writer.println(line); } writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) writer.close(); } } public static void main(String[] args) { List<DanceFloor> danceFloors = DanceFloor.parseFromFile(CodeJam.readInput()); List<String> output = new ArrayList<String>(); for(int i = 0; i < danceFloors.size(); i++) { System.out.println(danceFloors.get(i)); String line = ""; line += "Case #" + (i + 1) + ": " + danceFloors.get(i).calculate(); output.add(line); } CodeJam.writeOutput(output); } } class DanceFloor { private List<Integer> tripletsTotalCounts; private int surpriseCount; private int targetScore; private int dancersCount; public DanceFloor(List<Integer> tripletsTotalCounts, int surpriseCount, int targetScore, int dancersCount) { this.tripletsTotalCounts = tripletsTotalCounts; this.surpriseCount = surpriseCount; this.targetScore = targetScore; this.dancersCount = dancersCount; } public int calculate() { int result = 0; if (targetScore == 0) return dancersCount; for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if (total < (targetScore * 3 - 4)) { tripletsTotalCounts.remove(i--); } else if (total == 0) { tripletsTotalCounts.remove(i--); } } for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if ((surpriseCount > 0) && (total == targetScore * 3 - 4)) { result++; surpriseCount--; tripletsTotalCounts.remove(i--); } else if ((surpriseCount == 0) && (total == targetScore * 3 - 4)) { tripletsTotalCounts.remove(i--); } } for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if ((surpriseCount > 0) && (total == targetScore * 3 - 3)) { result++; surpriseCount--; tripletsTotalCounts.remove(i--); } else if ((surpriseCount == 0) && (total == targetScore * 3 - 3)) { tripletsTotalCounts.remove(i--); } } result += tripletsTotalCounts.size(); return result; } public static List<DanceFloor> parseFromFile(List<String> readInput) { List<DanceFloor> result = new ArrayList<DanceFloor>(); int testCaseCount = Integer.parseInt(readInput.get(0)); for (int i = 0; i < testCaseCount; i++) { String line[] = readInput.get(i + 1).split(" "); List<Integer> totalCounts = new ArrayList<Integer>(); for (int j = 0; j < Integer.parseInt(line[0]); j++) { totalCounts.add(Integer.parseInt(line[3 + j])); } result.add(new DanceFloor(totalCounts, Integer.parseInt(line[1]), Integer.parseInt(line[2]), Integer.parseInt(line[0]))); } return result; } @Override public String toString() { return "dancersCount = " + dancersCount + "; surpriseCount = " + surpriseCount + "; targetScore = " + targetScore + "; tripletsTotalCounts" + tripletsTotalCounts.toString(); } }
B11696
B11553
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.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; /** * * Google Code Jam 2012 Qualification Round - Problem C. Recycled Numbers * * @author matlock * */ public class RecycledNumbers { public static void main(String[] args) { RecycledNumbers g = new RecycledNumbers(); g.goGo(); } public void goGo() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { int testCases = Integer.parseInt(in.readLine()); for (int i = 1; i <= testCases; i++) { String inputText = in.readLine(); String[] numberPair = inputText.split(" ", 2); int matches = runTestCase(Integer.valueOf(numberPair[0]), Integer.valueOf(numberPair[1])); System.out.println("Case #" + i + ": " + matches); } } catch (IOException e) { System.out.println("Exception: " + e.getMessage()); } } public int runTestCase(int startVal, int endVal) { Set<String> sourceSet = new HashSet<String>(); Set<String> discoveredSet = new HashSet<String>(); int totalMatches = 0; // first store all the source numbers for (int j = startVal; j <= endVal; j++) { sourceSet.add(String.valueOf(j)); } for (int j = startVal; j <= endVal; j++) { StringBuffer buf = new StringBuffer(String.valueOf(j)); int len = buf.length() - 1; // don't need last rotation, so -1 // rotate the characters for (int k = 0; k < len; k++) { buf.append(buf.charAt(0)); buf.deleteCharAt(0); if (Integer.valueOf(buf.toString()) != j) { if (sourceSet.contains(buf.toString()) && !discoveredSet.contains(String.valueOf(j) + buf.toString())) { discoveredSet.add(String.valueOf(j) + buf.toString()); discoveredSet.add(buf.toString() + String.valueOf(j)); totalMatches++; sourceSet.remove(String.valueOf(j)); // remove from set } } } } return totalMatches; } }
B21790
B22185
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.util.Scanner; import java.io.IOException; import java.util.Arrays; import java.util.ArrayList; import java.io.PrintStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream("C-large.in"); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream("gcj3.out"); } catch (IOException e) { throw new RuntimeException(e); } Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); GCJ3 solver = new GCJ3(); solver.solve(1, in, out); out.close(); } } class GCJ3 { public void solve(int testNumber, Scanner in, PrintWriter out) { int cases = in.nextInt(); for(int caseNum =0;caseNum<cases;caseNum++) { int res = 0; long A = in.nextInt(); long B = in.nextInt(); int N = IntLib.numDigits(A,10); long[] pow = new long[N+1]; pow[0]=1; for(int i=1;i<=N;i++)pow[i]=10*pow[i-1]; long[] done = new long[N]; for(long i=A;i<=B;i++) { inner: for(int j=1;j<=N-1;j++) { long left = i; long right = i; left/=pow[N-j]; right%=pow[N-j]; right*=pow[j]; long nw = left+right; done[j-1]=nw; if(nw>i && nw>=A && nw<=B) { for(int k=0;k<j-1;k++) { if(done[k]==nw)continue inner; } res++; } } } out.println("Case #"+(caseNum+1)+": "+res); } } } class IntLib { public static int numDigits(long a, long base) { int res = 0; while(a>0) { a/=base; res++; } return res; } }
B12082
B12965
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 com.code.jam; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class RecycledNumbers { FileInputStream in; FileOutputStream out; BufferedReader br; void open() throws IOException { in = new FileInputStream(new File( "/home/lenovo/Documents/GCJ/C-small-attempt0.in")); out = new FileOutputStream(new File( "/home/lenovo/Documents/GCJ/C-small-attempt0.out")); br = new BufferedReader(new InputStreamReader(new DataInputStream(in))); } void close() throws IOException { out.close(); } void run() throws IOException { int tn = new Integer(br.readLine()); for (int i = 1; i <= tn; i++) { // System.out.println(br.readLine()); String AB = br.readLine(); BigInteger A = new BigInteger(AB.split(" ")[0]); BigInteger B = new BigInteger(AB.split(" ")[1]); int count = 0; Map nm = new HashMap(); for (BigInteger k = A; k.compareTo(B) == -1; k = k .add(BigInteger.ONE)) { String n = k.toString(); String m = n; nm.clear(); for(int l=0;l<n.length();l++) { m = rotateDigitRight(m); BigInteger mBig = new BigInteger(m); if (mBig.compareTo(k) >0 && mBig.compareTo(B) <= 0 && mBig.compareTo(A) >0 && !nm.containsValue(m) ) { count++; nm.put(n, m); System.out.println(n + ", " +m+" "+ count); } } } out.write(("Case #" + i + ": " + count).getBytes()); out.write("\n".getBytes()); } } public static String rotateDigitRight(String A) { String val = A.toString(); String val0 = String.valueOf(val.charAt(val.length()-1)); String valRest = ""; if(val.length()>=2) { valRest = val.substring(0, val.length()-1); } val = val0 + valRest; return val; } public static void main(String[] args) throws IOException { RecycledNumbers solution = new RecycledNumbers(); solution.open(); solution.run(); solution.close(); } }
A12570
A10454
0
package util.graph; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Set; public class DynDjikstra { public static State FindShortest(Node start, Node target) { PriorityQueue<Node> openSet = new PriorityQueue<>(); Set<Node> closedSet = new HashSet<>(); openSet.add(start); while (!openSet.isEmpty()) { Node current = openSet.poll(); for (Edge edge : current.edges) { Node end = edge.target; if (closedSet.contains(end)) { continue; } State newState = edge.travel(current.last); //if (end.equals(target)) { //return newState; //} if (openSet.contains(end)) { if (end.last.compareTo(newState)>0) { end.last = newState; } } else { openSet.add(end); end.last = newState; } } closedSet.add(current); if (closedSet.contains(target)) { return target.last; } } return target.last; } }
import java.io.BufferedReader; import java.io.FileReader; public class DG { public static void main (String[] args) throws Exception { BufferedReader sr = new BufferedReader(new FileReader("c:\\Projects\\DG.txt")); int total = Integer.parseInt(sr.readLine()); for (int i=0; i<total; i++) { String[] tokens = sr.readLine().split(" "); int N = Integer.parseInt (tokens[0]); int S = Integer.parseInt (tokens[1]); int p = Integer.parseInt (tokens[2]); int[] scores = new int[N]; for (int j=0; j<N; j++) scores[j] = Integer.parseInt (tokens[j+3]); solve (i+1, S, p, scores); } } private static void solve (int c, int S, int p, int[] scores) { int remaining = S; int total = 0; for (int i=0; i<scores.length; i++) { int base = scores[i] / 3; int add = scores[i] % 3; if (add == 2) { if ((base+1)>=p) total++; else { //it could be a surprising one if ((base+2)>=p && remaining >0) { total++; remaining--; } } } else if (add == 0) { if (base >= p) total++; else { //it could be surprising as well if ((base+1) >= p && remaining > 0 && base > 0) { total++; remaining--; } } } else { if ((base+add)>=p) total++; } } System.out.printf ("Case #%d: %d\n", c, total); } }
B12115
B12639
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.util.Scanner; /** * * @author Yasura */ public class C { public static void main(String[] args) { Scanner scanInt = new Scanner(System.in); int noOfCases = scanInt.nextInt(); int count, length, A, B, tmp, base, invBase; for (int i = 0; i < noOfCases; i++) { count = 0; A = scanInt.nextInt(); B = scanInt.nextInt(); length = (Integer.toString(A)).length(); for (int k = A; k <= B; k++) { for (int j = 1; j < length; j++) { base = (int) Math.pow(10, j); invBase = (int) Math.pow(10, length - j); tmp = ((k % base) * invBase + k / base); if (tmp > k && tmp <= B ) { count++; } } } System.out.println("Case #"+(i+1)+": "+count); } } }
B10702
B10746
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; } }
package qualification; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Scanner; public class RecycledNumber { public static void main(String[] args) throws IOException { String inputFile = "C-small-attempt0.in"; Scanner input = new Scanner(new FileInputStream(inputFile)); FileOutputStream out = new FileOutputStream(inputFile + ".out", false); slove(input, out); out.close(); } private static void slove(Scanner input, FileOutputStream out) throws IOException { int cases = input.nextInt(); for (int caseOrder = 1; caseOrder <= cases; caseOrder++) { int a = input.nextInt(); int b = input.nextInt(); long r = 0; for (int i = a; i <= b; i++) { for (int x: getRecycled(i)) { if (x >= a && x <= b && i < x && x > 0) { // System.out.printf("(%d, %d)\n", i, x); r++; } } } String outline = String.format("Case #%d: %d\r\n", caseOrder, r); System.out.print(outline); out.write(outline.getBytes()); } } private static Collection<Integer> getRecycled(int a) { String s = Integer.toString(a); HashSet<Integer> ret = new HashSet<Integer>(); for (int i = 1; i < s.length(); i++) { String s2 = s.substring(i) + s.substring(0, i); if (!s2.startsWith("0")) { ret.add(Integer.parseInt(s2)); } } return ret; } }
A22771
A22606
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(); } }
public class ProblemB extends FileWrapper { private int N[] = null; private int S[] = null; private int P[] = null; private int t[][] = null; public ProblemB(String fileName) { this.processInput(fileName); this.calculate(); this.processOutput(OUTPUT); } private int getResult(int caseNum) { int total = 0; for (int i=0; i<this.t[caseNum].length; i++) { if (this.t[caseNum][i]/3 >= this.P[caseNum]) { total++; }else if (this.t[caseNum][i]/3 == this.P[caseNum] - 1) { if (this.t[caseNum][i]%3 >= 1) { total++; }else if (S[caseNum] > 0 && this.t[caseNum][i]/3 > 0) { total++; S[caseNum]--; } }else if (this.t[caseNum][i]/3 == this.P[caseNum] - 2 && this.t[caseNum][i]%3 == 2 && this.t[caseNum][i]/3 > 0 && S[caseNum] > 0) { total++; S[caseNum]--; } } return total; } @Override protected void processInput(String fileName) { try { this.openReadFile(fileName); this.caseNum = Integer.parseInt(this.readLine()); this.output = new String[this.caseNum]; this.N = new int[this.caseNum]; this.S = new int[this.caseNum]; this.P = new int[this.caseNum]; this.t = new int[this.caseNum][]; for (int i = 0; i < this.caseNum; i++) { String elem[] = this.readLine().split(" "); this.N[i] = Integer.parseInt(elem[0]); this.S[i] = Integer.parseInt(elem[1]); this.P[i] = Integer.parseInt(elem[2]); this.t[i] = new int[N[i]]; for (int j=0; j<N[i]; j++) { this.t[i][j] = Integer.parseInt(elem[3+j]); } } this.closeReadFile(); } catch (Exception e) { } } @Override protected void calculate() { for (int i=0; i<this.caseNum; i++) { this.output[i] = CASE + (i+1) + ": " + this.getResult(i); } } public static void main(String argv[]) { if (argv.length > 0) { new ProblemB(argv[0]); } else { new ProblemB("B-large.in"); } } }
A22191
A21214
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 ? " *" : "")); // } }
import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner s = new Scanner(System.in); int size = s.nextInt(); for (int count = 1; count <= size; count++){ int dancerNum = s.nextInt(); int surpNum = s.nextInt(); int score = s.nextInt(); int[] dancerScore = new int[dancerNum]; char[] marks = new char[dancerNum]; for (int i = 0; i < dancerNum; i++){ dancerScore[i] = s.nextInt(); } int highB = score * 3 - 2; int lowB = (score - 1) * 3 - 1; int output = 0; int sup = surpNum; int markIdx = 0; if (score < 2) { for (Integer i : dancerScore){ if (i >= score) { marks[markIdx] = '+'; output++; }else{ marks[markIdx] = '-'; } markIdx++; } } else { for (Integer i : dancerScore){ if (i >= highB){ output++; marks[markIdx] = '+'; }else if (i< highB && i >= lowB && sup > 0){ //if (){ output++; sup--; marks[markIdx] = '*'; // }else{ // // marks[markIdx] = '-'; // } } else{ marks[markIdx] = '-'; } markIdx++; } } // System.out.print("Case #"+count+": " + dancerNum + " " + surpNum + " "+ score + " "); // for (Integer i: dancerScore) // { // System.out.print(i+" "); // } System.out.println("Case #"+count+": "+output); // for (Character mark: marks) // { // System.out.print(mark+" "); // } // System.out.println(); } } }
A11917
A11511
0
package com.silverduner.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; public class Dancing { public static void main(String[] args) throws Exception { File input = new File("B-small-attempt0.in"); BufferedReader in = new BufferedReader(new FileReader(input)); File output = new File("1.out"); BufferedWriter out = new BufferedWriter(new FileWriter(output)); // parse input int N = Integer.parseInt(in.readLine()); for(int i=0;i<N;i++) { String str = in.readLine(); out.write("Case #"+(i+1)+": "); System.out.println("-------"); String[] words = str.split(" "); int n = Integer.parseInt(words[0]); int suprise = Integer.parseInt(words[1]); int threshold = Integer.parseInt(words[2]); int[] scores = new int[n]; for(int j=0;j<n;j++) { scores[j] = Integer.parseInt(words[3+j]); } int count = 0; for(int score : scores) { int a,b,c; boolean find = false; boolean sfind = false; for(a = 10; a>=0 && !find; a--) { if(3*a-4>score) continue; for(b = a; b>=0 && b >=a-2 && !find; b--) { for(c = b; c>=0 && c >=b-2 && c >=a-2 && !find; c--) { System.out.println(a+","+b+","+c); if(a+b+c==score) { if(a >= threshold) { if(a-c <= 1){ count++; find = true; System.out.println("find!"); } else if(a-c == 2){ sfind = true; System.out.println("suprise!"); } } } } } } if(!find && sfind && suprise > 0) { count++; suprise --; } } int maxCount = count; out.write(maxCount+"\n"); } out.flush(); out.close(); in.close(); } }
package Qualification; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.StringTokenizer; public class ProblemB { int good; int needsSuprise; int bad; int p; public ProblemB() throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter(new File("out.txt"))); Scanner scanner = new Scanner(System.in); int T = Integer.parseInt(scanner.nextLine()); for(int i=1;i<=T;i++) { good = needsSuprise = bad = 0; StringTokenizer tokens = new StringTokenizer(scanner.nextLine()); int numGooglers = Integer.parseInt(tokens.nextToken()); int suprises = Integer.parseInt(tokens.nextToken()); p = Integer.parseInt(tokens.nextToken()); for(int j=0;j<numGooglers;j++) { int totalPoints = Integer.parseInt(tokens.nextToken()); analyze(totalPoints); } int solution = good + Math.min(needsSuprise,suprises); System.out.println("Case #" + i + ": " + solution); out.write("Case #" + i + ": " + solution + "\n"); } out.close(); } public void analyze(int totalPoints) { int score = (totalPoints+1)/3; int diffScore = totalPoints - score*2; if(score>=p || diffScore>=p) { good++; return; } if(totalPoints>=2 && (score+1>=p || diffScore+1>=p)) { needsSuprise++; return; } bad++; } public static void main(String args[]) throws IOException { new ProblemB(); } }
A12846
A12503
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); } }
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 DancingWithTheGooglers { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub int testCaseNumber; String input; BufferedReader in = new BufferedReader(new FileReader("B-small-attempt0.in")); input = in.readLine(); testCaseNumber = Integer.parseInt(input.trim()); int[] totalScoreArray = new int[testCaseNumber]; for(int i=0; i<testCaseNumber; i++){ input = in.readLine(); String[] dataArrayString = input.split(" "); int[] dataArray = new int[dataArrayString.length]; for(int z=0;z<dataArrayString.length; z++){ dataArray[z] = Integer.parseInt(dataArrayString[z]); } int googlerNum = dataArray[0]; int surprisingNum = dataArray[1]; int minPeakScore = dataArray[2]; int score = 0; int minNos; int minS; if(minPeakScore<=1){ minNos = minPeakScore; minS = minPeakScore; } else{ minNos = (minPeakScore*3)-2; minS = (minPeakScore*3)-4; } for(int j=3; j<googlerNum+3; j++){ if(dataArray[j]>=minNos){ score++; } else if(surprisingNum>0 && dataArray[j]>=minS){ score++; surprisingNum--; } } System.out.println(score); totalScoreArray[i] = score; } in.close(); FileWriter fstream = new FileWriter("B-small-attempt0.out"); BufferedWriter out = new BufferedWriter(fstream); for(int i=1; i<=testCaseNumber;i++){ String outLine = "Case #"+i+": "+totalScoreArray[i-1]+"\n"; out.write(outLine); } out.close(); System.out.println("File created successfully."); } }
A20490
A22566
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 qualifying; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class B { public static String solve(int N, int S, int p, int[] t) { int cnt = 0; for(int i=0; i<t.length; i++) { if(t[i]>=2*Math.max(p-1,0)+p) cnt++; if(t[i]<2*Math.max(0,p-1)+p && t[i]>=2*Math.max(0,p-2)+p) { if(S>0) { cnt++; S--; } } } return Integer.toString(cnt); } public static void main(String[] args) throws Exception { String fs_in = "/Users/ctynan/Downloads/test.txt"; String fs_out = "/Users/ctynan/Documents/B-out.txt"; String line; BufferedReader br = new BufferedReader(new FileReader(fs_in)); BufferedWriter bw = new BufferedWriter(new FileWriter(fs_out)); line=br.readLine(); line=line.toLowerCase(); int tst = Integer.valueOf(line); for(int ii=0;ii<tst; ii++) { line=br.readLine(); String output = "Case #" + Integer.toString(ii+1) +": "; String[] tem = line.split(" "); int N = Integer.valueOf(tem[0]); int S = Integer.valueOf(tem[1]); int p = Integer.valueOf(tem[2]); int[] t = new int[N]; for(int i=3; i<tem.length; i++) { t[i-3] = Integer.valueOf(tem[i]); } String res = solve(N,S,p,t); bw.write(output+res); if(ii<tst-1) bw.write('\n'); } bw.close(); return; } }
A22360
A20490
0
import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; public class Dancing_With_the_Googlers { /** * 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. * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // Reading the input file Scanner in = new Scanner(new File("B-large.in")); // writting the input file FileOutputStream fos = new FileOutputStream("B-large.out"); PrintStream out = new PrintStream(fos); //Close the output stream int testCase=Integer.parseInt(in.nextLine()); for(int i=0;i<testCase;i++) { out.print("Case #" + (i + 1) + ":\t"); int NoOfGooglers= in.nextInt(); int NoOfSurprisingResults = in.nextInt(); int atLeastP=in.nextInt(); ArrayList<Integer> scores= new ArrayList<Integer>(); int BestResults=0; int Surprising=0; for(int j=0;j<NoOfGooglers;j++) { scores.add(in.nextInt()); //System.out.print(scores.get(j)); int modulus=scores.get(j)%3; int temp = scores.get(j); switch (modulus) { case 0: if (((temp / 3) >= atLeastP)) { BestResults++; } else { if (((((temp / 3) + 1) >= atLeastP) && ((temp / 3) >= 1)) && (Surprising < NoOfSurprisingResults)) { BestResults++; Surprising++; } System.out.println("Case 0"+"itr:"+i+" surprising:"+temp); } break; case 1: if ((temp / 3) + 1 >= atLeastP) { BestResults++; continue; } break; case 2: if ((temp / 3) + 1 >= atLeastP) { BestResults++; } else { if (((temp / 3) + 2 >= atLeastP) && (Surprising < NoOfSurprisingResults)) { BestResults++; Surprising++; } System.out.println("Case 2"+"itr:"+i+" surprising:"+temp); } break; default: System.out.println("Error"); } }// Internal for out.println(BestResults); // System.out.println(BestResults); System.out.println(Surprising); BestResults = 0; }// for in.close(); out.close(); fos.close(); } }
/** * */ 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); } }
A10996
A11214
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); } } }
package problemb; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class DancingWithTheGooglers { public static void main(String[] args) { int T = 1; String G = ""; String[] inputs; BufferedReader reader; reader = new BufferedReader(new InputStreamReader(System.in)); try { T = Integer.parseInt(reader.readLine()); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } StringBuffer buffer = new StringBuffer(); for (int X = 1; X <= T; X++) { try { G = reader.readLine(); inputs = G.split(" "); int N = Integer.parseInt(inputs[0]); int S = Integer.parseInt(inputs[1]); int p = Integer.parseInt(inputs[2]); int[] t; if (inputs.length - 3 > N) { t = new int[N]; } else { t = new int[inputs.length - 3]; } for (int i = 0; i < t.length; i++) { t[i] = Integer.parseInt(inputs[i + 3]); } int surprizing = 0; Arrays.sort(t); int result = 0; for (int j = t.length - 1; j >= 0; j--) { if(p==0){ result = t.length; break; } int dev = t[j] / 3; int mod = t[j] % 3; if (dev >= p) { result++; continue; } if (mod == 1 && dev + 1 >= p) { result++; continue; } if (mod == 2 && dev + 1 >= p) { result++; continue; } if (mod == 2 && dev + 2 >= p && surprizing < S) { surprizing++; result++; continue; } if (mod == 0 && dev > 0 && dev + 1 >= p && surprizing < S) { surprizing++; result++; continue; } } buffer.append("Case #").append(X).append(": ").append(result) .append("\r\n"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(buffer.toString()); } }
A22992
A22149
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.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class B { public static int convert(String input) { int output = 0; String[] pairs = input.split(" "); // int N = Integer.parseInt(pairs[0]); int S = Integer.parseInt(pairs[1]); int P = Integer.parseInt(pairs[2]); int[] numbers = new int[pairs.length - 3]; for (int i = 3; i < pairs.length; i++) { numbers[i - 3] = Integer.parseInt(pairs[i]); } boolean[] done = new boolean[numbers.length]; boolean[] five = new boolean[numbers.length]; boolean[] sur = new boolean[numbers.length]; for (int i = 0; i < numbers.length; i++) { int num = numbers[i]; for (int j = P; j <= num; j++) { if ((3 * j) == num || ((j + (j - 1) + (j - 1)) == num && ((j-1)>=0)) || ((j + j + (j - 1)) == num && ((j-1)>=0)) || (j + (j + 1) + (j + 1)) == num || (j + j + (j + 1)) == num ) { // System.out.println("1 : "+num); done[i] = true; five[i] = true; sur[i] = false; break; } } } int surprised = 0; for (int i = 0; i < numbers.length && surprised < S; i++) { if (!done[i]) { int num = numbers[i]; for (int j = P; j <= num; j++) { if ( (((j - 2) + (j - 1) + (j)) == num&& ((j-1)>=0)&& ((j-2)>=0)) || (((j - 2) + (j) + (j)) == num && ((j-2)>=0)) || (((j - 2) + (j - 2) + (j)) == num && ((j-2)>=0)) || ((j + 2) + (j + 1) + (j)) == num || ((j + 2) + (j) + (j)) == num || ((j + 2) + (j + 2) + (j)) == num ) { // System.out.println("2 : "+num); done[i] = true; five[i] = true; sur[i] = true; surprised ++; break; } } } } if(surprised < S){ for (int i = 0; i < numbers.length && surprised < S; i++) { if (!done[i]) { int num = numbers[i]; for (int j = 0; j <= num; j++) { if ( (((j - 2) + (j - 1) + (j)) == num&& ((j-1)>=0)&& ((j-2)>=0)&& ((j-1)!=P)&& ((j-2)!=P)&& ((j)!=P)) || (((j - 2) + (j) + (j)) == num && ((j-2)>=0)&& ((j-2)!=P)&& ((j)!=P)) || (((j - 2) + (j - 2) + (j)) == num && ((j-2)>=0)&&((j-2)!=P)&& ((j)!=P)) ) { // System.out.println("3 : "+num); done[i] = true; five[i] = false; sur[i] = true; surprised ++; break; } } } } } if(surprised < S){ for (int i = 0; i < numbers.length && surprised < S; i++) { if (!sur[i]&&five[i]) { int num = numbers[i]; for (int j = P; j <= num; j++) { if ( (((j - 2) + (j - 1) + (j)) == num&& ((j-1)>=0)&& ((j-2)>=0)) || (((j - 2) + (j) + (j)) == num && ((j-2)>=0)) || (((j - 2) + (j - 2) + (j)) == num && ((j-2)>=0)) || ((j + 2) + (j + 1) + (j)) == num || ((j + 2) + (j) + (j)) == num || ((j + 2) + (j + 2) + (j)) == num ) { // System.out.println("4 : "+num); done[i] = true; five[i] = true; sur[i] = true; surprised ++; break; } } } } } if(surprised < S){ for (int i = 0; i < numbers.length && surprised < S; i++) { if (!sur[i]&&five[i]) { int num = numbers[i]; for (int j = 0; j <= num; j++) { if ( (((j - 2) + (j - 1) + (j)) == num&& ((j-1)>=0)&& ((j-2)>=0)&& ((j-1)!=P)&& ((j-2)!=P)&& ((j)!=P)) || (((j - 2) + (j) + (j)) == num && ((j-2)>=0)&& ((j-2)!=P)&& ((j)!=P)) || (((j - 2) + (j - 2) + (j)) == num && ((j-2)>=0)&&((j-2)!=P)&& ((j)!=P)) ) { // System.out.println("5 : "+num); done[i] = true; five[i] = false; sur[i] = true; surprised ++; break; } } } } } // if(surprised < S) // System.out.println("lesaa"); // System.out.println(surprised + "----"+S); for (int i = 0; i < sur.length; i++) { if(five[i]) output++; } return output; } public static void main(String[] args) { String inputFile = "B-large.in"; String outPutFile = "B-large.out"; try { FileInputStream fstream = new FileInputStream(inputFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fstream2 = new FileWriter(outPutFile); BufferedWriter out = new BufferedWriter(fstream2); String strLine; strLine = br.readLine(); int casesNum = Integer.parseInt(strLine); for (int i = 0; i < casesNum; i++) { strLine = br.readLine(); String parse = "Case #" + (i + 1) + ": " + convert(strLine); System.out.println(parse); if (i < casesNum - 1) parse += "\n"; out.write(parse); } in.close(); out.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } }
B12669
B12266
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 RecycledNumbers { public RecycledNumbers() {} public Integer count(String num, int A, int B) { int count = 0; Integer numS = new Integer(num); for (int i = 1; i < num.length(); i++) { Integer newNum = new Integer(num.substring(i) + num.substring(0, i)); if (newNum <= B && newNum > A && newNum > numS) { count++; //System.out.println("(" + numS + ", " + newNum + ")"); } } return count; } public static void main(String[] args) { RecycledNumbers rn = new RecycledNumbers(); try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; Integer T; int cn = 0; while ((line = in.readLine()) != null) { if (cn == 0) { T = new Integer(line); cn++; } else { int count = 0; String[] AB = line.split(" "); int A = new Integer(AB[0]); int B = new Integer(AB[1]); for (int n = A; n < B; n++) { count += rn.count(Integer.toString(n), A, B); } System.out.println("Case #" + cn + ": " + count); cn++; } } } catch (Exception e) {} } }
A11917
A11243
0
package com.silverduner.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; public class Dancing { public static void main(String[] args) throws Exception { File input = new File("B-small-attempt0.in"); BufferedReader in = new BufferedReader(new FileReader(input)); File output = new File("1.out"); BufferedWriter out = new BufferedWriter(new FileWriter(output)); // parse input int N = Integer.parseInt(in.readLine()); for(int i=0;i<N;i++) { String str = in.readLine(); out.write("Case #"+(i+1)+": "); System.out.println("-------"); String[] words = str.split(" "); int n = Integer.parseInt(words[0]); int suprise = Integer.parseInt(words[1]); int threshold = Integer.parseInt(words[2]); int[] scores = new int[n]; for(int j=0;j<n;j++) { scores[j] = Integer.parseInt(words[3+j]); } int count = 0; for(int score : scores) { int a,b,c; boolean find = false; boolean sfind = false; for(a = 10; a>=0 && !find; a--) { if(3*a-4>score) continue; for(b = a; b>=0 && b >=a-2 && !find; b--) { for(c = b; c>=0 && c >=b-2 && c >=a-2 && !find; c--) { System.out.println(a+","+b+","+c); if(a+b+c==score) { if(a >= threshold) { if(a-c <= 1){ count++; find = true; System.out.println("find!"); } else if(a-c == 2){ sfind = true; System.out.println("suprise!"); } } } } } } if(!find && sfind && suprise > 0) { count++; suprise --; } } int maxCount = count; out.write(maxCount+"\n"); } out.flush(); out.close(); in.close(); } }
/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib.converters; import com.isotopeent.codejam.lib.InputConverter; import com.isotopeent.codejam.lib.Utils; public class IntArrayLine implements InputConverter<int[]> { private int length; private int[] input; private int[] inputBuffer; /** * fixed length arrays */ public IntArrayLine(int length) { this.length = length; } /** * dynamic length arrays */ public IntArrayLine(int[] buffer) { inputBuffer = buffer; } @Override public boolean readLine(String data) { if (length > 0) { input = new int[length]; input = Utils.convertToIntArray(data, length); } else { int count = Utils.convertToIntArray(data, inputBuffer); input = new int[count]; System.arraycopy(inputBuffer, 0, input, 0, count); } return false; } @Override public int[] generateObject() { return input; } }
B10361
B12999
0
package codejam; import java.util.*; import java.io.*; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("in.txt")); PrintWriter out = new PrintWriter(new File("out.txt")); int T = Integer.parseInt(in.readLine()); for (int t = 1; t <= T; ++t) { String[] parts = in.readLine().split("[ ]+"); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); int cnt = 0; for (int i = A; i < B; ++i) { String str = String.valueOf(i); int n = str.length(); String res = ""; Set<Integer> seen = new HashSet<Integer>(); for (int j = n - 1; j > 0; --j) { res = str.substring(j) + str.substring(0, j); int k = Integer.parseInt(res); if (k > i && k <= B) { //System.out.println("(" + i + ", " + k + ")"); if (!seen.contains(k)) { ++cnt; seen.add(k); } } } } out.println("Case #" + t + ": " + cnt); } in.close(); out.close(); System.exit(0); } }
package mgg.problems; import mgg.utils.FileUtil; /** * @author manolo * @date 14/04/12 */ public class ProblemD { public final static String EXAMPLE_IN = "D-example.in"; public final static String EXAMPLE_OUT = "D-example.out"; public final static String D_SMALL_IN = "D-small-practice.in"; public final static String D_SMALL_OUT = "D-small-practice.out"; public final static String D_LARGE_IN= "D-large-practice.in"; public final static String D_LARGE_OUT = "D-large-practice.out"; public final static String delim = " "; public static String solve(FileUtil util) { //TODO return null; } }
A22191
A21126
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.codejam.qualification.b; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; public class DancingWithGooglers { private Map<String, String> language = new HashMap<String, String>(); public void main() throws IOException { List<String> inputLines = FileUtils.readLines(new File("B-large.in")); int numberOfCases = Integer.parseInt(inputLines.get(0)); List<String> outputLines = new ArrayList<String>(); for (int idx = 1; idx < numberOfCases + 1; idx++) { int[] numbers = getNumbersForLine(inputLines, idx); int numberOfGooglersDancing = numbers[0]; int numberOfSuprisingTriplets = numbers[1]; int resultBetterThan = numbers[2]; int countSimilarScores = 0; int countSuprisingScores = 0; int possibleGoodResult = resultBetterThan * 3 - 2; int possibleEdgeResult = resultBetterThan * 3 - 4; for (int resultIdx = 3; resultIdx < numbers.length; resultIdx++) { int result = numbers[resultIdx]; if (result < resultBetterThan) continue; if (result >= possibleGoodResult) { countSimilarScores++; } else if (result >= possibleEdgeResult) { countSuprisingScores++; } } int maximumResultsAbove = countSimilarScores; if (countSuprisingScores > numberOfSuprisingTriplets) { countSuprisingScores = numberOfSuprisingTriplets; } maximumResultsAbove += countSuprisingScores; outputLines.add("Case #" + idx + ": " + maximumResultsAbove); } FileUtils.writeLines(new File("out.txt"), outputLines); } private int[] getNumbersForLine(List<String> outputLines, int idx) { String rawNumbers[] = outputLines.get(idx).split(" "); int numbers[] = new int[rawNumbers.length]; for (int javaSux = 0; javaSux < rawNumbers.length; javaSux++) { numbers[javaSux] = Integer.parseInt(rawNumbers[javaSux]); } return numbers; } }
A12460
A12613
0
/** * */ package pandit.codejam; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Scanner; /** * @author Manu Ram Pandit * */ public class DancingWithGooglersUpload { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { FileInputStream fStream = new FileInputStream( "input.txt"); Scanner scanner = new Scanner(new BufferedInputStream(fStream)); Writer out = new OutputStreamWriter(new FileOutputStream("output.txt")); int T = scanner.nextInt(); int N,S,P,ti; int counter = 0; for (int count = 1; count <= T; count++) { N=scanner.nextInt(); S = scanner.nextInt(); counter = 0; P = scanner.nextInt(); for(int i=1;i<=N;i++){ ti=scanner.nextInt(); if(ti>=(3*P-2)){ counter++; continue; } else if(S>0){ if(P>=2 && ((ti==(3*P-3)) ||(ti==(3*P-4)))) { S--; counter++; continue; } } } // System.out.println("Case #" + count + ": " + counter); out.write("Case #" + count + ": " + counter + "\n"); } fStream.close(); out.close(); } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public abstract class FileReaderWriter { FileInputStream in; FileWriter out; BufferedReader br; BufferedWriter bw; String strLine; String outPath; int nTestCases; FileReaderWriter(String inPath, String outPath) throws FileNotFoundException { in = new FileInputStream(inPath); br = new BufferedReader(new InputStreamReader(in)); this.outPath = outPath; } public void reader() throws IOException { } public void writer() throws IOException { //String test = ClassLoader.getSystemResource(".").getPath(); out = new FileWriter(this.outPath); bw = new BufferedWriter(out); } }
A20490
A21980
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); } }
import java.util.*; class B{ public static void main(String... arg){ Scanner sc = new Scanner(System.in); int cases = sc.nextInt(); for(int caseNo = 1; caseNo <= cases; caseNo++ ){ int N = sc.nextInt(); int S = sc.nextInt(); int p = sc.nextInt(); int[] t = new int[N]; int n = 0; for(int i = 0; i < N; i++) t[i] = sc.nextInt(); if(p == 0) System.out.println("Case #" + caseNo + ": " + N); else{ for(int i = 0; i < N; i++){ int tmp = ((int)(t[i]/3)); if(t[i] == 0) tmp = 0; else{ if(t[i] % 3 != 0) tmp = tmp + 1; } if(tmp >= p) n++; } if (S == 0) System.out.println("Case #" + caseNo + ": " + n); else{ Arrays.sort(t); for(int i = N-n-1; i >= 0 && S > 0; i--){ int tmp = ((int)(t[i]/3)); if(t[i] == 0) tmp = 0; else{ int rem = t[i] % 3; if(rem == 2 && t[i] <= 28) tmp = tmp + 2; else if(rem == 0 && t[i] <= 29) tmp = tmp + 1; else continue; } if(tmp >= p) { n++; S--; } } System.out.println("Case #" + caseNo + ": " + n); } } } } }
B10245
B13172
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; } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; public class RecycledNumber { private void solve(BufferedReader f, PrintWriter out) throws IOException { int T = read(f); HashSet<String> set = new HashSet<String>(); for (int i=0; i<T; i++) { int count = 0; int[] a = read(f, 2); int A = a[0]; int B = a[1]; for (int n=A; n<B; n++) { String s = "" + n; for (int j=0; j<s.length()-1; j++) { s = s.substring(1) + s.charAt(0); if (s.charAt(0) == '0' || set.contains(s)) continue; set.add(s); int m = Integer.parseInt(s); if (m > n && m <= B) { count++; } } set.clear(); } out.println("Case #" + (i+1) + ": " + count); } } public int read(BufferedReader f) throws IOException { return Integer.parseInt(f.readLine()); } public int[] read(BufferedReader f, int N) throws IOException { String[] t = f.readLine().split(" "); int[] a = new int[N]; for (int i=0; i<N; i++) { a[i] = Integer.parseInt(t[i]); } return a; } public static void main(String[] args) throws IOException { String name = "C-small-attempt0"; BufferedReader f = new BufferedReader(new FileReader("F:/CodeJam/problem3/" + name + ".in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter( "F:/CodeJam/problem3/" + name + ".out"))); new RecycledNumber().solve(f, out); out.close(); } }
B11318
B10368
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; } }
/* * 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; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; /** * * @author acer */ public class C { /** * @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()); int A, B; for (int i = 0; i < T; i++) { String[] temp = br.readLine().split(" "); A = Integer.parseInt(temp[0]); if (A < 12) { A = 12; } B = Integer.parseInt(temp[1]); if (B < A) { output.write(("Case #" + (i + 1) + ": " + "0" + "\n").getBytes()); continue; } int j = A, count = 0; while (j <= B) { String thisNo = new Integer(j).toString(); Set<Integer> intSet = new HashSet<Integer>(); for (int k = 1; k < thisNo.length(); k++) { int newNo = Integer.parseInt(thisNo.substring(thisNo.length() - k) + thisNo.substring(0, thisNo.length() - k)); if (newNo <= B && Integer.parseInt(thisNo) < newNo && !intSet.contains(newNo)) { count++; intSet.add(newNo); } } j++; } output.write(("Case #" + (i + 1) + ": " + count + "\n").getBytes()); } } }
B11318
B12053
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.util.*; public class Recycled { public static void main(String args[]) { Scanner in=new Scanner(System.in); int cases=in.nextInt(); for(int i=1; i<=cases; i++) { int a=in.nextInt(), b=in.nextInt(); long ans=0; for(int x=a; x<=b; x++) { for(int y=x+1; y<=b; y++) { String one=Integer.toString(x), two=Integer.toString(y); if(one.length()!=two.length()) break; for(int s=1; s<two.length(); s++) { String temp=two.substring(s)+two.substring(0, s); if(temp.equals(one)) { ans++; break; } } } } System.out.printf("Case #%d: %d%n",i,ans); } } }
B20006
B22044
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; } }
package google.problems; import google.loader.Challenge; public abstract class AbstractChallenge implements Challenge{ private final int problemNumber; private String result; public AbstractChallenge(int i) { this.problemNumber = i; } protected void setResult(String result){ this.result = result; } @Override public String getResult() { return "Case #"+problemNumber+": "+result+"\n"; } protected int getInt(int pos, String[] tokens) { return Integer.parseInt(tokens[pos]); } }
B10231
B13157
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.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * Problem Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers. Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros. Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A ² n < m ² B? Input The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B. Output For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A ² n < m ² B. Limits 1 ² T ² 50. A and B have the same number of digits. Small dataset 1 ² A ² B ² 1000. Large dataset 1 ² A ² B ² 2000000. Sample Input Output 4 1 9 10 40 100 500 1111 2222 Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 Are we sure about the output to Case #4? Yes, we're sure about the output to Case #4. * @author andrey * */ public class QCRecycledNumbers { private static int[] INT_LENGTH = new int[] {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000}; public static void solve(BufferedReader reader, BufferedWriter writer) throws IOException { int testCount = readIntFromLine(reader); for (int test = 1; test <= testCount; test++) { writer.append("Case #").append(Integer.toString(test)).append(": "); solveTestCase(reader, writer); writer.newLine(); } writer.flush(); } private static void solveTestCase(BufferedReader reader, BufferedWriter writer) throws IOException { String[] testCase = reader.readLine().split("\\s"); int minValue = Integer.parseInt(testCase[0]); int maxValue = Integer.parseInt(testCase[1]); int length = testCase[0].length(); if (minValue >= maxValue) { writer.append('0'); return; } int recycledCount = 0; int recycledNumber; int lowerPart; int foundRecycledNumbersCount; int[] foundRecycledNumbers = new int[length - 1]; for (int i = minValue; i < maxValue; i++) { foundRecycledNumbersCount = 0; for (int j=1; j < length; j++) { lowerPart = i % INT_LENGTH[j]; if (lowerPart < INT_LENGTH[j - 1]) { // can't rotate, because first digit in lowerPart is 0 continue; } recycledNumber = lowerPart*INT_LENGTH[length - j] + i/INT_LENGTH[j]; if (recycledNumber <= i || recycledNumber > maxValue) { // recycled number exceeds limits continue; } boolean duplicate = false; for (int k=0; k < foundRecycledNumbersCount; k++) { if (foundRecycledNumbers[k] == recycledNumber) { duplicate = true; break; } } if (duplicate) { continue; // such permutation already found } // if (foundRecycledNumbersCount == 0) { // System.out.print(i + " -> "); // } // System.out.print(recycledNumber + ", "); foundRecycledNumbers[foundRecycledNumbersCount++] = recycledNumber; recycledCount++; } // if (foundRecycledNumbersCount > 0) { // System.out.println(); // } } writer.append(Integer.toString(recycledCount)); } public static void solve(String inputFile, String outputFile) throws IOException { File input = new File(inputFile); File output = new File(outputFile); if (!input.exists()) { throw new IllegalArgumentException("Input file doesn't exist: " + inputFile); } BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(input)); writer = new BufferedWriter(new FileWriter(output)); solve(reader, writer); } finally { if (reader != null) reader.close(); if (writer != null) writer.close(); } } public static int readIntFromLine(BufferedReader reader) throws IOException { String line = reader.readLine(); int testCount = Integer.parseInt(line); return testCount; } public static void main(String[] args) throws IOException { System.out.println("Start..."); solve("res/input.txt", "res/output.txt"); System.out.println("Done!"); } }
B12570
B12214
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 hk.polyu.cslhu.codejam.thread; import hk.polyu.cslhu.codejam.lib.ResultCollector; import hk.polyu.cslhu.codejam.solution.Solution; import java.util.List; import org.apache.log4j.Logger; public abstract class JamThread implements Runnable { public static Logger logger = Logger.getLogger(JamThread.class); private ResultCollector resultCollector; private int indexOfList; private List<List<String>> testCaseList; private Solution solution; /** * Return the solution * * @return Solution */ public Solution getSolution() { return solution; } /** * Set the solution used for test cases * * @param solution Solution */ public void setSolution(Solution solution) { this.solution = solution; } /** * Return the result collector * * @return ResultCollector */ public ResultCollector getResultCollector() { return resultCollector; } /** * Set the result collector * * @param resultCollector ResultCollector */ public void setResultCollector(ResultCollector resultCollector) { this.resultCollector = resultCollector; } /** * Return the index of list * * @return int The index of list */ public int getIndexOfList() { return indexOfList; } /** * Set the index of list * * @param indexOfList int The index of list */ public void setIndexOfList(int indexOfList) { this.indexOfList = indexOfList; } /** * Set the list of test cases * * @param testCaseList List<LIst<String>> */ public void setTestCaseList(List<List<String>> testCaseList) { this.testCaseList = testCaseList; logger.debug("Total " + testCaseList.size() + " test cases have been added"); } /** * Get the list of test cases * * @return List<List<String>> The list of test cases */ public List<List<String>> getTestCaseList() { return this.testCaseList; } public abstract void run(); }
A22992
A22245
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 dancingwiththegooglers; import inout.In; import inout.Out; import java.util.ArrayList; import java.util.Collections; public class Main { public static void main(String[] args) throws Exception { String[] strings = In.read("B-large.in", 1); int cont = 1; for (String str : strings) { String[] split = str.split(" "); int number = Integer.parseInt(split[0]); int surprises = Integer.parseInt(split[1]); int atLeast = Integer.parseInt(split[2]); ArrayList<Integer> scores = new ArrayList<Integer>(number); for (int i = 0; i < number; i++) { scores.add(Integer.parseInt(split[i + 3])); } Collections.sort(scores); int maxGooglers = 0; int newSurprises = 0; boolean mores = surprises == 0 ? false : true; for (int i = 0; i < number; i++) { int score = scores.get(i); int result = score / 3; int rest = score % 3; if (rest != 0) { if (result + rest <= 10 && (mores || rest != 2)) { if (result + rest >= atLeast) { maxGooglers++; } if (rest == 2) { newSurprises++; } } else { if (result + 1 >= atLeast) { maxGooglers++; } if (result + 1 == 2) { newSurprises++; } } } else { if (result > 0 && result < 10 && mores) { if (result + 1 >= atLeast) { maxGooglers++; } newSurprises++; } else { if (result >= atLeast) { maxGooglers++; } } } if (newSurprises == surprises) { mores = false; } } Out.write("output.txt", cont++, maxGooglers + ""); } } }
B10702
B12430
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 CodeJamC { public static void main (String[] args) throws IOException { int i, j, k; long startTime = System.currentTimeMillis(); File inFile = new File("C-small-attempt0.in"); // File to read from File outFile = new File("C-small.out"); BufferedReader reader = new BufferedReader(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); String line = null; line = reader.readLine(); int cases = Integer.parseInt(line); int counter = 1; while ((line=reader.readLine()) != null) { int A,B; int pairs = 0; String[] node = line.split(" "); A = Integer.parseInt(node[0]); B = Integer.parseInt(node[1]); if ((node[0].length() == 1) || (A == B)) { ; } else if (node[0].length() == 2) { for(i = A; i <= B; i++) { int oneth = i % 10; int tenth = i /10; int newNum = oneth*10+tenth; if(newNum > i && newNum <= B) pairs++; } } else if (node[0].length() == 3) { for(i = A; i <= B; i++) { int oneth = i % 10; int tenth = (i /10) % 10; int hunth = i /100; int newNum1 = oneth*100+hunth*10+tenth; int newNum2 = tenth*100+oneth*10+hunth; if(newNum1 > i && newNum1 <= B) pairs++; if(newNum2 > i && newNum2 <= B) pairs++; } } //System.out.println("Case #"+counter+": "+pairs); writer.write("Case #"+counter+": "+pairs); writer.newLine(); counter++; } writer.close(); long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; System.out.println("Total Time: " + totalTime); } }
A22191
A21831
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 ? " *" : "")); // } }
import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: Linkov Mikl * Date: 15.04.12 * Time: 2:51 * To change this template use File | Settings | File Templates. */ public class ProblemB { public static void main(String [] args) { Scanner scanner = new Scanner(System.in); int testCount = scanner.nextInt(); for (int i = 0; i < testCount; i++) { int n = scanner.nextInt(); int s = scanner.nextInt(); int p = scanner.nextInt(); int answer = 0; for (int j = 0; j < n; j++) { int point = scanner.nextInt(); int flag = 0; int max1 = -1; int max2 = -1; for (int k1 = 0; k1 < 11; k1++) { for (int k2 = 0; k2 < 11; k2++) { for (int k3 = 0; k3 < 11; k3++) { if (k3 + k2 + k1 == point) { if ((Math.abs(k3 - k2) < 3) && (Math.abs(k1 - k2) < 3) && (Math.abs(k3 - k1) < 3)) { if ((Math.abs(k3 - k2) == 2) || (Math.abs(k2 - k1) == 2) || (Math.abs(k3 - k1) == 2)) { flag = 1; max1 = Math.max(k1, max1); max1 = Math.max(k2, max1); max1 = Math.max(k3, max1); } else { max2 = Math.max(k1, max2); max2 = Math.max(k2, max2); max2 = Math.max(k3, max2); } } } } } } if (max2 >= p) { answer++; } else { if (s > 0) { if (max1 >= p) { answer++; s--; } } } } System.out.println("Case #" + (i + 1) + ": " + answer); } } }
A11201
A11119
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); } } }
package jam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; public class Dance { public static void main(String[] x)throws IOException{ File file=new File("A.in"); Writer output = null; File out=new File("A.out"); output = new BufferedWriter(new FileWriter(out)); BufferedReader fileIn = new BufferedReader(new FileReader(file)); String fileLine,delims,outs; String[] tokens; int cases,num,surprise,goal,ans,indA,indB,i; int [] items; fileLine=fileIn.readLine(); cases = Integer.parseInt(fileLine); delims = "[ ]+"; System.out.println("Cases = "+cases); for (i=0;i<cases;++i) { output.write("Case #"); output.write(Integer.toString(i+1)); output.write(": "); fileLine=fileIn.readLine(); tokens = fileLine.split(delims); num = Integer.parseInt(tokens[0]); surprise = Integer.parseInt(tokens[1]); goal = Integer.parseInt(tokens[2]); items = new int[tokens.length-3]; transfer(items,tokens); ans = solve(goal,surprise,items); output.write(Integer.toString(ans)); output.write("\r\n"); System.out.println(ans); } output.close(); } private static int solve(int goal, int surprise, int[] items) { int rej,acc,i,out,s; s = surprise; out = 0; rej = 3*goal-4; if(rej<1) { rej = 1; } acc = 3*goal-3; for(i=0;i<items.length;++i) { if(items[i]>acc) { ++out; } else if(items[i]>=rej&&s>0) { ++out; --s; } else { } } return out; } private static void transfer(int[] items, String[] tokens) { int size = tokens.length; int i = 3; for(i = 3;i<size;++i) { items[i-3] = Integer.parseInt(tokens[i]); } return; } }
B12762
B10782
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); } } }
//import java.io.*; import java.util.*; public class ProblemC { public static void main(String[] args) { /* try { System.setIn(new FileInputStream("c-example.in")); } catch (Exception e) {} */ new ProblemC(); } public ProblemC() { Scanner input = new Scanner(System.in); int cases = input.nextInt(); for (int n = 0; n < cases; n++) { int lower = input.nextInt(); int upper = input.nextInt(); System.out.println("Case #" + (n+1) + ": " + findPairs(lower, upper)); } } private int findPairs(int lower, int upper) { List<Integer> pairs = new ArrayList<Integer>(); for (int i = lower; i <= upper; i++) { List<Integer> p = recycle(i); for (int j : p) { if (j >= i && j <= upper) { pairs.add(j); //System.out.println(i + ", " + j); } } } return pairs.size(); } private List<Integer> recycle(int n) { List<Integer> p = new ArrayList<Integer>(); int m = n; int len = Integer.toString(n).length(); int mult = (int)Math.pow(10, len - 1); for (int i = 0; i < len; i++) { int d = m % 10; m /= 10; m += (d * mult); if (m != n && len == Integer.toString(m).length() && !p.contains(m)) { p.add(m); } } return p; } }
A20261
A20803
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; } }
package be.mokarea.gcj.common; import java.io.FileWriter; import java.io.PrintWriter; import java.io.Writer; public abstract class GoogleCodeJamBase<T extends TestCase> { protected abstract Transformation<T> createTransformation(TestCaseReader<T> testCaseReader, PrintWriter outputWriter) throws Exception; protected abstract String getOutputFileName() throws Exception; protected abstract TestCaseReader<T> getTestCaseReader() throws Exception; public void execute() { try { PrintWriter outputWriter = null; try { outputWriter = new PrintWriter(new FileWriter(getOutputFileName())); Transformation<T> transformation = createTransformation(getTestCaseReader(),outputWriter); transformation.transformAll(); outputWriter.flush(); } finally { closeQuietly(outputWriter); } } catch (Throwable t) { t.printStackTrace(); } } private void closeQuietly(Writer outputWriter) { if (outputWriter != null) { try { outputWriter.close(); } catch (Throwable t) { t.printStackTrace(); } } } }
B10702
B13232
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.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class ProblemC { public static void main(String[] args) throws NumberFormatException, IOException{ BufferedReader reader=new BufferedReader(new FileReader(new File(args[0]))); int numTestCases=Integer.parseInt(reader.readLine()); String[] split; for (int testCase=0; testCase<numTestCases; testCase++){ split=reader.readLine().split("\\s+"); int a=Integer.parseInt(split[0]); int b=Integer.parseInt(split[1]); String stra=String.valueOf(a); String curr; int currVal; int len=stra.length(); Set<String> iCanHasPair=new HashSet<String>(); int result=0; for (int i=a; i<=b; i++){ curr=String.valueOf(i); boolean inRange; for (int k=1; k<len; k++){ currVal=0; inRange=true; for (int j=0; j<len; j++){ currVal+=((int)Math.pow(10, len-j-1))*(curr.charAt((j+k)%len)-'0'); if (currVal>b){ inRange=false; break; } } if (currVal<a) continue; if (!inRange) continue; if (i!=currVal){ String key=i<currVal?i+":"+currVal:currVal+":"+i; if (!iCanHasPair.contains(key)){ iCanHasPair.add(key); result++; } } } } System.out.println("Case #"+(testCase+1)+": "+result); } } }
B20734
B21015
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.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); } } }
B12669
B10199
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.util.*; import java.lang.*; import java.io.*; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class main { /** * @param args */ public static String lireString() // lecture d'une chaine { String ligne_lue = null; try { InputStreamReader lecteur = new InputStreamReader(System.in); BufferedReader entree = new BufferedReader(lecteur); ligne_lue = entree.readLine(); } catch (IOException err) { System.exit(0); } return ligne_lue; } public static Scanner s =new Scanner(System.in); public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Input"); String filename = "C:\\A-small-attempt1.in"; String ligne = ""; int nbrLigne = 0, i=0, j=0,rech=0; char cchar=' '; File f = new File(filename); if (f.exists()) { System.out.println("File exists"); } else { System.out.println("File does not exist"); } String aa="ejpmyslckdxvnribtahwfougqz "; String bb="ourlangeismpbtdhwyxfckjvzq "; String g=""; try { FileInputStream fStream = new FileInputStream(filename); BufferedReader in = new BufferedReader(new InputStreamReader( fStream)); if (in.ready()) { ligne = in.readLine(); nbrLigne = Integer.parseInt(ligne); String res[]=new String[nbrLigne]; for (j = 0; j < nbrLigne; j++) { ligne = in.readLine(); for (i = 0; i < ligne.length(); i++) { g+=bb.charAt(aa.indexOf(ligne.charAt(i))); } System.out.println("Case #"+(j+1)+": "+g); g=""; } } }catch (IOException e) { System.out.println("File input error"); } } }
B20006
B20478
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.*; import java.util.*; import java.math.*; public class Main implements Runnable { static int power = 1; private static String filename; public static void main(String[] args) { if (args.length>0 && args[0].equals("f")) filename = "input.txt"; else filename = ""; new Thread(new Main()).start(); } private static void debug(Object ... str) { for (Object s : str) System.out.print(s + ", "); System.out.println(); } private void check(int x, int y, int ndig) { int temp = x; int[] digx = new int[ndig]; int[] digy = new int[ndig]; for (int i = 0; i < ndig; ++i, temp = temp / 10) { digx[i] = temp % 10; } temp = y; for (int i = 0; i < ndig; ++i, temp = temp / 10) { digy[i] = temp % 10; } boolean equal = false; for (int sh = 1; !equal && sh < ndig; ++sh) { equal = true; for (int i = 0; equal && i < ndig; ++i) { if (digx[(i + sh) % ndig] != digy[i]) { equal = false; } } } if (!equal || x >= y) System.out.println("HAHAHA " + x + " " + y); } public void run() { try{ MyScanner in; Locale.setDefault(Locale.US); if (filename.length()>0) in = new MyScanner(filename); else in = new MyScanner(System.in); PrintWriter out = new PrintWriter(System.out); int T = in.nextInt(); for (int test = 0; test < T; ++test) { int a = in.nextInt(); int b = in.nextInt(); int temp = a; int ndig = 0; while (temp > 0) { temp /= 10; ndig++; } int[] dig = new int[ndig]; power = 1; for (int i = 1; i<ndig; ++i) power *= 10; int ans = 0; boolean[] was = new boolean[2000001]; int[] stack = new int[ndig]; for (int x = a; x <= b; ++x) { temp = x; for (int c = 0; c < ndig; ++c, temp = temp / 10) { dig[c] = temp % 10; if (dig[c] == 0) continue; } int stack_size = 0; int y = x / 10 + dig[0] * power; for (int c = 1; c < ndig; ++c) { if ((x < y && y <= b) && !was[y]) { ans++; stack[stack_size++] = y; was[y] = true; //check(x, y, ndig); } y = y / 10 + dig[c] * power; } for (int i = 0; i < stack_size; ++i) { was[stack[i]] = false; stack[i] = 0; } } out.println("Case #" + (1 + test) + ": " + ans); } out.close(); in.close(); }catch(Exception e) { e.printStackTrace(); } } } class MyScanner { BufferedReader in; StringTokenizer st; MyScanner(String file){ try{ in = new BufferedReader(new FileReader(new File(file))); }catch(Exception e){ e.printStackTrace(); } } MyScanner(InputStream inp){ try{ in = new BufferedReader(new InputStreamReader(inp)); }catch (Exception e){ e.printStackTrace(); } } void skipLine(){ st = null; } boolean hasMoreTokens(){ String s = null; try{ while ((st==null || !st.hasMoreTokens())&& (s=in.readLine()) != null) st = new StringTokenizer(s); if ((st==null || !st.hasMoreTokens())&& s==null) return false; }catch(IOException e){ e.printStackTrace(); } return true; } String nextToken(){ if (hasMoreTokens()){ return st.nextToken(); } return null; } int nextInt(){ return Integer.parseInt(nextToken()); } long nextLong(){ return Long.parseLong(nextToken()); } double nextDouble(){ return Double.parseDouble(nextToken()); } String nextString(){ return nextToken(); } void close(){ try{ in.close(); }catch(IOException e){ e.printStackTrace(); } } }
A12273
A12191
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.util.*; import java.io.*; public class QR_Bsmall { public static void main(String[] args) throws Exception{ // Scanner sc = new Scanner(System.in); // PrintWriter pw = new PrintWriter(System.out); // Scanner sc = new Scanner(new FileReader("input.in")); // PrintWriter pw = new PrintWriter(new FileWriter("output.out")); Scanner sc = new Scanner(new FileReader("B-small-attempt0.in")); PrintWriter pw = new PrintWriter(new FileWriter("B-small-attempt0.out")); int T; int N, S, p; int[] t = new int[100]; int ans; T = sc.nextInt(); for(int times = 1; times <= T; times++){ N = sc.nextInt(); S = sc.nextInt(); p = sc.nextInt(); for(int i = 0; i < N; i++){ t[i] = sc.nextInt(); } ans = 0; for(int i = 0; i < N; i++){ if(t[i] <= 1){ if(p <= t[i]){ ans++; } continue; } t[i] = t[i] - (p * 3); if(t[i] > -3){ ans++; }else if(t[i] > -5 && S > 0){ ans++; S--; } } System.out.print("Case #" + times + ": "); System.out.print(ans); System.out.println(); pw.print("Case #" + times + ": "); pw.print(ans); pw.println(); } sc.close(); pw.close(); } }
A20119
A22654
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.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; public class QualifiRound2012B { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { BufferedReader br = new BufferedReader(new FileReader(args[0])); PrintWriter pw = new PrintWriter(args[1]); String line = br.readLine(); System.out.println(line); int T = Integer.valueOf(line.trim()); for (int i=0; i<T; i++) { line = br.readLine(); System.out.println(line); String[] input = line.trim().split(" "); int N = Integer.valueOf(input[0]); int S = Integer.valueOf(input[1]); int p = Integer.valueOf(input[2]); int good = 0; for(int j=0; j<N; j++) { int score = Integer.valueOf(input[3+j]); if(Math.ceil((double)score/3)>=p) good++; else if(S>0) { if(score==0) { if(p==0) good++; } else if((score%3 != 2)&&(score/3+1>=p) ||(score%3 == 2)&&(score/3+2>=p)) { good++; S--; } } } pw.println("Case #"+(i+1)+": "+good); System.out.println("Case #"+(i+1)+": "+good); } pw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
B21790
B20741
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(); } }
package fixjava; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class CollectionUtils { /** * @return the single value in the collection, throws an exception if there isn't exactly one item. * @throws IllegalArgumentException * if there is more than one value in the set. */ public static <T> T getSingleVal(Collection<T> collection) { if (collection.size() != 1) throw new IllegalArgumentException(collection.size() + " objects in collection, expected exactly 1"); T ret = null; for (T val : collection) { ret = val; break; } return ret; } /** * @return the first value returned by an iterator on the collection, throws an exception if there isn't exactly one item. * @throws IllegalArgumentException * if collection is empty */ public static <T> T getFirstVal(Collection<T> collection) { if (collection.size() == 0) throw new IllegalArgumentException(collection.size() + " objects in collection, expected at least 1"); T ret = null; for (T val : collection) { ret = val; break; } return ret; } // --------------------------------------------------------------------------------------------------------------------- /** * Pass values in an Iterable through a function to produce an ArrayList of mapped values, one output value generated per input * value. Returns null if input is null. */ public static <S, T> ArrayList<T> map(Iterable<S> values, Lambda<S, T> mapFunction) { if (values == null) return null; ArrayList<T> result = new ArrayList<T>(); for (S val : values) result.add(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce an ArrayList of mapped values, one output value generated per input * value. Returns null if input is null. */ public static <S, T> ArrayList<T> map(S[] values, Lambda<S, T> mapFunction) { if (values == null) return null; ArrayList<T> result = new ArrayList<T>(); for (S val : values) result.add(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce an ArrayList of mapped values, zero or more output values generated * per input value. Returns null if input is null. */ public static <S, T> ArrayList<T> mapMultiple(Iterable<S> values, Lambda<S, ? extends Collection<T>> mapFunction) { if (values == null) return null; ArrayList<T> result = new ArrayList<T>(); for (S val : values) result.addAll(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce a HashSet of mapped values, one output value generated per input * value. Returns null if input is null. */ public static <S, T> HashSet<T> mapSet(Iterable<S> values, Lambda<S, T> mapFunction) { if (values == null) return null; HashSet<T> result = new HashSet<T>(); for (S val : values) result.add(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce a HashSet of mapped values, one output value generated per input * value. Returns null if input is null. */ public static <S, T> HashSet<T> mapSet(S[] values, Lambda<S, T> mapFunction) { if (values == null) return null; HashSet<T> result = new HashSet<T>(); for (S val : values) result.add(mapFunction.apply(val)); return result; } /** * Pass values in an Iterable through a function to produce a HashSet of mapped values, zero or more output values generated per * input value. Returns null if input is null. */ public static <S, T> HashSet<T> mapSetMultiple(Iterable<S> values, Lambda<S, ? extends Collection<T>> mapFunction) { if (values == null) return null; HashSet<T> result = new HashSet<T>(); for (S val : values) result.addAll(mapFunction.apply(val)); return result; } // --------------------------------------------------------------------------------------------------------------------- public static <T> HashSet<T> filterSet(Iterable<T> values, Lambda<T, Boolean> filterFunction) { if (values == null) return null; HashSet<T> result = new HashSet<T>(); for (T val : values) if (filterFunction.apply(val)) result.add(val); return result; } public static <T> ArrayList<T> filter(Iterable<T> values, Lambda<T, Boolean> filterFunction) { if (values == null) return null; ArrayList<T> result = new ArrayList<T>(); for (T val : values) if (filterFunction.apply(val)) result.add(val); return result; } public static <T> HashSet<T> filterSet(T[] values, Lambda<T, Boolean> filterFunction) { if (values == null) return null; HashSet<T> result = new HashSet<T>(); for (T val : values) if (filterFunction.apply(val)) result.add(val); return result; } public static <T> ArrayList<T> filter(T[] values, Lambda<T, Boolean> filterFunction) { if (values == null) return null; ArrayList<T> result = new ArrayList<T>(); for (T val : values) if (filterFunction.apply(val)) result.add(val); return result; } // --------------------------------------------------------------------------------------------------------------------- /** * Iterate through multiple Iterables of the same element type, e.g. for (Integer i : CollectionUtils.iterateThroughAllOf(x, y, * z)) { } * * N.B. you will get a warning "Type safety: A generic array of type Iterable<T> is created for a Varargs parameter" (lame * Java). */ @SafeVarargs public static <T> Iterable<T> iterateThroughAllOf(final Iterable<T>... iterables) { if (iterables.length == 0) { return (Iterable<T>) new ArrayList<T>(); } else { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { Iterable<T>[] iters = iterables; int iterIdx = -1; Iterator<T> currIter = null; private void advanceIfNecessary() { if (currIter == null || (iterIdx < iters.length - 1 && !currIter.hasNext())) currIter = iterables[++iterIdx].iterator(); } @Override public boolean hasNext() { advanceIfNecessary(); return iterIdx < iters.length && (iterIdx < iters.length - 1 || currIter.hasNext()); } @Override public T next() { advanceIfNecessary(); if (iterIdx == iters.length) throw new RuntimeException("Out of elements"); return currIter.next(); } @Override public void remove() { advanceIfNecessary(); if (iterIdx == iters.length) throw new RuntimeException("Out of elements"); else currIter.remove(); } }; } }; } } /** * Iterate through multiple Arrays of the same element type, e.g. for (Integer i : CollectionUtils.iterateThroughAllOf(x, y, z)) * { } */ @SafeVarargs public static <T> Iterable<T> iterateThroughAllOf(final T[]... arrays) { if (arrays.length == 0) { return (Iterable<T>) new ArrayList<T>(); } else { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { T[][] arrs = arrays; int arrIdx = 0, arrSubIdx = 0; private void advanceIfNecessary() { if (arrIdx < arrs.length && arrSubIdx == arrs[arrIdx].length) { arrIdx++; arrSubIdx = 0; } } @Override public boolean hasNext() { advanceIfNecessary(); return arrIdx < arrs.length && (arrIdx < arrs.length - 1 || arrSubIdx < arrs[arrIdx].length); } @Override public T next() { advanceIfNecessary(); if (arrIdx == arrs.length) throw new RuntimeException("Out of elements"); return arrs[arrIdx][arrSubIdx++]; } @Override public void remove() { throw new RuntimeException("Not implemented"); } }; } }; } } /** * Iterate through multiple Iterables of the same element type (skipping over null iterables, *not* null elements), e.g. for * (Integer i : CollectionUtils.iterateThroughAllOf(x, y, z)) { } * * N.B. you will get a warning "Type safety: A generic array of type Iterable<T> is created for a Varargs parameter" (lame * Java). */ @SuppressWarnings("unchecked") public static <T> Iterable<T> iterateThroughAllOfIgnoringNulls(Iterable<T>... iterables) { ArrayList<Iterable<T>> filter = filter(iterables, new Lambda<Iterable<T>, Boolean>() { @Override public Boolean apply(Iterable<T> param) { return param != null; } }); Iterable<T>[] nonNulls = new Iterable[filter.size()]; filter.toArray(nonNulls); return iterateThroughAllOf(nonNulls); } /** * Iterate through multiple arrays of the same element type (skipping over null arrays, *not* null elements), e.g. for (Integer * i : CollectionUtils.iterateThroughAllOf(x, y, z)) { } */ @SuppressWarnings("unchecked") public static <T> Iterable<T> iterateThroughAllOfIgnoringNulls(T[]... arrays) { ArrayList<T[]> filter = filter(arrays, new Lambda<T[], Boolean>() { @Override public Boolean apply(T[] param) { return param != null; } }); Iterable<T>[] nonNulls = new Iterable[filter.size()]; filter.toArray(nonNulls); return iterateThroughAllOf(nonNulls); } // public static void main(String[] args) { // ArrayList<Integer> x = new ArrayList<Integer>(); // ArrayList<Integer> y = new ArrayList<Integer>(); // ArrayList<Integer> z = new ArrayList<Integer>(); // x.add(1); // x.add(2); // x.add(3); // y.add(19); // y.add(23); // z.add(100); // z.add(999); // for (Integer i : iterateThroughAllOf(x, y, z)) // System.out.println(i); // Integer[] a = new Integer[3]; // Integer[] b = new Integer[2]; // a[0] = 10; // a[1] = 11; // a[2] = 12; // b[0] = 7; // b[1] = 8; // for (Integer i : iterateThroughAllOf(a, b)) // System.out.println(i); // } /** * Iterate through a varargs list of iterable objects of type T, and return all the objects in a list. Null iterables are * skipped. */ @SafeVarargs public static <T> ArrayList<T> toListIgnoringNulls(Iterable<T>... iterables) { ArrayList<T> result = new ArrayList<T>(); for (T item : iterateThroughAllOfIgnoringNulls(iterables)) result.add(item); return result; } /** * Iterate through a varargs list of iterable objects of type T, and return all the objects in a set (removing duplicates). Null * iterables are skipped. */ @SafeVarargs public static <T> HashSet<T> toSetIgnoringNulls(Iterable<T>... iterables) { return new HashSet<T>(toListIgnoringNulls(iterables)); } // --------------------------------------------------------------------------------------------------------------------- /** * Look up keys in the map, and return a collection of the corresponding values. Returns null if 'keys' is null. * * @throw IllegalArgumentException if key doesn't exist in map or if a key is null, depending on params. */ public static <K, V, C extends Collection<V>> C lookup(Collection<K> keys, Map<K, V> map, LambdaVoid<K> applyIfKeyIsNullWithoutAddingValue, Lambda<K, V> applyIfKeyIsNullAndAddReturnedValue, LambdaVoid<K> applyWhenKeyDoesntExistWithoutAddingValue, Lambda<K, V> applyWhenKeyDoesntExistAndAddReturnedValue, C result) { if (keys == null) return null; for (K key : keys) { V val = null; boolean addValue = false; if (applyIfKeyIsNullWithoutAddingValue != null && key == null) { applyIfKeyIsNullWithoutAddingValue.apply(key); } else if (applyIfKeyIsNullAndAddReturnedValue != null && key == null) { val = applyIfKeyIsNullAndAddReturnedValue.apply(key); addValue = true; } else if (applyWhenKeyDoesntExistWithoutAddingValue != null && !map.containsKey(key)) { applyWhenKeyDoesntExistWithoutAddingValue.apply(key); } else if (applyWhenKeyDoesntExistAndAddReturnedValue != null && !map.containsKey(key)) { val = applyWhenKeyDoesntExistAndAddReturnedValue.apply(key); addValue = true; } else { val = map.get(key); addValue = true; } if (addValue) result.add(val); } return result; } /** * Look up keys in the map, and return an ArrayList of the corresponding values. Returns null if 'keys' is null. * * @throw IllegalArgumentException if key doesn't exist in map or if a key is null, depending on params. */ public static <K, V> ArrayList<V> lookup(Collection<K> keys, Map<K, V> map, boolean throwExceptionIfKeyNull, boolean throwExceptionIfKeyDoesntExist) { if (keys == null) return null; return lookup(keys, map, throwExceptionIfKeyNull ? new LambdaVoid<K>() { @Override public void apply(K key) { throw new IllegalArgumentException("Key is null"); } } : null, null, throwExceptionIfKeyDoesntExist ? new LambdaVoid<K>() { @Override public void apply(K key) { throw new IllegalArgumentException("Could not find key " + key + " in map"); } } : null, null, new ArrayList<V>()); } /** * Look up keys in the map, and return an ArrayList of the corresponding values. Performs no checking. Returns null if 'keys' is * null. */ public static <K, V> ArrayList<V> lookup(Collection<K> keys, Map<K, V> map) { if (keys == null) return null; ArrayList<V> vals = new ArrayList<V>(keys.size()); for (K key : keys) { // Simple version for speed V val = map.get(key); vals.add(val); } return vals; } /** * Look up keys in the map, and return an ArrayList of the corresponding values. Applies the given function if the key doesn't * exist. Returns null if 'keys' is null. */ public static <K, V> ArrayList<V> lookup(Collection<K> keys, Map<K, V> map, LambdaVoid<K> applyWhenKeyDoesntExist) { return lookup(keys, map, null, null, applyWhenKeyDoesntExist, null, new ArrayList<V>()); } /** * Look up keys in the map, and return an ArrayList of the corresponding values. Applies the given function if the key doesn't * exist to produce a default value. Returns null if 'keys' is null. */ public static <K, V> ArrayList<V> lookup(Collection<K> keys, Map<K, V> map, Lambda<K, V> applyWhenKeyDoesntExistToGetDefaultVal) { return lookup(keys, map, null, null, null, applyWhenKeyDoesntExistToGetDefaultVal, new ArrayList<V>()); } /** * Look up keys in the map, and return a HashSet of the corresponding values. Returns null if 'keys' is null. * * @throw IllegalArgumentException if key doesn't exist in map or if a key is null, depending on params. */ public static <K, V> HashSet<V> lookupAsSet(Collection<K> keys, Map<K, V> map, boolean throwExceptionIfKeyNull, boolean throwExceptionIfKeyDoesntExist) { if (keys == null) return null; return lookup(keys, map, throwExceptionIfKeyNull ? new LambdaVoid<K>() { @Override public void apply(K key) { throw new IllegalArgumentException("Key is null"); } } : null, null, throwExceptionIfKeyDoesntExist ? new LambdaVoid<K>() { @Override public void apply(K key) { throw new IllegalArgumentException("Could not find key " + key + " in map"); } } : null, null, new HashSet<V>()); } /** * Look up keys in the map, and return a HashSet of the corresponding values. Performs no checking. Returns null if 'keys' is * null. */ public static <K, V> HashSet<V> lookupAsSet(Collection<K> keys, Map<K, V> map) { if (keys == null) return null; HashSet<V> vals = new HashSet<V>(keys.size()); for (K key : keys) { // Simple version for speed V val = map.get(key); vals.add(val); } return vals; } /** * Look up keys in the map, and return a HashSet of the corresponding values. Applies the given function if the key doesn't * exist. Returns null if 'keys' is null. */ public static <K, V> HashSet<V> lookupAsSet(Collection<K> keys, Map<K, V> map, LambdaVoid<K> applyWhenKeyDoesntExist) { return lookup(keys, map, null, null, applyWhenKeyDoesntExist, null, new HashSet<V>()); } /** * Look up keys in the map, and return a HashSet of the corresponding values. Applies the given function if the key doesn't * exist to produce a default value. Returns null if 'keys' is null. */ public static <K, V> HashSet<V> lookupAsSet(Collection<K> keys, Map<K, V> map, Lambda<K, V> applyWhenKeyDoesntExistToGetDefaultVal) { return lookup(keys, map, null, null, null, applyWhenKeyDoesntExistToGetDefaultVal, new HashSet<V>()); } // --------------------------------------------------------------------------------------------------------------------- /** Take the union of all items in all passed collections/Iterables */ public static <T> HashSet<T> union(Iterable<? extends Iterable<T>> iterables) { HashSet<T> result = new HashSet<T>(); for (Iterable<T> iterable : iterables) for (T item : iterable) result.add(item); return result; } /** Put each item in an array into a set. c.f. makeSet(), toSetIgnoringNulls(). */ public static <T> HashSet<T> union(T[] items) { HashSet<T> result = new HashSet<T>(); for (T item : items) result.add(item); return result; } // --------------------------------------------------------------------------------------------------------------------- /** Varargs constructor for a typed set */ @SafeVarargs public static <T> HashSet<T> makeSet(T... items) { HashSet<T> set = new HashSet<T>(items.length); for (T it : items) set.add(it); return set; } /** Varargs constructor for a typed list */ @SafeVarargs public static <T> ArrayList<T> makeList(T... items) { ArrayList<T> list = new ArrayList<T>(items.length); for (T it : items) list.add(it); return list; } /** Varargs constructor for a typed list, specifying initial capacity */ @SafeVarargs public static <T> ArrayList<T> makeListWithInitialCapacity(int initialCapacity, T... items) { ArrayList<T> list = new ArrayList<T>(Math.max(items.length, initialCapacity)); for (T it : items) list.add(it); return list; } // --------------------------------------------------------------------------------------------------------------------- public static <K, V> ArrayList<Pair<K, V>> mapToListOfPairs(Map<K, V> map) { ArrayList<Pair<K, V>> result = new ArrayList<Pair<K, V>>(); for (Entry<K, V> ent : map.entrySet()) result.add(Pair.make(ent.getKey(), ent.getValue())); return result; } // --------------------------------------------------------------------------------------------------------------------- /** * Generate a sorted ArrayList of values from any collection. Does not sort in-place, but rather sorts a copy of the collection. */ public static <T extends Comparable<T>> ArrayList<T> sortCopy(Collection<T> vals) { ArrayList<T> sorted = new ArrayList<T>(vals); Collections.sort(sorted); return sorted; } /** * Generate a sorted ArrayList of values from any collection, using the specified comparator. Does not sort in-place, but rather * sorts a copy of the collection. */ public static <T> ArrayList<T> sortCopy(Collection<T> vals, Comparator<T> comparator) { ArrayList<T> sorted = new ArrayList<T>(vals); Collections.sort(sorted, comparator); return sorted; } /** * Make a comparator by passing in a lambda that simply returns a comparable field for an object, e.g. * * <code> * CollectionUtils.sort(nodeList, CollectionUtils.makeComparator(new Lambda<Node, String>() { * public String apply(Node obj) { * return obj.getName(); * } * }); * </code> * * This is not much shorter than declaring a comparator in the sort call (and has more overhead), but may be a little simpler or * could reduce code duplication in the comparator. * * @param <O> * The type of the objects to compare * @param <F> * The type of the field to compare * @param getFieldToCompare * A simple getter for the field to compare * @return A comparator that can be used for sorting */ public static <O, F extends Comparable<F>> Comparator<O> makeComparator(final Lambda<O, F> getFieldToCompare) { return new Comparator<O>() { @Override public int compare(O o1, O o2) { return getFieldToCompare.apply(o1).compareTo(getFieldToCompare.apply(o2)); } }; } // --------------------------------------------------------------------------------------------------------------------- /** * Build a map from objects in an Iterable to an index mapping that object to its index in the Iterable. Objects must be unique * (!equals()) or an exception is thrown. */ public static <T> HashMap<T, Integer> buildIndex(Iterable<T> collection) { HashMap<T, Integer> map = new HashMap<T, Integer>(); for (IndexedItem<T> it : IndexedItem.iterate(collection)) if (map.put(it.getItem(), it.getIndex()) != null) throw new IllegalArgumentException( "Duplicate object in collection, cannot uniquely map objects to indices (try buildIndexMulti()?): " + it.getItem()); return map; } /** * Build a map from objects in an array to an index mapping that object to its index in the array. Objects must be unique * (!equals()) or an exception is thrown. */ public static <T> HashMap<T, Integer> buildIndex(T[] arr) { HashMap<T, Integer> map = new HashMap<T, Integer>(); for (IndexedItem<T> it : IndexedItem.iterate(arr)) if (map.put(it.getItem(), it.getIndex()) != null) throw new IllegalArgumentException( "Duplicate object in collection, cannot uniquely map objects to indices (try buildIndexMulti()?): " + it.getItem()); return map; } /** Build a map from objects in a collection to a list of indices containing equal objects. */ public static <T> MultiMapKeyToList<T, Integer> buildIndexMulti(Iterable<T> collection) { MultiMapKeyToList<T, Integer> map = new MultiMapKeyToList<T, Integer>(); for (IndexedItem<T> it : IndexedItem.iterate(collection)) { T o = it.getItem(); map.put(o, it.getIndex()); } return map; } // --------------------------------------------------------------------------------------------------------------------- /** * Count the number of .equal() occurrences of objects of type T in the collection, and produce histogram of the results. The * histogram can be sorted in order of ascending count if desired. */ public static <T> ArrayList<Pair<T, Integer>> countEqualOccurrences(Iterable<T> collection) { CountedSet<T> set = new CountedSet<T>(collection); ArrayList<Pair<T, Integer>> result = new ArrayList<Pair<T, Integer>>(); for (Entry<T, Integer> ent : set.iteratableWithCounts()) result.add(Pair.make(ent.getKey(), ent.getValue())); return result; } /** * Build a histogram of the number of unique objects that occur each number of times. Objects occur multiple times if there are * multiple instances that match with .equals(). Returns a Pair<Integer, Integer> with number of occurrences of each unique * object as left and number of unique objects with that number of occurrences as right. */ public static <T> ArrayList<Pair<Integer, Integer>> buildHistogramOfNumObjectsThatOccurGivenNumberOfTimesSparse( Iterable<T> collection) { // Count unique occurrences of the objects of type T ArrayList<Pair<T, Integer>> counts = countEqualOccurrences(collection); // Now count unique occurrences each of the count values to build the histogram ArrayList<Pair<Integer, Integer>> countCounts = countEqualOccurrences(Pair.getAllRights(counts)); // Sort the result in order of number of occurrences (i.e. left) Pair.sortPairsByLeft(countCounts, true); return countCounts; } /** * Build a histogram of the number of unique objects that occur each number of times. Objects occur multiple times if there are * multiple instances that match with .equals(). Returns an array with the number of occurrences of each unique object as the * index and number of unique objects with that number of occurrences as the value of the array at that index. */ public static <T> int[] buildHistogramOfNumObjectsThatOccurGivenNumberOfTimesNonSparse(Iterable<T> collection) { // Build histogram ArrayList<Pair<Integer, Integer>> histList = buildHistogramOfNumObjectsThatOccurGivenNumberOfTimesSparse(collection); // Desparsify into an array and return int maxAbscissa = histList.isEmpty() ? -1 : histList.get(histList.size() - 1).getLeft(); int[] result = new int[maxAbscissa + 1]; for (Pair<Integer, Integer> pair : histList) result[pair.getLeft()] = pair.getRight(); return result; } // --------------------------------------------------------------------------------------------------------------------- /** Reverse a list */ public static <T> ArrayList<T> reverse(List<T> list) { ArrayList<T> result = new ArrayList<T>(list.size()); for (int i = list.size() - 1; i >= 0; --i) result.add(list.get(i)); return result; } /** * Arrayify/rectangularize a list of lists, inserting the given filler element to make the result rectangular if lists are not * the same length */ public static <T> ArrayList<ArrayList<T>> rectangularize(List<? extends List<T>> input, T filler) { int numRows = input.size(); int numCols = 0; for (int i = 0; i < numRows; i++) numCols = Math.max(numCols, input.get(i).size()); ArrayList<ArrayList<T>> output = new ArrayList<ArrayList<T>>(numRows); for (int i = 0; i < numRows; i++) { ArrayList<T> outRow = new ArrayList<T>(input.get(i)); output.add(outRow); while (outRow.size() < numCols) outRow.add(filler); } return output; } public static <S, T> MultiMapKeyToSet<T, S> invertMap(HashMap<S, T> map) { MultiMapKeyToSet<T, S> result = new MultiMapKeyToSet<T, S>(); for (Entry<S, T> ent : map.entrySet()) result.put(ent.getValue(), ent.getKey()); return result; } }
B20856
B21927
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; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Recycled { public static void main(String[] args) { Scanner s = new Scanner(System.in); int numCases = s.nextInt(); for (int i = 1; i <= numCases; i++) { int a = s.nextInt(); int b = s.nextInt(); int numRecycled = countRecycled(a, b); System.out.printf("Case #%d: %d\n", i, numRecycled); } } private static int countRecycled(int a, int b) { int result = 0; StringBuilder sbB = new StringBuilder(); sbB.append(b); List<Integer> register = new ArrayList<Integer>(); for (int i = a; i <= b; i++) { register.clear(); if (i < 10) continue; StringBuilder sb = new StringBuilder(); sb.append(i); for (int j = sb.length() - 1; j > 0; j--) { StringBuilder newCombinedSb = new StringBuilder(); newCombinedSb.append(sb.substring(j)).append(sb.substring(0, j)); if (newCombinedSb.charAt(0) == '0') continue; if (newCombinedSb.charAt(0) > sbB.charAt(0)) continue; if (newCombinedSb.charAt(0) < sb.charAt(0)) continue; int newCombinedInt = Integer.parseInt(newCombinedSb.toString()); if (newCombinedInt <= b && newCombinedInt > i) { if (!register.contains(newCombinedInt)) { register.add(newCombinedInt); } } } result += register.size(); } return result; } }
A12211
A12266
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.FileReader; import java.io.FileWriter; import java.util.StringTokenizer; public class GoogleDancers{ public static void main(String[] args) throws Exception{ FileReader fr = new FileReader("C:\\Projects\\Learning\\src\\B-small-attempt1.in"); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter("C:\\Projects\\Learning\\src\\BLarge.txt"); int N = new Integer(br.readLine()); for (int cases = 1; cases <= N; cases++) { String str = br.readLine(); StringTokenizer st = new StringTokenizer(str); int numberParticipants = Integer.parseInt(st.nextToken()); int surprise = Integer.parseInt(st.nextToken()); int goodScore = Integer.parseInt(st.nextToken()); int a[] = new int[numberParticipants]; for(int i=0; i< numberParticipants; i++) { a[i] = Integer.parseInt(st.nextToken()); } int count = 0; int possibility = 0; int minToGetGoodScore = Math.max(((3 * goodScore) - 2), 1); System.out.println("minToGetGoodScore" + minToGetGoodScore); int surpriseRange = Math.max(((3* goodScore) - 4), 1); if (goodScore > 0 ) { for (int i = 0; i < numberParticipants; i++) { if (a[i] >= minToGetGoodScore) { count++; System.out.println("Count" + count); } else if (a[i] >= surpriseRange && a[i] < minToGetGoodScore) { possibility++; } }System.out.println("Count" + count); count = count + Math.min(possibility, surprise); System.out.println("Count" + count); } else { count = numberParticipants; } fw.write("Case #" + cases + ": " + count + "\n"); } fw.flush(); fw.close(); } }
A22771
A21430
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.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.Scanner; // Qualification Round 2012 // Problem A public class DancingWithTheGooglers { public static void main(String[] args) { Scanner sc = null; try { sc = new Scanner(new File("B-large.in")); } catch (FileNotFoundException e) { e.printStackTrace(); } PrintStream output = null; try { output = new PrintStream(new File("B-large.out")); } catch (IOException e) { e.printStackTrace(); } int[][] maxScores = new int[31][2]; for(int i = 0; i < 31; i++){ maxScores[i][0] = (int) Math.round((i + 1) / 3.0); if(i < 2 || i > 28) maxScores[i][1] = -1; else maxScores[i][1] = (int) Math.round((i + 3) / 3.0); } int cases = sc.nextInt(); sc.nextLine(); for(int c = 0; c < cases; c++){ int googlers = sc.nextInt(); int surprises = sc.nextInt(); int p = sc.nextInt(); int count = 0; for(int s = 1; s <= googlers; s++){ int score = sc.nextInt(); if(maxScores[score][0] >= p) count++; else if (maxScores[score][1] >= p && surprises > 0){ count++; surprises--; } } System.out.printf("Case #%d: %s\n", c + 1, count); output.printf("Case #%d: %s\n", c + 1, count); } } }
B10899
B11307
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; } }
/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib.converters; import com.isotopeent.codejam.lib.InputConverter; public class StringLine implements InputConverter<String> { private String input; @Override public boolean readLine(String data) { input = data; return false; } @Override public String generateObject() { return input; } }
A11502
A11480
0
package template; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class TestCase { private boolean isSolved; private Object solution; private Map<String, Integer> intProperties; private Map<String, ArrayList<Integer>> intArrayProperties; private Map<String, ArrayList<ArrayList<Integer>>> intArray2DProperties; private Map<String, Double> doubleProperties; private Map<String, ArrayList<Double>> doubleArrayProperties; private Map<String, ArrayList<ArrayList<Double>>> doubleArray2DProperties; private Map<String, String> stringProperties; private Map<String, ArrayList<String>> stringArrayProperties; private Map<String, ArrayList<ArrayList<String>>> stringArray2DProperties; private Map<String, Boolean> booleanProperties; private Map<String, ArrayList<Boolean>> booleanArrayProperties; private Map<String, ArrayList<ArrayList<Boolean>>> booleanArray2DProperties; private Map<String, Long> longProperties; private Map<String, ArrayList<Long>> longArrayProperties; private Map<String, ArrayList<ArrayList<Long>>> longArray2DProperties; private int ref; private double time; public TestCase() { initialise(); } private void initialise() { isSolved = false; intProperties = new HashMap<>(); intArrayProperties = new HashMap<>(); intArray2DProperties = new HashMap<>(); doubleProperties = new HashMap<>(); doubleArrayProperties = new HashMap<>(); doubleArray2DProperties = new HashMap<>(); stringProperties = new HashMap<>(); stringArrayProperties = new HashMap<>(); stringArray2DProperties = new HashMap<>(); booleanProperties = new HashMap<>(); booleanArrayProperties = new HashMap<>(); booleanArray2DProperties = new HashMap<>(); longProperties = new HashMap<>(); longArrayProperties = new HashMap<>(); longArray2DProperties = new HashMap<>(); ref = 0; } public void setSolution(Object o) { solution = o; isSolved = true; } public Object getSolution() { if (!isSolved) { Utils.die("getSolution on unsolved testcase"); } return solution; } public void setRef(int i) { ref = i; } public int getRef() { return ref; } public void setTime(double d) { time = d; } public double getTime() { return time; } public void setInteger(String s, Integer i) { intProperties.put(s, i); } public Integer getInteger(String s) { return intProperties.get(s); } public void setIntegerList(String s, ArrayList<Integer> l) { intArrayProperties.put(s, l); } public void setIntegerMatrix(String s, ArrayList<ArrayList<Integer>> l) { intArray2DProperties.put(s, l); } public ArrayList<Integer> getIntegerList(String s) { return intArrayProperties.get(s); } public Integer getIntegerListItem(String s, int i) { return intArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Integer>> getIntegerMatrix(String s) { return intArray2DProperties.get(s); } public ArrayList<Integer> getIntegerMatrixRow(String s, int row) { return intArray2DProperties.get(s).get(row); } public Integer getIntegerMatrixItem(String s, int row, int column) { return intArray2DProperties.get(s).get(row).get(column); } public ArrayList<Integer> getIntegerMatrixColumn(String s, int column) { ArrayList<Integer> out = new ArrayList(); for(ArrayList<Integer> row : intArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setDouble(String s, Double i) { doubleProperties.put(s, i); } public Double getDouble(String s) { return doubleProperties.get(s); } public void setDoubleList(String s, ArrayList<Double> l) { doubleArrayProperties.put(s, l); } public void setDoubleMatrix(String s, ArrayList<ArrayList<Double>> l) { doubleArray2DProperties.put(s, l); } public ArrayList<Double> getDoubleList(String s) { return doubleArrayProperties.get(s); } public Double getDoubleListItem(String s, int i) { return doubleArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Double>> getDoubleMatrix(String s) { return doubleArray2DProperties.get(s); } public ArrayList<Double> getDoubleMatrixRow(String s, int row) { return doubleArray2DProperties.get(s).get(row); } public Double getDoubleMatrixItem(String s, int row, int column) { return doubleArray2DProperties.get(s).get(row).get(column); } public ArrayList<Double> getDoubleMatrixColumn(String s, int column) { ArrayList<Double> out = new ArrayList(); for(ArrayList<Double> row : doubleArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setString(String s, String t) { stringProperties.put(s, t); } public String getString(String s) { return stringProperties.get(s); } public void setStringList(String s, ArrayList<String> l) { stringArrayProperties.put(s, l); } public void setStringMatrix(String s, ArrayList<ArrayList<String>> l) { stringArray2DProperties.put(s, l); } public ArrayList<String> getStringList(String s) { return stringArrayProperties.get(s); } public String getStringListItem(String s, int i) { return stringArrayProperties.get(s).get(i); } public ArrayList<ArrayList<String>> getStringMatrix(String s) { return stringArray2DProperties.get(s); } public ArrayList<String> getStringMatrixRow(String s, int row) { return stringArray2DProperties.get(s).get(row); } public String getStringMatrixItem(String s, int row, int column) { return stringArray2DProperties.get(s).get(row).get(column); } public ArrayList<String> getStringMatrixColumn(String s, int column) { ArrayList<String> out = new ArrayList(); for(ArrayList<String> row : stringArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setBoolean(String s, Boolean b) { booleanProperties.put(s, b); } public Boolean getBoolean(String s) { return booleanProperties.get(s); } public void setBooleanList(String s, ArrayList<Boolean> l) { booleanArrayProperties.put(s, l); } public void setBooleanMatrix(String s, ArrayList<ArrayList<Boolean>> l) { booleanArray2DProperties.put(s, l); } public ArrayList<Boolean> getBooleanList(String s) { return booleanArrayProperties.get(s); } public Boolean getBooleanListItem(String s, int i) { return booleanArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Boolean>> getBooleanMatrix(String s) { return booleanArray2DProperties.get(s); } public ArrayList<Boolean> getBooleanMatrixRow(String s, int row) { return booleanArray2DProperties.get(s).get(row); } public Boolean getBooleanMatrixItem(String s, int row, int column) { return booleanArray2DProperties.get(s).get(row).get(column); } public ArrayList<Boolean> getBooleanMatrixColumn(String s, int column) { ArrayList<Boolean> out = new ArrayList(); for(ArrayList<Boolean> row : booleanArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setLong(String s, Long b) { longProperties.put(s, b); } public Long getLong(String s) { return longProperties.get(s); } public void setLongList(String s, ArrayList<Long> l) { longArrayProperties.put(s, l); } public void setLongMatrix(String s, ArrayList<ArrayList<Long>> l) { longArray2DProperties.put(s, l); } public ArrayList<Long> getLongList(String s) { return longArrayProperties.get(s); } public Long getLongListItem(String s, int i) { return longArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Long>> getLongMatrix(String s) { return longArray2DProperties.get(s); } public ArrayList<Long> getLongMatrixRow(String s, int row) { return longArray2DProperties.get(s).get(row); } public Long getLongMatrixItem(String s, int row, int column) { return longArray2DProperties.get(s).get(row).get(column); } public ArrayList<Long> getLongMatrixColumn(String s, int column) { ArrayList<Long> out = new ArrayList(); for(ArrayList<Long> row : longArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; public class Dancing { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader("dancing.in")); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("botTrust.out"))); int T = Integer.parseInt(f.readLine()); for (int i = 0; i < T; i++) { StringTokenizer tok = new StringTokenizer(f.readLine()); int N = Integer.parseInt(tok.nextToken()); int S = Integer.parseInt(tok.nextToken()); int P = Integer.parseInt(tok.nextToken()); int count = 0; for (int j = 0; j < N; j++) { int x = Integer.parseInt(tok.nextToken()); if (x % 3 == 0) { if (x/3 >= P) count++; if (x/3 == P-1 && x > 0) { if (S > 0) { S--; count++; } } } if (x % 3 == 1) { if (x/3 >= P-1) count++; } if (x % 3 == 2) { if (x/3 >= P-1) count++; if (x/3 == P-2) { if (S > 0) { S--; count++; } } } } System.out.println("Case #" + (i+1) + ": " + count); } } }
B11696
B11588
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; } }
package world2012.qualification; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; public class C { public static int countRecycled(int A, int B) { int count = 0; for (int n = A; n <= B; n++) { for (int m = n + 1; m <= B; m++) { String nStr = "" + n + n; String mStr = "" + m; if (nStr.contains(mStr)) count++; } } return count; } static PrintWriter out; public static void parseInput() throws Exception { String file = "world2012/qualification/C-small-attempt0.in"; // String file = "world2012/qualification/B-large.in"; // String file = "input.in"; Scanner scanner = new Scanner(new File(file)); out = new PrintWriter(new FileWriter((file.replaceAll(".in", "")))); int T = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < T; i++) { String[] in = scanner.nextLine().split("\\s"); int A = Integer.parseInt(in[0]); int B = Integer.parseInt(in[1]); int r = countRecycled(A, B); out.println("Case #"+(i+1)+": "+r+""); } } public static void main(String[] args) throws Exception { parseInput(); out.close(); System.out.println("Done!"); } }
A11917
A11861
0
package com.silverduner.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; public class Dancing { public static void main(String[] args) throws Exception { File input = new File("B-small-attempt0.in"); BufferedReader in = new BufferedReader(new FileReader(input)); File output = new File("1.out"); BufferedWriter out = new BufferedWriter(new FileWriter(output)); // parse input int N = Integer.parseInt(in.readLine()); for(int i=0;i<N;i++) { String str = in.readLine(); out.write("Case #"+(i+1)+": "); System.out.println("-------"); String[] words = str.split(" "); int n = Integer.parseInt(words[0]); int suprise = Integer.parseInt(words[1]); int threshold = Integer.parseInt(words[2]); int[] scores = new int[n]; for(int j=0;j<n;j++) { scores[j] = Integer.parseInt(words[3+j]); } int count = 0; for(int score : scores) { int a,b,c; boolean find = false; boolean sfind = false; for(a = 10; a>=0 && !find; a--) { if(3*a-4>score) continue; for(b = a; b>=0 && b >=a-2 && !find; b--) { for(c = b; c>=0 && c >=b-2 && c >=a-2 && !find; c--) { System.out.println(a+","+b+","+c); if(a+b+c==score) { if(a >= threshold) { if(a-c <= 1){ count++; find = true; System.out.println("find!"); } else if(a-c == 2){ sfind = true; System.out.println("suprise!"); } } } } } } if(!find && sfind && suprise > 0) { count++; suprise --; } } int maxCount = count; out.write(maxCount+"\n"); } out.flush(); out.close(); in.close(); } }
package googleJam; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class GoogleDancers { public static void main(String[] args) { Scanner scan = null; try { scan = new Scanner(new File(args[0])); } catch (FileNotFoundException e) { System.err.println("File not found!"); return; } if (!scan.hasNext()) { System.err.println("Nothing in File!"); return; } int testCases = Integer.parseInt(scan.nextLine()); String[] line; String str; int theFabulousGoogleDancers; int soManySurprises; int whoIsBetterThanMe; int itsAStretch; int noSurpriseNeeded; int iAmBetterThanYou; int canReachWithSurprise; int number = 1; int combined; while (scan.hasNext()) { System.out.print("Case #" + number + ": "); iAmBetterThanYou = 0; itsAStretch = 0; str = scan.nextLine(); line = str.split(" "); theFabulousGoogleDancers = Integer.parseInt(line[0]); soManySurprises = Integer.parseInt(line[1]); whoIsBetterThanMe = Integer.parseInt(line[2]); noSurpriseNeeded = (whoIsBetterThanMe + (whoIsBetterThanMe-1) + (whoIsBetterThanMe-1)); canReachWithSurprise = (whoIsBetterThanMe + (whoIsBetterThanMe-2) + (whoIsBetterThanMe - 2)); if (whoIsBetterThanMe == 1) { noSurpriseNeeded = 1; canReachWithSurprise = 1; } if (whoIsBetterThanMe == 0) { noSurpriseNeeded = 0; canReachWithSurprise = 0; } for (int score = 3; score < line.length; score++) { if ((Integer.parseInt(line[score])) >= canReachWithSurprise && Integer.parseInt(line[score]) < noSurpriseNeeded) { itsAStretch++; } else if (Integer.parseInt(line[score]) >= noSurpriseNeeded) { iAmBetterThanYou++; } } if (itsAStretch <= soManySurprises) { combined = iAmBetterThanYou + itsAStretch; } else { combined = iAmBetterThanYou + soManySurprises; } System.out.print(combined); if(scan.hasNext()) { System.out.println(); } number++; } } }
B10485
B10711
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 codejam; import java.io.*; public class RecycledNumbers { private BufferedReader br; private BufferedWriter wr; public RecycledNumbers(String filein,String fileout){ try{ br = new BufferedReader(new InputStreamReader(new FileInputStream(filein))); wr = new BufferedWriter(new FileWriter(fileout)); int num = 0; num = Integer.parseInt(br.readLine()); for (int i = 1;i<=num;i++){ String buf = br.readLine(); String[] bufarray = buf.split(" "); int num1 = Integer.parseInt(bufarray[0]); int num2 = Integer.parseInt(bufarray[1]); int pairs = 0; for (int n = num1;n <= num2;n++){ int digit = getDigits(n); for (int d = 1;d < digit;d++){ if (isTwin(n,digit) && d == (digit/2)+1) break; int pair = (n%((int)Math.pow(10, d)))*((int)Math.pow(10, digit-d))+ n/((int)Math.pow(10, d)); if (pair > n && pair <= num2){ if (num1 > 1000) System.out.println(n+" "+pair); pairs++; } } } String out = "Case #"+i+": "+pairs; wr.write(out); if (i != num) wr.newLine(); } br.close(); wr.close(); }catch (IOException e){ System.out.println("IO failure"); } } private boolean isTwin(int n,int digit){ if (digit%2 == 1) return false; return (n%(int)Math.pow(10, digit/2) == n/(int)Math.pow(10, digit/2)); } private int getDigits(int n){ int digit = 1; while(n/10 != 0){ digit++; n /= 10; } return digit; } public static void main(String[] args) { RecycledNumbers sp = new RecycledNumbers("C-small-attempt0.in","C-small-attempt0.out"); } }
A22078
A22593
0
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; public class GooglersDancer { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub InputStreamReader converter = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(converter); if (in == null) { return; } String numTest = in.readLine(); int maxCases = Integer.valueOf(numTest); for(int i=1;i<= maxCases;i++){ String linea = in.readLine(); String[] datos = linea.split(" "); Integer googlers = Integer.valueOf(datos[0]); Integer sospechosos = Integer.valueOf(datos[1]); Integer p = Integer.valueOf(datos[2]); Integer puntuacion; Integer personas = 0; ArrayList<Integer> puntuaciones = new ArrayList<Integer>(); for(int j=0;j<googlers;j++){ puntuacion = Integer.valueOf(datos[3+j]); puntuaciones.add(puntuacion); } Integer[] pOrdenado = null; pOrdenado = (Integer[]) puntuaciones.toArray(new Integer[puntuaciones.size()]); Arrays.sort(pOrdenado); int j; for(j=pOrdenado.length-1;j>=0;j--){ if(pOrdenado[j] >= p*3-2){ personas += 1; }else{ break; } } int posibles = j+1-sospechosos; for(;j>=posibles && j>= 0;j--){ if(pOrdenado[j] >= p*3-4 && pOrdenado[j] > p){ personas += 1; }else{ break; } } System.out.println("Case #"+i+": "+personas); } } }
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Scanner; public class SecondQuestions { private static long getLeastScore(long maxScore, long subtract) { return (maxScore - subtract) < 0 ? 0 : (maxScore - subtract); } public static void main(String[] args) throws Exception { try { Scanner sc = new Scanner(new File("B-large.in")); BufferedWriter bufferedWriter = null; bufferedWriter = new BufferedWriter(new FileWriter("output.txt")); long totalCases = sc.nextLong(); for (int i = 1; i <= totalCases; i++) { long numContestants = sc.nextLong(); long numSurprises = sc.nextLong(); long maxScore = sc.nextLong(); long minSurpriseTotalScore = maxScore + getLeastScore(maxScore, 2) + getLeastScore(maxScore, 2); long minTotalScore = maxScore + getLeastScore(maxScore, 1) + getLeastScore(maxScore, 1); long qualifiers = 0; for (int j = 0; j < numContestants; j++) { long nextScore = sc.nextLong(); if ((nextScore >= minTotalScore)) { qualifiers++; } else if (((nextScore < minTotalScore) && ((nextScore >= minSurpriseTotalScore) && (numSurprises > 0)))) { qualifiers++; numSurprises--; } } bufferedWriter.append("Case #" + i + ": "); bufferedWriter.append(String.valueOf(qualifiers)); bufferedWriter.append("\n"); } bufferedWriter.flush(); bufferedWriter.close(); } catch (Exception e) { e.printStackTrace(); } } }
A22360
A20895
0
import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; public class Dancing_With_the_Googlers { /** * 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. * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // Reading the input file Scanner in = new Scanner(new File("B-large.in")); // writting the input file FileOutputStream fos = new FileOutputStream("B-large.out"); PrintStream out = new PrintStream(fos); //Close the output stream int testCase=Integer.parseInt(in.nextLine()); for(int i=0;i<testCase;i++) { out.print("Case #" + (i + 1) + ":\t"); int NoOfGooglers= in.nextInt(); int NoOfSurprisingResults = in.nextInt(); int atLeastP=in.nextInt(); ArrayList<Integer> scores= new ArrayList<Integer>(); int BestResults=0; int Surprising=0; for(int j=0;j<NoOfGooglers;j++) { scores.add(in.nextInt()); //System.out.print(scores.get(j)); int modulus=scores.get(j)%3; int temp = scores.get(j); switch (modulus) { case 0: if (((temp / 3) >= atLeastP)) { BestResults++; } else { if (((((temp / 3) + 1) >= atLeastP) && ((temp / 3) >= 1)) && (Surprising < NoOfSurprisingResults)) { BestResults++; Surprising++; } System.out.println("Case 0"+"itr:"+i+" surprising:"+temp); } break; case 1: if ((temp / 3) + 1 >= atLeastP) { BestResults++; continue; } break; case 2: if ((temp / 3) + 1 >= atLeastP) { BestResults++; } else { if (((temp / 3) + 2 >= atLeastP) && (Surprising < NoOfSurprisingResults)) { BestResults++; Surprising++; } System.out.println("Case 2"+"itr:"+i+" surprising:"+temp); } break; default: System.out.println("Error"); } }// Internal for out.println(BestResults); // System.out.println(BestResults); System.out.println(Surprising); BestResults = 0; }// for in.close(); out.close(); fos.close(); } }
import java.util.Scanner; import java.util.StringTokenizer; public class DancingWiththeGooglers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner in =new Scanner(System.in); int cases=Integer.parseInt(in.nextLine())+1; for(int tt=1;tt<cases;tt++){ StringTokenizer cmd=new StringTokenizer(in.nextLine()); int players=Integer.parseInt(cmd.nextToken()); int surprise=Integer.parseInt(cmd.nextToken()); int best=Integer.parseInt(cmd.nextToken()); int count=0; for(int i=0;i<players;i++){ int score=Integer.parseInt(cmd.nextToken()); if(score>=best+Math.max(best-1, 0)*2){ count++; }else if(score>=best+Math.max(best-2,0)*2&&surprise>0){ count++; surprise--; } } System.out.printf("Case #%d: %d\n",tt,count); } } }
A12544
A12212
0
package problem1; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; public class Problem1 { public static void main(String[] args) throws FileNotFoundException, IOException{ try { TextIO.readFile("L:\\Coodejam\\Input\\Input.txt"); } catch (IllegalArgumentException e) { System.out.println("Can't open file "); System.exit(0); } FileOutputStream fout = new FileOutputStream("L:\\Coodejam\\Output\\output.txt"); PrintStream ps=new PrintStream(fout); int cases=TextIO.getInt(); int googlers=0,surprising=0,least=0; for(int i=0;i<cases;i++){ int counter=0; googlers=TextIO.getInt(); surprising=TextIO.getInt(); least=TextIO.getInt(); int score[]=new int[googlers]; for(int j=0;j<googlers;j++){ score[j]=TextIO.getInt(); } Arrays.sort(score); int temp=0; int sup[]=new int[surprising]; for(int j=0;j<googlers && surprising>0;j++){ if(biggestNS(score[j])<least && biggestS(score[j])==least){ surprising--; counter++; } } for(int j=0;j<googlers;j++){ if(surprising==0)temp=biggestNS(score[j]); else { temp=biggestS(score[j]); surprising--; } if(temp>=least)counter++; } ps.println("Case #"+(i+1)+": "+counter); } } static int biggestNS(int x){ if(x==0)return 0; if(x==1)return 1; return ((x-1)/3)+1; } static int biggestS(int x){ if(x==0)return 0; if(x==1)return 1; return ((x-2)/3)+2; } }
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Scanner; public class ProbBv3 { public static void main(String[] args) throws IOException { new ProbBv3().run(); } PrintWriter out; void run() throws IOException { out = new PrintWriter(new FileWriter("B-small-attempt2.out")); // out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.flush(); } void solve() throws IOException { Scanner sc = new Scanner(new File("B-small-attempt2.in")); int T = sc.nextInt(); for (int q = 0; q < T; q++) { int N = sc.nextInt(); int S = sc.nextInt(); int p = sc.nextInt(); out.print("Case #" + (q + 1) + ": "); int ans = 0; for (int i = 0; i < N; i++) { int quotient; int remainder; int n = sc.nextInt(); if (n >= (p * 3) - 2) { ans++; // out.print(n + "A "); } else if ((p * 3) - 4 >= 0 && n >= (p * 3) - 4 && S > 0) { ans++; S--; // out.print(n + "B "); } } out.println(ans); } } }
A22992
A21039
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 package02; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class DancingWithTheGooglers { private static void checkInputFile(String filePath) throws IOException{ BufferedReader br=new BufferedReader(new FileReader(new File(filePath))); PrintWriter output=new PrintWriter(filePath.concat(".out")); String str=new String(); int row=0; while((str=br.readLine())!=null){ if(row!=0){ int as=checkOneline(str); output.println("Case #"+row+": "+as); } row=row+1; } output.close(); br.close(); } private static int checkOneline(String str) { int as=0; int s=0; int p=0; int tst1=0; int tst2=0; //将一行数字的字符串转为整型List; List<Integer> iLst=new ArrayList<Integer>(); int j=0; for(int i=0;i<str.length();i++){ if(str.substring(i, i+1).equals(" ")){ iLst.add(Integer.valueOf(str.substring(j, i))); j=i+1; } } iLst.add(Integer.valueOf(str.substring(j, str.length()))); s=iLst.get(1); p=3*iLst.get(2); for(int i=3;i<iLst.size();i++){ if(iLst.get(i)>p-3){ tst1=tst1+1; } if((iLst.get(i)<p-2)&&(iLst.get(i)>p-5)&&(iLst.get(i)!=0)){ tst2=tst2+1; } } //如果tst2比意外分多的话,就等于意外数 if(tst2>s){ tst2=s; } as=tst1+tst2; return as; } public static void main(String args[]) throws IOException{ Scanner scanner=new Scanner(System.in); String inputFilePath=scanner.nextLine(); checkInputFile(inputFilePath); } }
A12273
A10898
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.util.ArrayList; import java.util.Scanner; public class B { public static void output(int T, int count) { System.out.print(String.format("Case #%d: ", T)); System.out.print(count); System.out.println(); } public static int getScores(int total, int p) { int first = p; int second = p; int third = p; if (first + second + third > total) { second--; } else { return 0; } if (first + second + third > total) { third--; } else { return 0; } if (first + second + third > total) { second--; } else { return 0; } if (first + second + third > total) { third--; } else { return 1; } if (first + second + third > total) { return -1; } else { return 1; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); in.nextLine(); for (int i=0; i<T; i++) { int N = in.nextInt(); int S = in.nextInt(); int p = in.nextInt(); int count = 0; ArrayList<Integer> t = new ArrayList<Integer>(); for (int j=0; j<N; j++) { int tmp = in.nextInt(); if (tmp >= p) { t.add(tmp); } } for (int j=0; j<t.size(); j++) { int tmp = t.get(j); int score = getScores(tmp, p); if (score == 0) { count++; } else if (score == 1 && S > 0) { count++; S--; } } output(i + 1, count); } } }
B11696
B10489
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.IOException; import java.io.OutputStreamWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Formatter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Recycled { /** * @param args */ public static void main(String[] args) { Path path = Paths.get(args[0]); Path file = Paths.get("recycled.txt"); int numberOfCases; try (Scanner scanner = new Scanner(Files.newInputStream(path), "UTF-8"); OutputStreamWriter output = new OutputStreamWriter(Files.newOutputStream(file), "UTF-8")) { Formatter f = new Formatter(output); numberOfCases = scanner.nextInt(); for (int i = 1; i <= numberOfCases; i++) { int from = scanner.nextInt(); int to = scanner.nextInt(); int result = solve(from, to); f.format("Case #%d: %d\n", i, result); } f.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static int solve(int from, int to) { Set<Pair> pairs = new HashSet<>(); for (int a = from; a < to; a++) { String n = Integer.toString(a); StringBuilder b; for (int i = 1; i < n.length(); i++) { b = new StringBuilder(n.substring(n.length()-i)); b.append(n.substring(0, n.length()-i)); String rec = b.toString(); if (rec.charAt(0) != '0') { int rev = Integer.parseInt(rec); if (rev > a && rev <= to) { pairs.add(new Pair(a, rev)); } } } } return pairs.size(); } private static class Pair { int first; int second; public Pair(int first, int second) { super(); this.first = first; this.second = second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (first != other.first) return false; if (second != other.second) return false; return true; } } }
B12570
B10414
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 com.google.codjam.utils; import com.google.codjam.problems.BotTrust; import com.google.codjam.problems.CandySplitting; import com.google.codjam.problems.RecycledNumbers; public class MainRun { public static void main(String[] args) { String prefixPath = "D:\\pry\\googlejam\\2012\\pryCodJam\\src\\"; FileDataAndSettings fS = new FileDataAndSettings(); FileLoader.processFile( fS ,prefixPath+ "input.in", 1 ,new RecycledNumbers() ); } }
B12669
B10302
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.*; import java.util.ArrayList; import java.util.List; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author home */ public class RecycledNumbers { public static void main(String args[])throws IOException{ FileReader reader = new FileReader("D:\\NetBeansProjects\\DBInteractionWithWS\\src\\java\\C-small-attempt0.in"); BufferedReader br = new BufferedReader(reader); File file = new File("rloutput.txt"); FileWriter fw = new FileWriter(file); int count = Integer.parseInt(br.readLine()); for(int s=0;s<count;s++){ int recycledNumbers=0; String str = br.readLine(); //System.out.println(str); int start = Integer.parseInt(str.split(" ")[0]); int end = Integer.parseInt(str.split(" ")[1]); for(int i=start;i<end;i++){ List<String> list = new ArrayList(); if(end<=10) break; else{ if(i<=10) continue; String temp1 = i+""; for(int j=1;j<temp1.length();j++){ String subString=temp1.substring(temp1.length()-j)+temp1.substring(0,temp1.length()-j); if(!subString.startsWith("0")) if(!temp1.equals(subString)){ if((i<Integer.parseInt(subString))&&(Integer.parseInt(subString)<=end)){ if(list.isEmpty()){ //System.out.println(temp1+" : "+subString); list.add(subString); recycledNumbers++; } else if(!available(subString,list)) { //System.out.println(temp1+" : "+subString); list.add(subString); recycledNumbers++; } } } } } } System.out.println("Case #"+(s+1)+": "+recycledNumbers); } } public static boolean available(String str, List list){ for(int i=0;i<list.size();i++){ //System.out.println((String)list.get(i)); if(((String)list.get(i)).equals(str)){ return true; } } return false; } }
B10858
B11097
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.*; import java.util.HashSet; import java.util.Set; public class C { private static final String FILE = "C-small-attempt0"; private static final boolean SAVE_OUT = true; public static void main(String[] args) throws IOException { BufferedReader in = createReader(); FileWriter out; if (SAVE_OUT) { out = new FileWriter(FILE + ".out"); } int t = Integer.parseInt(in.readLine()); int c = 0; while (t-- > 0) { String row = in.readLine(); String[] split = row.split(" "); int a = Integer.parseInt(split[0]); int b = Integer.parseInt(split[1]); int num = 0; for (int i = a; i <= b; ++i) { num += calc(i, a, b); } String res = String.format("Case #%d: %d", ++c, num / 2); System.out.println(res); if (SAVE_OUT) { out.append(res); out.append("\n"); } } if (SAVE_OUT) { out.close(); } } private static int calc(int c, int a, int b) { int num = 0; String s = Integer.toString(c); Set<Integer> seen = new HashSet<Integer>(); for (int i = 1; i < s.length(); ++i) { int cc = flip(s, i); while (cc <= b) { if (seen.contains(cc)) { break; } if (cc >= a && c != cc) { ++num; seen.add(cc); } cc *= 10; } } return num; } private static int flip(String s, int k) { String first = s.substring(0, k); StringBuilder sb = new StringBuilder(); sb.append(s.substring(k)); sb.append(first); while (sb.charAt(0) == '0') { sb.deleteCharAt(0); } return Integer.parseInt(sb.toString()); } private static BufferedReader createReader() throws FileNotFoundException { return new BufferedReader(new FileReader(FILE + ".in")); } }
B12074
B10757
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 recycledNumbers; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class RecycledNumbers { public static String processaCaso(String linha, int i) { String[] nums = linha.split(" "); int a = Integer.parseInt(nums[0]); int b = Integer.parseInt(nums[1]); int numDistincPairs = 0; int lenNum = Integer.toString(a).length()-1; Set<Integer> ms = new HashSet<Integer>(); for (; a < b; a++) { String n = Integer.toString(a); ms.clear(); for (int j = 0; j < lenNum; j++) { int indice = lenNum-j; String strM = n.substring(indice)+n.substring(0,indice); int m = Integer.parseInt(strM); if (!(a < m && m <= b)) continue; ms.add(m); } numDistincPairs += ms.size(); } return String.format("Case #%d: %d", i, numDistincPairs); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner scan = new Scanner(new File(args[0])); int numTestCases = scan.nextInt(); scan.nextLine(); Writer saida = new FileWriter(args[0]+".out"); for (int i = 1 ; i <= numTestCases; i++) { saida.write(processaCaso(scan.nextLine(),i)+"\n"); } saida.close(); } }
A21010
A23004
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.util.ArrayList; import java.util.List; import java.util.Scanner; public class addy { public static int counter = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int lines = Integer.parseInt(sc.nextLine()); for (int count = 0; count < lines; count++) { String inputLine = sc.nextLine(); String input[] = inputLine.split(" "); int noOfDancers = Integer.parseInt(input[0]); int noOfSurprise = Integer.parseInt(input[1]); int minScore = Integer.parseInt(input[2]); List<Integer> dancerScore = new ArrayList<Integer>(); for (int i = 0; i < noOfDancers; i++) { // System.out.println("dancer "+i+"score:"+Integer.parseInt(input[3+i])); dancerScore.add(Integer.parseInt(input[3 + i])); } int counting = 0; for (int dancer : dancerScore) { counter = 0; int temp = dancer % 3; int no = dancer / 3; if(dancer<minScore) { continue; }else if(dancer==0 && minScore==0) { counting++; } else if (minScore - no == 1 && temp > 0) { counting++; } else if (minScore - no == 0) { counting++; } else if (minScore - no == 2 && temp == 2) { if (noOfSurprise > 0) { counting++; noOfSurprise--; } } else if (minScore - no < 0) { counting++; } else if (minScore - no == 1 && temp == 0) { if (noOfSurprise > 0) { counting++; noOfSurprise--; } } } counter = counting; System.out.println("Case #" + (count + 1) + ": " + counter); } } }
B12762
B10846
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 com.forthgo.google.g2012r0; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Created by Xan Gregg. * Date: 4/14/12 */ public class ProblemC { public static void main(String[] args) { try { Scanner in = new Scanner(new File("C.in")); PrintWriter out = new PrintWriter(new FileWriter("C.out")); //PrintWriter out = new PrintWriter(System.out); int t = in.nextInt(); for (int i = 0; i < t; i++) { int a = in.nextInt(); int b = in.nextInt(); int k = solve(a, b); out.printf("Case #%d: %d%n", i + 1, k); out.flush(); } } catch (IOException e) { throw new RuntimeException(); } } private static int solve(int a, int b) { int k = 0; int nda = (int) (Math.log10(a) + 1); int ndb = (int) (Math.log10(b) + 1); Set<Long> pairs = new HashSet<Long>(b - a); for (int i = Math.max(2, nda); i <= ndb; i++) { k += solve(pairs, a, b, i); } return k; } private static int solve(Set<Long> pairs, int a, int b, int nd) { int k = 0; for (int i = 1; i <= nd / 2; i++) k += solve(pairs, a, b, nd, i); return k; } private static int solve(Set<Long> pairs, int a, int b, int nd, int ndc) { int c10 = (int) Math.pow(10, ndc); int ndd = nd - ndc; int d10 = (int) Math.pow(10, ndd); int c0 = a / d10; int d0 = a / c10; int k = 0; for (int c = c0; c < c10; c++) { if (c * d10 > b) break; int d00 = d0; if (ndc == ndd) d00 = Math.max(d00, c + 1); for (int d = d00; d < d10; d++) { if (d * c10 > b) break; int x = c * d10 + d; int y = d * c10 + c; if (x != y && x >= a && x <= b && y >= a && y <= b) { long xx = Math.min(x, y); long yy = Math.max(x, y); long pair = xx * c10 * d10 + yy; if (!pairs.contains(pair)) { k++; pairs.add(pair); // System.out.printf("%d %d%n", Math.min(x, y), Math.max(x, y)); } } } } return k; } }
A22360
A21548
0
import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; public class Dancing_With_the_Googlers { /** * 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. * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // Reading the input file Scanner in = new Scanner(new File("B-large.in")); // writting the input file FileOutputStream fos = new FileOutputStream("B-large.out"); PrintStream out = new PrintStream(fos); //Close the output stream int testCase=Integer.parseInt(in.nextLine()); for(int i=0;i<testCase;i++) { out.print("Case #" + (i + 1) + ":\t"); int NoOfGooglers= in.nextInt(); int NoOfSurprisingResults = in.nextInt(); int atLeastP=in.nextInt(); ArrayList<Integer> scores= new ArrayList<Integer>(); int BestResults=0; int Surprising=0; for(int j=0;j<NoOfGooglers;j++) { scores.add(in.nextInt()); //System.out.print(scores.get(j)); int modulus=scores.get(j)%3; int temp = scores.get(j); switch (modulus) { case 0: if (((temp / 3) >= atLeastP)) { BestResults++; } else { if (((((temp / 3) + 1) >= atLeastP) && ((temp / 3) >= 1)) && (Surprising < NoOfSurprisingResults)) { BestResults++; Surprising++; } System.out.println("Case 0"+"itr:"+i+" surprising:"+temp); } break; case 1: if ((temp / 3) + 1 >= atLeastP) { BestResults++; continue; } break; case 2: if ((temp / 3) + 1 >= atLeastP) { BestResults++; } else { if (((temp / 3) + 2 >= atLeastP) && (Surprising < NoOfSurprisingResults)) { BestResults++; Surprising++; } System.out.println("Case 2"+"itr:"+i+" surprising:"+temp); } break; default: System.out.println("Error"); } }// Internal for out.println(BestResults); // System.out.println(BestResults); System.out.println(Surprising); BestResults = 0; }// for in.close(); out.close(); fos.close(); } }
import java.io.*; public class ProbB { public static void main (String[] args) throws Exception { MyInputReader in = new MyInputReader(new FileInputStream("B-large.in")); PrintWriter pw = new PrintWriter("output.txt"); int T = in.nextInt(); for(int q=0; q<T; q++) { int n = in.nextInt(); int s = in.nextInt(); int p = in.nextInt(); int result = 0; int count = 0; for(int i=0; i<n; i++) { int temp = in.nextInt(); if(temp==0 && p>0) continue; if(3*p<=temp || 3*p-2==temp || 3*p-1==temp) result++; else if(count<s && ((3*p-3)==temp || (3*p-4)==temp || (3*p+4)==temp || (3*p+3)==temp)) { result++; count++; } } pw.println("Case #"+(q+1)+": "+result); pw.flush(); } } static class MyInputReader { final private int BUFFER_SIZE = 1 << 17; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public MyInputReader(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString() throws Exception { StringBuffer sb=new StringBuffer(""); byte c = read(); while(c <= '\n') c = read(); do { sb.append((char)c); c=read(); } while(c>'\n'); return sb.toString(); } public String nextWord() throws Exception { StringBuffer sb=new StringBuffer(""); byte c = read(); while(c <= ' ') c = read(); do { sb.append((char)c); c=read(); } while(c>' '); return sb.toString(); } public char nextChar() throws Exception { byte c=read(); while(c<=' ') c= read(); return (char)c; } public int nextInt() throws Exception { int ret = 0; byte c = read(); while(c <= ' ') c = read(); boolean neg = c == '-'; if(neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if(neg) return -ret; return ret; } public long nextLong() throws Exception { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if(neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if(neg) return -ret; return ret; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if(bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if(bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } } }
A10996
A12209
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.util.*; import java.io.*; public class Main { char []a; BufferedReader in; StringTokenizer str = null; PrintWriter out; private String next() throws Exception{ if (str == null || !str.hasMoreElements()) str = new StringTokenizer(in.readLine()); return str.nextToken(); } private int nextInt() throws Exception{ return Integer.parseInt(next()); } public void run() throws Exception{ in = new BufferedReader(new FileReader("in.txt")); out = new PrintWriter(new File("out.txt")); int t = nextInt(); for(int i=1;i<=t;i++){ solve(i); } out.close(); } private void solve(int x) throws Exception{ int n = nextInt(); int s = nextInt(); int p = nextInt(); int ret = 0; int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); for(int i=0;i<n;i++){ int k = a[i]/3; int r = a[i]%3; if (r == 0){ if (k >= p){ ret++; }else{ if (k > 0 && k + 1 >= p && s > 0){ ret++; s--; } } }else if (r == 1){ if (k + 1 >= p){ ret++; } }else{ if (k + 1 >= p){ ret++; }else{ if (k + 2 >= p && s > 0){ ret++; s--; } } } } out.println("Case #" + x + ": " + ret); } public static void main(String[] args) throws Exception{ new Main().run(); } }
B10702
B11328
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; } }
package recycledNumbers; import java.util.ArrayList; public class Algorithms { public static OutputData getOutput(InputData inputdata) { // TODO Auto-generated method stub int [] Results = new int[inputdata.getTest_Number()]; for(int i=0;i<Results.length;i++){ Results[i] = getSingleResult(inputdata.getA()[i], inputdata.getB()[i]); } OutputData outputdata = new OutputData(Results); return outputdata; } private static int getSingleResult(int a, int b) { // TODO Auto-generated method stub 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); } return result; } private static Integer pow(int i, int k) { // TODO Auto-generated method stub if(k==0){ return 1; }else{ return pow(i, k-1)*i; } } }
B10245
B11991
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 googleJamCode2; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.*; /** * * @author gollum1er */ public class Permutation { private String chemin = "C:\\Users\\gollum1er\\Desktop\\"; public Integer moveNDigits(Integer nb, Integer nbDigitsToMove) { String strNb = nb.toString(); String res = strNb.substring(strNb.length() - nbDigitsToMove, strNb.length()) + strNb.substring(0, strNb.length() - nbDigitsToMove); return Integer.parseInt(res); } public List<Integer> findAllPermutationsWithDigits(Integer nb, Integer nbDigitsToMove, Integer min, Integer max) { List<Integer> resListTmp = new ArrayList<Integer>(); Integer tmpRes = this.moveNDigits(nb, nbDigitsToMove); if (tmpRes > nb && tmpRes >= min && tmpRes <= max) { resListTmp.add(tmpRes); } Set set = new HashSet(); set.addAll(resListTmp); ArrayList resList = new ArrayList(set); return resList; } public List<Integer> findAllPermutations(Integer nb, Integer min, Integer max) { String strNb = nb.toString(); List<Integer> resListTmp = new ArrayList<Integer>(); for (int i = 1; i < strNb.length(); i++) { List<Integer> resListTmp2 = this.findAllPermutationsWithDigits(nb, i, min, max); resListTmp.addAll(resListTmp2); } Set set = new HashSet(); set.addAll(resListTmp); ArrayList resList = new ArrayList(set); return resList; } public Integer findRes(int min, int max) { Integer res = 0; for (int i = min; i < max + 1; i++) { List<Integer> tmpList = this.findAllPermutations(i, min, max); res += tmpList.size(); } return res; } //lecture pour le fichier de recherche public List readFile(String nFichier) { List<String> res = new ArrayList<String>(); String nomFichier = chemin + nFichier; try { BufferedReader in = new BufferedReader(new FileReader(nomFichier)); String line =in.readLine(); while ((line = in.readLine()) != null) { res.add(line); } in.close(); } catch (Exception e) { e.printStackTrace(); } return res; } //écrit le résultat des trie public void writeFile(List content, String nFichier) { String nomFichier = chemin + nFichier; try { PrintWriter out = new PrintWriter(new FileWriter(nomFichier)); Iterator it = content.iterator(); int cpt = 1; while (it.hasNext()) { String str = (String) it.next(); out.println("Case #" + cpt + ": " +str); cpt++; } out.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String args[]) { Permutation pm = new Permutation(); List inputList = pm.readFile("C-small-attempt0.in"); Iterator it = inputList.iterator(); List resList = new ArrayList<String>(); while (it.hasNext()) { String resTmp = (String)it.next(); String str[] = resTmp.split(" "); Integer res = pm.findRes(Integer.parseInt(str[0]), Integer.parseInt(str[1])); resList.add(Integer.toString(res)); } pm.writeFile(resList, "toto.txt"); } }
B10245
B11484
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; } }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class C { private void solve() throws IOException { int T = nextInt(); while (T-- > 0) { int A = nextInt(); int B = nextInt(); int res = 0; for (int i = A; i <= B; i++) for (int j = i + 1; j <= B; j++) { if (can(i, j)) { res++; } } pf(); pl(res); } } private boolean can(int i, int j) { String s = "" + i; for (int c = 0; c < s.length(); c++) { String a = s.substring(c); String b = s.substring(0, c); String res = a + b; if (Integer.parseInt(res) == j) return true; } return false; } public static void main(String[] args) { new C().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new FileReader("C.in")); // reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; // writer = new PrintWriter(System.out); writer = new PrintWriter("C.out"); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } BigInteger nextBigInteger() throws IOException { return new BigInteger(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } void p(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.flush(); writer.print(objects[i]); writer.flush(); } } void pl(Object... objects) { p(objects); writer.flush(); writer.println(); writer.flush(); } int cc; void pf() { writer.printf("Case #%d: ", ++cc); writer.flush(); } }
B11421
B11326
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; } }
package recycledNumbers; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Flow { public static InputData Readin(String filename){ try { FileReader fr = new FileReader(filename); Scanner sc = new Scanner(fr); int Test_Number = sc.nextInt(); System.out.println("The Number of Tests: "+Test_Number); int[] A = new int[Test_Number]; int [] B = new int[Test_Number]; for(int i=0;i<Test_Number;i++){ int testA = sc.nextInt(); A[i] = testA; int testB = sc.nextInt(); B[i] = testB; System.out.print("Test "+(i+1)+" "+testA+" "); System.out.println(testB+" "); } sc.close(); InputData inputdata = new InputData(Test_Number, A, B); return inputdata; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public static void Writeout(OutputData outputdata, String filename) { // TODO Auto-generated method stub try { PrintWriter pw = new PrintWriter(new FileWriter(filename)); int Test_Number = outputdata.getSteps().length; for(int i=0;i<Test_Number;i++){ pw.println("Case #"+(i+1)+": "+outputdata.getSteps()[i]); } pw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
A10996
A12059
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.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class main { /** * @param args */ public static void main(String[] args) { try { System.setOut(new PrintStream(new File("B-small-attempt0.out"))); Scanner sc = new Scanner(new File("B-small-attempt0.in")); int T = sc.nextInt(); sc.nextLine(); for (int tc = 1; tc<=T; tc++) { int y = 0, y2 = 0; int N = sc.nextInt(); int S = sc.nextInt(); int p = sc.nextInt(); for (int i = 0; i<N; i++) { int t = sc.nextInt(); if(t/3>=p || (t/3==p-1 && t%3>0)) { y++; } else if((t/3==p-1 && t%3==0) || (t/3==p-2 && t%3==2)) { if(S>0 && t>=2 && t<=28) { y++; S--; } } } System.out.format("Case #%d: %d%n", tc, y); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
A11201
A10438
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); } } }
package ulohy; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Codejam_2 { static byte cases; static int[] googlers = new int[100]; static int[] supr_triplets = new int[100]; static int[][] total_scores = new int[100][100]; static int[][] max = new int[100][100]; static int[][] supr_max = new int[100][100]; static int[] treshold = new int[100]; static int[] result = new int[100]; public static void read_input() { Scanner s = null; try { s = new Scanner(new FileReader("./src/ulohy/B-small-attempt0.in")); } catch (FileNotFoundException e) { e.printStackTrace(); } cases = s.nextByte(); for (int i = 0; i < cases; i++) { googlers[i] = s.nextInt(); supr_triplets[i] = s.nextInt(); treshold[i] = s.nextInt(); for (int j = 0; j < googlers[i]; j++) { total_scores[i][j] = s.nextInt(); } } s.close(); } public static void write_output() { FileWriter outFile; try { outFile = new FileWriter("./src/ulohy/output"); PrintWriter out = new PrintWriter(outFile); for (int i = 1; i <= cases; i++) { out.println("Case #"+i+": "+result[i-1]); } out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String args[]) { read_input(); for (int i = 0; i < cases; i++) { for (int j = 0; j < googlers[i]; j++) { if (total_scores[i][j] > 0) { switch (total_scores[i][j] % 3) { case 0: max[i][j] = total_scores[i][j]/3; supr_max[i][j] = total_scores[i][j]/3 + 1; break; case 1: max[i][j] = total_scores[i][j]/3 + 1; supr_max[i][j] = total_scores[i][j]/3 + 1; break; case 2: max[i][j] = total_scores[i][j]/3 + 1; supr_max[i][j] = total_scores[i][j]/3 + 2; break; default: break; } } } for (int j = 0; j < googlers[i]; j++) { if (max[i][j] >= treshold[i]) { result[i]++; } else { if (supr_max[i][j] >= treshold[i] && supr_triplets[i] > 0) { result[i]++; supr_triplets[i]--; } } } } write_output(); } }
B21207
B20946
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; import java.util.Set; public class ProblemC { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); int T = Integer.valueOf(str); int[] A = new int[T]; int[] B = new int[T]; int[] res = new int[T]; for (int i = 0; i < T; i++) { A[i] = sc.nextInt(); B[i] = sc.nextInt(); } for (int i = 0; i < T; i++) { for (int n = A[i]; n < B[i]; n++) { Set<String> pairs = new HashSet<String>(); String jstr = String.valueOf(n); for (int j = 0; j < jstr.length() - 1; j++) { jstr = jstr.charAt(jstr.length() - 1) + jstr.substring(0, jstr.length() - 1); int m = Integer.valueOf(jstr); if (n < m && m <= B[i]) { if (!pairs.contains(n + "," + m)) { pairs.add(n + "," + m); res[i]++; } } } } System.out.println("Case #" + (i + 1) + ": " + res[i]); } } }
A21010
A20593
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.util.ArrayList; import java.util.Scanner; public class GooglerDancer { private int caseNumber; private int numberOfGooglers; private int numberOfSuprisingTriplets; private int minimumBestScoreP; private ArrayList<Integer> list; public GooglerDancer(int caseNumber,String data) { this.caseNumber=caseNumber; Scanner s=new Scanner(data); this.numberOfGooglers=s.nextInt(); this.numberOfSuprisingTriplets=s.nextInt(); this.minimumBestScoreP=s.nextInt(); list=new ArrayList<Integer>(); while(s.hasNextInt()){ list.add(s.nextInt()); } } public void process() { int count =0; if(numberOfGooglers>0){ ///// if(minimumBestScoreP>0){ for(int i=0;i<numberOfGooglers;i++){ if(list.get(i)>0) { if((Integer)(list.get(i)/minimumBestScoreP)>=3){ count++; } else{ if((Integer)(minimumBestScoreP-(list.get(i)-minimumBestScoreP)/2)==1){ count++; } else{ if((Integer)(minimumBestScoreP-(list.get(i)-minimumBestScoreP)/2)==2 && numberOfSuprisingTriplets>0){ count++; numberOfSuprisingTriplets--; } } } } } //////////// }else{ count=numberOfGooglers; } } System.out.println("Case #"+caseNumber+": "+count); } }
A12273
A12360
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); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package inout; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * * @author Hasier Rodriguez */ public final class In { private In() { } public static String[] read(String path, int mult) throws FileNotFoundException, IOException { System.out.println("IN"); File f = new File(path); BufferedReader br = new BufferedReader(new FileReader(f)); String[] array = new String[Integer.parseInt(br.readLine()) * mult]; String s = br.readLine(); int i = 0; while (s != null) { array[i] = s; System.out.println(s); i++; s = br.readLine(); } System.out.println(); System.out.println(); br.close(); return array; } }
A11277
A11267
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.util.ArrayList; import java.util.List; public class ProblemSample implements Problem { private int solution; private int googlers; private int surprises; private int note; private List<Integer> sums = new ArrayList<Integer>(); @Override public void solve() { int resultat = 0; for (int i = 0; i < sums.size(); i++) { if (note == 0) { // Ils ont tous eu au moins 0... resultat = this.googlers; } else if (note == 1) { // Tous ceux qui ont eu au moins 1 ont eu au moins la note de 1. if (sums.get(i) >= 1) { resultat++; } } else { if ((sums.get(i) == 3 * note - 4 || sums.get(i) == 3 * note - 3) && sums.get(i) > note) { // S'ils sont tout juste, ils ont utilisé une surprise. surprises--; // Et on les compte que si il restait des surprises à consommer if (surprises >= 0) { resultat++; } } if (sums.get(i) >= 3 * note - 2 && sums.get(i) > note) { // Ok sans surprise. resultat++; } } } this.setSolution(resultat); } @Override public void print() { System.out.println(googlers + " " + surprises + " " + note + " " + sums.toString()); } @Override public Object getSolution() { return solution; } public void setSolution(int solution) { this.solution = solution; } public int getGooglers() { return googlers; } public int getSurprises() { return surprises; } public int getNote() { return note; } public List<Integer> getSums() { return sums; } public void setGooglers(int googlers) { this.googlers = googlers; } public void setSurprises(int surprises) { this.surprises = surprises; } public void setNote(int note) { this.note = note; } public void setSums(List<Integer> sums) { this.sums = sums; } }
B12669
B12626
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.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; public class MinimumScalar extends JamProblem { public static void main(String[] args) throws IOException { MinimumScalar p = new MinimumScalar(); p.go(); } @Override String solveCase(JamCase jamCase) { MSCase c= (MSCase) jamCase; Arrays.sort(c.a); Arrays.sort(c.b); BigDecimal b = new BigDecimal(0); for (int i=0; i< c.lengh; i++) { BigDecimal aaa = new BigDecimal(c.a[i]); BigDecimal bbb = new BigDecimal(c.b[c.lengh - i - 1]); b = b.add(aaa.multiply(bbb)); } return "" + b; } @Override JamCase parseCase(List<String> file, int line) { MSCase c= new MSCase(); c.lineCount=3; int i = line; c.lengh = Integer.parseInt(file.get(i++)); c.a = JamUtil.parseIntList(file.get(i++),c.lengh); c.b = JamUtil.parseIntList(file.get(i++),c.lengh); return c; } } class MSCase extends JamCase { int lengh; int[] a; int[] b; }
B12082
B10856
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 be.mokarea.gcj.common; import java.io.FileWriter; import java.io.PrintWriter; import java.io.Writer; public abstract class GoogleCodeJamBase<T extends TestCase> { protected abstract Transformation<T> createTransformation(TestCaseReader<T> testCaseReader, PrintWriter outputWriter) throws Exception; protected abstract String getOutputFileName() throws Exception; protected abstract TestCaseReader<T> getTestCaseReader() throws Exception; public void execute() { try { PrintWriter outputWriter = null; try { outputWriter = new PrintWriter(new FileWriter(getOutputFileName())); Transformation<T> transformation = createTransformation(getTestCaseReader(),outputWriter); transformation.transformAll(); outputWriter.flush(); } finally { closeQuietly(outputWriter); } } catch (Throwable t) { t.printStackTrace(); } } private void closeQuietly(Writer outputWriter) { if (outputWriter != null) { try { outputWriter.close(); } catch (Throwable t) { t.printStackTrace(); } } } }
A22378
A21767
0
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class CodeJam { // public static final String INPUT_FILE_PATH = "D://CodeJamInput.txt"; public static final String INPUT_FILE_PATH = "D://B-large.in"; public static final String OUTPUT_FILE_PATH = "D://CodeJamOutput.txt"; public static List<String> readInput() { List<String> list = new ArrayList<String>(); try { BufferedReader input = new BufferedReader(new FileReader( INPUT_FILE_PATH)); try { String line = null; while ((line = input.readLine()) != null) { list.add(line); } } finally { input.close(); } } catch (IOException ex) { ex.printStackTrace(); } return list; } public static void writeOutput(List<String> output) { PrintWriter writer = null; try { writer = new PrintWriter(new FileWriter(OUTPUT_FILE_PATH)); for (String line : output) { writer.println(line); } writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) writer.close(); } } public static void main(String[] args) { List<DanceFloor> danceFloors = DanceFloor.parseFromFile(CodeJam.readInput()); List<String> output = new ArrayList<String>(); for(int i = 0; i < danceFloors.size(); i++) { System.out.println(danceFloors.get(i)); String line = ""; line += "Case #" + (i + 1) + ": " + danceFloors.get(i).calculate(); output.add(line); } CodeJam.writeOutput(output); } } class DanceFloor { private List<Integer> tripletsTotalCounts; private int surpriseCount; private int targetScore; private int dancersCount; public DanceFloor(List<Integer> tripletsTotalCounts, int surpriseCount, int targetScore, int dancersCount) { this.tripletsTotalCounts = tripletsTotalCounts; this.surpriseCount = surpriseCount; this.targetScore = targetScore; this.dancersCount = dancersCount; } public int calculate() { int result = 0; if (targetScore == 0) return dancersCount; for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if (total < (targetScore * 3 - 4)) { tripletsTotalCounts.remove(i--); } else if (total == 0) { tripletsTotalCounts.remove(i--); } } for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if ((surpriseCount > 0) && (total == targetScore * 3 - 4)) { result++; surpriseCount--; tripletsTotalCounts.remove(i--); } else if ((surpriseCount == 0) && (total == targetScore * 3 - 4)) { tripletsTotalCounts.remove(i--); } } for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if ((surpriseCount > 0) && (total == targetScore * 3 - 3)) { result++; surpriseCount--; tripletsTotalCounts.remove(i--); } else if ((surpriseCount == 0) && (total == targetScore * 3 - 3)) { tripletsTotalCounts.remove(i--); } } result += tripletsTotalCounts.size(); return result; } public static List<DanceFloor> parseFromFile(List<String> readInput) { List<DanceFloor> result = new ArrayList<DanceFloor>(); int testCaseCount = Integer.parseInt(readInput.get(0)); for (int i = 0; i < testCaseCount; i++) { String line[] = readInput.get(i + 1).split(" "); List<Integer> totalCounts = new ArrayList<Integer>(); for (int j = 0; j < Integer.parseInt(line[0]); j++) { totalCounts.add(Integer.parseInt(line[3 + j])); } result.add(new DanceFloor(totalCounts, Integer.parseInt(line[1]), Integer.parseInt(line[2]), Integer.parseInt(line[0]))); } return result; } @Override public String toString() { return "dancersCount = " + dancersCount + "; surpriseCount = " + surpriseCount + "; targetScore = " + targetScore + "; tripletsTotalCounts" + tripletsTotalCounts.toString(); } }
import java.util.*; public class Dancers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int times = sc.nextInt(); for (int c = 1; c <= times; c++) { int players = sc.nextInt(); int surprises = sc.nextInt(); int best = sc.nextInt(); int count = 0; int[] scores = new int[] { 0, 0, 0 }; for (int i = 0; i < players; i++) { int score = sc.nextInt(); scores[0] = scores[1] = scores[2] = score / 3; if (score / 3 >= best) { count++; } else { int difference = score - scores[0]*3; switch (difference) { case 0: { if (surprises > 0) { if (scores[0] > 0 && scores[0] + 1 >= best) { count++; surprises--; } } break; } case 1: { if (scores[0] + 1 >= best) { count++; } else if (surprises > 0) { if (scores[0] + 1 >= best) { count++; surprises--; } } break; } case 2: { if (scores[0] + 1 >= best) { count++; } else if (surprises > 0) { if (scores[0] + 2 >= best) { count++; surprises--; } } break; } default: break; } } } System.out.println("Case #"+c+": "+count); } } }
A13029
A13196
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.io.*; import java.util.*; class triple{ static int p; int a , b, c; public triple(int i ,int j ,int k){ a = i; b = j; c = k; } boolean isSurprise(){ return a - c == 2; } boolean isP(){ return a >= p; } } public class QualB{ private BufferedReader in; private StringTokenizer st; private PrintWriter out; void solve() throws IOException{ ArrayList<triple>[] s = new ArrayList[31]; for (int i = 0; i < s.length; i++) { s[i] = new ArrayList<triple>(); } HashSet<String> h = new HashSet<String>(); for (int i = 0; i <= 10; i++) { for (int j = Math.max(0, i-2); j <= Math.min(i+2, 10); j++) { for (int k = Math.max(0, i-2); k <= Math.min(i+2, 10); k++) { if(Math.abs(k-j) > 2) continue; int [] a = {i,j,k}; Arrays.sort(a); String str = a[0]+","+a[1]+","+a[2]; if(!h.contains(str)){ h.add(str); triple t = new triple(a[2],a[1],a[0]); s[i+j+k].add(t); } } } } int kases = nextInt(); int kase = 0; while(kases-->0){ kase++; out.print("Case #"+kase+": "); int n = nextInt(); int sp = nextInt(); int p = nextInt(); triple.p = p; int []vals = new int[n]; for (int i = 0; i < vals.length; i++) { vals[i] = nextInt(); } int ans = 0; int P = 0; int PnotS = 0; for (int i = 0; i < vals.length; i++) { // System.out.println(vals[i]); // System.out.print(s[vals[i]].get(0).a+" "); // System.out.print(s[vals[i]].get(0).b+" "); // System.out.println(s[vals[i]].get(0).c); // if(s[vals[i]].size() > 1){ // System.out.print(s[vals[i]].get(1).a+" "); // System.out.print(s[vals[i]].get(1).b+" "); // System.out.println(s[vals[i]].get(1).c); // } // System.out.println("-------------------------------"); if(s[vals[i]].size() == 1){ if(s[vals[i]].get(0).isP() && s[vals[i]].get(0).isSurprise()) P++; if(s[vals[i]].get(0).isP() && !s[vals[i]].get(0).isSurprise()) ans++; } else{ boolean a = s[vals[i]].get(0).isP(); boolean b = s[vals[i]].get(1).isP(); if(a&&b){ ans++; } else if( a || b){ int j = a?0:1; if(s[vals[i]].get(j).isP() && s[vals[i]].get(j).isSurprise()) P++; if(s[vals[i]].get(j).isP() && !s[vals[i]].get(j).isSurprise()) PnotS++; } } } // System.out.println(ans); // System.out.println(P); // System.out.println(PnotS); if(sp > P){ ans += P; sp -= P; PnotS -= sp; PnotS = Math.max(0, PnotS); ans += PnotS; } else{ ans += sp + PnotS; } // ans += Math.min(sp, P); out.println(ans); } } QualB() throws IOException { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); eat(""); solve(); out.close(); } private void eat(String str) { st = new StringTokenizer(str); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { new QualB(); } int gcd(int a,int b){ if(b>a) return gcd(b,a); if(b==0) return a; return gcd(b,a%b); } }
A12273
A10411
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.FileOutputStream; import java.io.OutputStream; import java.util.Scanner; public class EjercicioA { public static boolean prueba = false; public static void main(String args[]){ try { FileOutputStream fos = new FileOutputStream(new File("solucion.txt")); OutputStream os = System.out; if (!prueba) os = fos; Scanner s = new Scanner(new File("problema.txt")); int a = s.nextInt(); for(int i = 0; i < a; i++){ int cantP = s.nextInt(); int sorpresa = s.nextInt(); int puntos = s.nextInt(); int total = 0; int minP = 0; int maxSin = puntos + ((puntos -1) > 0 ? (puntos -1) : 0)*2; int maxSorp = puntos + ((puntos -2) > 0 ? (puntos -2) : 0)*2; for (int j = 0; j< cantP; j++){ int totP = s.nextInt(); if (totP < puntos) continue; if (totP >= maxSin) total++; else if (sorpresa > 0 && totP >= maxSorp){ sorpresa --; total++; } } os.write(("Case #" + (i + 1) + ": " + (total) + "\n").getBytes()); } } catch (Exception e) { e.printStackTrace(); } } }
B12570
B12974
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 hu.hke.gcj; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class RecycledNumbers { static RecycledNumbers rn = new RecycledNumbers(); /** * @param args */ public static void main(String[] args) { readAndCalculate(args[0], args[1]); } private static void readAndCalculate(String inputF, String outputF) { BufferedReader input = null; BufferedWriter output = null; try { String line = null; input = new BufferedReader(new FileReader(inputF)); output = new BufferedWriter(new FileWriter(outputF)); boolean first = true; int expectedRows = 0; int actualRows = -1; while ((( line = input.readLine()) != null) && (actualRows < expectedRows)) { System.out.print(actualRows+1); System.out.println("----------------------------------------------------"); if (first) { first = false; expectedRows = Integer.parseInt(line); } else { output.write("Case #" +(actualRows+1)+": "+ rn.recicledNumbers(line)); if (actualRows +1 < expectedRows) { output.write("\n"); } } actualRows++; } input.close(); output.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } } private String recicledNumbers(String line) { C c = new C(line); return c.calculate(); } class C { int a; int b; public C(String line) { String[] numbers = line.split(" "); a = Integer.parseInt(numbers[0]); b = Integer.parseInt(numbers[1]); } public String calculate() { int result = 0; for (int i = a; i<b; i++) { int calculate = calculate(i); result += calculate; } return Integer.toString(result); } private int calculate(int i) { int[] digits = getDigits(i); int recycledCount = 0; int cycled = 0; List<Integer> counted = new ArrayList<Integer>(); for (int j = 1; j < digits.length; j++) { if (digits[j]>=digits[0]) { cycled = cycle(digits, j); if ( (i<cycled) && (cycled <=b)) { if (!counted.contains(cycled)) { // System.out.println("i: "+i+" cycled:" +cycled + " digits j:" +digits[j]); counted.add(cycled); recycledCount++; } } } } return recycledCount; } private int cycle(int[] digits, int j) { int result = 0; int n = 1; for (int k= 1; k<=j; k++) { result += digits[j-k] *n; n = n*10; } for (int k = j; k<digits.length; k++) { result += digits[digits.length - k +j -1 ] *n; n = n*10; } return result; } private int[] getDigits(int i) { // TODO Auto-generated method stub int[] result = null; int length = 0; int n = i; while (n!=0) { length++; n = n/10; } n = i; result = new int[length]; for (int j = 0; j<length; j++) { result[length-j-1] = n%10; n = n/10; } return result; } } }
B10155
B13019
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); } } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package question3; import com.sun.org.apache.xpath.internal.FoundIndex; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * * @author karim */ public class Question3 { static Map<Pair, Integer> found = new HashMap<Pair, Integer>(); /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter("output.out")); BufferedReader in = new BufferedReader(new FileReader("C-small-attempt0.in")); int numOfcases = Integer.parseInt(in.readLine()); for (int caseNum = 1; caseNum <= numOfcases; caseNum++) { found = new HashMap<Pair, Integer>(); String input = in.readLine(); Scanner s = new Scanner(input); int a = s.nextInt(); int b = s.nextInt(); long output = 0; if (b >= 10) { for (int currentNum = b; currentNum >= a; currentNum--) { int temp = currentNum; int divisor = 10; while (temp / divisor != 0) { int div = temp / divisor; int reminder = temp % divisor; divisor *= 10; int newNumber = Integer.parseInt("" + reminder + div); if (newNumber >= a && newNumber <= b && newNumber != currentNum) { Pair p = new Pair(newNumber, currentNum); if (!found.containsKey(p)) { System.out.println(currentNum + " " + newNumber); found.put(p, 1); output++; } } } } } out.write("Case #" + caseNum + ": " + output); out.newLine(); } out.flush(); out.close(); in.close(); } }
B21207
B21813
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; } }
public abstract class JamCase { int lineCount; }
B13196
B10839
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.PrintStream; import java.util.HashSet; /** * * @author peterboyen */ public class RecycledNumbers { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader("/Users/peterboyen/Downloads/C-small-attempt1.in")); String line = br.readLine(); int testCases = Integer.parseInt(line); PrintStream ps = new PrintStream("/Users/peterboyen/Downloads/C-small-attempt1.out"); for (int i = 1; i <= testCases; i++) { line = br.readLine(); ps.println("Case #" + i + ": " + solve(line)); } br.close(); ps.close(); } private static int solve(String line) { String[] split = line.split(" "); int A = Integer.parseInt(split[0]); int B = Integer.parseInt(split[1]); int result = 0; for (int m = A + 1; m <= B; m++) { result += getRecycled(m, A); } return result; } private static int getRecycled(int m, int A) { String M = "" + m; HashSet<Integer> set = new HashSet<Integer>(); int result = 0; for (int i = 0; i < M.length() - 1; i++) { M = M.substring(1) + M.charAt(0); if (M.charAt(0) != '0') { int n = Integer.parseInt(M); if (n >= A && n < m && !set.contains(n)) { result++; set.add(n); } } } return result; } }
A20261
A21571
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; } }
package me.mevrad.codejam; import java.util.ArrayList; public class DataTemplate { public int numberOfGooglers; public int surprisingScores; int p; public ArrayList<Integer> scores; public DataTemplate(){ scores = new ArrayList<Integer>(); } }
A12544
A12863
0
package problem1; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; public class Problem1 { public static void main(String[] args) throws FileNotFoundException, IOException{ try { TextIO.readFile("L:\\Coodejam\\Input\\Input.txt"); } catch (IllegalArgumentException e) { System.out.println("Can't open file "); System.exit(0); } FileOutputStream fout = new FileOutputStream("L:\\Coodejam\\Output\\output.txt"); PrintStream ps=new PrintStream(fout); int cases=TextIO.getInt(); int googlers=0,surprising=0,least=0; for(int i=0;i<cases;i++){ int counter=0; googlers=TextIO.getInt(); surprising=TextIO.getInt(); least=TextIO.getInt(); int score[]=new int[googlers]; for(int j=0;j<googlers;j++){ score[j]=TextIO.getInt(); } Arrays.sort(score); int temp=0; int sup[]=new int[surprising]; for(int j=0;j<googlers && surprising>0;j++){ if(biggestNS(score[j])<least && biggestS(score[j])==least){ surprising--; counter++; } } for(int j=0;j<googlers;j++){ if(surprising==0)temp=biggestNS(score[j]); else { temp=biggestS(score[j]); surprising--; } if(temp>=least)counter++; } ps.println("Case #"+(i+1)+": "+counter); } } static int biggestNS(int x){ if(x==0)return 0; if(x==1)return 1; return ((x-1)/3)+1; } static int biggestS(int x){ if(x==0)return 0; if(x==1)return 1; return ((x-2)/3)+2; } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class gcjq1 { public static void main(String[] args) { try{ FileInputStream ifstream = new FileInputStream("files/B-small-attempt0.in"); DataInputStream in = new DataInputStream(ifstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileOutputStream ofstream = new FileOutputStream("files/output"); DataOutputStream out = new DataOutputStream(ofstream); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); int numCases = Integer.parseInt(br.readLine()); for(int i=0; i<numCases; i++){ bw.write("Case #" + Integer.toString(i+1) + ": " + compute(br.readLine()) + "\n"); bw.flush(); } in.close(); out.close(); }catch (Exception e){ System.err.println("Error: " + e.getMessage()); e.printStackTrace(); } } public static String compute(String in){ String[] parms = in.split(" "); int N = Integer.parseInt(parms[0]); int s = Integer.parseInt(parms[1]); int p = Integer.parseInt(parms[2]); int []t = new int[N]; for(int i=0; i<N; i++){ t[i] = Integer.parseInt(parms[i+3]); } int c = 0; for(int i=0; i<N; i++){ int n = p+(2*(p-1)); if(t[i] >= n){ c++; } else { n = p+(2*(p-2)); if(t[i] >= n && t[i] > 0 && s>0){ c++; s--; } } } return Integer.toString(c); } }
B12762
B10975
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); } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CodeJam { static String [][] mapping = new String [6][]; static String f,s,t,ff,ss,tt; public static void map(){ f = "ejp mysljylc kd kxveddknmc re jsicpdrysi"; s = "rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"; t = "de kr kd eoya kw aej tysr re ujdr lkgc jv"; ff="our language is impossible to understand"; ss="there are twenty six factorial possibilities"; tt="so it is okay if you want to just give up"; mapping[0] = f.split(" "); mapping[1] = ff.split(" "); mapping[2] = s.split(" "); mapping[3] = ss.split(" "); mapping[4] = t.split(" "); mapping[5] = tt.split(" "); } public static String returnLetter(String l){ if(l.equals("q")) return "z"; if(l.equals("z")) return "q"; for(int i=0;i<6;i+=2){ for(int j=0;j<mapping[i].length;j++){ int n; if((n=mapping[i][j].indexOf(l))!=-1){ return mapping [i+1][j].charAt(n)+""; } } } return "***"; } public static boolean isRecycled(String p1, String p2){ if(p1.length()!=p2.length()) return false; for(int i=0;i<p1.length();i++){ String s = p1.substring((p1.length()-i-1)); if(p2.indexOf(s)==0 && p2.substring(s.length()).equals(p1.substring(0, (p1.length()-i-1)))) {return true;} } return false; } public static String decode(String sen){ String res = ""; for(int i=0;i<sen.length();i++){ if((sen.charAt(i)+"").equals(" ")) {res+=" ";continue;} res = res + returnLetter(sen.charAt(i)+""); }return res; } public static int enumerate(int low,int high){ int c=0; for(int i=low;i<high;i++){ for(int j=i+1;j<=high;j++){ if(isRecycled(i+"", j+"")) c++; } } return c; } public static void main(String [] areg) throws IOException{ map(); BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(bf.readLine()); for(int i=0;i<n;i++){ String sen = bf.readLine(); String [] r = sen.split(" "); System.out.println("Case #"+((int)(i+1))+": "+enumerate(Integer.parseInt(r[0]), Integer.parseInt(r[1]))); } // String s = bf.readLine(); // String ss = bf.readLine(); // System.out.println(enumerate(Integer.parseInt(s), Integer.parseInt(ss))); } }
A21010
A22533
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); } }
/******************************************************************************* * Copyright (c) 2012 by Institute of Computing Technology, * Chinese Academic of Sciences, Beijing, China. * * Author: Ruijian Wang * File: B.java * Date: 2012-04-14 * Time: 13:29:55 ******************************************************************************/ package gcj12; import java.util.Scanner; /** * Todo. * <p/> * User: Ruijian Wang * Date: 4/14/12 * Time: 1:29 PM * * @author Ruijian Wang<br> * @version 1.0.0 2012-04-14<br> */ public class B { void solve() { int tCase, n, s, p; Scanner scan = new Scanner(System.in); tCase=scan.nextInt(); for (int i = 1; i <= tCase; i++) { int num = 0; n = scan.nextInt(); s = scan.nextInt(); p = scan.nextInt(); int t; for (int j = 0; j < n; j++) { t = scan.nextInt(); int m = t % 3; int max = -1; if (m == 1) { max = t / 3 + 1; if (max >= p) { num ++; } } else if (m == 2) { max = t / 3 + 1; if (max >= p) { num ++; } else if (s > 0 && max + 1 >= p) { s--; num++; } } else { max = t / 3; if (max >= p) { num++; } else if (s > 0 && t >= 3 && max + 1 >= p) { s--; num++; } } } System.out.println("Case #" + i + ": " + num); } } public static void main(String[] args) { new B().solve(); } }