F1
stringlengths
6
6
F2
stringlengths
6
6
label
stringclasses
2 values
text_1
stringlengths
149
20.2k
text_2
stringlengths
48
42.7k
B12941
B12450
0
package com.menzus.gcj._2012.qualification.c; import com.menzus.gcj.common.InputBlockParser; import com.menzus.gcj.common.OutputProducer; import com.menzus.gcj.common.impl.AbstractProcessorFactory; public class CProcessorFactory extends AbstractProcessorFactory<CInput, COutputEntry> { public CProcessorFactory(String inputFileName) { super(inputFileName); } @Override protected InputBlockParser<CInput> createInputBlockParser() { return new CInputBlockParser(); } @Override protected OutputProducer<CInput, COutputEntry> createOutputProducer() { return new COutputProducer(); } }
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; public class C { public static HashSet<Integer> used; public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(new File("C.out")); Scanner in = new Scanner(System.in); int cases = in.nextInt(); used = new HashSet<Integer>(); for(int caseOn = 1; caseOn <= cases; caseOn++) { used.clear(); int a = in.nextInt(); int b = in.nextInt(); int ans = 0; for(int i = a; i < b; i++) { if(used.contains(i)) continue; int count = 0; ArrayList<Integer> rotations = gen(i); for(int t : rotations) { if(!used.contains(t)) { used.add(t); if(a <= t && t <= b) { count++; } } } count--; ans+=(count*(count+1))/2; } out.printf("Case #%d: %d\n",caseOn,ans); } out.close(); } public static ArrayList<Integer> gen(int a) { int dig = countDigits(a); int ten = 1; for(int i = 1; i < dig; i++) { ten*=10; } ArrayList<Integer> ret = new ArrayList<Integer>(); for(int i = 0; i < dig; i++) { if(countDigits(a)==dig) ret.add(a); a = (a%10)*ten + (a/10); } return ret; } public static int countDigits(int a) { int c = 0; while(a!=0) { c++; a/=10; } return c; } } /* 4 1 9 10 40 100 500 1111 2222 */
A22378
A20948
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(); } }
package org.moriraaca.codejam; public interface TestCase { }
B10702
B11188
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.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Recycling { public static void main(String[] args) throws FileNotFoundException { File file = new File("C-small-attempt0.in"); Scanner in = new Scanner(file); int cases = in.nextInt(); for (int i = 0; i < cases; i++) { int A = in.nextInt(); int B = in.nextInt(); int pairs = 0; while (A < B) { String perm = A+""; for (int j = 1; j < perm.length(); j++) { String x = perm.substring(0,j); String y = perm.substring(j,perm.length()); String out = y+x; int testCase = Integer.parseInt(out); if (A < testCase && testCase <= B ) { pairs++; } } A++; } System.out.println("Case #"+ (i+1) + ": " + pairs); } } }
A22078
A20778
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); } } }
package problemB; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class DancingwithTheGooglers { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("B-large.in")); FileWriter fw = new FileWriter("B-large.out"); /*BufferedReader in = new BufferedReader(new FileReader("A-large-practice.in")); FileWriter fw = new FileWriter("A-large-practice.out");*/ int T = new Integer(in.readLine()); for (int cases = 1; cases <= T; cases++){ StringTokenizer st=new StringTokenizer(in.readLine()); int numG = new Integer(st.nextToken()); int numTriplets = new Integer(st.nextToken()); int leastP = new Integer(st.nextToken()); Integer[] A = new Integer[numG]; for (int i = 0; i < A.length; i++){ A[i] = new Integer(st.nextToken()); } Arrays.sort(A, Collections.reverseOrder()); int result = 0; for (int i = 0; i < A.length; i++){ if (A[i] >= 2){ if (A[i] > (leastP * 3 - 3)){ result++; } else{ if ((A[i] > (leastP *3 - 5)) && numTriplets > 0){ result++; numTriplets--; } } } else{ if (A[i] >= leastP){ result++; } } } if (cases != T) {fw.write("Case #" + cases + ": "+ result + "\n"); } else{fw.write("Case #" + cases + ": "+ result);} } fw.flush(); fw.close(); } }
B10702
B11368
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.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class recycled { static HashMap<Long, HashMap<Long, Integer>> found; static Set<Long> touched; public static int calc(long a, long b){ int compteur = 0; int nbchiffres = 1; long pow = 10; while(pow<a){ pow=pow*10; nbchiffres++; } for(long n=a; n<=b; n++){ if(n>pow){ pow=pow*10; nbchiffres++; } //System.out.println(n+" "+a+" "+b); compteur+= nbpossibleM(a,b,n, nbchiffres, pow); } return compteur; } private static int nbpossibleM(long a, long b, long n, int nbchiffre, long pow) { long smallpow = 10; long bigpow = pow/10; //System.out.println("-------- "+nbchiffre+" "+smallpow+" "+bigpow+"\n\n\n"); long m=0; int possibilities =0; touched.clear(); for(int k=1; k<nbchiffre; k++){ m= n/smallpow + (n%smallpow)*bigpow; if(m<n && m>=a && !touched.contains(m)){ /*if(found.containsKey(m)){ HashMap<Long, Integer> map = found.get(m); if(map.containsKey(n)){ map.put(n, map.get(n)+1); } else{ map.put(n, 1); } } else{ HashMap<Long,Integer> map = new HashMap<Long, Integer>(); map.put(n, 1); found.put(m, map); }*/ possibilities++; touched.add(m); } smallpow=smallpow*10; bigpow=bigpow/10; } return possibilities; } public static void main(String[] args) throws FileNotFoundException{ //found = new HashMap<Long , HashMap<Long, Integer>>(); touched = new HashSet<Long>(); Scanner s = new Scanner(new File("input.txt")); int nbcas = s.nextInt(); for(int i=0; i<nbcas; i++){ long a = s.nextLong(); long b = s.nextLong(); System.out.println("Case #"+(i+1)+": "+calc(a,b)); } /* for(long m: found.keySet()){ HashMap<Long, Integer> map = found.get(m); for(long n: map.keySet()){ if(map.get(n)==2){ System.out .println(m+" "+n); } } }*/ } }
A12460
A12305
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(); } }
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-small-attempt0.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 ? " *" : "")); // } }
A22191
A22748
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.google.code.p_b; 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 Main { private static final String fromFile = "D:\\hobbies & work\\programing\\CodeJamTextFiles\\2012\\B-large.in"; private static final String toFile = "D:\\hobbies & work\\programing\\CodeJamTextFiles\\2012\\B-large.out"; /** * @param args */ public static void main(String[] args) { System.out.println("Problem B start"); try { FileInputStream fstream = new FileInputStream(fromFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fstreamout = new FileWriter(toFile); BufferedWriter out = new BufferedWriter(fstreamout); String strLine; boolean firstLine = true; int i = 1; while ((strLine = br.readLine()) != null) { if (!firstLine) { System.out.println(strLine); System.out.println("Case #" + i + ": " + ansForLine(strLine) + "\n"); out.write("Case #" + i + ": " + ansForLine(strLine) + "\n"); i++; } else { firstLine = false; } } out.close(); in.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } System.out.println("Problem B end"); } private static int ansForLine(String strLine) { String [] splitedLine = strLine.split(" "); int nRes = Integer.parseInt(splitedLine[0]); int nSurprises = Integer.parseInt(splitedLine[1]); int nMax = Integer.parseInt(splitedLine[2]); System.out.println("res: " + nRes + ", surprises: " + nSurprises +", max: " + nMax); int count = 0; for (int i = 3; i < splitedLine.length; i++) { int j = Integer.parseInt(splitedLine[i]); int avg = j / 3; int m = j % 3; if (j == 0) { if (nMax == 0) count ++; continue; } if (avg >= nMax) { count ++; } else if (avg + 1 >= nMax) { if (m == 0 && nSurprises > 0) { count ++; nSurprises --; } else if (m == 1 || m == 2) { count ++; } } else if (avg + 2 >= nMax) { if (m == 2 && nSurprises > 0) { count ++; nSurprises --; } } } return count; } }
A22191
A22058
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.io.*; import java.util.*; public class BDancingGooglers { public static void main(String[] args) throws IOException { // parsing file Scanner scanner = new Scanner(new File("B-large.in")); int cases = Integer.parseInt(scanner.nextLine()); int[][] lineArray = new int[cases][]; int index = 0; while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] split = line.split("\\s"); lineArray[index] = new int[split.length]; for (int i = 0; i < split.length; i++) { lineArray[index][i] = Integer.parseInt(split[i]); } // printing parsed information for (int i = 0; i < split.length; i++) { // System.out.print(lineArray[index][i] + " "); } // System.out.println(); // index++; // DON'T DELETE } // doing computation by case FileWriter fw = new FileWriter("outputb.txt"); for (int i = 0; i < lineArray.length; i++) { int count = 0; // int googlers = lineArray[i][0]; int surprises = lineArray[i][1]; int p = lineArray[i][2]; // System.out.println("p is " + p + ", surprises is " + surprises); int base1 = Math.max(3 * p - 2, 0); int base2 = Math.max(3 * p - 4, 0); for (int j = 3; j < lineArray[i].length; j++) { if (p == 0) { count++; } else if (lineArray[i][j] == 0) { } else if (base1 <= lineArray[i][j]) { count++; // System.out.println("\tscore " + lineArray[i][j] + ", count " + count); } else if (base2 <= lineArray[i][j] && surprises != 0) { count++; surprises--; // System.out.println("\t2score " + lineArray[i][j] + ", count " + count + ", surprises left " + surprises); } else { // System.out.println("\t3score " + lineArray[i][j]); } } fw.write("Case #" + (i + 1) + ": " + count + "\n"); // System.out.println("Case #" + (i + 1) + ": " + count); // System.out.println(); } fw.close(); } }
A11502
A11199
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.FileReader; import java.util.Scanner; public class Scores { public static void main(String[] args) { Scanner scan = new Scanner(System.in); try { scan = new Scanner(new FileReader("B-small-attempt0.in")); } catch (Exception e) { System.out.println("poop"); } int inputSize = Integer.parseInt(scan.nextLine()); int i = 0; while (scan.hasNextLine() && i < inputSize) { i++; String line = scan.nextLine(); String[] strings = line.split(" "); int googlers = Integer.parseInt(strings[0]); int surprises = Integer.parseInt(strings[1]); int atLeast = Integer.parseInt(strings[2]); int j = 0; int output = 0; int surprisesSoFar = 0; for (String s : strings) { if (j > 2) { int total = Integer.parseInt(s); if (total == 0) { if (atLeast == 0) output++; } else if (atLeast + atLeast + atLeast - 2 <= total) { output++; } else if ((surprisesSoFar < surprises) && atLeast + atLeast + atLeast -4 <= total) { output++; surprisesSoFar++; } } j++; } // System.out.println(line); System.out.println("Case #" + i + ": " + output); } } }
B10231
B11044
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.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.StringTokenizer; public class Code3 { private BufferedReader reader = null; PrintStream out = null; public static void main(String[] args) throws Exception { String file = "C-small-attempt0"; Code3 code2 = new Code3(); try { code2.reader = new BufferedReader(new FileReader("source/" + file + ".in")); code2.out = new PrintStream(new FileOutputStream("source/" + file + ".out")); code2.runCases(); } finally { code2.reader.close(); code2.out.close(); } } private void runCases() throws IOException { int cases = getInt(); for (int c = 1; c <= cases; c++) { out.print("Case #" + c + ": "); execute(); out.print("\n"); } } private String readNext() throws IOException { String s = reader.readLine(); return s; } private int getInt() throws IOException{ String s= this.readNext(); return Integer.valueOf(s); } private void execute() throws IOException { String s = this.readNext(); Code3DataStructure ds = new Code3DataStructure(); StringTokenizer st = new StringTokenizer(s," "); ds.setA(Integer.parseInt(st.nextToken())); ds.setB(Integer.parseInt(st.nextToken())); System.out.println("========================="); this.processData(ds); System.out.println("========================="); out.print(ds.getResult()); } private void processData(Code3DataStructure ds) { if(ds.getA()==ds.getB()) { ds.setResult(0); return; } int recyclePairCount = 0; for (int i = ds.getA(); i < ds.getB(); i++) { for (int j = i+1; j < ds.getB(); j++) { if(isRecyclePair(i, j)) { recyclePairCount++; } } } ds.setResult(recyclePairCount); } private boolean isRecyclePair(int m, int n) { boolean recyclePair = false; if((m+"").length() == (n+"").length()) { int length = (m+"").length(); for (int i = 1; i <= length; i++) { int rotatedValue = rotateNumber(m, i); if(rotatedValue == n) { return true; } } } return recyclePair; } private static int denomination(int baseDenomination, int amount) { int denomination = 1; for (int i = 0; i < amount; i++) { denomination*=baseDenomination; } return denomination; } private static int rotateNumber(int m,int chunkSize) { int chunk = m%(denomination(10,chunkSize)); int leftover = m/(denomination(10,chunkSize)); int leftoverSize = (leftover+"").length(); int output = chunk*(denomination(10,leftoverSize))+leftover; return output; } }
A20119
A20260
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 com.gcj.parser; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class Parser { private String inputFileDest; private FileInputStream fileInputStream; public Parser(String inputFileDest) { super(); this.inputFileDest = inputFileDest; try { fileInputStream = new FileInputStream(new File(inputFileDest)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String getInputFileDest() { return inputFileDest; } public void setInputFileDest(String inputFileDest) { this.inputFileDest = inputFileDest; } public FileInputStream getFileInputStream() { return fileInputStream; } public void setFileInputStream(FileInputStream fileInputStream) { this.fileInputStream = fileInputStream; } @SuppressWarnings("unchecked") public ArrayList<Integer>[] toArray(){ Scanner scan = new Scanner(getFileInputStream()); // The first line must be an number Integer nbOfLines = new Integer(scan.nextLine()); ArrayList<Integer>[] parsedData = new ArrayList[nbOfLines]; int index = 0; while (scan.hasNextLine()){ String line = scan.nextLine(); String[] datas = line.split(" "); ArrayList<Integer> dataRow = new ArrayList<Integer>(); for (String data : datas){ dataRow.add(new Integer(data)); } parsedData[index] = dataRow; index++; } return parsedData; } }
A10699
A10466
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Dancing { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // read input file File file = new File("B-small-attempt4.in"); //File file = new File("input.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String ln = ""; int count = Integer.parseInt(br.readLine()); // write output file File out = new File("outB.txt"); BufferedWriter bw = new BufferedWriter(new FileWriter(out)); int y = 0; for (int i=0; i < count; i++){ ln = br.readLine(); y = getY(ln); bw.write("Case #" + (i+1) + ": " + y); bw.newLine(); } bw.close(); } private static int getY(String str) { String[] data = str.split(" "); int n = Integer.parseInt(data[0]); int s = Integer.parseInt(data[1]); int p = Integer.parseInt(data[2]); int[] t = new int[n]; for (int i=0; i < n; i++){ t[i] = Integer.parseInt(data[i+3]); } int y = 0; int base = 0; for(int j=0; j < t.length; j++){ base = t[j] / 3; if(base >= p) { y++; } else if(base == p-1){ if(t[j] - (base+p) > base-1 && t[j] > 0){ y++; } else if(s>0 && t[j] - (base+p) > base-2 && t[j] > 0){ s -= 1; y++; } } else if(base == p-2){ if(s > 0 && t[j] - (base+p) > base-1 && t[j] > 0){ s -= 1; y++; } } } return y; } }
package codejam.suraj.quals2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public abstract class CodeJamSkeleton { // To Read Input file private BufferedReader fileReader = null; private BufferedWriter fileWriter = null; private StringBuffer output = null; public CodeJamSkeleton() { this.output = new StringBuffer(); } public CodeJamSkeleton(String inputFilename, String outputFilename) throws IOException { super(); try{ fileReader = new BufferedReader(new FileReader(inputFilename)); } catch(IOException e) { System.err.println("Could not read from file."); e.printStackTrace(); throw e; } try{ fileWriter = new BufferedWriter( new FileWriter(outputFilename)); }catch(IOException e) { System.err.println("Error opening output file."); System.err.println("Output = " + output.toString()); throw e; } this.output = new StringBuffer(); } /* * This method return next non empty line until it encounters * the end of file */ protected String readLine() throws IOException { String line = null; do{ line = fileReader.readLine(); if(line != null) { if(line.trim().equals("")) continue; else return line; } }while(line != null); return line; } protected void addOutput(int testCaseNumber, String outputText) { output.append("Case #" + testCaseNumber + ": " + outputText + "\n"); } protected void writeOutput() throws IOException { try{ System.out.println(output); fileWriter.write(output.toString()); fileWriter.flush(); }catch(IOException e) { System.err.println("Error writing in output file."); System.err.println("Output = " + output.toString()); throw e; } try{ fileWriter.close(); }catch(IOException e) { System.err.println("Error closing output file."); System.err.println("Output = " + output.toString()); throw e; } } protected abstract void handleTestCase(int testCaseNumber) throws IOException; protected void iterateTestCase() throws IOException { String currentLineRead = readLine(); int numCases = Integer.parseInt(currentLineRead.trim()); for(int i = 0; i < numCases; i++) { handleTestCase(i+1); } } public void handleAllTestCases(String inputFilename, String outputFilename) { try{ fileReader = new BufferedReader(new FileReader(inputFilename)); } catch(IOException e) { System.err.println("Could not read from file."); e.printStackTrace(); System.exit(1); } try{ fileWriter = new BufferedWriter( new FileWriter(outputFilename)); }catch(IOException e) { System.err.println("Error opening output file."); System.err.println("Output = " + output.toString()); System.exit(1); } try{ iterateTestCase(); writeOutput(); } catch(IOException e) { e.printStackTrace(); System.exit(1); } } }
A22360
A21714
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 ex2; import java.util.Scanner; public class main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); for(int i = 0; i < n; i++) { int g = in.nextInt(); // participants int su = in.nextInt(); // anomalies int s = in.nextInt(); // note maximum int ctn = 0; for(int j = 0; j < g; j++) { int p = in.nextInt(); // score if(3*s <= p || 2*(s-1)+s <= p || (s-1) + 2*s <= p) ctn++; else if (su > 0 && p > 0 && ((s-2)+2*s <= p || 2*(s-2)+s <= p || (s-2)+(s-1)+s <= p)) { ctn++; su--;} } System.out.println("Case #"+(i+1)+": "+ctn); } } }
B12762
B11157
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 code.jam.y2012.quali; import java.io.*; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class ProblemC { private static String PATH = "F:\\dev\\projects\\code-jam-2012\\src\\code\\jam\\y2012\\quali"; File inputFile = new File(PATH, "C-small-attempt0.in"); File outputFile = new File(PATH, "C-small-attempt0.out"); BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); public static void main(String[] args) throws Exception { new ProblemC().solve(); } void solve() throws Exception { in = new BufferedReader(new FileReader(inputFile)); out = new PrintWriter(outputFile); for (int testCase = 1, testCount = nextInt(); testCase <= testCount; testCase++) { solve(testCase); } out.close(); } void solve(int testCase) throws IOException { final int min = nextInt(); final int max = nextInt(); Set validPatterns = new HashSet(); for (int i = min; i <= max; i++) { String[] patterns = getRecycledPatterns(String.valueOf(i)); for (int j = 0; j < patterns.length - 1; j++) { for (int k = j; k < patterns.length; k++) { if (isValid(Integer.parseInt(patterns[j]), Integer.parseInt(patterns[k]), min, max)) { validPatterns.add(patterns[j] + "-" + patterns[k]); } } } } print("Case #" + testCase + ": " + validPatterns.size()); } private static String[] getRecycledPatterns(String pattern) { String[] result = new String[pattern.length()]; for (int i = 0; i < result.length; i++) { result[i] = pattern.substring(i) + pattern.substring(0, i); } return result; } private boolean isValid(int a, int b, int min, int max) { return min <= a && a < b && b <= max && String.valueOf(a).length()==String.valueOf(b).length(); } private void print(String text) { out.println(text); System.out.println(text); } /** * helpers */ String nextToken() throws IOException { while (!st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } int nextChar() throws IOException { return in.read(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) { return true; } st = new StringTokenizer(s); } return false; } }
B20006
B21234
0
import java.io.*; import java.math.BigInteger; import java.util.*; import org.jfree.data.function.PowerFunction2D; public class r2a { Map numMap = new HashMap(); int output = 0; /** * @param args */ public static void main(String[] args) { r2a mk = new r2a(); try { FileInputStream fstream = new FileInputStream("d:/cjinput.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String str; int i = 0; while ((str = br.readLine()) != null) { int begin=0,end = 0; i++; if (i == 1) continue; mk.numMap = new HashMap(); StringTokenizer strTok = new StringTokenizer(str, " "); while (strTok.hasMoreTokens()) { begin = Integer.parseInt(((String) strTok.nextToken())); end = Integer.parseInt(((String) strTok.nextToken())); } mk.evaluate(i, begin, end); } in.close(); } catch (Exception e) { System.err.println(e); } } private void evaluate(int rowNum, int begin, int end) { output=0; for (int i = begin; i<= end; i++) { if(numMap.containsKey(Integer.valueOf(i))) continue; List l = getPairElems(i); if (l.size() > 0) { Iterator itr = l.iterator(); int ctr = 0; ArrayList tempList = new ArrayList(); while (itr.hasNext()) { int next = ((Integer)itr.next()).intValue(); if (next <= end && next > i) { numMap.put(Integer.valueOf(next), i); tempList.add(next); ctr++; } } ctr = getCounter(ctr+1,2); /* if (tempList.size() > 0 || ctr > 0) System.out.println("DD: " + i + ": " + tempList +" ; ctr = " + ctr);*/ output = output + ctr; } } String outputStr = "Case #" + (rowNum -1) + ": " + output; System.out.println(outputStr); } private int getCounter(int n, int r) { int ret = 1; int nfactorial =1; for (int i = 2; i<=n; i++) { nfactorial = i*nfactorial; } int nrfact =1; for (int i = 2; i<=n-r; i++) { nrfact = i*nrfact; } return nfactorial/(2*nrfact); } private ArrayList getPairElems(int num) { ArrayList retList = new ArrayList(); int temp = num; if (num/10 == 0) return retList; String str = String.valueOf(num); int arr[] = new int[str.length()]; int x = str.length(); while (temp/10 > 0) { arr[x-1] = temp%10; temp=temp/10; x--; } arr[0]=temp; int size = arr.length; for (int pos = size -1; pos >0; pos--) { if(arr[pos] == 0) continue; int pairNum = 0; int multiplier =1; for (int c=0; c < size-1; c++) { multiplier = multiplier*10; } pairNum = pairNum + (arr[pos]*multiplier); for(int ctr = pos+1, i=1; i < size; i++,ctr++) { if (ctr == size) ctr=0; if (multiplier!=1) multiplier=multiplier/10; pairNum = pairNum + (arr[ctr]*multiplier); } if (pairNum != num) retList.add(Integer.valueOf(pairNum)); } return retList; } }
import java.util.ArrayList; import java.util.List; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { List<String> inputList = FileIO.readFile("C-large.in"); List<String> outputList = new ArrayList<String>(); int caseNo = 1 ; int testCaseCount = Integer.parseInt(inputList.get(0)); while (caseNo <= testCaseCount) { Number n = new Number(inputList.get(caseNo)); outputList.add("Case #" +caseNo +": " +n.getRecycledPairCount()); caseNo++; } FileIO.writeFile("C-large.out", outputList); } }
B12074
B12955
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 google.contest.A; import google.loader.Challenge; import google.problems.AbstractReader; public class AReader extends AbstractReader { @Override protected Challenge createChallenge(int number) { int theLine = getActualLine(); String[] lines = getLines(); AChallenge chal = new AChallenge(theLine,lines[theLine]); setActualLine(theLine+1); return chal; } }
B22190
B21914
0
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class Recycled { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for (int i = 0; i < t; i++) { String[] str = br.readLine().split(" "); int a = Integer.parseInt(str[0]); int b = Integer.parseInt(str[1]); System.out.println("Case #" + (i + 1) + ": " + find(a, b)); } } catch (IOException e) { e.printStackTrace(); } } private static int find(int a, int b) { HashSet<Long> used = new HashSet<Long>(); int digits = String.valueOf(a).length(); if (digits == 1) return 0; for (int i = a; i <= b; i++) { int s = 10; int m = (int) Math.pow(10, digits-1); for (int j = 0; j < digits-1; j++) { int r = i % s; if (r < s/10) continue; int q = i / s; int rn = r * m + q; s *= 10; m /= 10; if (i != rn && rn >= a && rn <= b) { long pp; if (rn < i) pp = (long)rn << 30 | i; else pp = (long)i << 30 | rn; if (!used.contains(pp)) { used.add(pp); } } } } return used.size(); } }
public class ProblemC extends FileWrapper { private int A[] = null; private int B[] = null; private int digt[] = null; public ProblemC(String fileName) { this.processInput(fileName); this.calculate(); this.processOutput(OUTPUT); } @Override protected void processInput(String fileName) { try { this.openReadFile(fileName); this.caseNum = Integer.parseInt(this.readLine()); this.output = new String[this.caseNum]; this.A = new int[this.caseNum]; this.B = new int[this.caseNum]; this.digt = new int[this.caseNum]; for (int i = 0; i < this.caseNum; i++) { String elem[] = this.readLine().split(" "); this.A[i] = Integer.parseInt(elem[0]); this.B[i] = Integer.parseInt(elem[1]); this.digt[i] = elem[0].length()-1; } this.closeReadFile(); } catch (Exception e) { } } @Override protected void calculate() { for (int i=0; i<this.caseNum; i++) { int total = 0; this.output[i] = CASE + (i+1) + ": "; if (this.digt[i] == 0) { this.output[i] += total; continue; } int div = 10; for (int x=1; x<this.digt[i]; x++) { div *= 10; } for (int j=A[i]; j<B[i]; j++) { int value = j; for (int x=0; x<this.digt[i]; x++) { value = value%div*10+value/div; if (value>j && value<=B[i]) { total++; }else if (value==j) { break; } } } this.output[i] += total; } } public static void main(String argv[]) { if (argv.length > 0) { new ProblemC(argv[0]); } else { new ProblemC("C-large.in"); } } }
B20734
B20731
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(); } }
package fixjava; /** * Convenience class for declaring a method inside a method, so as to avoid code duplication without having to declare a new method * in the class. This also keeps functions closer to where they are applied. It's butt-ugly but it's about the best you can do in * Java. */ public interface Lambda2<P, Q, V> { public V apply(P param1, Q param2); }
B12762
B11837
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.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; public class Numbers { public static FileReader fr; public static BufferedReader br; public static FileWriter fw; public static BufferedWriter bw; public void read(String path) throws Exception { fr = new FileReader(path); br=new BufferedReader(fr); } public void write(String path) throws Exception { } public void execute(BufferedReader br,String path)throws Exception { String s; fw =new FileWriter(path,false); bw=new BufferedWriter(fw); s=br.readLine(); int i1=1; while((s=br.readLine())!=null) { int count =0; String st[]=s.split("\\s"); int a=Integer.parseInt(st[0]); int b=Integer.parseInt(st[1]); for(int i=a;i<=b;i++) { int temp=i; String abc=Integer.toString(temp); int length=abc.length(); int index=length-1; String tempString=abc; while(index>0) { String first=tempString.substring(0, index); String second=tempString.substring(index,length); abc=second+first; int newnumber=Integer.parseInt(abc); if((newnumber<=b && newnumber>temp )&& !abc.startsWith("0") && (Integer.toString(temp).length())==abc.length()) count++; index--; } } bw.write("Case #"+ i1++ +": " +count +"\n"); } bw.close(); fr.close(); } public static void main(String[] args) throws Exception { Numbers t=new Numbers(); t.read("E:\\codejam\\Files\\A.in"); t.execute(br,"E:\\codejam\\Files\\A.out"); } }
A12460
A11452
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(); } }
package de.hg.codejam.tasks.io; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public abstract class Writer { public static String generateOutputPath(String inputPath) { return inputPath.substring(0, inputPath.lastIndexOf('.') + 1) + "out"; } public static void print(String[] output) { for (String s : output) System.out.println(s); } public static void write(String[] output) { for (int i = 0; i < output.length; i++) System.out.println(getCase(i + 1, output[i])); } public static void write(String[] output, String path) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(path, false))) { for (int i = 0; i < output.length; i++) { writer.append(getCase(i + 1, output[i])); writer.newLine(); writer.flush(); } } catch (IOException e) { e.printStackTrace(); } } private static String getCase(int number, String caseString) { return "Case #" + (number) + ": " + caseString; } }
A22078
A20638
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.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Dancers { public static void main(String args[]) throws IOException { Scanner s = new Scanner(new File("D:\\input2.txt")); FileWriter fo = new FileWriter(new File("D:\\workspace\\GC12\\src\\output2.txt")); int num = s.nextInt(); for(int i = 1; i<= num; i++) { fo.write("Case #" + i + ": "); int nd = s.nextInt(); int ns = s.nextInt(); //System.out.println("\n"+ i + " - " + nd + " , "+ ns); int p = s.nextInt(); int aHigh = Math.max(p, 0) + Math.max(p-1, 0) + Math.max(p-1, 0); int surpScore = Math.max(p, 0) + Math.max(p-2, 0) + Math.max(p-2, 0); int bScore = 0; int canSurprise = 0; for(int j = 1; j<=nd; j++) { int score = s.nextInt(); //System.out.print(score + " - "); if (score == 0) { continue; } if (score >= aHigh) { bScore ++; } else if(score >= surpScore) { canSurprise ++; } } if (canSurprise < ns) { bScore += canSurprise; } else { bScore += ns; } if(p==0) { fo.write(nd + "\n"); } else { fo.write(bScore + "\n"); } } fo.close(); s.close(); } }
B20734
B21343
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.*; import java.util.*; public class C { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; enum InputType { SAMPLE, SMALL, LARGE; } static final InputType currentInputType = InputType.LARGE; static final int attemptNumber = 0; // for small inputs only int pow10; void solve() throws IOException { int a = nextInt(); int b = nextInt(); pow10 = 1; int cnt = Integer.toString(a).length(); for (int i = 0; i < cnt - 1; i++) pow10 *= 10; long ans = 0; for (int i = a; i <= b; i++) { for (int j = (i % 10) * pow10 + (i / 10); j != i; j = (j % 10) * pow10 + j / 10) if (a <= j && j <= b && j > i) ans++; } out.println(ans); } void inp() throws IOException { switch (currentInputType) { case SAMPLE: br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); break; case SMALL: String fileName = "C-small-attempt" + attemptNumber; br = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); break; case LARGE: fileName = "C-large"; br = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); break; } int test = nextInt(); for (int i = 1; i <= test; i++) { System.err.println("Running test " + i); out.print("Case #" + i + ": "); solve(); } out.close(); } public static void main(String[] args) throws IOException { new C().inp(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (Exception e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
A22771
A21985
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.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.Scanner; public class DancingWiththeGooglers { public static void main(String[] args) throws IOException { FileWriter wr=new FileWriter("Output.txt"); BufferedWriter buff=new BufferedWriter(wr); FileReader read=new FileReader("B-large.in"); BufferedReader buffr=new BufferedReader(read); String str; str=buffr.readLine(); int n=Integer.parseInt(str); int j=1; Scanner sc; int googleres,s,p; int list[]; int i; int num; int total=0; while(j<=n) { int non[]={0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10}; int sup[]={-1,-1,-1,2,3,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,10,10,10,-1,-1,-1}; total=0; str=buffr.readLine(); sc=new Scanner(str); sc.useDelimiter(" "); googleres=sc.nextInt(); s=sc.nextInt(); p=sc.nextInt(); i=1; list=new int[googleres]; while(i<=googleres) { list[i-1]=sc.nextInt(); i++; } if(s==0) { for(int k=1;k<=googleres;k++) { num=list[k-1]; if(non[num]>=p) ++total; } } else { for(int k=1;k<=googleres;k++) { if(s!=0) { num=list[k-1]; if(non[num]>=p) ++total; else { if(sup[num]>=p) { --s; ++total; } } } else { num=list[k-1]; if(non[num]>=p) ++total; } } } StringBuffer temp = new StringBuffer("Case #"+j+": "); temp=temp.append(Integer.toString(total)); buff.write(temp.toString()); buff.newLine(); j++; } buff.close(); } }
A12273
A10276
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Dancing * Jason Bradley Nel * 16287398 */ import java.io.*; public class Dancing { public static void main(String[] args) { In input = new In("input.txt"); int T = Integer.parseInt(input.readLine()); for (int i = 0; i < T; i++) { System.out.printf("Case #%d: ", i + 1); int N = input.readInt(); int s = input.readInt(); int p = input.readInt(); int c = 0;//counter for >=p cases //System.out.printf("N: %d, S: %d, P: %d, R: ", N, s, p); for (int j = 0; j < N; j++) { int score = input.readInt(); int q = score / 3; int m = score % 3; //System.out.printf("%2d (%d, %d) ", scores[j], q, m); switch (m) { case 0: if (q >= p) { c++; } else if (((q + 1) == p) && (s > 0) && (q != 0)) { c++; s--; } break; case 1: if (q >= p) { c++; } else if ((q + 1) == p) { c++; } break; case 2: if (q >= p) { c++; } else if ((q + 1) == p) { c++; } else if (((q + 2) == p) && (s > 0)) { c++; s--; } break; } } //System.out.printf("Best result of %d or higher: ", p); System.out.println(c); } } }
package qualifs; import gcj.Gcj; import java.util.List; public class B { final String file; B (String f) { file = f; } public void run() { Gcj gcj = new Gcj(file); gcj.readLine(); int ncase = gcj.iToken(); for (int cas=1 ; cas <= ncase ; cas++) { gcj.readLine(); int N = gcj.iToken(); int S = gcj.iToken(); int p = gcj.iToken(); int[] t = gcj.iBunch(); int up = 0; for (int i=0 ; i<N ; i++) { int x = t[i]; if (x >= 28) { if (10 >= p) up++; } else if (x == 0) { if (0 >= p) up++; } else { int u = x / 3; int m = x % 3; if (m > 0) u++; if (u >= p) up++; else { if (S > 0 && m != 1) { u++; if (u >= p) { S--; up++; } } } } } Gcj.outcase(cas, false); System.out.println(up); } gcj.terminate(); } }
A21557
A21470
0
import java.io.*; import java.util.*; public class DancingWithGooglers { public static class Googlers { public int T; public int surp; public boolean surprising; public boolean pSurprising; public boolean antiSurprising; public boolean pAntiSurprising; public Googlers(int T, int surp) { this.T = T; this.surp = surp; } public void set(int a, int b, int c) { if (c >= 0 && (a + b + c) == T) { int diff = (Math.max(a, Math.max(b, c)) - Math.min(a, Math.min(b, c))); if (diff <= 2) { if (diff == 2) { if (a >= surp || b >= surp || c >= surp) { pSurprising = true; } else { surprising = true; } } else { if (a >= surp || b >= surp || c >= surp) { pAntiSurprising = true; } else { antiSurprising = true; } } } } } } public static void main(String... args) throws IOException { // BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedReader reader = new BufferedReader(new FileReader("B-large.in")); // PrintWriter writer = new PrintWriter(System.out); PrintWriter writer = new PrintWriter("B-large.out"); int len, cases = Integer.parseInt(reader.readLine()); List<Googlers> satisfied = new ArrayList<Googlers>(); List<Googlers> unsatisfied = new ArrayList<Googlers>(); String[] inputs; int N, S, p; for (int i = 1; i <= cases; i++) { inputs = reader.readLine().split(" "); p = Integer.parseInt(inputs[1]); S = Integer.parseInt(inputs[2]); satisfied.clear(); unsatisfied.clear(); for (int j = 3; j < inputs.length; j++) { int t = Integer.parseInt(inputs[j]); Googlers googlers = new Googlers(t, S); for (int k = 0; k <= 10; k++) { int till = k + 2 > 10 ? 10 : k + 2; for (int l = k; l <= till; l++) { googlers.set(k, l, (t - (k + l))); } } if (googlers.pAntiSurprising) { satisfied.add(googlers); } else { unsatisfied.add(googlers); } } int pSurprising = 0; if (p > 0) { for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) { Googlers googlers = iter.next(); if (googlers.pSurprising) { pSurprising++; iter.remove(); p--; if (p <= 0) break; } } } if(p > 0){ for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) { Googlers googlers = iter.next(); if (googlers.surprising) { iter.remove(); p--; if (p <= 0) break; } } } if(p > 0){ for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) { Googlers googlers = iter.next(); if (googlers.pSurprising) { iter.remove(); pSurprising++; p--; if (p <= 0) break; } } } if(p > 0){ for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) { Googlers googlers = iter.next(); if (googlers.surprising) { iter.remove(); p--; if (p <= 0) break; } } } if(p > 0){ writer.print("Case #" + i + ": 0"); }else { writer.print("Case #" + i + ": " + (satisfied.size() + pSurprising)); } writer.println(); } writer.flush(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejam2012; import java.io.FileNotFoundException; /** * * @author Pavlos */ public class ProblemB { public static void main(String[] args) throws FileNotFoundException { Read.OpenFile("B-large.in"); Write.OpenFile("solB.txt"); int T = Read.readInt(); for (int zz = 1; zz <= T; zz++) { int N = Read.readInt(); int S = Read.readInt(); int p = Read.readInt(); int t[] = new int[N]; for (int i = 0; i < t.length; i++) { t[i] = Read.readInt(); } int counter = 0; for (int i = 0; i < t.length; i++) { if(t[i] >= p){ int temp = t[i] - 3*p; if(temp >= -2) counter++; else if(temp >= -4 && temp < -2 && S > 0) { counter++; S--; } } } //counter -= S; if(counter > 3) counter = 3; Write.WriteToFile(String.format("Case #%d: %d\n",zz, counter)); }//end zz Write.CloseFile(); } }
A11917
A11258
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(); } }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; public class DancingWiththeGooglers { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub System.setIn(new FileInputStream("dancing.in")); BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int Case = Integer.parseInt(bf.readLine()); int cCase = 1; while(Case > 0){ String line = bf.readLine(); String [] parts = line.trim().split("[ ]+"); int [][] t = new int[Integer.parseInt(parts[0])][2]; int S = Integer.parseInt(parts[1]); int p = Integer.parseInt(parts[2]); for (int i = 3; i < parts.length; i++){ int sum = Integer.parseInt(parts[i]); if(sum == 0){ t[i-3][0] = 0; t[i-3][1] = 0; } else if(sum == 1){ t[i-3][0] = 1; t[i-3][1] = 1; } else if(sum == 2){ t[i-3][0] = 1; t[i-3][1] = 2; } else{ int caso = 0; if((sum-1)%3 == 0)caso = 1; double h = sum/3.0; int x = (int) Math.ceil(h); t[i-3][0] = x; if(caso == 1 || x == 10)t[i-3][1] = x; else t[i-3][1] = x+1; } } int count = 0; for(int i = 0; i < Integer.parseInt(parts[0]);i++){ if(t[i][0] >= p)count++; else if(t[i][1] >= p && S>0){ S--; count++; } } System.out.println("Case #"+cCase+": "+count); cCase++; Case--; } } }
B12115
B12667
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.*; public class C { static int[] ten; static { ten = new int[10]; ten[0] = 1; for (int i = 1; i < ten.length; ++i) { ten[i] = ten[i - 1] * 10; } } static int max(int x) { int n = 0; while (ten[n + 1] <= x) { ++n; } int y = x; for (int i = 0; i < n; ++i) { x = x / 10 + x % 10 * ten[n]; y = Math.max(x, y); } return y; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int re = in.nextInt(); int[] c = new int[10000000]; for (int ri = 1; ri <= re; ++ri) { int a = in.nextInt(); int b = in.nextInt(); Arrays.fill(c, 0); for (int i = a; i <= b; ++i) { ++c[max(i)]; } long s = 0; for (int i: c) { s += i * (i - 1) / 2; } System.out.println("Case #" + ri + ": " + s); } } }
A12570
A12956
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.*; import java.util.*; public class b { public static void main(String[] args) { Scanner fin = new Scanner(System.in); int numCases = fin.nextInt(); for (int loop=1; loop<=numCases; loop++) { int numPeople = fin.nextInt(); int numSurprise = fin.nextInt(); int threshold = fin.nextInt(); int safe = 0; int surprise = 0; int lost = 0; int either = 0; for (int i=0; i<numPeople; i++) { int next = fin.nextInt(); if (threshold >= 2) { if (next >= 3*threshold - 2) safe++; else if (next >= 3*threshold - 4) surprise++; else lost++; } else { if (threshold == 0) safe++; else { if (next >= 1) safe++; else lost++; } } } System.out.println("Case #"+loop+": "+(safe+Math.min(surprise, numSurprise))); } } }
A12113
A11005
0
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class B { static int[][] memo; static int[] nums; static int p; public static void main(String[] args)throws IOException { Scanner br=new Scanner(new File("B-small-attempt0.in")); PrintWriter out=new PrintWriter(new File("b.out")); int cases=br.nextInt(); for(int c=1;c<=cases;c++) { int n=br.nextInt(),s=br.nextInt(); p=br.nextInt(); nums=new int[n]; for(int i=0;i<n;i++) nums[i]=br.nextInt(); memo=new int[n][s+1]; for(int[] a:memo) Arrays.fill(a,-1); out.printf("Case #%d: %d\n",c,go(0,s)); } out.close(); } public static int go(int index,int s) { if(index>=nums.length) return 0; if(memo[index][s]!=-1) return memo[index][s]; int best=0; for(int i=0;i<=10;i++) { int max=i; for(int j=0;j<=10;j++) { if(Math.abs(i-j)>2) continue; max=Math.max(i,j); thisone: for(int k=0;k<=10;k++) { int ret=0; if(Math.abs(i-k)>2||Math.abs(j-k)>2) continue; max=Math.max(max,k); int count=0; if(Math.abs(i-k)==2) count++; if(Math.abs(i-j)==2) count++; if(Math.abs(j-k)==2) count++; if(i+j+k==nums[index]) { boolean surp=(count>=1); if(surp&&s>0) { if(max>=p) ret++; ret+=go(index+1,s-1); } else if(!surp) { if(max>=p) ret++; ret+=go(index+1,s); } best=Math.max(best,ret); } else if(i+j+k>nums[index]) break thisone; } } } return memo[index][s]=best; } }
package com.clausewitz.codejam; import com.clausewitz.codejam.qr2012.Dancing; public class CodeJam { /** * @param args */ public static void main(String[] args) { //Solver s = new Googlerese(); //s.solve("res/qr2012/A-small-attempt.in"); Solver s = new Dancing(); s.solve("res/qr2012/B-small-attempt2.in"); } }
B21270
B21901
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(); } }
package codejam03; import java.io.*; import java.util.StringTokenizer; public class CodeJam03 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T,A,B; String temp1,temp2; int output,n; T = Integer.parseInt(br.readLine()); for(int i=0; i<T; i++) { output = 0; StringTokenizer st = new StringTokenizer(br.readLine()); A = Integer.parseInt(st.nextToken()); B = Integer.parseInt(st.nextToken()); for(int j=A; j<B; j++) { temp1 = Integer.toString(j); for(int k=0; k<temp1.length(); k++) { temp2 = temp1.substring(k+1) + temp1.substring(0, k+1); n = Integer.parseInt(temp2); if(n>j && Integer.parseInt(temp2)<=B) output++; if(n==j) break; } } System.out.println("Case #" +(i+1) + ": " + output); } } }
A12570
A12116
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.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.FileInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Prabu */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream("IO/B-small-attempt1.in"); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream("IO/B-small-attempt1.out"); } catch (IOException e) { throw new RuntimeException(e); } Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); CJ2012QR_Dancing solver = new CJ2012QR_Dancing(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } class CJ2012QR_Dancing { public void solve(int testNumber, Scanner in, PrintWriter out) { int N = in.nextInt(); int S = in.nextInt(); int p = in.nextInt(); int ti, base, remainder; int result = 0; for(int i = 0; i < N; i++) { ti = in.nextInt(); base = ti / 3; if(base >= p) { result++; continue; } remainder = ti % 3; if(remainder > 0 && (base+1) >= p) { result++; continue; } remainder = (remainder == 0 && ti != 0)? 1: remainder; if(S > 0 && (base+remainder) >= p) { S--; result++; continue; } } out.printf("Case #%d: %d\n", testNumber, result); } }
B12941
B12638
0
package com.menzus.gcj._2012.qualification.c; import com.menzus.gcj.common.InputBlockParser; import com.menzus.gcj.common.OutputProducer; import com.menzus.gcj.common.impl.AbstractProcessorFactory; public class CProcessorFactory extends AbstractProcessorFactory<CInput, COutputEntry> { public CProcessorFactory(String inputFileName) { super(inputFileName); } @Override protected InputBlockParser<CInput> createInputBlockParser() { return new CInputBlockParser(); } @Override protected OutputProducer<CInput, COutputEntry> createOutputProducer() { return new COutputProducer(); } }
import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; public class Main { private static final int[][] cache; private static final int A = 0, B = 2000000; static { try { File f = new File("cache"); if (f.exists()) { cache = (int[][]) new ObjectInputStream(new FileInputStream(f)).readObject(); } else { cache = new int[B+1][]; for (int j = 12; j < B; j++) { int permutation = String.valueOf(j).length(); HashMap<Integer, Boolean> hit = new HashMap<Integer, Boolean>(); for (int z = 1; z < permutation; z++) { int div = (int) Math.pow(10, z); if (j % div >= div / 10) { int newnum = j / div + j % div * (int) Math.pow(10, permutation - z); if (newnum >= A && newnum <= B && newnum > j) { if (hit.get(newnum) == null) { hit.put(newnum, true); } } } } ArrayList<Integer> l = new ArrayList<Integer>(hit.keySet()); Collections.sort(l); int[] vals = new int[l.size()]; for (int i = 0; i < l.size(); i++) { vals[i] = l.get(i); } cache[j] = vals; } new ObjectOutputStream(new FileOutputStream(f)).writeObject(cache); } } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) throws Exception { Scanner s = new Scanner(new File("input")); BufferedWriter w = new BufferedWriter(new FileWriter(new File("output"))); int cases = s.nextInt(); for (int i = 0; i < cases; i++) { s.nextLine(); int a = s.nextInt(); if (a < 12) { a = 12; } int b = s.nextInt(); int answer = 0; for (int j = a; j < b; j++) { int[] vals = cache[j]; for (int val : vals) { if (val < 0) { continue; } if (val > b) { break; } answer++; } } w.write("Case #"); w.write(String.valueOf(i + 1)); w.write(": "); w.write(String.valueOf(answer)); w.write("\n"); } w.close(); } }
A10699
A10260
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Dancing { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // read input file File file = new File("B-small-attempt4.in"); //File file = new File("input.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String ln = ""; int count = Integer.parseInt(br.readLine()); // write output file File out = new File("outB.txt"); BufferedWriter bw = new BufferedWriter(new FileWriter(out)); int y = 0; for (int i=0; i < count; i++){ ln = br.readLine(); y = getY(ln); bw.write("Case #" + (i+1) + ": " + y); bw.newLine(); } bw.close(); } private static int getY(String str) { String[] data = str.split(" "); int n = Integer.parseInt(data[0]); int s = Integer.parseInt(data[1]); int p = Integer.parseInt(data[2]); int[] t = new int[n]; for (int i=0; i < n; i++){ t[i] = Integer.parseInt(data[i+3]); } int y = 0; int base = 0; for(int j=0; j < t.length; j++){ base = t[j] / 3; if(base >= p) { y++; } else if(base == p-1){ if(t[j] - (base+p) > base-1 && t[j] > 0){ y++; } else if(s>0 && t[j] - (base+p) > base-2 && t[j] > 0){ s -= 1; y++; } } else if(base == p-2){ if(s > 0 && t[j] - (base+p) > base-1 && t[j] > 0){ s -= 1; y++; } } } return y; } }
package files; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class Googler3 { public static void main(String[] args) { try { //BufferedReader br = new BufferedReader(new FileReader("/Users/Sush/Documents/workspace1/CJ/src/files/Input.txt")); BufferedReader br = new BufferedReader(new FileReader("/Users/Sush/Downloads/B-small-attempt0.in.txt")); String line; StringBuffer sb = new StringBuffer(); while((line= br.readLine())!= null) { sb = sb.append(line + "\n"); } String[] cases = sb.toString().split("\n"); String data = ""; for(int i= 1;i<cases.length;i++) { int count = 0; String[] num = cases[i].split(" "); int surp = Integer.parseInt(num[1]); int p = Integer.parseInt(num[2]); int track = surp; for (int j = 3; j< num.length; j++) { int n = Integer.parseInt(num[j]); if (surp == 0) { int min = p + (p-1) + (p-1); if (n>=min) { count = count +1; } } else { int upper = p + (p-1) + (p-1); int lower = p + (p-2) + (p-2); if (p==1) { lower = 1; } if (n >= upper) { count = count +1; } else if(n>=lower && n < upper && track >0) { count = count + 1; track = track - 1; } } } data = data + "Case #"+i+": "+count+"\n"; System.out.print("Case #"+i+": "+count+"\n"); } File ff = new File("Output3.txt"); if (ff.exists()) { ff.delete(); } BufferedWriter bw = new BufferedWriter(new FileWriter(ff, true)); bw.write(data); bw.close(); } catch(Exception e) { System.out.println(e); } } }
B21207
B20092
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.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.FileWriter; class Start{ BufferedInputStream bis=new BufferedInputStream(System.in); PrintWriter out=new PrintWriter(System.out, true); int i,j,k,l,m,n,o,p,q,r,s,t,w,x,y,z,ry,rz,rs; long a,b,c; double d,e,f,g,h; char u,v; String st; int[] in,arr,res; final double pi=3.14159265; final double l2=0.69314718; char chr()throws IOException{ while((ry=bis.read())==10 || ry==13 || ry==32){} return (char)ry; } int num()throws IOException{ rz=0;rs=0; ry=bis.read(); if(ry=='-') rs=-1; else rz+=(ry-'0'); while((ry=bis.read())>='0' && ry<='9') rz=rz*10+(ry-'0'); if(rs==-1) rz=-rz; if(ry==13) bis.read(); return rz; } String str()throws IOException{ StringBuilder sb=new StringBuilder(); while((ry=bis.read())!=10 & ry!=13 && ry!=32) sb.append((char)ry); if(ry==13) bis.read(); return sb.toString(); } String line()throws IOException{ StringBuilder sb=new StringBuilder(); while((ry=bis.read())!=10 && ry!=13) sb.append((char)ry); if(ry==13)bis.read(); return sb.toString(); } int log2(double par){return (int)(Math.log(par)/l2);} long perm(int p1,int p2){ long ret=1; int it; it=p1; while(it>p2) ret*=it--; return ret; } long comb(int p1,int p2){ long ret=1; int it; if(p2<p1-p2) k=p1-p2; it=p1; while(it>p2) ret*=it--; it=p1-p2; while(it>1) ret/=it--; return ret; } public void go()throws IOException{ out =new PrintWriter(new FileWriter("out.txt"),true); t=num(); w=t; while(--t>=0){ a=0; y=num(); z=num(); if(y<10) y=10; p=(int)Math.log10((double)z); q=(int)Math.pow(10.0, (double)p); for(i=y; i<=z; i++) { k=i; r=p; while(r-->0){ k = (k/10) + ((k%10)*q); if(k>i && k<=z) a++; } } out.println("Case #"+(w-t)+": "+a); } while(bis.available()>0)bis.read(); out.close(); } public static void main(String args[])throws IOException{new Start().go();} }
B10361
B10423
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); } }
import java.io.*; import java.util.*; public class RecycledNumbers { public static void main(String[] args){ try{ Scanner scan = new Scanner(new File("C:/personal/InterviewResource/GoogleCode2012/recycled/C-small-attempt0.in")); BufferedWriter output = new BufferedWriter(new FileWriter(new File("C:/personal/InterviewResource/GoogleCode2012/recycled/output.txt"))); boolean isFirstLine=true; int n =0; int linecount=0; while(scan.hasNextLine()){ if(isFirstLine){ isFirstLine=false; n= Integer.parseInt(scan.nextLine()); continue; } String line = scan.nextLine(); String[] vals = line.split(" "); String result=""; linecount++; output.write("Case #"+Integer.toString(linecount)+": "+ getCount(Integer.parseInt(vals[0]), Integer.parseInt(vals[1]))); output.newLine(); } output.close(); System.out.println("Done"); } catch(IOException e){ e.printStackTrace(); } } public static String getCount(int a, int b){ int count=0; TreeSet<String> repeats = new TreeSet<String>(); for(int i=a; i<=b; i++){ //int digits = getDigits(i); String astr = Integer.toString(i); int n = astr.length(); for(int j=1; j<n; j++){ String bstr = astr.substring(n-j,n) + astr.substring(0,n-j); if(isEqual(astr, bstr, b)){ //System.out.println(astr+ " "+ bstr); //System.out.println(bstr); if(!repeats.add(astr+bstr)){ //System.out.println("whoa"); } count++; } } } String res = Integer.toString(repeats.size()); return res; } public static boolean isEqual(String A, String B, int limit){ boolean result = false; //String A = Integer.toString(a); //String B = Integer.toString(b); if(B.startsWith("0")) return false; int a = Integer.parseInt(A); int b = Integer.parseInt(B); if(a==b || b>limit || b<=a) return false; char[] Achar = A.toCharArray(); Arrays.sort(Achar); String Astr = new String(Achar); char[] Bchar = B.toCharArray(); Arrays.sort(Bchar); String Bstr = new String(Bchar); if(Astr.equals(Bstr)){ return true; } return false; } public static int getDigits(int x){ int res=0; while (x>0){ int z =x%10; if(z>0) res++; x=x/10; } return res; } }
B11327
B11244
0
package recycledNumbers; public class OutputData { private int[] Steps; public int[] getSteps() { return Steps; } public OutputData(int [] Steps){ this.Steps = Steps; for(int i=0;i<this.Steps.length;i++){ System.out.println("Test "+(i+1)+": "+Steps[i]); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recyclednumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; /** * * @author Madhav */ public class RecycledNumbers { /** * @param args the command line arguments */ public static HashSet<String> set; public static void main(String[] args) throws Exception { FileIO fileHandler = new FileIO(); int totalTestCases = Integer.parseInt(fileHandler.readLine()); for (int tc = 0; tc < totalTestCases; tc++) { set = new HashSet<String>(); String input = fileHandler.readLine(); String nm[] = input.split(" "); int start = Integer.valueOf(nm[0]); int end = Integer.valueOf(nm[1]); for(int i=start; i<=end; i++){ String currVal = String.valueOf(i); countPairs(currVal, start, end, nm); } fileHandler.writeLine(String.valueOf(set.size())); } fileHandler.closeFileIO(); } public static void countPairs(String input, int start, int end, String[] nm){ String clonedValue = new String(input); if(nm[1].length() <= 1) return; else{ int length = input.length(); for(int i=0; i<length;i++){ String rotated = rotate(input); int calValue = Integer.valueOf(rotated); if( rotated.charAt(0) != '0' && calValue <= end && calValue >= start && !rotated.equals(clonedValue) ){ if(Integer.valueOf(clonedValue) < Integer.valueOf(rotated)) set.add(clonedValue+"-"+rotated); else set.add(rotated+"-"+clonedValue); } input = rotated; } } } public static String rotate(String input){ return input.substring(1) + input.charAt(0); } } /* * File IO is used to read and Write - Keep it simple. */ class FileIO { private FileReader inFileReader; private FileWriter outFileWriter; private BufferedReader br = null; private BufferedWriter bw = null; private int lineNumber = 1; public FileIO() throws Exception { inFileReader = new FileReader("C:\\CodeJam2012\\in.txt"); br = new BufferedReader(inFileReader); outFileWriter = new FileWriter("C:\\CodeJam2012\\out.txt"); bw = new BufferedWriter(outFileWriter); } public FileIO(String in, String out) throws Exception { inFileReader = new FileReader(in); br = new BufferedReader(inFileReader); outFileWriter = new FileWriter(out); bw = new BufferedWriter(outFileWriter); } /* * This procedure returns null if all the rows are read from input file. */ public String readLine() throws Exception { return br.readLine(); } /* * This procedure writes a line to output file as per the google codejam * standard */ public void writeLine(String line) throws Exception { bw.write("Case #" + lineNumber + ": " + line + "\r\n"); lineNumber++; } public void closeFileIO() throws Exception { br.close(); bw.flush(); bw.close(); } }
A10699
A10233
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Dancing { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // read input file File file = new File("B-small-attempt4.in"); //File file = new File("input.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String ln = ""; int count = Integer.parseInt(br.readLine()); // write output file File out = new File("outB.txt"); BufferedWriter bw = new BufferedWriter(new FileWriter(out)); int y = 0; for (int i=0; i < count; i++){ ln = br.readLine(); y = getY(ln); bw.write("Case #" + (i+1) + ": " + y); bw.newLine(); } bw.close(); } private static int getY(String str) { String[] data = str.split(" "); int n = Integer.parseInt(data[0]); int s = Integer.parseInt(data[1]); int p = Integer.parseInt(data[2]); int[] t = new int[n]; for (int i=0; i < n; i++){ t[i] = Integer.parseInt(data[i+3]); } int y = 0; int base = 0; for(int j=0; j < t.length; j++){ base = t[j] / 3; if(base >= p) { y++; } else if(base == p-1){ if(t[j] - (base+p) > base-1 && t[j] > 0){ y++; } else if(s>0 && t[j] - (base+p) > base-2 && t[j] > 0){ s -= 1; y++; } } else if(base == p-2){ if(s > 0 && t[j] - (base+p) > base-1 && t[j] > 0){ s -= 1; y++; } } } return y; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; public class Dancing { public int specials = 0; public int p = 0; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); int n = Integer.parseInt(stdin.readLine()); int j = 0; while(j<n) { String read = stdin.readLine(); String arr[] = read.split("\\s"); int qty = Integer.parseInt(arr[0]); int s = Integer.parseInt(arr[1]); int p = Integer.parseInt(arr[2]); Dancing dancing = new Dancing(); dancing.specials = s; dancing.p = p; int total = 0; for(int i = 3; i<qty+3; i++ ) { total += processGoogler(Integer.parseInt(arr[i]) , dancing); } StringBuffer sb = new StringBuffer(); sb.append("Case #"+(j+1)+": "); sb.append(Integer.toString(total)); j++; System.out.println(sb.toString()); } } private static int processGoogler(int t, Dancing dancing ) { if( t == 0 && dancing.p == 0) return 1; int k = 0; if( t != 0) { if((t-1) % 3 == 0) { k = (t-1)/3; if(k+1>=dancing.p) return 1; return 0; } if(t % 3 == 0) { k = t/3; if(k>= dancing.p) return 1; if(dancing.specials>0) { if(k+1>=dancing.p) { dancing.specials--; return 1; } } } if( (t-2) % 3 == 0) { k =(t-2)/3; if(k+1>= dancing.p) { return 1; } if(dancing.specials>0) { if(k+2>=dancing.p) { dancing.specials--; return 1; } } } } return 0; } }
A22191
A22277
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.io.File; import java.util.Scanner; public class Googlers { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("resource/B-large.in")); int T = sc.nextInt(); int i = 1; while (i<=T) { int N = sc.nextInt(); int S = sc.nextInt(); int p = sc.nextInt(); int t[] = new int[N]; for(int j=0; j<N; j++){ t[j] = sc.nextInt(); } System.out.println("Case #"+i+": "+process(N, S, p, t)); i++; } } private static int process(int n, int s, int p, int[] t) { int counter = 0; if(p==0) return t.length; for(int i=0; i<n; i++){ if( t[i] <= 3*((p-2)>=0? (p-2): 0) + 1) { //Never happen continue; } else if(t[i] >= 3 * p - 2){ //Not surprising counter++; } else { //Surprising if(s>0){ s--; counter++; } } } return counter; } }
B12762
B13114
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.vp.common; public class CommonUtility { public static int[] convertStringArraytoIntArray(String[] sarray) { if (sarray != null) { int intarray[] = new int[sarray.length]; for (int i = 0; i < sarray.length; i++) { intarray[i] = Integer.parseInt(sarray[i]); } return intarray; } return null; } public static float[] convertStringArraytoFloatArray(String[] sarray) { if (sarray != null) { float floatArray[] = new float[sarray.length]; for (int i = 0; i < sarray.length; i++) { floatArray[i] = Float.parseFloat(sarray[i]); } return floatArray; } return null; } public static double[] convertStringArraytoDoubleArray(String[] sarray) { if (sarray != null) { double darray[] = new double[sarray.length]; for (int i = 0; i < sarray.length; i++) { darray[i] = Double.parseDouble(sarray[i]); } return darray; } return null; } public static long[] convertStringArraytoLongArray(String[] sarray) { if (sarray != null) { long longarray[] = new long[sarray.length]; for (int i = 0; i < sarray.length; i++) { longarray[i] = Long.parseLong(sarray[i]); } return longarray; } return null; } public static void print(int a[]) { System.out.print("[ "); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + ", "); } System.out.print(" ]"); System.out.println(""); } public static void printWithoutExtrLine(int a[]) { System.out.print("[ "); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + ", "); } System.out.print(" ]"); } public static void print(float a[]) { System.out.print("[ "); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + ", "); } System.out.print(" ]"); System.out.println(""); } public static void print(double a[]) { System.out.print("[ "); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + ", "); } System.out.print(" ]"); System.out.println(""); } public static void print(long a[]) { System.out.print("[ "); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + ", "); } System.out.print(" ]"); System.out.println(""); } public static void print(String a[]) { System.out.print("[ "); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + ", "); } System.out.print(" ]"); System.out.println(""); } }
B12762
B13119
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); } } }
/** * */ /** * @author Mostafa * */ public class RecycledNumbers { public static String traverse(String x) { char[] m = x.toCharArray(); m[0] = x.charAt(1); m[1] = x.charAt(0); String t = new String(m); return t; } public static String traverse1(String x) { char[] m = x.toCharArray(); m[0] = x.charAt(2); m[1] = x.charAt(0); m[2] = x.charAt(1); String t = new String(m); return t; } public static String traverse2(String x) { char[] m = x.toCharArray(); m[0] = x.charAt(1); m[1] = x.charAt(2); m[2] = x.charAt(0); String t = new String(m); return t; } public static int renumber(int first, int last) { String[] test = new String[last-first+1]; int i, j; int testc = 0; int count = 0; for (i = first; i<=last; i++) { String x = Integer.toString(i); test[testc] = x; testc++; } if (test[0].length() == 1) { count = 0; } else if (test[0].length() == 2) { for (i=0; i<test.length; i++) { for (j = i+1; j<test.length; j++) { if (test[i].compareTo(traverse(test[j])) == 0) { count++; } } } } else if (test[0].length() == 3) { for (i=0; i<test.length; i++) { for (j = i+1; j<test.length; j++) { if (test[i].compareTo(traverse1(test[j])) == 0) { count++; } if ((test[i].compareTo(traverse2(test[j])) == 0)) { count++; } } } } return count; } }
B21270
B20847
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(); } }
package codezam.exercise.WR1C2012; public class PairNumber { long numberA; long numberB; public PairNumber(long numberA, long numberB) { super(); this.numberA = numberA; this.numberB = numberB; } public long getNumberA() { return numberA; } public void setNumberA(long numberA) { this.numberA = numberA; } public long getNumberB() { return numberB; } public void setNumberB(long numberB) { this.numberB = numberB; } }
B10149
B11234
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.util.*; public class RecycledNumbers { public static void main(String[] args) { System.out.println("Enter case input:"); Scanner sc = new Scanner(System.in); int T = sc.nextInt(); sc.nextLine(); int[][] numbers = new int[T][2]; for (int t = 0; t < T; t++) { numbers[t][0] = sc.nextInt(); numbers[t][1] = sc.nextInt(); sc.nextLine(); } for (int t = 1; t <= T; t++) { int a = numbers[t - 1][0]; int b = numbers[t - 1][1]; int numRecycledPairs = 0; for (int n = a; n < b; n++) { String N = n + ""; int[] matches = new int[N.length()]; boolean duplicate = false; for (int digitFromBack = 1; digitFromBack <= N.length() - 1; digitFromBack++) { int newInt = Integer.parseInt(N.substring(N.length() - digitFromBack) + N.substring(0, N.length() - digitFromBack)); if (newInt > n && newInt <= b) { for (int match : matches) { if (newInt == match) duplicate = true; } //System.out.print(n + ":" + newInt + " "); if (!duplicate) { matches[digitFromBack] = newInt; numRecycledPairs++; } } } } System.out.println("Case #" + t + ": " + numRecycledPairs); } } }
A10699
A10595
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Dancing { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // read input file File file = new File("B-small-attempt4.in"); //File file = new File("input.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String ln = ""; int count = Integer.parseInt(br.readLine()); // write output file File out = new File("outB.txt"); BufferedWriter bw = new BufferedWriter(new FileWriter(out)); int y = 0; for (int i=0; i < count; i++){ ln = br.readLine(); y = getY(ln); bw.write("Case #" + (i+1) + ": " + y); bw.newLine(); } bw.close(); } private static int getY(String str) { String[] data = str.split(" "); int n = Integer.parseInt(data[0]); int s = Integer.parseInt(data[1]); int p = Integer.parseInt(data[2]); int[] t = new int[n]; for (int i=0; i < n; i++){ t[i] = Integer.parseInt(data[i+3]); } int y = 0; int base = 0; for(int j=0; j < t.length; j++){ base = t[j] / 3; if(base >= p) { y++; } else if(base == p-1){ if(t[j] - (base+p) > base-1 && t[j] > 0){ y++; } else if(s>0 && t[j] - (base+p) > base-2 && t[j] > 0){ s -= 1; y++; } } else if(base == p-2){ if(s > 0 && t[j] - (base+p) > base-1 && t[j] > 0){ s -= 1; y++; } } } return y; } }
package CaseSolvers; import Controller.IO; public class GooglereseCase extends CaseSolver { static Character[] opa; static { opa = new Character[26]; opa['a' - 97] = 'y'; opa['b' - 97] = 'h'; opa['c' - 97] = 'e'; opa['d' - 97] = 's'; opa['e' - 97] = 'o'; opa['f' - 97] = 'c'; opa['g' - 97] = 'v'; opa['h' - 97] = 'x'; opa['i' - 97] = 'd'; opa['j' - 97] = 'u'; opa['k' - 97] = 'i'; opa['l' - 97] = 'g'; opa['m' - 97] = 'l'; opa['n' - 97] = 'b'; opa['o' - 97] = 'k'; opa['p' - 97] = 'r'; opa['q' - 97] = 'z'; opa['r' - 97] = 't'; opa['s' - 97] = 'n'; opa['t' - 97] = 'w'; opa['u' - 97] = 'j'; opa['v' - 97] = 'p'; opa['w' - 97] = 'f'; opa['x' - 97] = 'm'; opa['y' - 97] = 'a'; opa['z' - 97] = 'q'; } StringBuilder line; public GooglereseCase(int order, int numberOfLines, IO io) { super(order, numberOfLines, io); } @Override public void addLine(String line) { this.line = new StringBuilder(line); } @Override public void printSolution() { System.err.println("Case #" + getOrder() + ": " + line); } @Override public CaseSolver process() { for (int i = 0; i < line.length(); i++) { char temp = line.charAt(i); if (temp != ' ') line.setCharAt(i, opa[temp - 97]); } return this; } @Override public void initializeVars() { // TODO Auto-generated method stub } }
A11135
A11703
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(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package test2; /** * * @author Student */ public class Score { private int i; private int j; private int k; private boolean surp; public Score(int i, int j, int k,boolean surp) { this.i = i; this.j = j; this.k = k; this.surp = surp; } public boolean isValid(){ return (i<=10&&j<=10&&k<=10)&&(i>=0&&j>=0&&k>=0); } public boolean isSurprising(){ return surp; } public boolean isbetter(int x){ return i>=x||j>=x||k>=x; } public String toString(){ return "("+i+","+j+","+k+")"; } }
A22360
A21321
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.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.util.Scanner; public class IOHelper{ Scanner sc=null; Writer output=null; public IOHelper(String input,String ouptPut){ try{ sc=new Scanner(new File(input)); output=new BufferedWriter(new FileWriter(ouptPut)); }catch(Exception e){ e.printStackTrace(); } } public String readLine(){ String result=null; result=sc.nextLine(); while(sc.hasNextLine()&& (result==" " ||result==null|| result=="")){ result=sc.nextLine(); } return result; } public void writeLine(String line){ try{ output.write(line); output.write('\n'); output.flush(); }catch(Exception e){ e.printStackTrace(); } } public void close(){ try{ output.flush(); output.close(); sc.close(); }catch(Exception e){ e.printStackTrace(); } } }
A10793
A10714
0
import java.io.*; import java.math.*; import java.util.*; import java.text.*; public class b { public static void main(String[] args) { Scanner sc = new Scanner(new BufferedInputStream(System.in)); int T = sc.nextInt(); for (int casenumber = 1; casenumber <= T; ++casenumber) { int n = sc.nextInt(); int s = sc.nextInt(); int p = sc.nextInt(); int[] ts = new int[n]; for (int i = 0; i < n; ++i) ts[i] = sc.nextInt(); int thresh1 = (p == 1 ? 1 : (3 * p - 4)); int thresh2 = (3 * p - 2); int count1 = 0, count2 = 0; for (int i = 0; i < n; ++i) { if (ts[i] >= thresh2) { ++count2; continue; } if (ts[i] >= thresh1) { ++count1; } } if (count1 > s) { count1 = s; } System.out.format("Case #%d: %d%n", casenumber, count1 + count2); } } }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class B { static BufferedReader br; static PrintWriter pw; static StringTokenizer st; static int k, ch, v = 0; static int t, n, s, p, tmp; static String str; static String[] stray = new String[110]; static int[] intray = new int[100]; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) br.read(); } public static void main(String[] args) throws IOException { br = new BufferedReader(new FileReader("input.in")); pw = new PrintWriter("output.out"); t = Integer.parseInt(br.readLine()); for (int i = 1; i <= t; i++) { str = br.readLine(); st = new StringTokenizer(str, " \t\n\r,."); while (st.hasMoreTokens()) { stray[k] = st.nextToken(); k++; } n = Integer.parseInt(stray[0]); s = Integer.parseInt(stray[1]); p = Integer.parseInt(stray[2]); for (int j = 3; j < k; j++) { intray[j - 3] = Integer.parseInt(stray[j]); } for (int j = 0; j < n; j++) { if (intray[j] == 0) { if (p == 0) { continue; } else { ch++; continue; } } if (intray[j] % 3 == 0) { tmp = intray[j] / 3; if (tmp >= p) { continue; } else { if (p - tmp <= 1) { if (s != 0) { s--; continue; } else { ch++; continue; } } else { ch++; continue; } } } else { tmp = (int) (intray[j] / 3 + 0.5); if (intray[j] % 3 == 1) { if (tmp + 1 >= p) { continue; } else { ch++; continue; } } else { if (tmp + 1 >= p) { continue; } if (tmp + 2 >= p) { if (s != 0) { s--; continue; } else { ch++; continue; } } else { ch++; continue; } } } } v++; pw.println("Case #" + v + ": " + (n - ch)); ch = 0; k = 0; } br.close(); pw.close(); } }
B10858
B11829
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.util.Arrays; import java.util.Scanner; //Recycle public class Main { public static void main(String[] args) { Main main = new Main(); main.run(); //main.checkRecycle(123, 233); } public void run() { Scanner input = new Scanner(System.in); int cases = input.nextInt(); for(int i = 0; i < cases; i++) { int a = input.nextInt(); int b = input.nextInt(); //countRecycle(a,b); System.out.println("Case #" + (i+1) + ": " + countRecycle(a,b)); } } public int countRecycle(int a, int b) { int count = 0; for(int i = a; i < b; i++) { int []alist = new int[10]; //get the count of the digits in a String inum = Integer.toString(i); for(int w = 0; w < inum.length(); w++) { alist[Integer.parseInt(inum.substring(w,w+1))]++; } for(int j = i+1; j <= b; j++) { int []blist = new int[10]; inum = Integer.toString(j); for(int x = 0; x < inum.length(); x++) { blist[Integer.parseInt(inum.substring(x,x+1))]++; } if(Arrays.equals(alist, blist) && checkRecycle(i,j)) { //System.out.println(i + " " + j); count++; } } } return count; } public boolean checkRecycle(int a, int b) { String anum = Integer.toString(a); String bnum = Integer.toString(b); for(int i = 0; i < anum.length() - 1;i++) { //System.out.println(anum + " " +anum.substring(i+1, anum.length()) + "|" + anum.substring(0, i+1)); if(bnum.equals(anum.substring(i+1, anum.length()) + anum.substring(0, i+1))) return true; } return false; } }
B10899
B12055
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; } }
package com.google.codejam2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; public class CRecycledNumbers { private void go() throws IOException { String fileIn = "resources/codejam2012/C-small-attempt0.in"; String fileOut = fileIn.replace(".in", ".out"); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut))); BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(fileIn))); int count = Integer.parseInt(r.readLine()); for(int i = 0; i < count; i++) { String out = processCase(r.readLine()); out = "Case #" + (i + 1) + ": " + out; System.out.println(out); w.write(out + "\n"); } w.close(); r.close(); } private Set<Integer> getRecycled(int n) { Set<Integer> recycled = new HashSet<Integer>(); String sn = String.valueOf(n); for(int i = 1; i < sn.length(); i++) { String newN = sn.substring(i) + sn.substring(0, i); if (!newN.startsWith("0") && !newN.equals(sn)) { recycled.add(Integer.parseInt(newN)); } } return recycled; } private String processCase(String text) { Scanner scanner = new Scanner(text); int a = scanner.nextInt(); int b = scanner.nextInt(); int out = 0; for(int i = a; i < b; i++) { Set<Integer> recycled = getRecycled(i); for(Integer rec : recycled) { int r = rec; if ((r >i) && (r <= b)) out++; } } return String.valueOf(out); } public static void main(String[] args) throws Exception { long now = System.currentTimeMillis(); new CRecycledNumbers().go(); System.out.println(String.valueOf(System.currentTimeMillis() - now) + "ms"); } }
B10245
B11949
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; } }
package codejam2012.qualification; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class ProblemC { public static void main(String[] args) throws Exception { System.setIn(new FileInputStream("C-small-attempt0.in")); System.setOut(new PrintStream(new FileOutputStream("C-small-attempt0.out"))); Scanner in = new Scanner(System.in); int testCase = in.nextInt(); Set<Integer> duplicates = new TreeSet<>(); for(int i = 1; i <= testCase; i++) { int a = in.nextInt(), b = in.nextInt(); int count = 0; for(int n = a; n < b; n++) { String s = String.valueOf(n); String s2 = s+s; duplicates.clear(); for(int j = 1, len = s.length(); j < len; j++) { int m = Integer.parseInt(s2.substring(j, j+len)); if(m > n && m <= b && !duplicates.contains(m)) { count++; duplicates.add(m); } } } System.out.printf("Case #%d: %d%n", i, count); } } }
B10155
B11757
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; /** * * @author eblanco */ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import javax.swing.JFileChooser; public class RecycledNumbers { public static String DatosArchivo[] = new String[10000]; public static int[] convertStringArraytoIntArray(String[] sarray) throws Exception { if (sarray != null) { int intarray[] = new int[sarray.length]; for (int i = 0; i < sarray.length; i++) { intarray[i] = Integer.parseInt(sarray[i]); } return intarray; } return null; } public static boolean CargarArchivo(String arch) throws FileNotFoundException, IOException { FileInputStream arch1; DataInputStream arch2; String linea; int i = 0; if (arch == null) { //frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); int rc = fc.showDialog(null, "Select a File"); if (rc == JFileChooser.APPROVE_OPTION) { arch = fc.getSelectedFile().getAbsolutePath(); } else { System.out.println("No hay nombre de archivo..Yo!"); return false; } } arch1 = new FileInputStream(arch); arch2 = new DataInputStream(arch1); do { linea = arch2.readLine(); DatosArchivo[i++] = linea; /* if (linea != null) { System.out.println(linea); }*/ } while (linea != null); arch1.close(); return true; } public static boolean GuardaArchivo(String arch, String[] Datos) throws FileNotFoundException, IOException { FileOutputStream out1; DataOutputStream out2; int i; out1 = new FileOutputStream(arch); out2 = new DataOutputStream(out1); for (i = 0; i < Datos.length; i++) { if (Datos[i] != null) { out2.writeBytes(Datos[i] + "\n"); } } out2.close(); return true; } public static void echo(Object msg) { System.out.println(msg); } public static void main(String[] args) throws IOException, Exception { String[] res = new String[10000], num = new String[2]; int i, j, k, ilong; int ele = 1; ArrayList al = new ArrayList(); String FName = "C-small-attempt0", istr, irev, linea; if (CargarArchivo("C:\\eblanco\\Desa\\CodeJam\\Code Jam\\test\\" + FName + ".in")) { for (j = 1; j <= Integer.parseInt(DatosArchivo[0]); j++) { linea = DatosArchivo[ele++]; num = linea.split(" "); al.clear(); // echo("A: "+num[0]+" B: "+num[1]); for (i = Integer.parseInt(num[0]); i <= Integer.parseInt(num[1]); i++) { istr = Integer.toString(i); ilong = istr.length(); for (k = 1; k < ilong; k++) { if (ilong > k) { irev = istr.substring(istr.length() - k, istr.length()) + istr.substring(0, istr.length() - k); //echo("caso: " + j + ": isrt: " + istr + " irev: " + irev); if ((Integer.parseInt(irev) > Integer.parseInt(num[0])) && (Integer.parseInt(irev) > Integer.parseInt(istr)) && (Integer.parseInt(irev) <= Integer.parseInt(num[1]))) { al.add("(" + istr + "," + irev + ")"); } } } } HashSet hs = new HashSet(); hs.addAll(al); al.clear(); al.addAll(hs); res[j] = "Case #" + j + ": " + al.size(); echo(res[j]); LeerArchivo.GuardaArchivo("C:\\eblanco\\Desa\\CodeJam\\Code Jam\\test\\" + FName + ".out", res); } } } }
import java.io.File; import java.io.FileInputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { try { File output = new File("output.txt"); if (output.exists()) { output.delete(); } PrintWriter pw = new PrintWriter(output); Scanner s = new Scanner(new FileInputStream("input.txt")); int T = s.nextInt(); s.nextLine(); for (int c = 0; c < T; c++) { int start = s.nextInt(); int end = s.nextInt(); int digits = digits(start); System.out.println(String.format("%d - %d (%d)", start, end, digits)); int found = 0; for (int n = start; n < end; n++) { int m = n; HashSet<Integer> pairs = new HashSet<>(); for (int i = 0; i < digits; i++) { m = rotate(m, digits); if (m <= n) continue; if (m >= start && m <= end && !pairs.contains(m)) { pairs.add(m); found++; //System.out.println(String.format("%d - %d", n, m)); } } } // pw.println(String.format("Case #%d: %d", (c+1), found)); System.out.println(String.format("Found %d numbers", found)); System.out.println("---------------------"); } // Read inputs and solve here pw.close(); System.out.println("Done !"); System.out.println(String.format("51234 rotated to %d", rotate(51234, 5))); } catch (Exception ex) { System.out.println("ERROR"); System.out.println(ex.getMessage()); ex.printStackTrace(); } } private static int digits(int n) { int d = 0; while (n > 0) { n /= 10; d++; } return d; } private static int rotate(int m, int digits) { if (digits == 1) return m; int left = m%10; m /= 10; m += left * (int)Math.pow(10, digits-1); return m; } public RecycledNumbers() { } }
B12074
B10978
0
package jp.funnything.competition.util; import java.math.BigInteger; /** * Utility for BigInteger */ public class BI { public static BigInteger ZERO = BigInteger.ZERO; public static BigInteger ONE = BigInteger.ONE; public static BigInteger add( final BigInteger x , final BigInteger y ) { return x.add( y ); } public static BigInteger add( final BigInteger x , final long y ) { return add( x , v( y ) ); } public static BigInteger add( final long x , final BigInteger y ) { return add( v( x ) , y ); } public static int cmp( final BigInteger x , final BigInteger y ) { return x.compareTo( y ); } public static int cmp( final BigInteger x , final long y ) { return cmp( x , v( y ) ); } public static int cmp( final long x , final BigInteger y ) { return cmp( v( x ) , y ); } public static BigInteger div( final BigInteger x , final BigInteger y ) { return x.divide( y ); } public static BigInteger div( final BigInteger x , final long y ) { return div( x , v( y ) ); } public static BigInteger div( final long x , final BigInteger y ) { return div( v( x ) , y ); } public static BigInteger mod( final BigInteger x , final BigInteger y ) { return x.mod( y ); } public static BigInteger mod( final BigInteger x , final long y ) { return mod( x , v( y ) ); } public static BigInteger mod( final long x , final BigInteger y ) { return mod( v( x ) , y ); } public static BigInteger mul( final BigInteger x , final BigInteger y ) { return x.multiply( y ); } public static BigInteger mul( final BigInteger x , final long y ) { return mul( x , v( y ) ); } public static BigInteger mul( final long x , final BigInteger y ) { return mul( v( x ) , y ); } public static BigInteger sub( final BigInteger x , final BigInteger y ) { return x.subtract( y ); } public static BigInteger sub( final BigInteger x , final long y ) { return sub( x , v( y ) ); } public static BigInteger sub( final long x , final BigInteger y ) { return sub( v( x ) , y ); } public static BigInteger v( final long value ) { return BigInteger.valueOf( value ); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.*; /** * * @author vichugof */ public class CodeJam { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here File archivo = null; FileReader fr = null; BufferedReader br = null; String delimiter = " "; String[] cadenaNumero; try { archivo = new File ("C://C-small-attempt2.in"); fr = new FileReader (archivo); br = new BufferedReader(fr); String linea; int numeroCasos = 0; linea=br.readLine(); numeroCasos = Integer.parseInt(linea); int A=0; int B=0; int cantidadDigitosN = 0; int cantidadDigitosM = 0; String digitoDerecha = ""; String digitoIzquierda = ""; int numComparar = 0; int cantidadNumReciclabe = 0; CodeJam objCodeJam = new CodeJam(); for(int idxCasos =0; idxCasos<numeroCasos; idxCasos++) { linea = br.readLine(); cadenaNumero = linea.split(delimiter); A = Integer.parseInt(cadenaNumero[0]); B = Integer.parseInt(cadenaNumero[1]); cantidadNumReciclabe = 0; if(B > A) { for(int idexN=A; idexN<B; idexN++) { for(int idexM=idexN+1; idexM<=B; idexM++) { cantidadDigitosN = objCodeJam.obtenerCantidadDigitos(idexN); for(int idxCambioDigito = 0; idxCambioDigito<cantidadDigitosN-1; idxCambioDigito++) { digitoDerecha = ""+objCodeJam.obtenerCantidadDigitosDerecha(idexN, idxCambioDigito); digitoIzquierda = ""+objCodeJam.obtenerCantidadDigitosIzquierda(idexN, idxCambioDigito); numComparar = Integer.parseInt(digitoDerecha+""+digitoIzquierda); if(numComparar == idexM) { //System.out.print(idexN+" : "+idexM+" - "+numComparar+" : "+idexM+" / "); cantidadNumReciclabe++; idxCambioDigito = cantidadDigitosN; } } } } } System.out.println("Case #"+(int)(idxCasos+1)+": "+cantidadNumReciclabe); } } catch(Exception e){ e.printStackTrace(); }finally{ try{ if( null != fr ){ fr.close(); } }catch (Exception e2){ e2.printStackTrace(); } } } public CodeJam() { } public int obtenerCantidadDigitos(int num) { int iCantidad = 0; int iTemp = num; while (iTemp>0) { iTemp = iTemp/10; iCantidad++; } return iCantidad; } public int obtenerCantidadDigitosDerecha(int num, int numeroDigitos) { int cantidadCien = 10; int numero = num; for(int idxCien=0; idxCien<numeroDigitos; idxCien++) { cantidadCien = cantidadCien*10; } return numero%cantidadCien; } public int obtenerCantidadDigitosIzquierda(int num, int numeroDigitos) { int cantidadCien = 10; int numero = num; for(int idxCien=0; idxCien<numeroDigitos; idxCien++) { cantidadCien = cantidadCien*10; } return numero/cantidadCien; } }
B20023
B20905
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class GoogleC { public String szamol(String input){ String result=""; String a=input; Integer min=Integer.parseInt(a.substring(0,a.indexOf(' '))); a=a.substring(a.indexOf(' ')+1); Integer max=Integer.parseInt(a); Long count=0l; for(Integer i=min; i<=max; i++){ String e1=i.toString(); Set<Integer> db=new HashSet<Integer>(); for (int j=1; j<e1.length();j++){ String e2=e1.substring(j)+e1.substring(0,j); Integer k=Integer.parseInt(e2); if (k>i && k<=max){ db.add(k); //System.out.println(e1+"\t"+e2); } } count+=db.size(); } return count.toString(); } public static void main(String[] args) { GoogleC a=new GoogleC(); //String filename="input.txt"; //String filename="C-small-attempt0.in"; String filename="C-large.in"; String thisLine; try { BufferedReader br = new BufferedReader(new FileReader(filename)); BufferedWriter bw= new BufferedWriter(new FileWriter(filename+".out")); thisLine=br.readLine(); Integer tnum=Integer.parseInt(thisLine); for(int i=0;i<tnum;i++) { // while loop begins here thisLine=br.readLine(); System.out.println(thisLine); System.out.println("Case #"+(i+1)+": "+a.szamol(thisLine)+"\n"); bw.write("Case #"+(i+1)+": "+a.szamol(thisLine)+"\n"); } // end while // end try br.close(); bw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib.converters; import com.isotopeent.codejam.lib.InputConverter; public class DynamicMultiLineConverter implements InputConverter<Object[]> { private static final int MAX_PARAM_COUNT = 10; private IntArrayLine paramConverter; private InputConverter<?> converter; private Object[] input; private int lineNumber; public DynamicMultiLineConverter(InputConverter<?> lineConverter) { this(lineConverter, 0); } public DynamicMultiLineConverter(InputConverter<?> lineConverter, int paramCount) { this.converter = lineConverter; if (paramCount > 0) { paramConverter = new IntArrayLine(paramCount); } else { paramConverter = new IntArrayLine(new int[MAX_PARAM_COUNT]); } } @Override public boolean readLine(String data) { if (lineNumber == 0) { paramConverter.readLine(data); int[] params = paramConverter.generateObject(); int count = getCount(params); input = new Object[count + 1]; input[lineNumber++] = params; } else { if (!converter.readLine(data)) { input[lineNumber++] = converter.generateObject(); } } if (lineNumber >= input.length){ lineNumber = 0; } return lineNumber == 0; } @Override public Object[] generateObject() { return input; } /** * default implementation, just uses first parameter value */ protected int getCount(int[] parameters) { return parameters[0]; } }
A12544
A12499
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.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(); } }
A20934
A22136
0
import java.util.*; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); B th = new B(); for (int i = 0; i < T; i++) { int n = sc.nextInt(); int s = sc.nextInt(); int p = sc.nextInt(); int[] t = new int[n]; for (int j = 0; j < n; j++) { t[j] = sc.nextInt(); } int c = th.getAnswer(s,p,t); System.out.println("Case #" + (i+1) + ": " + c); } } public int getAnswer(int s, int p, int[] t) { int A1 = p + p-1+p-1; int A2 = p + p-2+p-2; if (A1 < 0) A1 = 0; if (A2 < 0) A2 = 1; int remain = s; int count = 0; int n = t.length; for (int i = 0; i < n; i++) { if (t[i] >= A1) { count++; } else if (t[i] < A1 && t[i] >= A2) { if (remain > 0) { remain--; count++; } } } return count; } }
/** * */ package asem.googe.codejam.qround; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; /** * @author A.Alathwari * * Problem C : * */ public class ProblemC implements Runnable { asem.core.util.InputReader fin; java.io.PrintWriter fout; /** * @param fin * @param fout */ public ProblemC(asem.core.util.InputReader fin, PrintWriter fout) { this.fin = fin; this.fout = fout; } /** * @param fin * @param fout * @throws IOException * @throws FileNotFoundException */ public ProblemC(String fin, String fout) throws FileNotFoundException, IOException { this.fin = new asem.core.util.InputReader(new FileReader(fin)); this.fout = new PrintWriter(System.out); } /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { // TODO Auto-generated method stub try { for (int tNum = 1, inT = fin.readInt(); tNum <= inT; tNum++) { System.out.println("Case #" + tNum + ": " + ""); } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
B21227
B21211
0
import java.util.HashSet; import java.util.Scanner; public class C { static HashSet p = new HashSet(); static int low; static int high; int count = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int no = sc.nextInt(); for (int i = 1; i <= no; i++) { p.clear(); low = sc.nextInt(); high = sc.nextInt(); for (int l = low; l <= high; l++) { recycle(l); } System.out.println("Case #" + i + ": " + p.size()); } } public static void recycle(int no) { String s = Integer.toString(no); for (int i = 0; i < s.length(); i++) { String rec = s.substring(i) + s.substring(0, i); int r = Integer.parseInt(rec); if (r != no && r >= low && r <= high) { int min = Math.min(r, no); int max = Math.max(r, no); String a = Integer.toString(min) + "" + Integer.toString(max); p.add(a); } } } }
import java.util.*; import java.io.*; public class Solution { FastScanner in; PrintWriter out; int doFromStr(String s, int k) { int ans = 0; for (int i = k; i < s.length(); i++) { ans = ans * 10 + s.charAt(i) - '0'; } for (int i = 0; i < k; i++) { ans = ans * 10 + s.charAt(i) - '0'; } return ans; } public void solve() throws IOException { int cases = in.nextInt(); for (int nowCase = 1; nowCase <= cases; nowCase++) { int a = in.nextInt(); int b = in.nextInt(); long ans = 0; for (int x = a; x < b; x++) { ArrayList <Integer> add = new ArrayList<Integer>(); String s = (new Integer(x)).toString(); for (int k = 1; k < s.length(); k++) { int newVal = doFromStr(s, k); boolean newV = true; if (newVal > x && newVal <= b) { for (int i = 0; i < add.size(); i++) { if (add.get(i) == newVal) newV = false; } if (newV) add.add(newVal); } } ans += add.size(); } // out.print("Case #"); out.print(nowCase); out.print(": "); // out.print(ans); // out.println(); } } public void run() { try { in = new FastScanner(new File("c.in")); out = new PrintWriter(new File("c.out")); //in = new FastScanner(System.in); //out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String readLine() { try { return br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return " "; } int nextInt() { return Integer.parseInt(next()); } } public static void main(String[] arg) { new Solution().run(); } }
B20424
B22014
0
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { // static int MAX = 10000; static int MAX = 2000000; static Object[] All = new Object[MAX+1]; static int size( int x ) { if(x>999999) return 7; if(x>99999) return 6; if(x>9999) return 5; if(x>999) return 4; if(x>99) return 3; if(x>9) return 2; return 1; } static int[] rotate( int value ) { List<Integer> result = new ArrayList<Integer>(); int[] V = new int[8]; int s = size(value); int x = value; for(int i=s-1;i>=0;i--) { V[i] = x%10; x /=10; } int rot; for(int i=1; i<s; i++) { if(V[i]!=0){ rot=0; for(int j=0,ii=i;j<s; j++,ii=(ii+1)%s){ rot=rot*10+V[ii]; } if(rot>value && !result.contains(rot)) result.add(rot); } } if( result.isEmpty() ) return null; int[] r = new int[result.size()]; for(int i=0; i<r.length; i++) r[i]=result.get(i); return r; } static void precalculate() { for(int i=1; i<=MAX; i++){ All[i] = rotate(i); } } static int solve( Scanner in ) { int A, B, sol=0; A = in.nextInt(); B = in.nextInt(); for( int i=A; i<=B; i++) { // List<Integer> result = rotate(i); if( All[i]!=null ) { for(int value: (int[])All[i] ) { if( value <= B ) sol++; } } } return sol; } public static void main ( String args[] ) { int T; Scanner in = new Scanner(System.in); T = in.nextInt(); int cnt=0; int sol; precalculate(); for( cnt=1; cnt<=T; cnt++ ) { sol = solve( in ); System.out.printf("Case #%d: %d\n", cnt, sol); } } }
package er.dream.codejam.helpers; import java.io.File; import java.util.List; public abstract class ProblemSolver { protected FileHandler fileHandler = new FileHandler(); protected abstract List<String> handleInput(); public void execute(){ File[] files = fileHandler.listFiles(); for(File f : files){ long start = System.currentTimeMillis(); fileHandler.loadFile(f); List<String> results = handleInput(); fileHandler.writeOutput(results); fileHandler.closeConnection(); long stop = System.currentTimeMillis(); System.out.println("File "+f.getName()+" took me "+(stop-start)+"ms"); } } }
B11361
B10545
0
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class C{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int caze, T; int A, B; void run(){ T=sc.nextInt(); for(caze=1; caze<=T; caze++){ A=sc.nextInt(); B=sc.nextInt(); solve(); } } void solve(){ int ans=0; for(int n=A; n<=B; n++){ int digit=(int)(log10(n)+EPS); int d=(int)pow(10, digit); // debug("n", n); for(int m=rot(n, d); m!=n; m=rot(m, d)){ // debug("m", m); if(n<m&&m<=B){ ans++; } } } answer(ans+""); } int rot(int n, int d){ return n/10+n%10*d; } void answer(String s){ println("Case #"+caze+": "+s); } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(deepToString(os)); } public static void main(String[] args){ try{ System.setIn(new FileInputStream("dat/C-small.in")); System.setOut(new PrintStream(new FileOutputStream("dat/C-small.out"))); }catch(Exception e){} new C().run(); System.out.flush(); System.out.close(); } }
import java.io.*; import java.util.*; public class Q3{ public static void main(String args[]){ try { BufferedReader is = new BufferedReader( new InputStreamReader(new FileInputStream(new File("C-small-attempt0.in")))); BufferedWriter os = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(new File("q3output-s.txt")))); int num = Integer.parseInt(in(is)); for (int i=0;i<num;i++){ String s = in(is); String o = answer(s); p("Case #" + (i + 1) + ": " + o, os); } is.close(); os.close(); }catch(Exception e){ e.printStackTrace(); } } private static String in(BufferedReader is) throws IOException{ return is.readLine(); } private static void p(String n, String w){ System.out.println(n + ":" + w); } private static void p(String w) { System.out.println(w); } private static void p(int w) { p(""+w); } private static void p(String w, BufferedWriter os) throws IOException{ os.write(w); os.newLine(); } private static String answer(String s) { StringTokenizer sb = new StringTokenizer(s); int result = 0; int min = Integer.parseInt(sb.nextToken()); int max = Integer.parseInt(sb.nextToken()); int border = first(max); for (int i=min;i<=max;i++){ result += pair(i, border, max); } return ""+result; } private static int pair(int i, int border, int max){ int result = 0; int first = first(i); int num = i; int target = 0; int out = 0; Set<Integer> dup = new HashSet<Integer>(); while(num >= 10 ) { target = num % 10; num = num/10; out++; int convert = convert(num, i, out); if (target > first && target < border) { if(!dup.contains(convert)){ dup.add(convert); result++; } } else if(target == first && target == border) { if(!dup.contains(convert) && compare(convert, i) && !compare(convert, max)){ dup.add(convert); result++; } } else if(target == first) { if(!dup.contains(convert) && compare(convert, i) && !compare(convert, max)){ dup.add(convert); result++; } } else if(target == border) { if(!dup.contains(convert) && compare(convert, i) && !compare(convert, max)){ dup.add(convert); result++; } } } return result; } private static int first(int num){ int ret = num; while(ret >= 10) { ret = ret/10; } return ret; } private static int convert(int num, int all, int out){ int m = power(out); int p = digits(num); return (all - num * m) * p + num; } private static boolean compare(int n, int com){ return n > com; } private static int digits(int num){ int ret = 10; while(num >= 10) { num = num/10; ret*=10; } return ret; } private static int power(int out){ int ret = 1; for(int i =0;i<out;i++){ ret *= 10; } return ret; } }
A12273
A10768
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.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Dancing { private static Map<String, String> knowledgeBase = new HashMap<String, String>(); static { knowledgeBase.put("our language is impossible to understand", "ejp mysljylc kd kxveddknmc re jsicpdrysi"); knowledgeBase.put("there are twenty six factorial possibilities", "rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"); knowledgeBase.put("so it is okay if you want to just give up", "de kr kd eoya kw aej tysr re ujdr lkgc jv"); knowledgeBase.put("aozq", "yeqz"); } private BufferedReader reader; private BufferedWriter writer; /** * @param args */ public static void main(String[] args) { Dancing dancing = new Dancing(args[0]); dancing.executeTests(); } public Dancing(String filename) { // Open file File file = new File(filename); try { reader = new BufferedReader(new FileReader(file)); writer = new BufferedWriter(new FileWriter(file+".out")); } catch (IOException e) { // Failed to open new buffered reader System.err.println("Failed to open FileReader"); e.printStackTrace(); System.exit(-1); } } private void executeTests() { // Read number of test cases int numberOfTests = 0; try { // Read number of tests (first line) numberOfTests = Integer.parseInt(reader.readLine()); } catch (NumberFormatException | IOException e) { // Failed to read a line System.err.println("Failed to read a line"); e.printStackTrace(); System.exit(-1); } for (int testCase = 1; testCase <= numberOfTests; testCase++) { String[] input; try { input = reader.readLine().split("\\s"); int contestants = Integer.parseInt(input[0]); int surprises = Integer.parseInt(input[1]); int threshhold = Integer.parseInt(input[2]); List<Integer> scores = new ArrayList<Integer>(); for (int i = 3; i < 3 + contestants; i++) { scores.add(Integer.parseInt(input[i])); } int answer = findWinners(surprises, threshhold, scores); writer.write("Case #" + testCase + ": " + answer + '\n'); } catch (IOException e) { e.printStackTrace(); } } try { reader.close(); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } private static int findWinners(int surprises, int threshhold, List<Integer> scores) { int totalPossible = 0; int surprisesRemaining = surprises; for (Integer score : scores) { Map<String, Integer> maxScores = getMaxScores(score); if (maxScores.get("normal") >= threshhold) { totalPossible++; } else if (maxScores.get("surprise") >= threshhold && surprisesRemaining > 0) { totalPossible++; surprisesRemaining--; } } return totalPossible; } private static Map<String, Integer> getMaxScores(int totalScore) { int maxNormalScore = ((totalScore - 1) / 3) + 1; int maxSurpriseScore = maxNormalScore; if (totalScore % 3 != 1) { maxSurpriseScore++; } Map<String, Integer> maxScores = new HashMap<String, Integer>(); maxScores.put("normal", maxNormalScore); maxScores.put("surprise", maxSurpriseScore); // Special case to continue using integer division if (totalScore == 0) { maxScores.put("normal", 0); maxScores.put("surprise", 0); } return maxScores; } }
A12570
A12241
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.File; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class B { public static void main(String args[]) throws Exception { final String PATH = "/home/goalboy/software installation/codejam-commandline-1.0-beta4/source/"; final String FILE = "B-small-0"; Scanner in = new Scanner(new File(PATH + FILE + ".in")); PrintWriter out = new PrintWriter(PATH + FILE + ".out"); int test = in.nextInt(); for (int t = 1; t <= test; t++) { int N = in.nextInt(); int S = in.nextInt(); int p = in.nextInt(); int totals[] = new int[N]; int bests[] = new int[N]; boolean addables[] = new boolean[N]; for (int i = 0; i < N; i++) { totals[i] = in.nextInt(); } Arrays.sort(totals); for (int i = 0; i < N; i++) { if (totals[i] % 3 == 0) { bests[i] = totals[i] / 3; addables[i] = (bests[i] > 0); } else if (totals[i] % 3 == 1) { bests[i] = totals[i] / 3 + 1; addables[i] = false; } else { bests[i] = totals[i] / 3 + 1; addables[i] = (bests[i] > 0); } } int result = 0; for (int i = N - 1; i >= 0; i--) { if (bests[i] >= p) { result++; } else if (addables[i] && bests[i] + 1 >= p && S > 0) { result++; S--; } } out.println("Case #" + t + ": " + result); } out.close(); } }
B10702
B11564
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 codejam.is; /** * Created with IntelliJ IDEA. * User: ofer * Date: 4/13/12 * Time: 8:49 PM * To change this template use File | Settings | File Templates. */ public abstract class TestAbstract implements Test { private final static String newline = System.getProperty("line.separator"); @Override public String getOutput(int testNum) { return "Case #" + testNum + ": " + getTestResult() + newline; } protected abstract String getTestResult(); }
A22642
A20043
0
import java.util.*; import java.io.*; public class DancingWithTheGooglers { public DancingWithTheGooglers() { Scanner inFile = null; try { inFile = new Scanner(new File("inputB.txt")); } catch(Exception e) { System.out.println("Problem opening input file. Exiting..."); System.exit(0); } int t = inFile.nextInt(); int [] results = new int [t]; DancingWithTheGooglersMax [] rnc = new DancingWithTheGooglersMax[t]; int i, j; int [] scores; int s, p; for(i = 0; i < t; i++) { scores = new int [inFile.nextInt()]; s = inFile.nextInt(); p = inFile.nextInt(); for(j = 0; j < scores.length; j++) scores[j] = inFile.nextInt(); rnc[i] = new DancingWithTheGooglersMax(i, scores, s, p, results); rnc[i].start(); } inFile.close(); boolean done = false; while(!done) { done = true; for(i = 0; i < t; i++) if(rnc[i].isAlive()) { done = false; break; } } PrintWriter outFile = null; try { outFile = new PrintWriter(new File("outputB.txt")); } catch(Exception e) { System.out.println("Problem opening output file. Exiting..."); System.exit(0); } for(i = 0; i < results.length; i++) outFile.printf("Case #%d: %d\n", i+1, results[i]); outFile.close(); } public static void main(String [] args) { new DancingWithTheGooglers(); } private class DancingWithTheGooglersMax extends Thread { int id; int s, p; int [] results, scores; public DancingWithTheGooglersMax(int i, int [] aScores, int aS, int aP,int [] res) { id = i; s = aS; p = aP; results = res; scores = aScores; } public void run() { int a = 0, b = 0; if(p == 0) results[id] = scores.length; else if(p == 1) { int y; y = 3*p - 3; for(int i = 0; i < scores.length; i++) if(scores[i] > y) a++; else if(scores[i] > 0) b++; b = Math.min(b, s); results[id] = a+b; } else { int y, z; y = 3*p - 3; z = 3*p - 5; for(int i = 0; i < scores.length; i++) if(scores[i] > y) a++; else if(scores[i] > z) b++; b = Math.min(b, s); results[id] = a+b; } } } }
package Qual2012; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class Qual2012B { public static void main(String args[]){ // String filePath = "X:\\GCJ\\2012B-small-attempt0.in"; String filePath = "X:\\GCJ\\2012B-large-attempt0.in"; FileInputStream fis = null; BufferedReader readFile = null; String line; try { fis = new FileInputStream(filePath); readFile = new BufferedReader(new InputStreamReader(fis, "ISO-8859-1")); line = readFile.readLine(); int T = Integer.parseInt(line); for (int i = 1; i <= T; i++) { line = readFile.readLine(); System.out.println("Case #" + i + ": " + solve(line) ); } } catch(Exception e) { e.printStackTrace(); }finally{ try { fis.close(); readFile.close(); } catch (IOException e) { e.printStackTrace(); } } } private static int solve (String line) { String[] temp = line.split(" "); int n = Integer.parseInt(temp[0]); int s = Integer.parseInt(temp[1]); int p = Integer.parseInt(temp[2]); int[] t = new int[n]; int ret = 0; for (int i = 0; i < n; i++) t[i] = Integer.parseInt(temp[i + 3]); for (int i = 0; i < n; i++) { int remainder = t[i] % 3; int max = (t[i] + 2) / 3; if (max >= p) { ret++; continue; } else if (remainder != 1 && t[i] > 0 && max + 1 >= p && s > 0) { ret++; s--; } } return ret; } }
A22771
A20483
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(); } }
package dom.zar.jam.qualifications; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class DancingWithTheGooglers { public static void main(String[] args) { Scanner in = new Scanner(System.in); int inputLines = in.nextInt(); for (int i = 0; i < inputLines;) { int googlersAmount = in.nextInt(); int suprising = in.nextInt(); int minPoints = in.nextInt(); final int[] googlers = new int[googlersAmount]; for (int k = 0; k < googlersAmount; ++k) { googlers[k] = in.nextInt(); } System.out.println("Case #" + ++i + ": " + result(suprising, minPoints, googlers)); } } private static int result(int suprising, int minPoints, int[] googlers) { final List<Integer> filtered = new ArrayList<Integer>(); for (int points : googlers) { boolean hasMin = (points / 3) >= minPoints; boolean oneLessThanMin = ((points - minPoints) >> 1) == (minPoints - 1); if (!(hasMin || oneLessThanMin)) { filtered.add(points); } } int probable = 0; for (Integer points : filtered) { if (points - minPoints < 0) continue; int restPoints = (points - minPoints) >> 1; if (Math.abs(restPoints - minPoints) <= 2) probable++; } probable = Math.min(probable, suprising); return googlers.length - filtered.size() + probable; } }
B13196
B10921
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(); } }
package utils; /** * * @author Fabien Renaud */ public abstract class Jam implements Runnable, JamParser { protected final String[] lines; protected final JamCase[] cases; protected final int t; private final String filenameInput; private final String filenameOutput; private final String[] output; private final StopWatch timer; private int count; protected Jam(String filename) { this.filenameInput = filename; this.filenameOutput = filename.replace(".in", ".out"); this.count = 0; this.lines = File.readAllLines(filenameInput); this.timer = new StopWatch(); this.t = Integer.parseInt(lines[0]); this.cases = new JamCase[t]; this.output = new String[t]; File.delete(filenameOutput); } protected final synchronized void appendOutput(int number, String result) { output[number - 1] = String.format("Case #%1$d: %2$s", number, result); count++; if (count == t) { timer.stop(); saveOutput(); } } private void saveOutput() { if (count != t) { System.err.println(String.format("%1$d results are missing. File not saved.")); } else { File.writeAllLines(filenameOutput, output); System.out.println("File saved at " + filenameOutput); System.out.println("---------- OUTPUT ----------"); for (String s : output) { System.out.println(s); } System.out.println("--- Processed in " + timer.getElapsedSeconds() + " seconds."); } } @Override public final void run() { int j; count = 0; timer.start(); for (int i = 1; i <= t; i++) { j = i - 1; cases[j] = getJamCase(i); if (cases[j] != null) { new Thread(cases[j]).start(); } } } }
B22190
B21484
0
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class Recycled { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for (int i = 0; i < t; i++) { String[] str = br.readLine().split(" "); int a = Integer.parseInt(str[0]); int b = Integer.parseInt(str[1]); System.out.println("Case #" + (i + 1) + ": " + find(a, b)); } } catch (IOException e) { e.printStackTrace(); } } private static int find(int a, int b) { HashSet<Long> used = new HashSet<Long>(); int digits = String.valueOf(a).length(); if (digits == 1) return 0; for (int i = a; i <= b; i++) { int s = 10; int m = (int) Math.pow(10, digits-1); for (int j = 0; j < digits-1; j++) { int r = i % s; if (r < s/10) continue; int q = i / s; int rn = r * m + q; s *= 10; m /= 10; if (i != rn && rn >= a && rn <= b) { long pp; if (rn < i) pp = (long)rn << 30 | i; else pp = (long)i << 30 | rn; if (!used.contains(pp)) { used.add(pp); } } } } return used.size(); } }
import java.util.*; import java.io.*; class gcj2{ public static void main(String[] args) throws IOException{ BufferedReader inp = new BufferedReader(new FileReader("inp.txt")); BufferedWriter out = new BufferedWriter(new FileWriter("out.txt")); int test = Integer.parseInt(inp.readLine()); int p = 1; while(test>0){ String d[] = inp.readLine().split(" "); int a = Integer.parseInt(d[0]); int b = Integer.parseInt(d[1]); int i = a; int count = 0; while(i<=b){ String s = new Integer(i).toString(); int j = 1; HashSet<Integer> se = new HashSet<Integer>(); while(j<s.length()){ String temp = s.substring(j,s.length())+s.substring(0,j); if(temp.charAt(0)=='0') { j++; continue; } else { int t = Integer.parseInt(temp); se.add(t); } j++; } Iterator<Integer> it = se.iterator(); while(it.hasNext()){ int gg = it.next(); if(gg>i&&gg<=b){ // System.out.println(gg +" "+i); count++; } } // System.out.println("------------------"); i++; } out.write("Case #"+p+": "+count+"\n"); System.out.println(count); test--; p++; } out.close(); } }
A20119
A21138
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 com.gzroger.codejam2012; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; public class QB { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader(args[0])); int nCases = Integer.parseInt( reader.readLine() ); for (int iCases=0; iCases<nCases; iCases++) { String stLine = reader.readLine(); int N, S, p; StringTokenizer st = new StringTokenizer(stLine); N = Integer.parseInt( st.nextToken() ); S = Integer.parseInt( st.nextToken() ); p = Integer.parseInt( st.nextToken() ); int[] K = new int[N]; for (int i=0; i<N; i++) { K[i] = Integer.parseInt( st.nextToken() ); } System.out.println("Case #"+(iCases+1)+": "+ possible(N, S, p, K)); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static int possible(int N, int S, int p, int[] K) { int cPos = 0; for (int i=0; i<N; i++) { int maxIfS = (int) Math.floor( (K[i]+4) / 3.0d); int maxIfNotS = (int) Math.floor( (K[i]+2) / 3.0d ); if (K[i] == 0) { maxIfS = 0; maxIfNotS = 0; } else if (K[i] == 1) { maxIfS = 1; maxIfNotS = 1; } else if (K[i] == 2) { maxIfS = 2; maxIfNotS = 1; } if ( (maxIfS+maxIfS-2+maxIfS-2) > K[i] ) { System.out.println("problem!"); } if ( (maxIfNotS+maxIfNotS-1+maxIfNotS-1) > K[i] ) { System.out.println("problem!"); } if (maxIfNotS>=p) cPos++; else if (maxIfS>=p && S>0) { cPos++; S--; } } return cPos; } }
B20856
B20833
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"); } }
import java.io.File; import java.io.FileNotFoundException; import java.lang.Integer; import java.util.LinkedList; import java.util.Scanner; import java.util.TreeSet; public class RecycledNumbers { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File("input.in")); //Scanner sc = new Scanner(System.in); int T=sc.nextInt(); for( int i=0;i<T;i++) { int count =0; int A = sc.nextInt(); int B = sc.nextInt(); int n = A; for(n=A;n<B;n++) { int l = Integer.toString(n).length(); int n2=n; int n5=1; TreeSet<Integer> L = new TreeSet<Integer>(); for(int j=1;j<l;j++){ n5=n5*10; } for(int j=1;j<l;j++) { int n3=n2/10; int n4=n2%10; n2=n5*n4+n3; if(n2>n && n2<=B) { if(!L.contains(n2)) { L.add(n2); count ++; } } } } System.out.println("Case #"+(i+1)+": "+count); } } }
A21396
A21902
0
import java.util.*; public class Test { public static void main(String[] args){ Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int i = 1; i<=T; i++) { int n = in.nextInt(); int s = in.nextInt(); int p = in.nextInt(); int result = 0; for(int j = 0; j<n; j++){ int x = canAddUp(in.nextInt(), p); if(x == 0) { result++; } else if (x==1 && s > 0) { result++; s--; } } System.out.println("Case #"+i+": "+result); } } public static int canAddUp(int sum, int limit) { boolean flag = false; for(int i = 0; i<=sum; i++) { for(int j = 0; i+j <= sum; j++) { int k = sum-(i+j); int a = Math.abs(i-j); int b = Math.abs(i-k); int c = Math.abs(j-k); if(a > 2 || b > 2 || c> 2){ continue; } if (i>=limit || j>=limit || k>=limit) { if(a < 2 && b < 2 && c < 2) { return 0; }else{ flag = true; } } } } return (flag) ? 1 : 2; } }
import java.io.*; public class dancing { static int N; static int S; static int p; static int[] t; public static boolean normal(int tot){ int max = tot%3==0?tot/3:tot/3+1; return max>=p; } public static boolean surprising(int tot){ int max = tot==0?0:(tot+1)/3+1; return max>=p; } public static int solve(){ int DB=0; int SDB = S; for(int i=0; i<N; i++){ if(normal(t[i])) DB++; else if(SDB > 0 && surprising(t[i])){ DB++; SDB--; } } return DB; } public static void main (String args[]) throws IOException{ BufferedReader be = new BufferedReader(new FileReader("B-large.in")); int T = Integer.parseInt(be.readLine()); for(int i=1; i<=T; i++){ String s = be.readLine(); N = Integer.parseInt(s.split(" ")[0]); S = Integer.parseInt(s.split(" ")[1]); p = Integer.parseInt(s.split(" ")[2]); t = new int[N]; for(int j = 0; j < N; j++) t[j] = Integer.parseInt(s.split(" ")[j+3]); System.out.println("Case #"+i+": "+solve()); } be.close(); } }
B12074
B12736
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.Scanner; public class C_RecycledNumbers { static int[] bases = {0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000}; static int digits(int value) { int i = 0; for (; i < bases.length && value >= bases[i]; i++); return i; } static int shift(int value, int len) { int last = value % 10; return (int)(Math.pow(10, len - 1)) * last + (value / 10); } static int countRecycled(int value, int B) { int shifted = value; int len = digits(value); int[] cache = new int[len]; int ck = 0; out: for (int i = 0; i < len - 1; i++) { shifted = shift(shifted, len); if (shifted > value && shifted <= B) { for (int j = 0; cache[j] != 0; j++) if (cache[j] == shifted) continue out; //System.out.println("n=" + value + ", m=" + shifted); cache[ck++] = shifted; } } return ck; } /** * @param args */ public static void main(String[] args) { /*int A = 1; int B = 500; int count = 0; for (int val = A; val <= B; val++) { count += countRecycled(val, B); } System.out.println(count);*/ Scanner scan = new Scanner(System.in); int test = scan.nextInt(); for (int t = 1; t <= test; t++) { int A = scan.nextInt(); int B = scan.nextInt(); int count = 0; for (int val = A; val <= B; val++) { count += countRecycled(val, B); } System.out.println("Case #" + t + ": " + count); } } }
B11361
B10740
0
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class C{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int caze, T; int A, B; void run(){ T=sc.nextInt(); for(caze=1; caze<=T; caze++){ A=sc.nextInt(); B=sc.nextInt(); solve(); } } void solve(){ int ans=0; for(int n=A; n<=B; n++){ int digit=(int)(log10(n)+EPS); int d=(int)pow(10, digit); // debug("n", n); for(int m=rot(n, d); m!=n; m=rot(m, d)){ // debug("m", m); if(n<m&&m<=B){ ans++; } } } answer(ans+""); } int rot(int n, int d){ return n/10+n%10*d; } void answer(String s){ println("Case #"+caze+": "+s); } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(deepToString(os)); } public static void main(String[] args){ try{ System.setIn(new FileInputStream("dat/C-small.in")); System.setOut(new PrintStream(new FileOutputStream("dat/C-small.out"))); }catch(Exception e){} new C().run(); System.out.flush(); System.out.close(); } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class problem3 { void main() { solve(); } public void solve() { try { FileInputStream fstream = new FileInputStream("pr3_input.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fout = new FileWriter("output.txt"); BufferedWriter out = new BufferedWriter(fout); int iCases = Integer.parseInt(br.readLine()); for (int iStep = 0; iStep < iCases; iStep++) { String strLine = br.readLine(); String[] myNumbers = strLine.split(" "); int A = Integer.valueOf(myNumbers[0]).intValue(); int B = Integer.valueOf(myNumbers[1]).intValue(); int digits = myNumbers[0].length(); int iValue = 0; for (int jStep = A; jStep <= B; jStep++) { List<Integer> pairs = new ArrayList<Integer>(); for (int kStep = 1; kStep < digits; kStep++) { int m = perm(jStep, kStep); if ((A <= jStep)&&(jStep < m)&&(m <= B)) { if (false == pairs.contains(m)) { iValue++; pairs.add(m); } } } } if (iStep != (iCases - 1)) { out.write(String.format("Case #%d: %d\n", iStep + 1, iValue)); } else { out.write(String.format("Case #%d: %d", iStep + 1, iValue)); } } out.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } public int perm(int iNumber, int iDigitsPerm) { String strNumber = String.format("%d", iNumber); String strReturn = strNumber.substring(strNumber.length() - iDigitsPerm) + strNumber.substring(0, strNumber.length() - iDigitsPerm); if (strReturn.charAt(0) == '0') { strReturn = "0"; } return Integer.parseInt(strReturn); } }
A22992
A22367
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 com.blah; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; class Triplet { int numbers[] = new int[3]; public Triplet(int number) { numbers[0] = numbers[1] = numbers[2] = number; // TODO Auto-generated constructor stub } boolean hasBestResultOrMore(int p){ return numbers[0]>=p || numbers[1]>=p || numbers[2]>=p; } @Override public String toString() { // TODO Auto-generated method stub return "[" + numbers[0] +"," + numbers[1] +"," + numbers[2] +"]"; } } class ComponentNumber { @Override public String toString() { // TODO Auto-generated method stub return "Number "+total+" : "+primary+","+secondary+" (*)" ; } int total; boolean marked = false; Triplet primary,secondary = null;//secondary is a surprising result always boolean hasBestResultOrMore(int p){ return primary.hasBestResultOrMore(p); } boolean hasSurprisingBestResultOrMore(int p){ return secondary!=null && secondary.hasBestResultOrMore(p); } public ComponentNumber(int totalPoints) { total = totalPoints; int base = totalPoints/3; primary = new Triplet(base); if(totalPoints==0){ //do nothing, 0 = 0 + 0 + 0 } else if(totalPoints==1){ primary.numbers[2] = 1; //1 = 0 + 0 + 1 or any other permutation } else { switch(totalPoints%3){ case 2: primary.numbers[1] = primary.numbers[2] = base + 1; secondary = new Triplet(base); secondary.numbers[2] = base + 2; break; case 1: primary.numbers[2] = base + 1; secondary = new Triplet(base); secondary.numbers[0] = base - 1; secondary.numbers[1] = secondary.numbers[2] = base + 1; break; case 0: secondary = new Triplet(base); secondary.numbers[0] = base - 1; secondary.numbers[2] = base + 1; break; } } } } class Case { int googlers; int surprising; int bestResult; ArrayList<Integer> results; int components[][] = new int[3][2]; Case(String g,String s,String p){ googlers = Integer.parseInt(g); surprising = Integer.parseInt(s); bestResult = Integer.parseInt(p); results = new ArrayList<Integer>(); } void addResult(String result){ results.add(Integer.parseInt(result)); } } public class MainProblem3 { public static void main(String[] args) { ArrayList<Case> cases = new ArrayList<Case>(); try { System.setOut(new PrintStream("data.out")); BufferedReader br = new BufferedReader(new FileReader("data.in")); int numCases = Integer.parseInt(br.readLine()); StringTokenizer st; Case aCase; for (int i = 0; i < numCases; i++) { st = new StringTokenizer(br.readLine()); aCase = new Case(st.nextToken(), st.nextToken(), st.nextToken()); for (int j = 0; j < aCase.googlers; j++) { aCase.addResult(st.nextToken()); } cases.add(aCase); } resolver(cases); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void resolver(ArrayList<Case> cases) { Case aCase; for (int j = 0; j < cases.size(); j++) { aCase = cases.get(j); int p = aCase.bestResult; int s = aCase.surprising; ArrayList<ComponentNumber> theBest = new ArrayList<ComponentNumber>(); ArrayList<ComponentNumber> theSurprises = new ArrayList<ComponentNumber>(); ComponentNumber aCandidate; for (int k = 0; k < aCase.googlers; k++) { aCandidate = new ComponentNumber(aCase.results.get(k)); //System.out.println(aCandidate); if(aCandidate.hasBestResultOrMore(p)){ theBest.add(aCandidate); } else if(aCandidate.hasSurprisingBestResultOrMore(p)){ theSurprises.add(aCandidate); } } int totalBest = theBest.size() + Math.min(theSurprises.size(), s); System.out.println("Case #"+(j+1)+": "+totalBest); } } }
A10996
A13162
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 tr0llhoehle.cakemix.utility.googleCodeJam; import java.text.ParseException; /** * This class is a base class for all concrete problems. It is used to define * some methods necessary for the IOManager to work. It is crucial that the * addValue-Method gets extended and called (super.addValue(o)) by the extending * class. * * @author Cakemix * @see IOManager * @see Solver */ public abstract class Problem { protected SupportedTypes[] types; protected int cntr = 0; protected boolean isInitialised = false; /** * Returns an array of SupportedTypes which define exactly what data is * stored in this problem. * * The attribute "types" needs to be initialized in the constructor of the * extending class. * * @return An array of SupportedTypes which define exactly what data is * stored in this problem. * @see SupportedTypes */ public SupportedTypes[] getTypes() { return types; } public void addValue(Object o) throws ParseException { if (!isInitialised) { cntr++; isInitialised = (cntr == types.length); } else { throw new ParseException("Tried to add another value to this Problem even though all values are set.", cntr); } } }
A10568
A13032
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); } }
package b; import java.util.Arrays; import java.util.Scanner; public class B { public B() { Scanner s = new Scanner (System.in); int t = s.nextInt(); for(int i =0; i < t; i++) { int n = s.nextInt(); int ss = s.nextInt(); int p = s.nextInt(); int[] vals = new int[n]; for(int j = 0; j < n; j ++) vals[j]=s.nextInt(); Arrays.sort(vals); int num=0, numLeft = ss; for(int j=vals.length-1; j >=0;j--) { //System.out.println(vals[j]); if(numLeft==0 || vals[j]>=29 || vals[j]<2 || (vals[j]+2)/3>=p) { //System.out.println("here "+(vals[j]+2)/3); if((vals[j]+2)/3>=p) { num++; } } else { if((vals[j]+4)/3>=p) { numLeft--; num++; } } } System.out.println("Case #"+(i+1)+": "+num); } } /** * @param args */ public static void main(String[] args) { new B(); } }
A20382
A21902
0
package dancinggooglers; import java.io.File; import java.util.Scanner; public class DanceScoreCalculator { public static void main(String[] args) { if(args.length <= 0 || args[0] == null) { System.out.println("You must enter a file to read"); System.out.println("Usage: blah <filename>"); System.exit(0); } File argFile = new File(args[0]); try { Scanner googleSpeakScanner = new Scanner(argFile); String firstLine = googleSpeakScanner.nextLine(); Integer linesToScan = new Integer(firstLine); for(int i = 1; i <= linesToScan; i++) { String googleDancerLine = googleSpeakScanner.nextLine(); DanceScoreCase danceCase = new DanceScoreCase(googleDancerLine); System.out.println(String.format("Case #%d: %d", i, danceCase.maxDancersThatCouldPass())); } } catch (Exception e) { e.printStackTrace(); } } }
import java.io.*; public class dancing { static int N; static int S; static int p; static int[] t; public static boolean normal(int tot){ int max = tot%3==0?tot/3:tot/3+1; return max>=p; } public static boolean surprising(int tot){ int max = tot==0?0:(tot+1)/3+1; return max>=p; } public static int solve(){ int DB=0; int SDB = S; for(int i=0; i<N; i++){ if(normal(t[i])) DB++; else if(SDB > 0 && surprising(t[i])){ DB++; SDB--; } } return DB; } public static void main (String args[]) throws IOException{ BufferedReader be = new BufferedReader(new FileReader("B-large.in")); int T = Integer.parseInt(be.readLine()); for(int i=1; i<=T; i++){ String s = be.readLine(); N = Integer.parseInt(s.split(" ")[0]); S = Integer.parseInt(s.split(" ")[1]); p = Integer.parseInt(s.split(" ")[2]); t = new int[N]; for(int j = 0; j < N; j++) t[j] = Integer.parseInt(s.split(" ")[j+3]); System.out.println("Case #"+i+": "+solve()); } be.close(); } }
A22360
A20363
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 bsmall; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Vector; public class Bsmall { /** * @param args */ public static void main(String[] args) { int numLinhas = -1; Vector<String> linhas = new Vector<String>(); try { BufferedReader input = new BufferedReader(new FileReader("./src/bsmall/B-large.in")); String linha; while((linha = input.readLine()) != null){ if(numLinhas == -1) numLinhas = Integer.parseInt(linha); else linhas.add(linha + " "); } input.close(); BufferedWriter output = new BufferedWriter(new FileWriter(new File("output.txt"))); for(int i = 0; i < numLinhas; i++){ int numCase = i+1; output.write("Case #" + numCase + ": "); char[] letras = linhas.get(i).toCharArray(); String tmp = null; int N = -1; int S = -1; int p = -1; Vector<Integer> notes = new Vector<Integer>(); for(int j=0; j<letras.length; j++){ if( letras[j] != ' ' ) { if(tmp == null) tmp = Character.toString(letras[j]); else tmp = tmp+Character.toString(letras[j]); } else{ int num = Integer.parseInt(tmp); tmp = null; if( N == -1) N = num; else if ( S == -1 ) S = num; else if ( p == -1 ) p = num; else notes.add(num); // System.out.println(num); } } // System.out.println(N + " " + S + " " + p); // System.out.println(notes.get(0)); Vector<Integer> bom = new Vector<Integer>(); Vector<Integer> surprising = new Vector<Integer>(); for( int k = 0; k < notes.size(); k++){ if(notes.get(k) >= p*3 - 2) bom.add(notes.get(k)); else if( notes.get(k) >= p*3 - 4 && notes.get(k) > 1) surprising.add(notes.get(k)); } // System.out.println(bom.size() + " " + surprising.size()); int result = bom.size() + Math.min(surprising.size(), S); output.write(String.valueOf(result)); output.newLine(); } output.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
B10245
B13229
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.util.ArrayList; import java.util.HashMap; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { BufferedReader br = new BufferedReader(new FileReader("/Users/William/Desktop/C-small-attempt0.in")); String strLine; FileWriter fostream = new FileWriter("/Users/William/Desktop/output.txt"); BufferedWriter out = new BufferedWriter(fostream); strLine = br.readLine(); int numOfLine = Integer.parseInt(strLine); for (int i=1;i<numOfLine+1;i++) { strLine = br.readLine(); String splitedStr[] = strLine.split(" "); String first = splitedStr[0]; String second = splitedStr[1]; int firstNum = Integer.parseInt(first); int secondNum = Integer.parseInt(second); int count = 0; for (int k=firstNum;k<=secondNum;k++) { Integer kInt = new Integer(k); String kStr = kInt.toString(); HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>(); for (int j=1;j<kStr.length();j++) { String digit = kStr.substring(kStr.length()-j); String rest = kStr.substring(0, kStr.length()-j); String newStr = digit + rest; if (newStr.charAt(0)=='0') { continue; } int newNum = Integer.parseInt(newStr); ArrayList<Integer> list; if (map.get(k)==null) { list = new ArrayList<Integer>(); } else { list = map.get(k); } boolean contains = false; for (Integer m : list) { if (m.intValue()==newNum) { contains = true; break; } } if (contains) { continue; } list.add(newNum); map.put(k, list); if ((newNum>k) && (newNum<=secondNum)) { // System.out.println("(" + k + " , " + newNum + ")"); count ++; } } } System.out.println("Case #" + i + ": " + count); out.write("Case #" + i + ": " + count + "\n"); } out.close(); br.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } }
B11421
B10153
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Recycled { public static void main(String[] args) throws Exception{ String inputFile = "C-small-attempt0.in"; BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output"))); long num_cases = Long.parseLong(input.readLine()); int current_case = 0; while (current_case < num_cases){ current_case++; String[] fields = input.readLine().split(" "); int A = Integer.parseInt(fields[0]); int B = Integer.parseInt(fields[1]); int total = 0; for (int n = A; n < B; n++){ for (int m = n+1; m <= B; m++){ if (isRecycled(n,m)) total++; } } System.out.println("Case #" + current_case + ": " + total); output.write("Case #" + current_case + ": " + total + "\n"); } output.close(); } private static boolean isRecycled(int n, int m) { String sn = ""+n; String sm = ""+m; if (sn.length() != sm.length()) return false; int totaln = 0, totalm = 0; for (int i = 0; i < sn.length(); i++){ totaln += sn.charAt(i); totalm += sm.charAt(i); } if (totaln != totalm) return false; for (int i = 0; i < sn.length()-1; i++){ sm = sm.charAt(sm.length() - 1) + sm.substring(0, sm.length() - 1); if (sm.equals(sn)) return true; } return false; } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; public class CodeJam { private static BufferedReader reader; private static BufferedWriter writer; public static void main(String args[]) throws Exception { prepareFiles("C-small-attempt0"); int T = Integer.parseInt(reader.readLine()); for(int i = 0; i < T; i++) { String[] line = reader.readLine().split(" "); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); int l = String.valueOf(A).length(); int recycled = 0; for(int n = A; n <= B; n++) { HashSet<Integer> checkedCycles = new HashSet<>(); String recycledSequence = String.valueOf(n); for(int j = 1; j < l; j++) { recycledSequence = recycle(recycledSequence); int recycledInt = Integer.valueOf(recycledSequence); if(checkedCycles.contains(recycledInt)) { continue; } else { checkedCycles.add(recycledInt); } if(n < recycledInt && recycledInt <= B) { recycled ++; } } } print(getCase(i + 1)); print(recycled); print("\n"); } putAwayFiles(); } private static String recycle(String sequence) { String newSequence = new String(); newSequence += sequence.charAt(sequence.length() - 1); for(int i = 0; i < sequence.length() - 1; i++) { newSequence += sequence.charAt(i); } return newSequence; } private static void prepareFiles(String fileName) throws IOException { reader = new BufferedReader(new FileReader(new File(fileName + ".in"))); writer = new BufferedWriter(new FileWriter(new File(fileName + ".out"))); } private static void putAwayFiles() throws IOException { reader.close(); writer.flush(); writer.close(); } private static String getCase(int i) { return "Case #" + i + ": "; } private static void print(Object object) throws IOException { System.out.print(object.toString()); writer.write(object.toString()); } }
B10899
B10769
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class ReadFile { public static void main(String[] args) throws Exception { String srcFile = "C:" + File.separator + "Documents and Settings" + File.separator + "rohit" + File.separator + "My Documents" + File.separator + "Downloads" + File.separator + "C-small-attempt1.in.txt"; String destFile = "C:" + File.separator + "Documents and Settings" + File.separator + "rohit" + File.separator + "My Documents" + File.separator + "Downloads" + File.separator + "C-small-attempt0.out"; File file = new File(srcFile); List<String> readData = new ArrayList<String>(); FileReader fileInputStream = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileInputStream); StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { readData.add(line); } stringBuilder.append(generateOutput(readData)); File writeFile = new File(destFile); if (!writeFile.exists()) { writeFile.createNewFile(); } FileWriter fileWriter = new FileWriter(writeFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(stringBuilder.toString()); bufferedWriter.close(); System.out.println("output" + stringBuilder); } /** * @param number * @return */ private static String generateOutput(List<String> number) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < number.size(); i++) { if (i == 0) { continue; } else { String tempString = number.get(i); String[] temArr = tempString.split(" "); stringBuilder.append("Case #" + i + ": "); stringBuilder.append(getRecNumbers(temArr[0], temArr[1])); stringBuilder.append("\n"); } } if (stringBuilder.length() > 0) { stringBuilder.deleteCharAt(stringBuilder.length() - 1); } return stringBuilder.toString(); } // /* This method accepts method for google code jam */ // private static String method(String value) { // int intValue = Integer.valueOf(value); // double givenExpr = 3 + Math.sqrt(5); // double num = Math.pow(givenExpr, intValue); // String valArr[] = (num + "").split("\\."); // int finalVal = Integer.valueOf(valArr[0]) % 1000; // // return String.format("%1$03d", finalVal); // // } // // /* This method accepts method for google code jam */ // private static String method2(String value) { // StringTokenizer st = new StringTokenizer(value, " "); // String test[] = value.split(" "); // StringBuffer str = new StringBuffer(); // // for (int i = 0; i < test.length; i++) { // // test[i]=test[test.length-i-1]; // str.append(test[test.length - i - 1]); // str.append(" "); // } // str.deleteCharAt(str.length() - 1); // String strReversedLine = ""; // // while (st.hasMoreTokens()) { // strReversedLine = st.nextToken() + " " + strReversedLine; // } // // return str.toString(); // } private static int getRecNumbers(String no1, String no2) { int a = Integer.valueOf(no1); int b = Integer.valueOf(no2); Set<String> dupC = new HashSet<String>(); for (int i = a; i <= b; i++) { int n = i; List<String> value = findPerm(n); for (String val : value) { if (Integer.valueOf(val) <= b && Integer.valueOf(val) >= a && n < Integer.valueOf(val)) { dupC.add(n + "-" + val); } } } return dupC.size(); } private static List<String> findPerm(int num) { String numString = String.valueOf(num); List<String> value = new ArrayList<String>(); for (int i = 0; i < numString.length(); i++) { String temp = charIns(numString, i); if (!temp.equalsIgnoreCase(numString)) { value.add(charIns(numString, i)); } } return value; } public static String charIns(String str, int j) { String begin = str.substring(0, j); String end = str.substring(j); return end + begin; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String strNumberOfSentences = ""; InputStreamReader converter = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(converter); Integer numberOfSentences = -1; MyPair[] sentences = null; try { strNumberOfSentences = in.readLine(); numberOfSentences = Integer.parseInt(strNumberOfSentences); sentences = new MyPair[numberOfSentences]; for ( int i = 0; i < numberOfSentences; ++i) { sentences[i] = new MyPair(in.readLine()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if ( numberOfSentences == -1) { return; } Vector<MyPair> usedNumbers = new Vector<MyPair>(); for ( int i = 0; i < numberOfSentences; ++i) { int curr = sentences[i].lowerLimit; while (curr < sentences[i].higherLimit) { StringBuilder sss = new StringBuilder(""); sss.append(String.valueOf(curr)); StringBuilder sss2 = new StringBuilder(String.valueOf(curr)); for (int ii = 0; ii < sss.length()-1; ++ii) { char temp = sss2.charAt(0); sss2.replace(0, 0, String.valueOf(sss2.charAt(sss2.length()-1))); sss2.delete(sss2.length()-1, sss2.length()); if (Integer.parseInt(sss2.toString()) <= sentences[i].higherLimit && Integer.parseInt(sss2.toString()) >= sentences[i].lowerLimit && Integer.parseInt(sss.toString()) < Integer.parseInt(sss2.toString()) ) { MyPair x = new MyPair(Integer.parseInt(sss.toString()),Integer.parseInt(sss2.toString())); boolean isFound = false; for (int kkk =0; kkk < usedNumbers.size(); ++kkk ){ if ( usedNumbers.get(kkk).sameAs(x) ) { isFound = true; } } if ( !isFound ) { usedNumbers.add(x); //System.out.println("" + curr + ": " + x.lowerLimit + "," + x.higherLimit ); } } } curr++; } System.out.println("Case #" + new Integer(i+1).toString() + ": " + usedNumbers.size() ); SortedSet<Integer> usedNumbers2 = new TreeSet<Integer>(); for (int kkk =0; kkk < usedNumbers.size(); ++kkk ){ if ( !usedNumbers2.contains(usedNumbers.get(kkk).lowerLimit) ) { usedNumbers2.add(usedNumbers.get(kkk).lowerLimit); } if ( !usedNumbers2.contains(usedNumbers.get(kkk).higherLimit) ) { usedNumbers2.add(usedNumbers.get(kkk).higherLimit); } } for (Integer item: usedNumbers2 ){ //System.out.println("" + item.toString() ); } usedNumbers.clear(); } } } /* int length = sentences[i].lowerLimit.length(); if ( length == 0 || length == 1) { numberOfShits = 0; } else if ( length == 2) { int iii = Character.digit(sentences[i].higherLimit.charAt(0),10) - Character.digit(sentences[i].lowerLimit.charAt(0),10); numberOfShits *= iii * 2; } else if ( length > 2) { numberOfShits = (int) Math.pow(10, length-2); int iii = Character.digit(sentences[i].higherLimit.charAt(0),10) - Character.digit(sentences[i].lowerLimit.charAt(0),10); numberOfShits *= iii * iii; numberOfShits -= iii; } */
A10568
A11818
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.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class DancingGooglers { static BufferedReader br; static PrintWriter pw; public static void main(String args[])throws IOException { initFiles(); readFile(); } private static void readFile()throws IOException { int numCases = Integer.parseInt(br.readLine()); for(int i=1; i<=numCases; i++) { StringTokenizer tokens = new StringTokenizer(br.readLine()); int n = Integer.parseInt(tokens.nextToken()); int s = Integer.parseInt(tokens.nextToken()); int p = Integer.parseInt(tokens.nextToken()); int scores[] = new int[n]; int j = 0; while(tokens.hasMoreTokens()) scores[j++] = Integer.parseInt(tokens.nextToken()); Triplets triplets[] = findTriplets(scores); display(triplets); int currentSurprises = findSurprises(triplets); ArrayList<Integer> possibilities = new ArrayList<Integer>(); findSolution(triplets, (s - currentSurprises), p, 0, possibilities); int maxNumOfGooglers = findMaxNumOfGooglers(possibilities); System.out.println("Max Num of Googlers = " + maxNumOfGooglers); pw.println("Case #" + i + ": " + maxNumOfGooglers); } pw.close(); br.close(); } private static int findMaxNumOfGooglers(ArrayList<Integer> possibilities) { int max = possibilities.get(0); for(int i=1; i<possibilities.size(); i++) { if(possibilities.get(i) > max) max = possibilities.get(i); } return max; } private static void findSolution(Triplets triplets[], int surprises, int p, int startLimit, ArrayList<Integer> possibilities) { if(surprises == 0) { // System.out.println("Possibility: "); // display(triplets); int numOfGooglers = findNumOfBestResult(triplets, p); // System.out.println("Num of Googlers = " + numOfGooglers); possibilities.add(new Integer(numOfGooglers)); return; } else { for(int i=startLimit; i<triplets.length; i++) { if(triplets[i].isSurprising()) continue; if(!triplets[i].canBeConverted()) //Can't be converted continue; Triplets oldTriplet = triplets[i]; triplets[i] = triplets[i].converted(); findSolution(triplets, surprises-1, p, startLimit + 1, possibilities); triplets[i] = oldTriplet; } } } private static int findNumOfBestResult(Triplets triplets[], int p) { int count = 0; for(int i=0; i<triplets.length; i++) { if(triplets[i].getMaxScore() >= p) count++; } return count; } private static int findSurprises(Triplets triplets[]) { int count = 0; for(int i=0; i<triplets.length; i++) { if(triplets[i].isSurprising()) count++; } return count; } private static void display(Triplets triplets[]) { for(int i=0; i<triplets.length; i++) { triplets[i].display(); } } private static Triplets[] findTriplets(int scores[]) { Triplets triplets[] = new Triplets[scores.length]; for(int i=0; i<scores.length; i++) { int a = (int)Math.ceil(scores[i]/3); int b = (int)Math.ceil((scores[i] - a)/2); int c = (int)Math.ceil((scores[i] - a - b)); triplets[i] = new Triplets(a, b, c); } return triplets; } private static void initFiles()throws IOException { br = new BufferedReader(new FileReader("Dance.in")); pw = new PrintWriter(new FileWriter("Dance.out")); } }
B21790
B20260
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 codejam.recycle; import java.util.HashSet; import java.util.Set; public class Recycle { public String solve(String s) { String[] ss = s.split(" "); int a = Integer.parseInt(ss[0]); int b = Integer.parseInt(ss[1]); int n = ("" + a).length(); int m = 0; for (int i = a; i <= b; i++) { int[] digits = collectDigits(i); Set<Integer> done = new HashSet<Integer>(); for (int j = 1; j < n; j++) { int t = offsetNum(digits, j); if (t <= b && t > i && done.add(t)) { m++; } } } return "" + m; } private int[] collectDigits(int num) { int n = ("" + num).length(); int[] digits = new int[n]; int i = n; while (i > 0) { digits[--i] = num % 10; num = (int) (num / 10d); } return digits; } private int offsetNum(int[] x, int m) { int a = 0; for (int i = 0; i < x.length; i++) { a += x[(i + m) % x.length] * Math.pow(10, x.length - 1 - i); } return a; } }
A12846
A12498
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam.common; import java.util.ArrayList; import java.util.List; /** * * @author Lance Chen */ public class CodeHelper { private static String FILE_ROOT = "D:/workspace/googlecodejam/meta"; public static List<List<String>> loadInputsExcludes(String fileName) { List<List<String>> result = new ArrayList<List<String>>(); List<String> lines = FileUtil.readLines(FILE_ROOT + fileName); int index = 0; for (String line : lines) { if (index == 0) { index++; continue; } if (index % 2 == 1) { index++; continue; } List<String> dataList = new ArrayList<String>(); String[] dataArray = line.split("\\s+"); for (String data : dataArray) { if (data.trim().length() > 0) { dataList.add(data); } } result.add(dataList); index++; } return result; } public static List<List<String>> loadInputs(String fileName) { List<List<String>> result = new ArrayList<List<String>>(); List<String> lines = FileUtil.readLines(FILE_ROOT + fileName); for (String line : lines) { List<String> dataList = new ArrayList<String>(); String[] dataArray = line.split("\\s+"); for (String data : dataArray) { if (data.trim().length() > 0) { dataList.add(data); } } result.add(dataList); } return result; } public static List<String> loadInputLines(String fileName) { return FileUtil.readLines(FILE_ROOT + fileName); } public static void writeOutputs(String fileName, List<String> lines) { FileUtil.writeLines(FILE_ROOT + fileName, lines); } }
package com.google.codejam; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class DancingWithGooglers { public static void main(String argsp[]) throws NumberFormatException, IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("/Users/ashwinjain/Desktop/SmsLogger/InterviewStreet/src/com/google/codejam/in2.txt"))); int cases = Integer.parseInt(br.readLine()); for(int x=0;x<cases;x++){ String temp[] = br.readLine().split(" "); int googlers = Integer.parseInt(temp[0]); int suprises = Integer.parseInt(temp[1]); int minScore = Integer.parseInt(temp[2]); int nums[] = new int[googlers]; for(int i=0;i<googlers;i++) { nums[i]=Integer.parseInt(temp[i+3]); } int n[] = new int[googlers]; int s[] = new int[googlers]; for(int i=0;i<googlers;i++){ if(nums[i]==0){ n[i]=0;s[i]=0; }else if(nums[i]==1){ n[i]=1;s[i]=1; }else if(nums[i]==2){ n[i]=1;s[i]=2; }else if(nums[i]%3==0){ n[i]=nums[i]/3; s[i]=n[i]+1; }else if(nums[i]%3==1){ n[i]=nums[i]/3+1; s[i]=n[i]; }else if(nums[i]%3==2){ n[i]=nums[i]/3+1; s[i]=n[i]+1; } } int ans=0; int tempans = 0; for(int i=0;i<googlers;i++){ if(n[i]>=minScore){ ans++; s[i]=-1; } if(s[i]>=minScore){ tempans++; } } ans = ans+Math.min(suprises, tempans); System.out.println("Case #"+(x+1)+": "+ans); } } }
B11318
B13124
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.HashSet; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { Scanner mark = new Scanner(System.in); int t = mark.nextInt(); int A, B, counter; mark.nextLine(); for (int i = 0; i < t; i++) { A = mark.nextInt(); B = mark.nextInt(); counter = 0; mark.nextLine(); // This is for N for (int n = A; n < B; n++) { HashSet<Integer> ans = new HashSet<Integer>(); String strval = String.valueOf(n).trim(); int count = strval.length(); for (int j = 1; j < count; j++) { String beg = strval.substring(0, j); String end = strval.substring(j); // System.out.println(beg+end+" "+end+beg); int m = Integer.parseInt( end.concat(beg) ); if( (m > n) && (m <= B)) ans.add(m); } counter += ans.size(); } System.out.printf("Case #%d: %d\n",i+1,counter); } } }
B21790
B20058
0
import java.io.*; import java.util.*; public class C { void solve() throws IOException { in("C-large.in"); out("C-large.out"); long tm = System.currentTimeMillis(); boolean[] mask = new boolean[2000000]; int[] r = new int[10]; int t = readInt(); for (int cs = 1; cs <= t; ++cs) { int a = readInt(); int b = readInt(); int ans = 0; for (int m = a + 1; m <= b; ++m) { char[] d = String.valueOf(m).toCharArray(); int c = 0; for (int i = 1; i < d.length; ++i) { if (d[i] != '0' && d[i] <= d[0]) { int n = 0; for (int j = 0; j < d.length; ++j) { int jj = i + j; if (jj >= d.length) jj -= d.length; n = n * 10 + (d[jj] - '0'); } if (n >= a && n < m && !mask[n]) { ++ans; mask[n] = true; r[c++] = n; } } } for (int i = 0; i < c; ++i) { mask[r[i]] = false; } } println("Case #" + cs + ": " + ans); //System.out.println(cs); } System.out.println("time: " + (System.currentTimeMillis() - tm)); exit(); } void in(String name) throws IOException { if (name.equals("__std")) { in = new BufferedReader(new InputStreamReader(System.in)); } else { in = new BufferedReader(new FileReader(name)); } } void out(String name) throws IOException { if (name.equals("__std")) { out = new PrintWriter(System.out); } else { out = new PrintWriter(name); } } void exit() { out.close(); System.exit(0); } int readInt() throws IOException { return Integer.parseInt(readToken()); } long readLong() throws IOException { return Long.parseLong(readToken()); } double readDouble() throws IOException { return Double.parseDouble(readToken()); } String readLine() throws IOException { st = null; return in.readLine(); } String readToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } boolean eof() throws IOException { return !in.ready(); } void print(String format, Object ... args) { out.println(new Formatter(Locale.US).format(format, args)); } void println(String format, Object ... args) { out.println(new Formatter(Locale.US).format(format, args)); } void print(Object value) { out.print(value); } void println(Object value) { out.println(value); } void println() { out.println(); } StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) throws IOException { new C().solve(); } }
import java.io.*; import java.util.*; /** * @author Chris Dziemborowicz <chris@dziemborowicz.com> * @version 2012.0414 */ public class RecycledNumbers { public static void main(String[] args) throws Exception { // Get input files File dir = new File("/Users/Chris/Documents/UniSVN/code-jam/recycled-numbers/data"); File[] inputFiles = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".in"); } }); // Process each input file for (File inputFile : inputFiles) { System.out.printf("Processing \"%s\"...\n", inputFile.getName()); String outputPath = inputFile.getPath().replaceAll("\\.in$", ".out"); BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath)); Scanner scanner = new Scanner(inputFile); System.out.printf("Number of test cases: %s\n", scanner.nextLine()); int count = 0; while (scanner.hasNext()) { String line = scanner.nextLine(); String output = String.format("Case #%d: %d\n", ++count, process(line)); System.out.print(output); writer.write(output); } writer.close(); System.out.println("Done.\n"); } // Compare to reference files (if any) for (File inputFile : inputFiles) { System.out.printf("Verifying \"%s\"...\n", inputFile.getName()); String referencePath = inputFile.getPath().replaceAll("\\.in$", ".ref"); String outputPath = inputFile.getPath().replaceAll("\\.in$", ".out"); File referenceFile = new File(referencePath); if (referenceFile.exists()) { InputStream referenceStream = new FileInputStream(referencePath); InputStream outputStream = new FileInputStream(outputPath); boolean matched = true; int referenceRead, outputRead; do { byte[] referenceBuffer = new byte[4096]; byte[] outputBuffer = new byte[4096]; referenceRead = referenceStream.read(referenceBuffer); outputRead = outputStream.read(outputBuffer); matched = referenceRead == outputRead && Arrays.equals(referenceBuffer, outputBuffer); } while (matched && referenceRead != -1); if (matched) { System.out.println("Verified.\n"); } else { System.out.println("*** NOT VERIFIED ***\n"); } } else { System.out.println("No reference file found.\n"); } } } public static int process(String line) { Scanner scanner = new Scanner(line); final int a = scanner.nextInt(); final int b = scanner.nextInt(); final int[] pow10 = new int[] { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; int count = 0; for (int n = a; n < b; n++) { Set<Integer> set = new HashSet<Integer>(); int numDigits = numDigits(n); for (int d = 1; d < numDigits; d++) { int back = n % pow10[d]; int front = n / pow10[d]; int m = front + back * pow10[numDigits - d]; if (n < m && m <= b && numDigits == numDigits(m)) { set.add(m); } } count += set.size(); } return count; } public static int numDigits(int n) { if (n < 0) { return numDigits(-n); } else if (n < 1) { return 0; } else if (n < 10) { return 1; } else if (n < 100) { return 2; } else if (n < 1000) { return 3; } else if (n < 10000) { return 4; } else if (n < 100000) { return 5; } else if (n < 1000000) { return 6; } else if (n < 10000000) { return 7; } else if (n < 100000000) { return 8; } else if (n < 1000000000) { return 9; } else { return 10; } } }
A11277
A11081
0
package googlers; import java.util.Scanner; import java.util.PriorityQueue; import java.util.Comparator; public class Googlers { public static void main(String[] args) { int n,s,p,count=0,t; Scanner sin=new Scanner(System.in); t=Integer.parseInt(sin.nextLine()); int result[]=new int[t]; int j=0; if(t>=1 && t<=100) { for (int k = 0; k < t; k++) { count=0; String ip = sin.nextLine(); String[]tokens=ip.split(" "); n=Integer.parseInt(tokens[0]); s=Integer.parseInt(tokens[1]); p=Integer.parseInt(tokens[2]); if( (s>=0 && s<=n) && (p>=0 && p<=10) ) { int[] total=new int[n]; for (int i = 0; i < n; i++) { total[i] = Integer.parseInt(tokens[i+3]); } Comparator comparator=new PointComparator(); PriorityQueue pq=new PriorityQueue<Point>(1, comparator); for (int i = 0; i < n; i++) { int x=total[i]/3; int r=total[i]%3; if(x>=p) count++; else if(x<(p-2)) continue; else { //System.out.println("enter "+x+" "+(p-2)); if(p-x==1) { Point temp=new Point(); temp.q=x; temp.r=r; pq.add(temp); } else // p-x=2 { if(r==0) continue; else { Point temp=new Point(); temp.q=x; temp.r=r; pq.add(temp); } } } //System.out.println("hi "+pq.size()); } while(pq.size()!=0) { Point temp=(Point)pq.remove(); if(p-temp.q==1 && temp.q!=0) { if(temp.r>=1) count++; else { if(s!=0) { s--; count++; } } } else if(p-temp.q==2) { if(s!=0 && (temp.q+temp.r)>=p) { s--; count++; } } } //System.out.println(p); result[j++]=count; } } for (int i = 0; i < t; i++) { System.out.println("Case #"+(i+1)+": "+result[i]); } } } /*Point x=new Point(); x.q=8; Point y=new Point(); y.q=6; Point z=new Point(); z.q=7; pq.add(x); pq.add(y); pq.add(z); */ } class PointComparator implements Comparator<Point> { @Override public int compare(Point x, Point y) { // Assume neither string is null. Real code should // probably be more robust if (x.q < y.q) { return 1; } if (x.q > y.q) { return -1; } return 0; } } class Point { int q,r; public int getQ() { return q; } public void setQ(int q) { this.q = q; } public int getR() { return r; } public void setR(int r) { this.r = r; } }
package codejam; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class Second { public static void main(String[] args) throws FileNotFoundException { String path = ClassLoader.getSystemClassLoader().getResource("codejam/").getPath(); Second worker = new Second(); worker.scan(new File(path, "second-s.in"), new File(path, "second-s.out")); // worker.scan(new File(path, "second-x.in"), new File(path, "second-x.out")); } private void scan(File input, File output) throws FileNotFoundException { Scanner in = new Scanner(input); PrintWriter out = new PrintWriter(output); int n = Integer.parseInt(in.nextLine()); for (int i = 0; i < n; i++) { out.printf("Case #%d: %s\n", i + 1, solve(in.nextLine())); } out.flush(); out.close(); in.close(); } public String solve(String line) { String[] tokens = line.split(" "); int n = Integer.parseInt(tokens[0]); int s = Integer.parseInt(tokens[1]); int p = Integer.parseInt(tokens[2]); int[] points = new int[n]; for (int i = 0; i < points.length; i++) { points[i] = Integer.parseInt(tokens[3 + i]); } int result = 0; for (int pc : points) { int r = solve(pc, p); if (r == 3 && s > 0) { result++; s--; } else if (r == 1 || r == 2) { result++; } } return "" + result; } public int solve(int pc, int p) { if (pc == 0) { return p == 0 ? 1 : 0; } int m = pc / 3; while ( m < p) m++; int k = 0; do { k = 3 * m; if (k == pc || k - 1 == pc) { return 1; } if (k - 2 == pc) { return 2; } if (k - 3 == pc || k - 4 == pc) { return 3; } m++; } while (k - pc <= 4); return 0; } }
B12085
B13018
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; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package question3; /** * * @author karim */ public class Pair { private Integer int1; private Integer int2; public Pair() { } public Pair(int int1) { this.int1 = int1; } public Pair(int int1, int int2) { this.int1 = int1; this.int2 = int2; } public int getint1() { return int1; } public void setint1(int int1) { this.int1 = int1; } public int getint2() { return int2; } public void setint2(int int2) { this.int2 = int2; } @Override public boolean equals(Object obj) { Pair o = (Pair) obj; if ((o.int1.equals(int1) && o.int2.equals(int2)) || (o.int2.equals(int1) && o.int1.equals( int2))) { return true; } else { return false; } } @Override public int hashCode() { return int1.hashCode() + int2.hashCode(); } }
B12669
B11503
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 com.prob1; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class ClassB { public static void main(String args[]){ try{ BufferedReader in = new BufferedReader(new FileReader("D://NewFolder2//C-small-attempt0.in")); //BufferedReader in = new BufferedReader(new FileReader("D://NewFolder2//C-large.in")); PrintWriter out = new PrintWriter(new FileWriter("D://NewFolder2//test1.txt")); int c =1; //int x =0; while (in.ready()){ String text = in.readLine(); if(c != 1){ StringTokenizer tokenizer = new StringTokenizer(text," "); String[] allText = new String[2]; int pos = 0; while (tokenizer.hasMoreTokens()) allText[pos++] = tokenizer.nextToken(); long lower_limit = Long.parseLong(allText[0]); long upper_limit = Long.parseLong(allText[1]); long result = countRecycledNums(lower_limit,upper_limit); String text1 = "Case #"+(c-1)+": "+result; out.println(text1); c++; } else{ // x = Integer.parseInt(text); c++; } } out.close(); in.close(); }catch(IOException e){ System.out.print("Exception"); } } //end of main private static int countNumDigits( long number) { int count = 1; count = 1 + (int)Math.floor(Math.log10(number)); return count; } //Rotate a number by specified positioon private static long cyclicRotate( long num, int numLen, int pos ) { long new_num, suffix,prefix; long compute_by = (long)(Math.pow((double)10,(numLen - pos ))); suffix = num / compute_by ; prefix = num % compute_by ; new_num = prefix * (long)Math.pow((double)10, pos ) + suffix; return new_num; } static long countRecycledNums(long lower_limit, long upper_limit) { long uniq_recycle_pair_count = 0; int num_digits = countNumDigits ( lower_limit); if ( num_digits == 1 ){ return 0; } for ( int counter = (int)lower_limit ; counter < upper_limit ; counter++) { Set set = new HashSet(); for ( int pos = 1 ; pos < num_digits ; pos++ ) { long recycled_num = cyclicRotate(counter,num_digits,pos); if ( recycled_num <= counter) { continue; } if ( lower_limit <= recycled_num && upper_limit >= recycled_num ) { uniq_recycle_pair_count++; set.add(recycled_num); } } } return uniq_recycle_pair_count; } }
A11502
A10832
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; } }
package practice.GC2012; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Dancers { public static void main(String args[]) throws IOException { Scanner s = new Scanner(new File("Z:\\junkyard\\practice\\resources\\input2.txt")); FileWriter fo = new FileWriter(new File("Z:\\junkyard\\practice\\resources\\output2.txt")); int num = s.nextInt(); for(int i = 1; i<= num; i++) { fo.write("Case #" + i + ": "); int nd = s.nextInt(); int ns = s.nextInt(); System.out.println("\n"+ i + " - " + nd + " , "+ ns); int p = s.nextInt(); int alreadyhigh = Math.max(p, 0) + Math.max(p-1, 0) + Math.max(p-1, 0); int surpriseScore = Math.max(p, 0) + Math.max(p-2, 0) + Math.max(p-2, 0); int bestScorers = 0; int canSurprise = 0; for(int j = 1; j<=nd; j++) { int score = s.nextInt(); System.out.print(score + " - "); if (score == 0) { continue; } if (score >= alreadyhigh) { bestScorers ++; } else if(score >= surpriseScore) { canSurprise ++; } } if (canSurprise < ns) { bestScorers += canSurprise; } else { bestScorers += ns; } if(p==0) { fo.write(nd + "\n"); } else { fo.write(bestScorers + "\n"); } } fo.close(); s.close(); } }
B10485
B12894
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; } }
import java.util.Scanner; public class RecycledNumbers { public static void main(String[] argv) { int lineCount,counter,mHold; int n,m,recycledNumbers; Scanner input = null; try { input = new Scanner(System.in); } catch (Exception e) { System.err.println("FileNotFoundException: " + e.getMessage()); } lineCount = input.nextInt(); for (counter = 0; counter < lineCount; counter++) { recycledNumbers = 0; input.nextLine(); n = input.nextInt(); mHold = input.nextInt(); m = mHold; for (; n < m; n++) { for (; m > n; m--) { if (Integer.toString(n).length() == Integer.toString(m).length()) { if (checkRecycled(n,m)) recycledNumbers++; } } m = mHold; } System.out.printf("Case #%d: %d\n",counter+1,recycledNumbers); } } public static boolean checkRecycled(int n, int m) { int check,cursor; String toCheck; String holder = Integer.toString(n); for (cursor = holder.length() - 1; cursor > 0; cursor--) { toCheck = ""; toCheck += holder.substring(cursor,holder.length()); toCheck += holder.substring(0,cursor); check = Integer.valueOf(toCheck); if (check == m) return true; } return false; } }
B10149
B10919
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)); } }
package codejam.qualification; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class Recycled { /** * @param args */ public static void main(String[] args) throws IOException { String file = "input3small"; Scanner in = new Scanner(new File(file)); int tot = Integer.parseInt(in.nextLine()); // System.out.println(tot); for(int i=0;i<tot;i++) { String line = in.nextLine(); String[] data = line.split(" "); int A = Integer.parseInt(data[0]); int B = Integer.parseInt(data[1]); int output = 0; for(int j=A; j<=B; j++) { // System.out.println("("+j+")"); String s = j+""; output += countRecycled(s, B); } System.out.println("Case #"+(i+1)+": "+output); } } private static int countRecycled(String s, int B) { ArrayList<String> rec = new ArrayList<String>(); int count = 0; for(int i=s.length()-1; i>0; i--) { String r = s.substring(i) + s.substring(0, i); // System.out.println(r); int s_int = Integer.parseInt(s); int r_int = Integer.parseInt(r); if(r.charAt(0) != 0 && s_int < r_int && r_int <= B && !isIn(r,rec)) { // System.out.println("ok: "+s+"\t"+r); count++; rec.add(r); } } return count; } private static boolean isIn(String r, ArrayList<String> rec) { for(String r2 : rec) if(r.equals(r2)) return true; return false; } }
B21227
B20724
0
import java.util.HashSet; import java.util.Scanner; public class C { static HashSet p = new HashSet(); static int low; static int high; int count = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int no = sc.nextInt(); for (int i = 1; i <= no; i++) { p.clear(); low = sc.nextInt(); high = sc.nextInt(); for (int l = low; l <= high; l++) { recycle(l); } System.out.println("Case #" + i + ": " + p.size()); } } public static void recycle(int no) { String s = Integer.toString(no); for (int i = 0; i < s.length(); i++) { String rec = s.substring(i) + s.substring(0, i); int r = Integer.parseInt(rec); if (r != no && r >= low && r <= high) { int min = Math.min(r, no); int max = Math.max(r, no); String a = Integer.toString(min) + "" + Integer.toString(max); p.add(a); } } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class CodeJam { public static void main(String [] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine()); for(int ii=1;ii<=num;++ii) { StringTokenizer st = new StringTokenizer(br.readLine()); int begin = Integer.parseInt(st.nextToken()); int end = Integer.parseInt(st.nextToken()); int cnt=0; for(int i=begin; i<=end ; ++i) { int line = i; String orig = Integer.toString(line); String curr = orig; for(int j = 0; j<orig.length(); ++j ) { curr = curr.substring(1) + curr.charAt(0); int intcurr = Integer.parseInt(curr); if(intcurr == line) break; if(intcurr >= begin && intcurr <=end && intcurr > line) cnt++; } } System.out.println("Case #"+ii+": "+cnt); } } }
A10793
A10138
0
import java.io.*; import java.math.*; import java.util.*; import java.text.*; public class b { public static void main(String[] args) { Scanner sc = new Scanner(new BufferedInputStream(System.in)); int T = sc.nextInt(); for (int casenumber = 1; casenumber <= T; ++casenumber) { int n = sc.nextInt(); int s = sc.nextInt(); int p = sc.nextInt(); int[] ts = new int[n]; for (int i = 0; i < n; ++i) ts[i] = sc.nextInt(); int thresh1 = (p == 1 ? 1 : (3 * p - 4)); int thresh2 = (3 * p - 2); int count1 = 0, count2 = 0; for (int i = 0; i < n; ++i) { if (ts[i] >= thresh2) { ++count2; continue; } if (ts[i] >= thresh1) { ++count1; } } if (count1 > s) { count1 = s; } System.out.format("Case #%d: %d%n", casenumber, count1 + count2); } } }
package dancingwiththegooglers; import java.util.Arrays; import template.Template; public class DancingWithTheGooglers extends Template { public static void main(String[] args) throws Exception { init("src/dancingwiththegooglers/B-small-attempt3"); int lines = readInt(); for (int i = 1; i <= lines; i++) { int[] line = readIntArray(); int n = line[0]; int s = line[1]; int p = line[2]; int[] t = new int[n]; int result = 0; for (int j = 0; j < n; j++) { t[j] = line[j + 3]; int m = t[j] / 3; int r = t[j] % 3 > 0 ? 1 : 0; if (m >= p) result++; else if (m + r >= p && (m - r >= 0 || m + r > 0 && t[j] % 3 == 2)) result++; else if (m + r + 1 >= p && s > 0 && m - r - 1 >= 0 && t[j] % 3 != 1) { result++; s--; } } System.out.println("\n" + Arrays.toString(line)); write("Case #" + i + ": " + result); } } }
A21396
A21195
0
import java.util.*; public class Test { public static void main(String[] args){ Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int i = 1; i<=T; i++) { int n = in.nextInt(); int s = in.nextInt(); int p = in.nextInt(); int result = 0; for(int j = 0; j<n; j++){ int x = canAddUp(in.nextInt(), p); if(x == 0) { result++; } else if (x==1 && s > 0) { result++; s--; } } System.out.println("Case #"+i+": "+result); } } public static int canAddUp(int sum, int limit) { boolean flag = false; for(int i = 0; i<=sum; i++) { for(int j = 0; i+j <= sum; j++) { int k = sum-(i+j); int a = Math.abs(i-j); int b = Math.abs(i-k); int c = Math.abs(j-k); if(a > 2 || b > 2 || c> 2){ continue; } if (i>=limit || j>=limit || k>=limit) { if(a < 2 && b < 2 && c < 2) { return 0; }else{ flag = true; } } } } return (flag) ? 1 : 2; } }
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Locale; import java.util.StringTokenizer; public class Solution implements Runnable { private BufferedReader in; private StringTokenizer st; private PrintWriter out; private void solve() throws IOException { int t = nextInt(); for (int test = 1; test <= t; test++) { int answer = readAndSolve(); out.println("Case #" + test + ": " + answer); } } private int readAndSolve() throws IOException { int n = nextInt(); int s = nextInt(); int p = nextInt(); int[] t = new int[n]; for (int i = 0; i < n; i++) { t[i] = nextInt(); } int[] maxNorm = calcMaxNormal(t); int[] maxStrange = calcMaxStrange(t); int[][] a = new int[n + 1][n + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= n; j++) { a[i][j] = -1; } } a[0][0] = 0; for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { if (a[i][j] >= 0) { int[] d = {maxNorm[i], maxStrange[i]}; for (int k = 0; k < d.length; k++) { if (d[k] >= 0) { a[i + 1][j + k] = Math.max(a[i + 1][j + k], a[i][j] + (d[k] >= p ? 1 : 0)); } } } } } return a[n][s]; } private int[] calcMaxNormal(int[] t) { int[] result = new int[t.length]; for (int i = 0; i < t.length; i++) { result[i] = calcMaxNormal(t[i]); } return result; } private int calcMaxNormal(int sum) { return (sum + 2) / 3; } private int[] calcMaxStrange(int[] t) { int[] result = new int[t.length]; for (int i = 0; i < t.length; i++) { result[i] = calcMaxStrange(t[i]); } return result; } private int calcMaxStrange(int sum) { int result; if (sum % 3 == 2) { result = sum / 3 + 2; } else { result = sum / 3 + 1; } if (result - 2 < 0 || result > 10) { return -1; } return result; } @Override public void run() { try { solve(); } catch (Throwable e) { apstenu(e); } finally { out.close(); } } private int nextInt() throws IOException { return Integer.parseInt(next()); } private String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } private void apstenu(Throwable e) { e.printStackTrace(); System.exit(1); } public Solution(String filename) { try { in = new BufferedReader(new FileReader(filename + ".in")); st = new StringTokenizer(""); out = new PrintWriter(new FileWriter(filename + ".out")); } catch (IOException e) { apstenu(e); } } public static void main(String[] args) { Locale.setDefault(Locale.US); new Solution("data").run(); } }
B12085
B11754
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.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class CodeJamTextInputReader { private final BufferedReader reader; private final int numberOfTestCases; private int lastReadTestCase = 0; public CodeJamTextInputReader(File inputFile) throws IOException, InvalidInputException { reader = new BufferedReader(new FileReader(inputFile)); numberOfTestCases = readInNumberOfTestCases(); } private int readInNumberOfTestCases() throws IOException, InvalidInputException { String firstLine = reader.readLine(); try { return Integer.parseInt(firstLine); } catch (NumberFormatException e) { throw new InvalidInputException("Expected first line to be number of test cases", e); } } public boolean hasNextTestCase() { return numberOfTestCases != lastReadTestCase; } public String readNextLine() throws IOException { ++lastReadTestCase; return reader.readLine(); } public int getLastReadTestCaseNumber() { return lastReadTestCase; } public void close() throws IOException { this.reader.close(); } }
A21557
A23013
0
import java.io.*; import java.util.*; public class DancingWithGooglers { public static class Googlers { public int T; public int surp; public boolean surprising; public boolean pSurprising; public boolean antiSurprising; public boolean pAntiSurprising; public Googlers(int T, int surp) { this.T = T; this.surp = surp; } public void set(int a, int b, int c) { if (c >= 0 && (a + b + c) == T) { int diff = (Math.max(a, Math.max(b, c)) - Math.min(a, Math.min(b, c))); if (diff <= 2) { if (diff == 2) { if (a >= surp || b >= surp || c >= surp) { pSurprising = true; } else { surprising = true; } } else { if (a >= surp || b >= surp || c >= surp) { pAntiSurprising = true; } else { antiSurprising = true; } } } } } } public static void main(String... args) throws IOException { // BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedReader reader = new BufferedReader(new FileReader("B-large.in")); // PrintWriter writer = new PrintWriter(System.out); PrintWriter writer = new PrintWriter("B-large.out"); int len, cases = Integer.parseInt(reader.readLine()); List<Googlers> satisfied = new ArrayList<Googlers>(); List<Googlers> unsatisfied = new ArrayList<Googlers>(); String[] inputs; int N, S, p; for (int i = 1; i <= cases; i++) { inputs = reader.readLine().split(" "); p = Integer.parseInt(inputs[1]); S = Integer.parseInt(inputs[2]); satisfied.clear(); unsatisfied.clear(); for (int j = 3; j < inputs.length; j++) { int t = Integer.parseInt(inputs[j]); Googlers googlers = new Googlers(t, S); for (int k = 0; k <= 10; k++) { int till = k + 2 > 10 ? 10 : k + 2; for (int l = k; l <= till; l++) { googlers.set(k, l, (t - (k + l))); } } if (googlers.pAntiSurprising) { satisfied.add(googlers); } else { unsatisfied.add(googlers); } } int pSurprising = 0; if (p > 0) { for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) { Googlers googlers = iter.next(); if (googlers.pSurprising) { pSurprising++; iter.remove(); p--; if (p <= 0) break; } } } if(p > 0){ for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) { Googlers googlers = iter.next(); if (googlers.surprising) { iter.remove(); p--; if (p <= 0) break; } } } if(p > 0){ for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) { Googlers googlers = iter.next(); if (googlers.pSurprising) { iter.remove(); pSurprising++; p--; if (p <= 0) break; } } } if(p > 0){ for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) { Googlers googlers = iter.next(); if (googlers.surprising) { iter.remove(); p--; if (p <= 0) break; } } } if(p > 0){ writer.print("Case #" + i + ": 0"); }else { writer.print("Case #" + i + ": " + (satisfied.size() + pSurprising)); } writer.println(); } writer.flush(); } }
package tr0llhoehle.cakemix.utility.googleCodeJam; public interface Solver<T extends Problem> { public String solve(T p); }
B21752
B21413
0
package Main; import com.sun.deploy.util.ArrayUtil; import org.apache.commons.lang3.ArrayUtils; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; /** * Created with IntelliJ IDEA. * User: arran * Date: 14/04/12 * Time: 3:12 PM * To change this template use File | Settings | File Templates. */ public class Round { public StringBuilder parse(BufferedReader in) throws IOException { StringBuilder out = new StringBuilder(); String lineCount = in.readLine(); for (int i = 1; i <= Integer.parseInt(lineCount); i++) { out.append("Case #"+i+": "); System.err.println("Case #"+i+": "); String line = in.readLine(); String[] splits = line.split(" "); int p1 = Integer.valueOf(splits[0]); int p2 = Integer.valueOf(splits[1]); int r = pairRecyclable(p1, p2); out.append(r); // if (i < Integer.parseInt(lineCount)) out.append("\n"); } return out; } public static int pairRecyclable(int i1, int i2) { HashSet<String> hash = new HashSet<String>(); for (int i = i1; i < i2; i++) { String istr = String.valueOf(i); if (istr.length() < 2) continue; for (int p = 0; p < istr.length() ; p++) { String nistr = istr.substring(p,istr.length()).concat(istr.substring(0,p)); if (Integer.valueOf(nistr) < i1) continue; if (Integer.valueOf(nistr) > i2) continue; if (nistr.equals(istr)) continue; String cnistr = (Integer.valueOf(nistr) > Integer.valueOf(istr)) ? istr + "," + nistr : nistr + "," + istr; hash.add(cnistr); } } return hash.size(); } public static void main(String[] args) { InputStreamReader converter = null; try { int attempt = 0; String quest = "C"; // String size = "small-attempt"; String size = "large"; converter = new InputStreamReader(new FileInputStream("src/resource/"+quest+"-"+size+".in")); BufferedReader in = new BufferedReader(converter); Round r = new Round(); String str = r.parse(in).toString(); System.out.print(str); FileOutputStream fos = new FileOutputStream(quest+"-"+size+".out"); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw); bw.write(str); bw.flush(); bw.close(); } catch (IOException e) { e.printStackTrace(); } } }
package RecycledNumbers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class RecyledNumbers { public RecyledNumbers() { } public static int findRecycled(int low, int high) { Set<Pair> pairs = new HashSet<Pair>(); for (int i = low; i <= high; i++) { String s = String.valueOf(i); for (int j = 1; j < s.length(); j++) { String newString = s.substring(j) + s.substring(0, j); int newValue = Integer.parseInt(newString); if (newValue <= high && newValue >= low && newValue != i && !newString.startsWith("0")) { if (!pairs.contains(new Pair(newValue, i))) { pairs.add(new Pair(i, newValue)); } } } } return pairs.size(); } private static int parse(String input) { StringTokenizer st = new StringTokenizer(input, " "); if (st.countTokens() != 2) throw new IllegalArgumentException("Wrong no of values"); int low = Integer.parseInt(st.nextToken()); int high = Integer.parseInt(st.nextToken()); return findRecycled(low, high); } public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException("No file specified"); List<String> data = new ArrayList<String>(); List<String> results = new ArrayList<String>(); try { FileInputStream fstream = new FileInputStream(args[0]); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { data.add(strLine); } in.close(); } catch (Exception e) {// Catch exception if any System.err.println("Error: " + e.getMessage()); } if (data.size() == 0) throw new IllegalArgumentException("No data in file"); int noTestCases = Integer.parseInt(data.get(0)); if (data.size() != noTestCases + 1) throw new IllegalArgumentException("Number of test cases is not " + noTestCases); for (int i = 1; i <= noTestCases; i++) { results.add("Case #" + i + ": " + parse(data.get(i))); } try { FileWriter fostream = new FileWriter(args[1]); BufferedWriter out = new BufferedWriter(fostream); for (int i =0;i<results.size();i++) { String s = results.get(i); out.write(s); if (i<results.size()-1) out.newLine(); } out.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
A11135
A12409
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.util.*; import java.io.*; public class Googlers { public static void main(String[] args)throws IOException { Scanner sc = new Scanner(new File("input2.txt")); int loop = sc.nextInt(); int num; int s = 0; int p; int n; int count = 0; int check; ArrayList<Integer> array = new ArrayList<Integer>(); for (int i = 0 ; i < loop ; i++) { num = sc.nextInt(); s = sc.nextInt(); p = sc.nextInt(); for (int j=0 ; j<num ;j++){ array.add(sc.nextInt()); } n = p*3-2; for (Integer in : array){ if (in >= n) count++; else { if(s>0){ check = (p+(p-2)*2); if(in >= check && check >0){ count++; s--; } } } } System.out.println("Case #"+(i+1)+": "+count); count = 0; array.clear(); } } }
A12460
A12950
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.util.Scanner; public class Dancing { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int i=0; i<T; i++) { int N = sc.nextInt(); int S = sc.nextInt(); int p = sc.nextInt(); // int [] score = new int[N]; int numPass = 0; for(int j=0; j<N; j++) { int score = sc.nextInt(); int normalMax = (score + 2) / 3; if (normalMax >= p) numPass++; else if(normalMax + 1 == p) { if(S > 0 && ((score % 3) != 1) && score != 0) { S--; numPass++; } } } System.out.println("Case #" + (i+1) + ": " + numPass); } } }
A20934
A22406
0
import java.util.*; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); B th = new B(); for (int i = 0; i < T; i++) { int n = sc.nextInt(); int s = sc.nextInt(); int p = sc.nextInt(); int[] t = new int[n]; for (int j = 0; j < n; j++) { t[j] = sc.nextInt(); } int c = th.getAnswer(s,p,t); System.out.println("Case #" + (i+1) + ": " + c); } } public int getAnswer(int s, int p, int[] t) { int A1 = p + p-1+p-1; int A2 = p + p-2+p-2; if (A1 < 0) A1 = 0; if (A2 < 0) A2 = 1; int remain = s; int count = 0; int n = t.length; for (int i = 0; i < n; i++) { if (t[i] >= A1) { count++; } else if (t[i] < A1 && t[i] >= A2) { if (remain > 0) { remain--; count++; } } } return count; } }
import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.PrintStream; import java.io.PrintWriter; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; public class Googlers { public static void main(String args[]) throws IOException { int totalValid; int surp, numGooglers, maxNum, calcSurp; try { PrintWriter wt= new PrintWriter("C:\\Documents and Settings\\windows\\workspace\\test\\src\\file.out.txt"); Scanner I = new Scanner(new File("C:\\Documents and Settings\\windows\\workspace\\test\\src\\B-large.in")); String num = I.nextLine(); int numTests = Integer.parseInt(num); for(int x=0; x<numTests; x++) { int i = 0; String[] str = I.nextLine().split(" "); int inputs[] = new int[150]; for(int y = 0; y <str.length; y++ ) { inputs[y] = Integer.parseInt(str[y]); } numGooglers = inputs[0]; surp = inputs[1]; maxNum = inputs[2]; totalValid = 0; calcSurp = 0; for( i = 3; i < numGooglers + 3 ; i++) { if (isGoogler(inputs[i], maxNum) == 1) { totalValid++; } else if(isGoogler(inputs[i], maxNum) == 2) { calcSurp++; } else {} } // match surp numbers if (calcSurp > surp) { totalValid = totalValid + surp; } else { totalValid = totalValid + calcSurp; } //logic to write totalValid to file String finalResult = "Case #"+(x+1)+": "+totalValid; wt.println(finalResult); finalResult = ""; } wt.close(); I.close(); } catch(FileNotFoundException e) { e.printStackTrace(); } catch(IOException e) { System.out.println(e); } } // Replacement algorithm public static int isGoogler (int num,int max) { if (max == 0 && max <= num) return 1; else if (num <= 0) return 0; else if (num >= ((max * 3)-2 )) return 1; else if (num >= ((max * 3)-4 )) return 2; else return 0; } }
B11318
B13063
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; } }
package com.google.codejam.recycle; /** * Class to hold the result of given test case. * @author Sushant Deshpande */ public class TestResult { /** * variable to represent testOutput. */ private int testOutput; /** * Constructor to create TestResult with testOutput. * @param testOutput String */ public TestResult(final int testOutput) { this.testOutput = testOutput; } /** * Getter method for test output. * @return String */ public final int getTestOutput() { return testOutput; } }
B21790
B20600
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.*; import static java.lang.System.*; class C{ static public void main(String[] args){ Scanner sc = new Scanner(System.in); int cases = Integer.parseInt(sc.nextLine()); for(int c = 1; c<=cases; c++){ String[] s = sc.nextLine().split(" "); int a = Integer.parseInt(s[0]); int b = Integer.parseInt(s[1]); int l = s[0].length(); long cnt = 0; for(int i = a; i<b; i++){ HashSet<Integer> set = new HashSet<Integer>(); for(int pos = 1; pos<l; pos++){ int k = (int)Math.pow(10,pos); int kk = (int)Math.pow(10,l-pos); int front = i/k; int back = i-front*k; int newn = back*kk+front; if(newn>i && newn<=b){ set.add(newn); } } cnt+=set.size(); } out.println("Case #"+c+": "+cnt); } } }
A21557
A22445
0
import java.io.*; import java.util.*; public class DancingWithGooglers { public static class Googlers { public int T; public int surp; public boolean surprising; public boolean pSurprising; public boolean antiSurprising; public boolean pAntiSurprising; public Googlers(int T, int surp) { this.T = T; this.surp = surp; } public void set(int a, int b, int c) { if (c >= 0 && (a + b + c) == T) { int diff = (Math.max(a, Math.max(b, c)) - Math.min(a, Math.min(b, c))); if (diff <= 2) { if (diff == 2) { if (a >= surp || b >= surp || c >= surp) { pSurprising = true; } else { surprising = true; } } else { if (a >= surp || b >= surp || c >= surp) { pAntiSurprising = true; } else { antiSurprising = true; } } } } } } public static void main(String... args) throws IOException { // BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedReader reader = new BufferedReader(new FileReader("B-large.in")); // PrintWriter writer = new PrintWriter(System.out); PrintWriter writer = new PrintWriter("B-large.out"); int len, cases = Integer.parseInt(reader.readLine()); List<Googlers> satisfied = new ArrayList<Googlers>(); List<Googlers> unsatisfied = new ArrayList<Googlers>(); String[] inputs; int N, S, p; for (int i = 1; i <= cases; i++) { inputs = reader.readLine().split(" "); p = Integer.parseInt(inputs[1]); S = Integer.parseInt(inputs[2]); satisfied.clear(); unsatisfied.clear(); for (int j = 3; j < inputs.length; j++) { int t = Integer.parseInt(inputs[j]); Googlers googlers = new Googlers(t, S); for (int k = 0; k <= 10; k++) { int till = k + 2 > 10 ? 10 : k + 2; for (int l = k; l <= till; l++) { googlers.set(k, l, (t - (k + l))); } } if (googlers.pAntiSurprising) { satisfied.add(googlers); } else { unsatisfied.add(googlers); } } int pSurprising = 0; if (p > 0) { for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) { Googlers googlers = iter.next(); if (googlers.pSurprising) { pSurprising++; iter.remove(); p--; if (p <= 0) break; } } } if(p > 0){ for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) { Googlers googlers = iter.next(); if (googlers.surprising) { iter.remove(); p--; if (p <= 0) break; } } } if(p > 0){ for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) { Googlers googlers = iter.next(); if (googlers.pSurprising) { iter.remove(); pSurprising++; p--; if (p <= 0) break; } } } if(p > 0){ for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) { Googlers googlers = iter.next(); if (googlers.surprising) { iter.remove(); p--; if (p <= 0) break; } } } if(p > 0){ writer.print("Case #" + i + ": 0"); }else { writer.print("Case #" + i + ": " + (satisfied.size() + pSurprising)); } writer.println(); } writer.flush(); } }
import java.util.*; public class B { public static void main(String[] args) { Scanner s = new Scanner(System.in); int cases = s.nextInt(); for (int i=1; i<=cases; i++) { int n = s.nextInt(); int surprising = s.nextInt(); int p = s.nextInt(); int number = 0; for (int j=0; j<n; j++) { int t = s.nextInt(); int m = t/3; int remind = t%3; if ((remind == 0)&&(t!=0)) { if (m>=p) number++; else if ((m+1) >= p) { surprising--; if (surprising >=0) number++; } } if (t==0) if (t >= p) number++; if (remind == 1) { if ((m+1) >= p) number++; } if (remind == 2) { if ((m+1) >= p) number++; else if ((m+2) >= p) { surprising--; if (surprising >=0) number++; } } } System.out.println("Case #" + i + ": " + number); } } }