F1
stringlengths
6
6
F2
stringlengths
6
6
label
stringclasses
2 values
text_1
stringlengths
149
20.2k
text_2
stringlengths
48
42.7k
B21049
B21413
0
package it.simone.google.code.jam2012; import java.util.HashSet; import java.util.Set; public class RecycledNumber implements GoogleCodeExercise { int a = 0; int b = 0; Set<Couple> distinctCouple = null; long maxTime = 0; private class Couple { int x = 0; int y = 0; public Couple(int x, int y) { this.x = x; this.y = y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Couple other = (Couple) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (x == other.x && y == other.y) return true; if (x == other.y && y == other.x) return true; return false; } private RecycledNumber getOuterType() { return RecycledNumber.this; } } @Override public String execute(String line) { int result = 0; String[] data = line.split(" "); a = Integer.parseInt(data[0]); b = Integer.parseInt(data[1]); initialize(); int n = a; // while (n <= b) { result += analize(n); n++; // if (n % 1000 == 0) // System.out.println(n); } System.out.println(result); return "" + result; } @Override public void initialize() { distinctCouple = new HashSet<Couple>(); } private int analize(int number) { String numString = "" + number; initialize(); for (int i = 1; i < numString.length(); i++) { int m = shift(numString, i); if (a <= number && number < m && m <= b) { Couple couple=new Couple(number,m); if (!distinctCouple.contains(couple)) distinctCouple.add(couple); } } return distinctCouple.size(); } private int shift(String numString, int posx) { String result = null; result = "" + numString.substring(posx) + numString.substring(0, posx); return Integer.parseInt(result.toString()); } }
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(); } } }
B12082
B11877
0
package jp.funnything.competition.util; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import org.apache.commons.io.IOUtils; public class QuestionReader { private final BufferedReader _reader; public QuestionReader( final File input ) { try { _reader = new BufferedReader( new FileReader( input ) ); } catch ( final FileNotFoundException e ) { throw new RuntimeException( e ); } } public void close() { IOUtils.closeQuietly( _reader ); } public String read() { try { return _reader.readLine(); } catch ( final IOException e ) { throw new RuntimeException( e ); } } public BigDecimal[] readBigDecimals() { return readBigDecimals( " " ); } public BigDecimal[] readBigDecimals( final String separator ) { final String[] tokens = readTokens( separator ); final BigDecimal[] values = new BigDecimal[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = new BigDecimal( tokens[ index ] ); } return values; } public BigInteger[] readBigInts() { return readBigInts( " " ); } public BigInteger[] readBigInts( final String separator ) { final String[] tokens = readTokens( separator ); final BigInteger[] values = new BigInteger[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = new BigInteger( tokens[ index ] ); } return values; } public int readInt() { final int[] values = readInts(); if ( values.length != 1 ) { throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" ); } return values[ 0 ]; } public int[] readInts() { return readInts( " " ); } public int[] readInts( final String separator ) { final String[] tokens = readTokens( separator ); final int[] values = new int[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = Integer.parseInt( tokens[ index ] ); } return values; } public long readLong() { final long[] values = readLongs(); if ( values.length != 1 ) { throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" ); } return values[ 0 ]; } public long[] readLongs() { return readLongs( " " ); } public long[] readLongs( final String separator ) { final String[] tokens = readTokens( separator ); final long[] values = new long[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = Long.parseLong( tokens[ index ] ); } return values; } public String[] readTokens() { return readTokens( " " ); } public String[] readTokens( final String separator ) { return read().split( separator ); } }
package gcj2012; import java.io.BufferedReader; import java.io.FileReader; import java.io.BufferedWriter; import java.io.FileWriter; public class RecycledNumber { public String count(int A, int B, int caseNr) { StringBuffer sb = new StringBuffer(""); sb.append("Case #"); sb.append(caseNr); sb.append(": "); int result = 0; for (int i = A; i <= B; i++) { result += recycled(i, B); } sb.append(result); return sb.toString(); } public int recycled(int nr, int max) { if (nr < 12) return 0; int test = nr; int count = 0; int length = (int)Math.ceil(Math.log10((double)nr)); int[] digits = new int[length]; for (int i = length-1; i >=0; i--) { digits[i] = test%10; test = test/10; } int[] valuesFound = new int[length]; for (int i = 0; i < length; i++) { if (digits[i] != 0) { int value = 0; for (int j = 0; j < length; j++) { value = value*10; value += digits[(i+j)%length]; } valuesFound[i] = value; if ((value > nr) && (value <= max)) { boolean found = false; for (int k = 0; k < i; k++) { if (valuesFound[k] == valuesFound[i]) found = true; } //System.out.println(nr + " " + value); if (!found) count++; } } } return count; } /** * @param args */ public static void main(String[] args) { RecycledNumber test = new RecycledNumber(); String fileName = "in3.txt"; String outName = "out3.txt"; try { BufferedReader br = new BufferedReader(new FileReader(fileName)); String line = br.readLine(); BufferedWriter bw = new BufferedWriter(new FileWriter(outName)); int tests = new Integer(line).intValue(); for (int i = 0; i < tests; i++) { line = br.readLine(); String[] parts = line.split(" "); int A = new Integer(parts[0]).intValue(); int B = new Integer(parts[1]).intValue(); String line2 = test.count(A, B, i+1); System.out.println(line2); bw.write(line2+"\n"); } bw.flush(); } catch (Exception e) { e.printStackTrace(); } } } /** Input Ê 4 1 9 10 40 100 500 1111 2222 Output Ê Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 */
B20291
B21364
0
import java.io.*; import java.util.*; class B { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader("B.in")); PrintWriter pw = new PrintWriter(new FileWriter("B.out")); int X = Integer.parseInt(br.readLine()); for(int i=0; i<X; i++) { String[] S = br.readLine().split(" "); int A = Integer.parseInt(S[0]); int B = Integer.parseInt(S[1]); int R = 0; int x = 1; int n = 0; while(A/x > 0) { n++; x *= 10; } for(int j=A; j<B; j++) { Set<Integer> seen = new HashSet<Integer>(); for(int k=1; k<n; k++) { int p1 = j % (int)Math.pow(10, k); int p2 = (int) Math.pow(10, n-k); int p3 = j / (int)Math.pow(10, k); int y = p1*p2 + p3; if(j < y && !seen.contains(y) && y <= B) { seen.add(y); R++; } } } pw.printf("Case #%d: %d\n", i+1, R); pw.flush(); } } catch(Exception e) { e.printStackTrace(); } } }
package com.sam.googlecodejam.dance; import com.sam.googlecodejam.helper.InputReader; public class DanceScore { int iBestScore; int iSuprize; int iMean; int iSetCount = 0; class TripletScore { public int judge1; public int judge2; public int judge3; public void setValue(int j1, int j2, int j3) { judge1 = j1; judge2 = j2; judge3 = j3; } public int sum() { //System.out.println(judge1 + judge2 + judge3); return judge1 + judge2 + judge3; } public boolean containsGreater(int value) { //System.out.println(judge1 >= value || judge2 >= value || judge3 >= value); if(judge1 >=0 && judge2 >=0 && judge3 >=0) { return judge1 >= value || judge2 >= value || judge3 >= value; } return false; } } /* * e.g. If score is 13,14,15, 15 - avg = 15/3 + (15%3==0)= 5 (3,5,5), * (4,4,5) (4,5,5) (5,5,5) (4,6,5) If score is 22,23,24 22 - avg = 22/3 * +(22%3==0) = 8 (6,8,8), (7,7,8) (7,8,8) (8,8,8), (7,8,9) */ TripletScore possibleValues[] = new TripletScore[6]; public void generateTripletFromScore(int score) { int mean = score / 3 + (score % 3 == 0 ? 0 : 1); iMean = mean; for(int i=0;i<6;i++) { possibleValues[i] = new TripletScore(); } // Non Suprizing possibleValues[0].setValue(mean - 1, mean - 1, mean); possibleValues[1].setValue(mean - 1, mean, mean); possibleValues[2].setValue(mean, mean, mean); // Suprizing possibleValues[3].setValue(mean - 2, mean, mean); possibleValues[4].setValue(mean - 1, mean + 1, mean); possibleValues[5].setValue(mean - 1, mean - 1, mean + 1); } public void isScore(int score) { // check if any combination yeilds a result that would be greater than // the better score // We first check if a non-suprizing one works and only then use up a // suprizing! for (int i = 0; i < 3; i++) { if (possibleValues[i].sum() == score) { if (possibleValues[i].containsGreater(iBestScore)) { iSetCount++; return; } } } if (iSuprize != 0) { for (int i = 3; i < 6; i++) { if (possibleValues[i].sum() == score) { if (possibleValues[i].containsGreater(iBestScore)) { iSetCount++; iSuprize--; return; } } } } } public static void main(String[] args) { InputReader reader = new InputReader("c://input.in"); reader.readNextLine(); // read the line number off - we don't need it String lineRead = null; int i = 1; while ((lineRead = reader.readNextLine()) != null) { DanceScore score = new DanceScore(); System.out.print("Case #" + i + ": "); i++; String values[] = lineRead.split(" "); score.iSuprize = Integer.parseInt(values[1]); score.iBestScore = Integer.parseInt(values[2]); for (int LoopCount = 3; LoopCount <= Integer.parseInt(values[0])+2; LoopCount++) { score.generateTripletFromScore(Integer .parseInt(values[LoopCount])); score.isScore(Integer .parseInt(values[LoopCount])); } System.out.println(score.iSetCount); } } }
A20119
A21843
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(); } }
/** * @author Saifuddin Merchant * */ package com.sam.googlecodejam.helper; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class InputReader { BufferedReader iFileBuffer; long iCurrentLineNumber; public InputReader(String pFileName) { try { iFileBuffer = new BufferedReader(new FileReader(pFileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } iCurrentLineNumber = 0; } public String readNextLine() { try { return iFileBuffer.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public void close() { try { iFileBuffer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
A13029
A12755
0
import java.util.List; public class Case implements Runnable { private int id; private String output; private int n; private int s; private int p; private List<Integer> g; public Case(int id) { this.id = id; } public Case(int id, int n, int s, int p, List<Integer> g) { super(); this.id = id; this.n = n; this.s = s; this.p = p; this.g = g; } public String solve() { int res = 0; for (int googler : g) { int b = googler / 3; boolean div = googler % 3 == 0; if (b >= p) { res++; continue; } if (p == b+1) { if (div && s > 0 && b > 0) { res++; s--; continue; } if (!div) { res++; continue; } } if (p == b+2) { if (3*b+2 == googler && s > 0) { res++; s--; } } } return String.valueOf(res); } @Override public void run() { output = solve(); } @Override public String toString() { return "Case #" + id + ": " + output; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejam; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; /** * * @author massimo */ public class ProblemB { //It can be proven that b=min{10,2+floor((totalPoints-2)/3)),totalPoints} if the best possibile result. //The triple must be surprising iff totalPoints<=3*(b-1). public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader(new FileReader("in.in")); PrintWriter out = new PrintWriter("out.out"); int t = Integer.parseInt(in.readLine()); for (int i = 1; i <= t; i++) { StringTokenizer st = new StringTokenizer(in.readLine(), " "); int n = Integer.parseInt(st.nextToken()); int s = Integer.parseInt(st.nextToken()); int p = Integer.parseInt(st.nextToken()); int res = 0, surprising = 0; for (int j = 0; j < n; j++) { int totalPoints = Integer.parseInt(st.nextToken()); int b = Math.min(Math.min(totalPoints, 10), 2 + (totalPoints - 2) / 3); if (b > p) { res++; } else if (b == p) { if (totalPoints>3*(b-1)) { res++; } else if (surprising<s) { res++; surprising++; } } } out.println("Case #"+i+": "+res); } out.close(); } }
A12570
A10788
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; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dancing.with.the.googlers; /** * * @author Optee */ public class ScoreCounter { int numberOfGooglers; int surpriseCount; int minScore; int[] scores; public ScoreCounter(String line) { String[] numbers = line.split(" "); this.numberOfGooglers = Integer.valueOf(numbers[0]); this.surpriseCount = Integer.valueOf(numbers[1]); this.minScore = Integer.valueOf(numbers[2]); this.scores = new int[numbers.length-3]; int j = 0; for (int i = 3; i < numbers.length; i++) { scores[j++] = Integer.valueOf(numbers[i]); } } int Count2() { int winners = 0; Integer surprise = surpriseCount; for (int i = 0; i < numberOfGooglers; i++) { int score = this.scores[i]; int minCount = minScore * 3; if(score == 0 && minScore > 0) continue; if (score + 2 >= minCount) { winners++; } else if (score + 4 >= minCount && surprise > 0) { surprise--; winners++; } } return winners; } int Count() throws Exception { int winners = 0; Integer surprise = surpriseCount; Integer possibleSurprises = 0; for (int i = 0; i < numberOfGooglers; i++) { int score = this.scores[i]; int tail = score - minScore; if (tail <= 0) continue; int divTileOne = tail/2; int divTileTwo = tail - divTileOne; if (Math.max(divTileOne, divTileTwo) >= minScore){ if (Math.max(divTileOne, divTileTwo) - minScore >=2) possibleSurprises++; winners++; } else if (minScore - Math.min(divTileOne, divTileTwo) < 2) { winners++; } else if (minScore - Math.min(divTileOne, divTileTwo) == 2) { if (surprise > 0) { surprise--; winners++; } } } return winners; } }
A22078
A21925
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 codejam; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Gedion Moyo */ public class dance { /** * @param args the command line arguments */ static Scanner in; static PrintWriter out; public static void main(String[] args) { try { in = new Scanner(new FileReader("src/codejam/input.txt")); out = new PrintWriter(new FileWriter("src/codejam/output.txt")); solve(); } catch (Exception ex) { Logger.getLogger(CodeJam.class.getName()).log(Level.SEVERE, null, ex); } } public static void solve() throws Exception { int caseCount = Integer.valueOf(in.nextLine()); for (int caseNum = 0; caseNum < caseCount; caseNum++) { System.out.println("solving case " + caseNum); out.print("Case #" + (caseNum + 1) + ":"); out.print(" "); int N = in.nextInt(); int S = in.nextInt(); int p = in.nextInt(); int[] t = getScores(N); int count = 0; int suprises = 0; for (int j=0; j<t.length;j++){ if (t[j] >= p){ if ((t[j]/3 >= p)||((t[j]+2)/3>=p)){ count++; }else if (((t[j]+4)/3 >= p) && suprises < S){ count++; suprises++; } } } out.print(count); out.print("\n"); } out.flush(); out.close(); in.close(); } public static int[] getScores(int N){ int[] scores = new int[N]; for (int i =0; i < N;i++){ scores[i] = in.nextInt(); } return scores; } }
A22191
A21013
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 qualifiers.dancing; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Dancing { public static void main(String[] args) { try { FileReader fileReader = new FileReader("input/B-large.in"); BufferedReader bufferedReader = new BufferedReader(fileReader); String record = null; int numOfCases = -1; int lineCount = 0; List<String> inputList = new ArrayList<String>(); // Read input while ((record = bufferedReader.readLine()) != null) { // First row is number of cases if (lineCount == 0) { numOfCases = Integer.valueOf(record); } // Input else { inputList.add(record); } lineCount++; } fileReader.close(); // Perform algo List<Integer> results = new ArrayList<Integer>(); for (String input : inputList) { String[] inputStrArray = input.split(" "); int numOfGooglers = Integer.valueOf(inputStrArray[0]); int numOfSurprisingScores = Integer.valueOf(inputStrArray[1]); int point = Integer.valueOf(inputStrArray[2]); // Constraints int constraint1 = ((3 * point - 4) < point) ? point : (3 * point - 4); int constraint2 = (constraint1 < 2) ? constraint1 : constraint1 + 1; int surePassConstraint = (constraint2 < 2) ? constraint2 : constraint2 + 1; // Calc int result = 0; int count = 3 + numOfGooglers; for (int i = 3; i < count; i++) { int totalScoreOfGoogler = Integer.valueOf(inputStrArray[i]); // Sure pass if (totalScoreOfGoogler >= surePassConstraint) { result++; } // Sure fail else if (totalScoreOfGoogler < constraint1) { continue; } // Surprise score else if (totalScoreOfGoogler == constraint1 || totalScoreOfGoogler == constraint2) { if (numOfSurprisingScores > 0) { result++; numOfSurprisingScores--; } else { continue; } } } results.add(result); } // Write output FileWriter fileWriter = new FileWriter("output/results.out"); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); for (int i = 0; i < results.size(); i++) { int result = results.get(i); bufferedWriter.write("Case #" + (i+1) + ": " + result); if (i < results.size() - 1) bufferedWriter.write("\n"); } //Close the output stream bufferedWriter.close(); } catch (IOException e) { System.out.println("IOException error!"); e.printStackTrace(); } } }
A11277
A10756
0
package googlers; import java.util.Scanner; import java.util.PriorityQueue; import java.util.Comparator; public class Googlers { public static void main(String[] args) { int n,s,p,count=0,t; Scanner sin=new Scanner(System.in); t=Integer.parseInt(sin.nextLine()); int result[]=new int[t]; int j=0; if(t>=1 && t<=100) { for (int k = 0; k < t; k++) { count=0; String ip = sin.nextLine(); String[]tokens=ip.split(" "); n=Integer.parseInt(tokens[0]); s=Integer.parseInt(tokens[1]); p=Integer.parseInt(tokens[2]); if( (s>=0 && s<=n) && (p>=0 && p<=10) ) { int[] total=new int[n]; for (int i = 0; i < n; i++) { total[i] = Integer.parseInt(tokens[i+3]); } Comparator comparator=new PointComparator(); PriorityQueue pq=new PriorityQueue<Point>(1, comparator); for (int i = 0; i < n; i++) { int x=total[i]/3; int r=total[i]%3; if(x>=p) count++; else if(x<(p-2)) continue; else { //System.out.println("enter "+x+" "+(p-2)); if(p-x==1) { Point temp=new Point(); temp.q=x; temp.r=r; pq.add(temp); } else // p-x=2 { if(r==0) continue; else { Point temp=new Point(); temp.q=x; temp.r=r; pq.add(temp); } } } //System.out.println("hi "+pq.size()); } while(pq.size()!=0) { Point temp=(Point)pq.remove(); if(p-temp.q==1 && temp.q!=0) { if(temp.r>=1) count++; else { if(s!=0) { s--; count++; } } } else if(p-temp.q==2) { if(s!=0 && (temp.q+temp.r)>=p) { s--; count++; } } } //System.out.println(p); result[j++]=count; } } for (int i = 0; i < t; i++) { System.out.println("Case #"+(i+1)+": "+result[i]); } } } /*Point x=new Point(); x.q=8; Point y=new Point(); y.q=6; Point z=new Point(); z.q=7; pq.add(x); pq.add(y); pq.add(z); */ } class PointComparator implements Comparator<Point> { @Override public int compare(Point x, Point y) { // Assume neither string is null. Real code should // probably be more robust if (x.q < y.q) { return 1; } if (x.q > y.q) { return -1; } return 0; } } class Point { int q,r; public int getQ() { return q; } public void setQ(int q) { this.q = q; } public int getR() { return r; } public void setR(int r) { this.r = r; } }
import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class DancingWithGooglers { public static void main(String[] args) { Scanner problem = new Scanner(System.in); int T = problem.nextInt(); for (int i = 0; i < T; i++) { int answer = 0; int N = problem.nextInt(); int S = problem.nextInt(); int p = problem.nextInt(); List<Triplet> googlers = new ArrayList<Triplet>(); for (int j = 0; j < N; j++) { googlers.add(new Triplet(problem.nextInt())); } int possibleSurprises = 0; for (Triplet triplet : googlers) { if (triplet.minMax() >= p) { answer++; continue; } if (triplet.maxMax() >= p) { possibleSurprises++; } } answer += possibleSurprises >= S ? S : possibleSurprises; System.out.println(String.format("Case #%s: %s", i + 1, answer)); } } } class Triplet { private int totalScore; public Triplet(int totalScore) { this.totalScore = totalScore; } private int min() { return new BigDecimal(totalScore).divide(new BigDecimal(3), RoundingMode.FLOOR).intValue(); } public int minMax() { return new BigDecimal(totalScore).divide(new BigDecimal(3), RoundingMode.CEILING).intValue(); } public int maxMax() { int lalala = this.totalScore % 3; if (lalala == 0) { lalala = 1; } if (this.totalScore == 0) { lalala = 0; } return this.min() + lalala; } }
B22190
B21288
0
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class Recycled { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for (int i = 0; i < t; i++) { String[] str = br.readLine().split(" "); int a = Integer.parseInt(str[0]); int b = Integer.parseInt(str[1]); System.out.println("Case #" + (i + 1) + ": " + find(a, b)); } } catch (IOException e) { e.printStackTrace(); } } private static int find(int a, int b) { HashSet<Long> used = new HashSet<Long>(); int digits = String.valueOf(a).length(); if (digits == 1) return 0; for (int i = a; i <= b; i++) { int s = 10; int m = (int) Math.pow(10, digits-1); for (int j = 0; j < digits-1; j++) { int r = i % s; if (r < s/10) continue; int q = i / s; int rn = r * m + q; s *= 10; m /= 10; if (i != rn && rn >= a && rn <= b) { long pp; if (rn < i) pp = (long)rn << 30 | i; else pp = (long)i << 30 | rn; if (!used.contains(pp)) { used.add(pp); } } } } return used.size(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlecodejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; /** * * @author Wouter */ public class RecycledNumbers { ArrayList<String> cases = new ArrayList<String>(); public RecycledNumbers() { try { // Setup in/out System.setIn(new FileInputStream("C:\\GCJ\\C-large.in")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\GCJ\\C-large.out")); bw.flush(); int untill = Integer.parseInt(br.readLine()); for (int x = 1; x <= untill; x++) { int ans = 0; String[] s = br.readLine().split(" "); int a = Integer.parseInt(s[0]); int b = Integer.parseInt(s[1]); for (int z = a; z <= b; z++) { List<Integer> ints = getAllRecycledPairsOf(z); removeDups(ints); Collections.sort(ints); for (Integer nr : ints) { if (between(nr, a, b)) { ans++; } else if (nr > b) { break; } } } String out = "Case #" + x + ": " + ans; cases.add(out); } for (String s : cases) { System.out.println(s); bw.write(s); bw.flush(); bw.newLine(); } } catch (IOException ex) { System.out.println("SOMETHING WENT WRONG"); } } public List<Integer> getAllRecycledPairsOf(int nr) { List<Integer> ints = new ArrayList<Integer>(); StringBuilder s = new StringBuilder(); s.append(nr); String start = s.toString(); for (int x = 1; x < start.length(); x++) { s = new StringBuilder(); String back = start.substring(start.length() - x, start.length()); String front = start.substring(0, start.length() - x); s.append(back).append(front); if (!back.startsWith("0")) { Integer newNr = new Integer(s.toString()); if (newNr > nr) { ints.add(newNr); } } } return ints; } public static void main(String[] args) { RecycledNumbers test = new RecycledNumbers(); } public boolean between(int nr, int a, int b) { if (nr >= a && nr <= b) { //System.out.println(nr); return true; } return false; } public static void removeDups(List<Integer> list) { Set<Integer> s = new HashSet<Integer>(list); list.clear(); list.addAll(s); } }
A20261
A21504
0
package com.gcj.parser; public class MaxPoints { public static int normal(int value){ int toReturn = 0; switch (value) { case 0 : toReturn = 0 ; break; case 1 : toReturn = 1 ; break; case 2 : toReturn = 1 ; break; case 3 : toReturn = 1 ; break; case 4 : toReturn = 2 ; break; case 5 : toReturn = 2 ; break; case 6 : toReturn = 2 ; break; case 7 : toReturn = 3 ; break; case 8 : toReturn = 3 ; break; case 9 : toReturn = 3 ; break; case 10 : toReturn = 4 ; break; case 11 : toReturn = 4 ; break; case 12 : toReturn = 4 ; break; case 13 : toReturn = 5 ; break; case 14 : toReturn = 5 ; break; case 15 : toReturn = 5 ; break; case 16 : toReturn = 6 ; break; case 17 : toReturn = 6 ; break; case 18 : toReturn = 6 ; break; case 19 : toReturn = 7 ; break; case 20 : toReturn = 7 ; break; case 21 : toReturn = 7 ; break; case 22 : toReturn = 8 ; break; case 23 : toReturn = 8 ; break; case 24 : toReturn = 8 ; break; case 25 : toReturn = 9 ; break; case 26 : toReturn = 9 ; break; case 27 : toReturn = 9 ; break; case 28 : toReturn = 10 ; break; case 29 : toReturn = 10 ; break; case 30 : toReturn = 10 ; break; } return toReturn; } public static int surprising(int value){ int toReturn = 0; switch (value) { case 0 : toReturn = 0 ; break; case 1 : toReturn = 1 ; break; case 2 : toReturn = 2 ; break; case 3 : toReturn = 2 ; break; case 4 : toReturn = 2 ; break; case 5 : toReturn = 3 ; break; case 6 : toReturn = 3 ; break; case 7 : toReturn = 3 ; break; case 8 : toReturn = 4 ; break; case 9 : toReturn = 4 ; break; case 10 : toReturn = 4 ; break; case 11 : toReturn = 5 ; break; case 12 : toReturn = 5 ; break; case 13 : toReturn = 5 ; break; case 14 : toReturn = 6 ; break; case 15 : toReturn = 6 ; break; case 16 : toReturn = 6 ; break; case 17 : toReturn = 7 ; break; case 18 : toReturn = 7 ; break; case 19 : toReturn = 7 ; break; case 20 : toReturn = 8 ; break; case 21 : toReturn = 8 ; break; case 22 : toReturn = 8 ; break; case 23 : toReturn = 9 ; break; case 24 : toReturn = 9 ; break; case 25 : toReturn = 9 ; break; case 26 : toReturn = 10 ; break; case 27 : toReturn = 10 ; break; case 28 : toReturn = 10 ; break; case 29 : toReturn = 10 ; break; case 30 : toReturn = 10 ; break; } return toReturn; } }
import java.io.*; import java.lang.*; import java.util.*; public class B { public static void main(String[] args) { B prob = new B(); prob.run(args[0]); } public void run(String fileName) { try { Scanner fin = new Scanner(new File(fileName)); PrintWriter fout = new PrintWriter(new File(fileName + ".out")); int T = fin.nextInt(); for (int t = 1; t <= T; ++t) { fout.format("Case #%d: ", t); int N = fin.nextInt(); int S = fin.nextInt(); int p = fin.nextInt(); int result = 0; for (int i = 0; i < N; ++i) { int ti = fin.nextInt(); if (p == 0) { ++result; continue; } if (ti >= (3 * p - 2)) { ++result; continue; } if (p == 1) continue; if (ti >= (3 * p - 4)) { if (S == 0) continue; ++result; --S; } } fout.format("%d\n", result); } fin.close(); fout.close(); } catch (Exception e) { e.printStackTrace(); } } }
B12074
B10850
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.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Scanner; public class C { private static boolean isRecyledPair(String n, String m) { int l = n.length(); String s = ""; for (int i = 1; i < l; i++) { for (int j = 0; j < l; j++) { s += n.charAt((j+i) % (l)); } if (s.equals(m)) { return true; } s = ""; } return false; } public static void main(String[] args) { try { Scanner file = new Scanner(new File(args[0])); int T = Integer.parseInt(file.nextLine()); BufferedWriter out = new BufferedWriter(new FileWriter(args[0].substring(0, args[0].length()-2) +"out")); for (int i = 0; i < T; i++) { int A = file.nextInt(); int B = file.nextInt(); int ans = 0; for (int j = A; j < B; j++) { for (int k = j+1; k <= B; k++) { if (isRecyledPair(String.valueOf(j), String.valueOf(k))) { ans++; } } } out.write(new StringBuilder().append("Case #").append(i+1).append(": ").append(ans).append("\n").toString()); } out.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
B12115
B10152
0
package qual; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { new RecycledNumbers().run(); } private void run() { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int t = 0; t < T; t++) { int A = sc.nextInt(); int B = sc.nextInt(); int result = solve(A, B); System.out.printf("Case #%d: %d\n", t + 1, result); } } public int solve(int A, int B) { int result = 0; for (int i = A; i <= B; i++) { int dig = (int) Math.log10(A/*same as B*/) + 1; int aa = i; for (int d = 0; d < dig - 1; d++) { aa = (aa % 10) * (int)Math.pow(10, dig - 1) + (aa / 10); if (i == aa) { break; } if (i < aa && aa <= B) { // System.out.printf("(%d, %d) ", i, aa); result++; } } } return result; } }
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; import java.util.Scanner; public class RecycledNumbers { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub //System.setOut(new PrintStream(new File("RecycledNumbers.txt"))); Scanner scanner = new Scanner(System.in); int testcasenum = Integer.valueOf(scanner.next()); scanner.nextLine(); for (int testcase = 0; testcase < testcasenum; testcase++) { System.out.print("Case #"); System.out.print(testcase+1); System.out.print(": "); int from = scanner.nextInt(); int to = scanner.nextInt(); int count = 0; boolean table[] = new boolean[to+1]; for (int num = from; num <= to; num++) { if (!table[num]){ int len = String.valueOf(num).length(); int shift = num; table[num] = true; int pair = 1; for (int i = 0;i < len-1;i++){ shift = shiftLeft(shift, len); if (shift >= from && shift <= to&& !table[shift]){ pair++; table[shift] = true; } } count += pair*(pair-1)/2; } } System.out.println(count); } } public static int shiftLeft(int num, int len) { int digit = num % 10; num = num / 10; return num += Math.pow(10, len-1)*digit; } public static int getUniqueDigits(int num){ boolean digits[] = new boolean[10]; while (num != 0) { int digit = (num % 10); digits[digit] = true; num = num / 10; } int count = 0; for (int i = 0;i < 10;i++){ count += digits[i]?1:0; } return count; } }
B20291
B20468
0
import java.io.*; import java.util.*; class B { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader("B.in")); PrintWriter pw = new PrintWriter(new FileWriter("B.out")); int X = Integer.parseInt(br.readLine()); for(int i=0; i<X; i++) { String[] S = br.readLine().split(" "); int A = Integer.parseInt(S[0]); int B = Integer.parseInt(S[1]); int R = 0; int x = 1; int n = 0; while(A/x > 0) { n++; x *= 10; } for(int j=A; j<B; j++) { Set<Integer> seen = new HashSet<Integer>(); for(int k=1; k<n; k++) { int p1 = j % (int)Math.pow(10, k); int p2 = (int) Math.pow(10, n-k); int p3 = j / (int)Math.pow(10, k); int y = p1*p2 + p3; if(j < y && !seen.contains(y) && y <= B) { seen.add(y); R++; } } } pw.printf("Case #%d: %d\n", i+1, R); pw.flush(); } } catch(Exception e) { e.printStackTrace(); } } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Arrays; /** * Created by IntelliJ IDEA. * User: Abhishek * Date: 4/14/12 * Time: 1:09 PM * To change this template use File | Settings | File Templates. */ public class RecNum { public int recycled(String a, String b){ int a1 = Integer.parseInt(a); int b1 = Integer.parseInt(b); int num = a1; int count=0; while(num<=b1){ String x = String.valueOf(num); ArrayList<String> store = new ArrayList<String>(10); for(int i=1; i<x.length(); i++){ String y = x.substring(x.length()-i, x.length())+x.substring(0, x.length()-i); int k = Integer.parseInt(y); if(k<=b1 && k>num && !store.contains(y)){ count++; store.add(y); } } num++; } return count; } public static void main(String[] args) { RecNum spk = new RecNum(); try { BufferedReader buff = new BufferedReader(new FileReader("C-large.in")); FileWriter fstream = new FileWriter("out1.txt"); BufferedWriter out = new BufferedWriter(fstream); int numTest = Integer.parseInt(buff.readLine()); if (numTest < 1 || numTest > 50) System.exit(0); for (int k = 0; k < numTest; k++) { String[] inp = buff.readLine().split(" "); out.write("Case #" + (k + 1) + ": " + spk.recycled(inp[0],inp[1])); out.write("\n"); // System.out.println("Case #" + (k + 1) + ": " + spk.recycled(inp[0],inp[1])+"\n"); } out.close(); } catch (Exception e) { System.out.println("Exception" + e); } } }
B21207
B21132
0
/* * Problem C. Recycled Numbers * * Do you ever become frustrated with television because you keep seeing the * same things, recycled over and over again? Well I personally don't care about * television, but I do sometimes feel that way about numbers. * * Let's say a pair of distinct positive integers (n, m) is recycled if you can * obtain m by moving some digits from the back of n to the front without * changing their order. For example, (12345, 34512) is a recycled pair since * you can obtain 34512 by moving 345 from the end of 12345 to the front. Note * that n and m must have the same number of digits in order to be a recycled * pair. Neither n nor m can have leading zeros. * * Given integers A and B with the same number of digits and no leading zeros, * how many distinct recycled pairs (n, m) are there with A ≤ n < m ≤ B? * * Input * * The first line of the input gives the number of test cases, T. T test cases * follow. Each test case consists of a single line containing the integers A * and B. * * Output * * For each test case, output one line containing "Case #x: y", where x is the * case number (starting from 1), and y is the number of recycled pairs (n, m) * with A ≤ n < m ≤ B. * * Limits * * 1 ≤ T ≤ 50. * * A and B have the same number of digits. Small dataset 1 ≤ A ≤ B ≤ 1000. Large dataset 1 ≤ A ≤ B ≤ 2000000. Sample Input Output 4 1 9 10 40 100 500 1111 2222 Case #1: 0 Case #2: 3 Case #3: 156 Case #4: 287 */ package google.codejam.y2012.qualifications; import google.codejam.commons.Utils; import java.io.IOException; import java.util.StringTokenizer; /** * @author Marco Lackovic <marco.lackovic@gmail.com> * @version 1.0, Apr 14, 2012 */ public class RecycledNumbers { private static final String INPUT_FILE_NAME = "C-large.in"; private static final String OUTPUT_FILE_NAME = "C-large.out"; public static void main(String[] args) throws IOException { String[] input = Utils.readFromFile(INPUT_FILE_NAME); String[] output = new String[input.length]; int x = 0; for (String line : input) { StringTokenizer st = new StringTokenizer(line); int a = Integer.valueOf(st.nextToken()); int b = Integer.valueOf(st.nextToken()); System.out.println("Computing case #" + (x + 1)); output[x++] = "Case #" + x + ": " + recycledNumbers(a, b); } Utils.writeToFile(output, OUTPUT_FILE_NAME); } private static int recycledNumbers(int a, int b) { int count = 0; for (int n = a; n < b; n++) { count += getNumGreaterRotations(n, b); } return count; } private static int getNumGreaterRotations(int n, int b) { int count = 0; char[] chars = Integer.toString(n).toCharArray(); for (int i = 0; i < chars.length; i++) { chars = rotateRight(chars); if (chars[0] != '0') { int m = Integer.valueOf(new String(chars)); if (n == m) { break; } else if (n < m && m <= b) { count++; } } } return count; } private static char[] rotateRight(char[] chars) { char last = chars[chars.length - 1]; for (int i = chars.length - 2; i >= 0; i--) { chars[i + 1] = chars[i]; } chars[0] = last; return chars; } }
import java.util.Scanner; public class Test { public static void main(String []args){ int numT=0; Scanner kb=new Scanner(System.in); numT = kb.nextInt(); int a[] = new int[numT]; int b[]=new int[numT]; for (int i = 0; i < numT; i++) { a[i] = kb.nextInt(); b[i]=kb.nextInt(); } for(int i=0;i<numT;i++){ System.out.println("Case #"+(i+1)+":"+" "+cal(a[i],b[i])); } } public static int cal(int A,int B){ int score=0; for(int i=A;i<=B;i++){ String num=i+""; for(int j=1;j<num.length();j++){ String s=num.substring(0,j); String t = num.substring(j, num.length()); String sum=t+s; int sb=Integer.parseInt(sum); if (sb <= B&&sb>=A&&sb!=i&&sb>i){ score++; } } } return score; } }
B12085
B11361
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Scanner; /** * * @author daniele */ public class GCJ_C { public static void main(String[] args) throws Exception{ Scanner in = new Scanner(new File(args[0])); FileWriter out = new FileWriter("/home/daniele/Scrivania/Output"); int prove=in.nextInt(); int min,max; int cifre; int cifreaus; String temp; int aus; int count=0; ArrayList<Integer> vals = new ArrayList<Integer>(); int jcount=0; ArrayList<Integer> perm = new ArrayList<Integer>(); out.write(""); out.flush(); for(int i=1;i<=prove;i++){ out.append("Case #" +i+": ");out.flush(); min=in.nextInt(); max=in.nextInt(); for(int j=min;j<=max;j++){ if(!vals.contains(j)){ temp=""+j; cifre=temp.length(); aus=j; perm.add(j); for(int k=1;k<cifre;k++){ aus=rotateOnce(aus); temp=""+aus; cifreaus=temp.length();//elusione zeri iniziali if(aus>=min && aus<=max && aus!=j && cifreaus==cifre && nobody(vals,perm)){ perm.add(aus); jcount ++; } } while(jcount>0){count+=jcount; jcount--;} vals.addAll(perm); perm= new ArrayList<Integer>(); } } out.append(count+"\n");out.flush(); count=0; vals= new ArrayList<Integer>(); } } static public int rotateOnce(int n){ String s=""+n; if(s.length()>1){ s=s.charAt(s.length()-1) + s.substring(0,s.length()-1); n=Integer.parseInt(s); } return n; } static public boolean nobody(ArrayList<Integer> v,ArrayList<Integer> a){; for(int i=0;i<a.size();i++) if(v.contains(a.get(i))) return false; return true; } }
import java.util.*; import java.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(); } }
B11696
B12652
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycled; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.TreeSet; /** * * @author Alfred */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream("C-small-attempt0.in"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter outFile = new FileWriter("out.txt"); PrintWriter out = new PrintWriter(outFile); String line; line = br.readLine(); int cases = Integer.parseInt(line); for (int i=1; i<=cases;i++){ line = br.readLine(); String[] values = line.split(" "); int A = Integer.parseInt(values[0]); int B = Integer.parseInt(values[1]); int total=0; for (int n=A; n<=B;n++){ TreeSet<String> solutions = new TreeSet<String>(); for (int k=1;k<values[1].length();k++){ String m = circshift(n,k); int mVal = Integer.parseInt(m); if(mVal<=B && mVal!=n && mVal> n && !m.startsWith("0") && m.length()==Integer.toString(n).length() ) { solutions.add(m); } } total+=solutions.size(); } out.println("Case #"+i+": "+total); } in.close(); out.close(); } catch (Exception e) {//Catch exception if any System.err.println("Error: " + e.getMessage()); } } private static String circshift(int n, int k) { String nString=Integer.toString(n); int len=nString.length(); String m = nString.substring(len-k)+nString.subSequence(0, len-k); //System.out.println(n+" "+m); return m; } }
package codejem; import java.io.*; import java.util.HashSet; import java.util.Set; public class RecycleNumber { public static void main(String[] args) throws IOException { InputStream is; if (args.length > 0) { is = new FileInputStream(args[0]); }else{ is = System.in; } BufferedReader inputReader = new BufferedReader(new InputStreamReader(is)); String firstLine = inputReader.readLine(); int count_of_cases = Integer.parseInt(firstLine); for (int idx_of_case = 1; idx_of_case <= count_of_cases; idx_of_case++) { String caseLine = inputReader.readLine(); String[] numbers = caseLine.split(" "); int start = Integer.parseInt(numbers[0]); int end = Integer.parseInt(numbers[1]); int count = count_of_recyclable(start, end); System.out.println(String.format("Case #%d: %d", idx_of_case, count)); } } public static int count_of_recyclable(int start, int end) { int count = 0; for (int number = start; number <= end; number++) { char[] chars = int_to_char_array(number); char[] max_number = int_to_char_array(end); Set<String> matchNumbers = new HashSet<String>(); for (int chars_to_move = 1; chars_to_move < chars.length; chars_to_move++) { char[] rotated_chars = rotated_chars(chars, chars_to_move); if (rotated_chars[0] != '0' && not_greater_than_number(rotated_chars, max_number) && less_than_number(chars, rotated_chars)) { matchNumbers.add(String.valueOf(rotated_chars)); } } count+= matchNumbers.size(); } return count; } public static boolean not_greater_than_number(char[] rotated_chars, char[] max_number) { for (int i = 0; i < rotated_chars.length; i++) { if (max_number[i] > rotated_chars[i]) { return true; } if (rotated_chars[i] > max_number[i]) { return false; } } return true; } public static boolean less_than_number(char[] rotated_chars, char[] max_number) { for (int i = 0; i < rotated_chars.length; i++) { if (max_number[i] > rotated_chars[i]) { return true; } if (rotated_chars[i] > max_number[i]) { return false; } } return false; } private static char[] int_to_char_array(int number) { return String.valueOf(number).toCharArray(); } public static char[] rotated_chars(char[] chars, int chars_to_move) { int length = chars.length; char[] result = new char[length]; System.arraycopy(chars, length - chars_to_move, result, 0, chars_to_move); System.arraycopy(chars, 0, result, chars_to_move, length - chars_to_move); return result; } }
A21557
A20544
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.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class Main { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File("B-large.in")); PrintWriter out = new PrintWriter("C:\\Users\\JiaKY\\Desktop\\out.txt"); //Scanner in = new Scanner(System.in); int t = Integer.valueOf(in.nextLine()); for(int ii=0;ii<t;ii++){ String line = in.nextLine(); String[] data = line.split(" "); int n = Integer.valueOf(data[0]); int s = Integer.valueOf(data[1]); int p = Integer.valueOf(data[2]); int[] score = new int[n]; for(int i=0;i<n;i++){ score[i] = Integer.valueOf(data[3+i]); } Arrays.sort(score); int ans = 0; for(int i=score.length-1;i>=0;i--){ int valid = 3*p-2; if(p<2) valid = p; int min = 3*p-4; if(p <= 2) min = p; if(score[i] >= valid) ans++; else if(s > 0){ if(score[i] >= min){ ans++; s--; if(s == 0) break; } } } out.printf("Case #%d: %d",ii+1,ans); out.println(); out.flush(); } } }
B11327
B11020
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]); } } }
package org.moriraaca.codejam.recyclednumbers; import org.moriraaca.codejam.TestCase; public class RecycledNumbersTestCase implements TestCase { public int A; public int B; }
B20291
B21417
0
import java.io.*; import java.util.*; class B { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader("B.in")); PrintWriter pw = new PrintWriter(new FileWriter("B.out")); int X = Integer.parseInt(br.readLine()); for(int i=0; i<X; i++) { String[] S = br.readLine().split(" "); int A = Integer.parseInt(S[0]); int B = Integer.parseInt(S[1]); int R = 0; int x = 1; int n = 0; while(A/x > 0) { n++; x *= 10; } for(int j=A; j<B; j++) { Set<Integer> seen = new HashSet<Integer>(); for(int k=1; k<n; k++) { int p1 = j % (int)Math.pow(10, k); int p2 = (int) Math.pow(10, n-k); int p3 = j / (int)Math.pow(10, k); int y = p1*p2 + p3; if(j < y && !seen.contains(y) && y <= B) { seen.add(y); R++; } } } pw.printf("Case #%d: %d\n", i+1, R); pw.flush(); } } catch(Exception e) { e.printStackTrace(); } } }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; class Recycle extends Question{ public Recycle(String in, String out) { super(in, out); } public void solve(){ ArrayList<String> rst=new ArrayList<String>(); try { data=read(file_in); } catch (IOException e) { e.printStackTrace(); } int cases=pInt(0); data.remove(0); int count=1; for(String s:data){ int tot=0; ArrayList<Integer> arr=splitInt(s," "); int min=arr.get(0); int max=arr.get(1); for(int i=min;i<=max;i++){ tot+=cycles(i,min,max); } tot=tot/2; rst.add("Case #"+count+": "+tot); count++; } try { write(file_out,rst); } catch (IOException e) { e.printStackTrace(); } } public int cycles(int val,int min,int max){ String s=val+""; Set<Integer> ints=new HashSet<Integer>(); for(int i=0;i<s.length();i++){ s=shift(s); if(s.charAt(0)!='0'){ int val2=pInt(s); if(val2>=min&&val2<=max){ ints.add(val2); } } } return ints.size()-1; } public String shift(String s){ return s.substring(1)+s.substring(0,1); } } class Question{ String file_in; String file_out; ArrayList<String> data; public Question(String in,String out){ file_in=in; file_out=out; try { data=read(file_in); } catch (IOException e) { e.printStackTrace(); } } public void solve(){} public int pInt(int index){ return Integer.parseInt(data.get(index)); } public int pInt(String s){ return Integer.parseInt(s); } public ArrayList<String> splitString(String s,String sep){ ArrayList<String> arr=new ArrayList<String>(); String[] ss=s.split(sep); for(int i=0;i<ss.length;i++){ arr.add(ss[i]); } return arr; } public ArrayList<Integer> splitInt(String s,String sep){ ArrayList<Integer> arr=new ArrayList<Integer>(); String[] ss=s.split(sep); for(int i=0;i<ss.length;i++){ arr.add(Integer.parseInt(ss[i])); } return arr; } public ArrayList<String> splitString(int index,String sep){ return splitString(data.get(index), sep); } public ArrayList<Integer> splitInt(int index,String sep){ return splitInt(data.get(index), sep); } public ArrayList<String> read(String filename) throws IOException{ ArrayList<String> arr=new ArrayList<String>(); BufferedReader br=null; br=new BufferedReader(new FileReader(filename)); String l=null; while((l=br.readLine())!=null){ arr.add(l); } br.close(); return arr; } public void write(String filename,ArrayList<String> data) throws IOException{ PrintWriter pw=new PrintWriter(filename); for(String s:data){ pw.println(s); } pw.close(); } } public class Answer3 { public static void main(String[] args){ Question a=new Recycle("C-large.in","rst.txt"); a.solve(); } }
A10568
A10187
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.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class B { public void solve( Scanner sc, PrintWriter pw ) { int tests = sc.nextInt( ); sc.nextLine( ); for ( int i = 0 ; i < tests; i++ ) { int googlers = sc.nextInt( ); int suprises = sc.nextInt( ); int minScore = sc.nextInt( ); int minimumNsFoundIn = (((3*minScore)-2) > 0 ) ? ((3*minScore)-2) : 0; int minimumSFoundIn = (((3*minScore)-4) > 0 ) ? ((3*minScore)-4) : 2; int out = 0; int[]scores = new int[googlers]; for ( int j = 0 ; j < googlers; j++ ) { scores[j] = sc.nextInt( ); } Arrays.sort( scores ); for ( int j = 0 ; j < scores.length; j++ ) { int score = scores[j]; if ( score >= minimumNsFoundIn ) { out++; } else if ( suprises > 0 && score >= minimumSFoundIn ) { out++; suprises--; } } pw.println( "Case #" + (i+1) + ": " + out ); pw.flush( ); } } public static void main ( String[] args ) throws IOException { Scanner sc = new Scanner(new FileReader("B-small-attempt0.in")); PrintWriter pw = new PrintWriter(new FileWriter("B-small-attempt0.out")); new B( ).solve( sc, pw ); pw.close( ); sc.close( ); } // public final static HashMap<Integer, String> NON_SUPRISING = new HashMap<Integer, String>( ); // public final static HashMap<Integer, String> SUPRISING = new HashMap<Integer, String>( ); // static { // //target = ( 3k-2 > 0 ) ? 3k-2 : 0; // //0 = // //0 = 0 // //1 = 1 // //2 = 4 // //3 = 7 // //4 = 10 // //5 = 13 // //6 = 16 // //7 = 19 // //8 = 22 // //9 = 25 // //10 = 28 // NON_SUPRISING.put( 0, "0 0 0" ); // NON_SUPRISING.put( 1, "0 0 1" ); // NON_SUPRISING.put( 2, "0 1 1" ); // NON_SUPRISING.put( 3, "1 1 1" ); // NON_SUPRISING.put( 4, "1 1 2" ); // NON_SUPRISING.put( 5, "1 2 2" ); // NON_SUPRISING.put( 6, "2 2 2" ); // NON_SUPRISING.put( 7, "2 2 3" ); // NON_SUPRISING.put( 8, "2 3 3" ); // NON_SUPRISING.put( 9, "3 3 3" ); // NON_SUPRISING.put( 10, "3 3 4" ); // NON_SUPRISING.put( 11, "3 4 4" ); // NON_SUPRISING.put( 12, "4 4 4" ); // NON_SUPRISING.put( 13, "4 4 5" ); // NON_SUPRISING.put( 14, "4 5 5" ); // NON_SUPRISING.put( 15, "5 5 5" ); // NON_SUPRISING.put( 16, "5 5 6" ); // NON_SUPRISING.put( 17, "5 6 6" ); // NON_SUPRISING.put( 18, "6 6 6" ); // NON_SUPRISING.put( 19, "6 6 7" ); // NON_SUPRISING.put( 20, "6 7 7" ); // NON_SUPRISING.put( 21, "7 7 7" ); // NON_SUPRISING.put( 22, "7 7 8" ); // NON_SUPRISING.put( 23, "7 8 8" ); // NON_SUPRISING.put( 24, "8 8 8" ); // NON_SUPRISING.put( 25, "8 8 9" ); // NON_SUPRISING.put( 26, "8 9 9" ); // NON_SUPRISING.put( 27, "9 9 9" ); // NON_SUPRISING.put( 28, "9 9 10" ); // NON_SUPRISING.put( 29, "9 10 10" ); // NON_SUPRISING.put( 30, "10 10 10" ); // // //target = // //target = (3k - 4) > 0 ? 3k - 4 : 2 // //0 = 2 // //1 = 2 // //2 = 2 // //3 = 5 // //4 = 8 // //5 = 11 // //6 = 14 // //7 = 17 // //8 = 20 // //9 = 23 // //10 = 26 // SUPRISING.put( 2, "0 0 2" ); // SUPRISING.put( 3, "0 1 2" ); // SUPRISING.put( 4, "0 2 2" ); // SUPRISING.put( 5, "1 1 3" ); // SUPRISING.put( 6, "1 2 3" ); // SUPRISING.put( 7, "1 3 3" ); // SUPRISING.put( 8, "2 2 4" ); // SUPRISING.put( 9, "2 3 4" ); // SUPRISING.put( 10, "2 4 4" ); // SUPRISING.put( 11, "3 3 5" ); // SUPRISING.put( 12, "3 4 5" ); // SUPRISING.put( 13, "3 5 5" ); // SUPRISING.put( 14, "4 4 6" ); // SUPRISING.put( 15, "4 5 6" ); // SUPRISING.put( 16, "4 6 6" ); // SUPRISING.put( 17, "5 5 7" ); // SUPRISING.put( 18, "5 6 7" ); // SUPRISING.put( 19, "5 7 7" ); // SUPRISING.put( 20, "6 6 8" ); // SUPRISING.put( 21, "6 7 8" ); // SUPRISING.put( 22, "6 8 8" ); // SUPRISING.put( 23, "7 7 9" ); // SUPRISING.put( 24, "7 8 9" ); // SUPRISING.put( 25, "7 9 9" ); // SUPRISING.put( 26, "8 8 10" ); // SUPRISING.put( 27, "8 9 10" ); // SUPRISING.put( 28, "8 10 10" ); // } }
B20006
B20909
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; } }
/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam.lib; public interface InputConverter<T> { boolean readLine(String data); T generateObject(); }
B10858
B12820
0
package be.mokarea.gcj.common; public abstract class TestCaseReader<T extends TestCase> { public abstract T nextCase() throws Exception; public abstract int getMaxCaseNumber(); }
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Scanner; public class C { static final char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; /** * @param args */ public static void main(String[] args) { Scanner sc = null; if (args != null && args.length > 0) { try { sc = new Scanner(new File(args[0])); if (args.length > 1) { System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(new File(args[1])), 128))); } } catch (FileNotFoundException e) { // e.printStackTrace(); sc = new Scanner(System.in); } } else { sc = new Scanner(System.in); } int T = Integer.valueOf(sc.nextLine()); for (int i = 0; i < T; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int answer = solve(A, B); System.out.printf("Case #%d: %d\n", i + 1, answer); } System.out.close(); } public static int solve(int A, int B) { int answer = 0; int seedNum = A; do { answer += hasRecycled(seedNum++, A, B); } while (seedNum < B); return answer; } public static int hasRecycled(long seedNum, long A, long B) { int count = 0; int ptr; char[] old_num_chars = String.valueOf(seedNum).toCharArray(); int length = old_num_chars.length; char[] moved_num_chars = new char[length]; List<Long> newNumList = new ArrayList<Long>(); for (int i = length - 1; i > 0; i--) { ptr = i; for (int j = 0; j < length; j++) { if (ptr == 0) { moved_num_chars[ptr] = old_num_chars[length - 1]; } else { moved_num_chars[ptr] = old_num_chars[ptr - 1]; } if (--ptr < 0) { ptr += length; } } long newNum = Long.valueOf(new String(moved_num_chars)); if ( seedNum < newNum && newNum <= B) { boolean isNew = true; for (Iterator<Long> it = newNumList.iterator(); it.hasNext();) { Long l = it.next(); if (l.equals(newNum)) { isNew = false; break; } } if (isNew) { newNumList.add(newNum); count++; } } old_num_chars = moved_num_chars.clone(); } return count; } }
A20934
A20432
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 qr; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class B { public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File("B-large.in")); int tcn = scanner.nextInt(); int tc = 1; while (tc <= tcn) { int n = scanner.nextInt(); int s = scanner.nextInt(); int p = scanner.nextInt(); // int[] base = new int[n]; int y = 0; for (int i = 0; i < n; i++) { int t = scanner.nextInt(); int base = t / 3; int mmm = t % 3; if (mmm != 0) { base++; } if (base >= p) { if (mmm == 0 && t >= 0) y++; if (mmm == 1 && t >= 1) y++; if (mmm == 2 && t >= 2) y++; } else if (s > 0) { if (base + 1 == p) { if (mmm == 0 && t >= 3) { y++; s--; } // if (mmm == 1 && t >= 4) { // y+=0; // s--; // } if (mmm == 2 && t >= 2) { y++; s--; } } } } System.out.printf("Case #%d: %d\n", tc, y); // base >= p -> ok // base -1 -> can be ok tc++; } } }
A11917
A11116
0
package com.silverduner.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; public class Dancing { public static void main(String[] args) throws Exception { File input = new File("B-small-attempt0.in"); BufferedReader in = new BufferedReader(new FileReader(input)); File output = new File("1.out"); BufferedWriter out = new BufferedWriter(new FileWriter(output)); // parse input int N = Integer.parseInt(in.readLine()); for(int i=0;i<N;i++) { String str = in.readLine(); out.write("Case #"+(i+1)+": "); System.out.println("-------"); String[] words = str.split(" "); int n = Integer.parseInt(words[0]); int suprise = Integer.parseInt(words[1]); int threshold = Integer.parseInt(words[2]); int[] scores = new int[n]; for(int j=0;j<n;j++) { scores[j] = Integer.parseInt(words[3+j]); } int count = 0; for(int score : scores) { int a,b,c; boolean find = false; boolean sfind = false; for(a = 10; a>=0 && !find; a--) { if(3*a-4>score) continue; for(b = a; b>=0 && b >=a-2 && !find; b--) { for(c = b; c>=0 && c >=b-2 && c >=a-2 && !find; c--) { System.out.println(a+","+b+","+c); if(a+b+c==score) { if(a >= threshold) { if(a-c <= 1){ count++; find = true; System.out.println("find!"); } else if(a-c == 2){ sfind = true; System.out.println("suprise!"); } } } } } } if(!find && sfind && suprise > 0) { count++; suprise --; } } int maxCount = count; out.write(maxCount+"\n"); } out.flush(); out.close(); in.close(); } }
package com.googlecode.codejam.model; public final class Constants { public static final String PARENT_DIRECTORY = "/opt/workspaces/programming-contests/codejam-contest/src/main/resources/"; private Constants() {/* constants */} }
B10702
B11394
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; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Problem3; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; /** * * @author Mohammed */ public class Pairs { static int in[][], out[]; static int found; private static void readFile(String fileName) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader(fileName)); String line; int x = Integer.parseInt(br.readLine()); in = new int[x][2]; out = new int[x]; for (int i = 0; i < x; i++) { line = br.readLine(); StringTokenizer st = new StringTokenizer(line); int j = 0; while (st.hasMoreTokens()) { in[i][j++] = Integer.parseInt(st.nextToken()); } } } public static void main(String[] args) throws FileNotFoundException, IOException { readFile("data"); manipulate(); writeOutput("output.txt"); } private static void manipulate() { for (int i = 0; i < in.length;i++){ int start = in[i][0]; int end = in[i][1]; found = 0; for (int j = start; j<=end; j++){ String numString = j+""; int numValue = j; // System.out.println(numString); for(int k = 1; k < numString.length(); k++){ if (((char)(numString.charAt(k))) == '0') continue; String firstString = numString.substring(0,k); String secondString = numString.substring(k,numString.length()); String resultString = secondString + firstString; int num = Integer.parseInt(resultString); System.out.println(i + " " +resultString); if ((num>numValue)&&(num>=start)&&(num<=end)){ found++; System.out.println("hello"); } } } out[i] = found; } } private static void writeOutput(String string) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(string)); for (int i = 0; i < out.length; i++) { bw.write("Case #" + (i + 1) + ": " + out[i]); if (i != out.length - 1) { bw.write("\r\n"); } } bw.close(); } }
A22992
A21654
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 }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package dancinggooglers; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Scanner; import java.util.regex.Pattern; /** * * @author nasir */ public class Main { private String[] inputArray; private int surprising; private int P; private int maximumGooglers = 0; private Queue URLQueue = new LinkedList(); public Main() { readConsole(); parseInput(); } /** * @param args the command line arguments */ public static void main(String[] args) { Main m = new Main(); } public void readConsole() { boolean first = true; int testCases = 0; int loop = 0; int index = 0; Scanner scanner = new Scanner(System.in); while (loop <= testCases) { String str = scanner.nextLine(); if (first) { first = false; testCases = Integer.parseInt(str); inputArray = new String[testCases]; } else { inputArray[index++] = str; } loop++; } } public void parseInput() { String split = "[\\s]"; Pattern p = Pattern.compile(split); int k = 1; for (String str : inputArray) { String[] tokens = p.split(str); surprising = Integer.parseInt(tokens[1]); P = Integer.parseInt(tokens[2]); List<Integer> googlerList = new LinkedList<Integer>(); for(int i=3; i<tokens.length; i++){ googlerList.add(Integer.parseInt(tokens[i])); } Collections.sort(googlerList); System.out.println("sorted list "+googlerList); maximumGooglers = 0; for(int index = googlerList.size()-1; index>=0; index--){ Integer integer = googlerList.get(index); Integer avg = integer/3; Integer j1 = avg; Integer j2 = avg; Integer j3 = avg; Integer remainder = integer%3; if(remainder == 2){ j1+=1; j2+=1; remainder = 0; } if(remainder == 1){ j1+=1; } if(j1>= P || j2>=P || j3>=P){ System.out.println("J1 "+j1+" J2 "+j2+" J3 "+j3); maximumGooglers++; continue; } if(surprising>0){ if(j1==j2 && j2>0 && j1+1>=P){ surprising--; maximumGooglers++; } } } System.out.println("Case #"+k+": "+maximumGooglers); k++; } } public class dataStructure{ int total; int judge1; int judge2; int judge3; public int getJudge1() { return judge1; } public void setJudge1(int judge1) { this.judge1 = judge1; } public int getJudge2() { return judge2; } public void setJudge2(int judge2) { this.judge2 = judge2; } public int getJudge3() { return judge3; } public void setJudge3(int judge3) { this.judge3 = judge3; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } } }
B10231
B13074
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 sun.rmi.runtime.NewThreadAction; import java.io.*; import java.util.*; /** * Created by IntelliJ IDEA. * User: Veniversum * Date: 4/15/12 * Time: 2:26 AM */ public class Q3 { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("in.txt"))); Scanner scanner = new Scanner(new FileInputStream("in.txt")); int cases = scanner.nextInt(); scanner.nextLine(); String output=""; for (int i= 0;i<cases;i++){ HashSet<String> results = new HashSet<String>(); Scanner sc = new Scanner(scanner.nextLine()); int A = sc.nextInt(); int B = sc.nextInt(); int n; int m; for (int j = A; j <= B;j++) { n = j; m = j; String str = ("" + m); for (int k = 0; k < ("" + m).length();k++) { if (A <= n && n < m && m <= B) { results.add(m + "," + n); } str = str.concat("" + str.charAt(0)); //adds first digit to end str = str.substring(1); //remove first digit m = Integer.parseInt(str); } } output += "Case #" + (i+1) + ": " + results.size() + "\n"; PrintWriter outp = new PrintWriter(new FileOutputStream("out.txt")); outp.print(output); outp.close(); } System.out.print(output); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
A22191
A21829
0
package com.example; import java.io.IOException; import java.util.List; public class ProblemB { enum Result { INSUFFICIENT, SUFFICIENT, SUFFICIENT_WHEN_SURPRISING } public static void main(String[] a) throws IOException { List<String> lines = FileUtil.getLines("/B-large.in"); int cases = Integer.valueOf(lines.get(0)); for(int c=0; c<cases; c++) { String[] tokens = lines.get(c+1).split(" "); int n = Integer.valueOf(tokens[0]); // N = number of Googlers int s = Integer.valueOf(tokens[1]); // S = number of surprising triplets int p = Integer.valueOf(tokens[2]); // P = __at least__ a score of P int sumSufficient = 0; int sumSufficientSurprising = 0; for(int i=0; i<n; i++) { int points = Integer.valueOf(tokens[3+i]); switch(test(points, p)) { case SUFFICIENT: sumSufficient++; break; case SUFFICIENT_WHEN_SURPRISING: sumSufficientSurprising++; break; } // uSystem.out.println("points "+ points +" ? "+ p +" => "+ result); } System.out.println("Case #"+ (c+1) +": "+ (sumSufficient + Math.min(s, sumSufficientSurprising))); // System.out.println(); // System.out.println("N="+ n +", S="+ s +", P="+ p); // System.out.println(); } } private static Result test(int n, int p) { int fac = n / 3; int rem = n % 3; if(rem == 0) { // int triplet0[] = { fac, fac, fac }; // print(n, triplet0); if(fac >= p) { return Result.SUFFICIENT; } if(fac > 0 && fac < 10) { if(fac+1 >= p) { return Result.SUFFICIENT_WHEN_SURPRISING; } // int triplet1[] = { fac+1, fac, fac-1 }; // surprising // print(n, triplet1); } } else if(rem == 1) { // int triplet0[] = { fac+1, fac, fac }; // print(n, triplet0); if(fac+1 >= p) { return Result.SUFFICIENT; } // if(fac > 0 && fac < 10) { // int triplet1[] = { fac+1, fac+1, fac-1 }; // print(n, triplet1); // } } else if(rem == 2) { // int triplet0[] = { fac+1, fac+1, fac }; // print(n, triplet0); if(fac+1 >= p) { return Result.SUFFICIENT; } if(fac < 9) { // int triplet1[] = { fac+2, fac, fac }; // surprising // print(n, triplet1); if(fac+2 >= p) { return Result.SUFFICIENT_WHEN_SURPRISING; } } } else { throw new RuntimeException("error"); } return Result.INSUFFICIENT; // System.out.println(); // System.out.println(n +" => "+ div3 +" ("+ rem +")"); } // private static void print(int n, int[] triplet) { // System.out.println("n="+ n +" ("+ (n/3) +","+ (n%3) +") => ["+ triplet[0] +","+ triplet[1] +","+ triplet[2] +"]" + (triplet[0]-triplet[2] > 1 ? " *" : "")); // } }
import java.util.*; import java.io.*; public class B { public static void main (String [] args) { try { BufferedReader br = new BufferedReader(new FileReader("B-large-0.in")); PrintWriter pw = new PrintWriter("B-large-0.out"); int inputNo; inputNo = Integer.parseInt(br.readLine()); for (int i = 1; i <= inputNo; i++) { // get one input here String in = br.readLine(); pw.println("Case #" + i + ": " + processInput(in)); } br.close(); pw.close(); } catch (Exception e) { e.printStackTrace(); } } public static int processInput(String in) { int result = 0; Scanner sc = new Scanner(in); int gNo = Integer.parseInt(sc.next()); int sup = Integer.parseInt(sc.next()); int max = Integer.parseInt(sc.next()); int supNo = 0; int goodNo = 0; for (int i = 0; i < gNo; i++) { int total = Integer.parseInt(sc.next()); int can = canMax(max, total); if (can == 1) supNo++; if (can == 0) goodNo++; } if (supNo > sup) result = goodNo + sup; else result = goodNo + supNo; return result; } public static int canMax(int max, int total) { int av = total/3; int r = total%3; if (r == 0) { if (av >= max) return 0; if (av+1 >= max && av+1 <= 10 && av-1 >= 0) return 1; return -1; } if (r == 1) { if (av+1 >= max && av + 1 <= 10) return 0; return -1; } if (r == 2) { if (av+1 >= max && av+1 <= 10) return 0; if (av+2 >=max && av+2 <= 10) return 1; return -1; } return -1; } }
B12762
B11916
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.FileInputStream; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class RecycleNumber { /** * @param args */ public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(".in"))); int num =0; String line = null; line = br.readLine(); int i=0; num = Integer.parseInt(line); while(num-->0){ int result = 0; line = br.readLine(); i++; String[] nums = line.split(" "); int min = Integer.parseInt(nums[0]); int max = Integer.parseInt(nums[1]); for(int t=min;t<=max;t++){ result += countRecyles(t,min,max); } System.out.println("Case #"+i+": "+result/2); } br.close(); } public static int countRecyles(int num,int min,int max){ int count = 0; Set<Integer> result = getNums(num); for(int i:result){ if(i>=min&&i<=max){ count++; // System.out.println(num+","+i); } } return count; } public static Set<Integer> getNums(int num){ Set<Integer> list = new HashSet<Integer>(); StringBuilder sb = new StringBuilder(num+""); for(int i=0;i<sb.length();i++){ char last = sb.charAt(sb.length()-1); sb.deleteCharAt(sb.length()-1); sb.insert(0, last); if(last!='0'){ int tmp = Integer.parseInt(sb.toString()); if(tmp != num) list.add(tmp); } } return list; } }
B12570
B12507
0
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; class RecycledNumbers{ int getcount(int small,int large){ int count = 0; for(int currnum = small; currnum < large; currnum++){ int permut = currnum; int no_of_digits = 0; while(permut > 0){ permut = permut/10; no_of_digits++; } int lastDigit = currnum % 10; permut = currnum / 10; permut = permut + lastDigit * (int)Math.pow(10, no_of_digits-1); while(permut != currnum){ if(permut >= currnum && permut <= large){ count++; } lastDigit = permut % 10; permut = permut / 10; permut = permut + lastDigit * (int)Math.pow(10, no_of_digits-1); } } return count; } public static void main(String args[]){ RecycledNumbers d = new RecycledNumbers(); int no_of_cases = 0; String input = ""; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ no_of_cases = Integer.parseInt(br.readLine()); } catch(Exception e){ System.out.println("First line is not a number"); } for(int i=1; i <= no_of_cases;i++){ try{ input = br.readLine(); } catch(Exception e){ System.out.println("Number of test cases different from the number mentioned in first line"); } System.out.print("Case #" +i+": "); StringTokenizer t = new StringTokenizer(input); int small=0,large=0; if(t.hasMoreTokens()){ small = Integer.parseInt(t.nextToken()); } if(t.hasMoreTokens()){ large = Integer.parseInt(t.nextToken()); } System.out.println(d.getcount(small,large)); } } }
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Chung Lee */ public class RecycleNumber { public static void Main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File(args[0])); PrintWriter writer = new PrintWriter(args[1]); int noCase = scanner.nextInt(); for (int i = 0; i < noCase; i++) { int A = scanner.nextInt(); int B = scanner.nextInt(); int noRecyclePair = 0; for (int j = A; j <= B; j++) { noRecyclePair += getNoRecyclePair(j, A, B); } noRecyclePair /= 2; System.out.print(String.format("Case #%d: %d", i + 1, noRecyclePair)); writer.print(String.format("Case #%d: %d", i + 1, noRecyclePair)); if (i != noCase - 1) { System.out.println(); writer.println(); } } writer.close(); } public static int getNoRecyclePair(int num, int A, int B) { int temp = num; int digits = 0; while (temp != 0) { temp /= 10; digits++; } int noRecyclePair = 0; for (int i = 1; i <= digits; i++) { int recycleNum = (int) ((num % Math.pow(10, i)) * Math.pow(10, digits - i) + (num / Math.pow(10, i))); if (recycleNum != num && recycleNum >= A && recycleNum <= B) { noRecyclePair++; } } return noRecyclePair; } }
B20566
B20477
0
import java.util.Scanner; import java.io.*; import java.lang.Math; public class C{ public static int recycle(String str){ String[] numbers = str.split(" "); int min = Integer.parseInt(numbers[0]); int max = Integer.parseInt(numbers[1]); int ret = 0; for(int i = min; i < max; i++){ String num = i + ""; int len = num.length(); int k = i; for(int j = 1; j < len; j++){ k = (k/10) + (int)java.lang.Math.pow(10.0,(double)(len-1))*(k%10); if (k > i && k <= max) ret++; else if(k == i) break; } } return ret; } public static void main(String[] args){ Scanner sc = null; String next; int out; try{ sc = new Scanner(new File("C-large.in")); int cases = Integer.parseInt(sc.nextLine()); int current = 0; FileWriter fs = new FileWriter("output.txt"); BufferedWriter buff = new BufferedWriter(fs); while(current < cases){ next = sc.nextLine(); current++; out = recycle(next); buff.write("Case #" + current + ": " + out + "\n"); } buff.close(); } catch(Exception ex){} } }
/* Ana: - For a given number of digit, e.g. 5, there are n-1 number will be its recycle number, i.e. 5-1=4 distinct paris, as follows: - 12345 => - 51234 - 45123 - 34512 - 23451 - Since leading 0 is not count, 100, 001 are not pairs, so any number if the swap number start with 0 will not have pairs. - Divide the number into 2 parts, left, right by a mid point. - Then compare the left right to the range-left, range-right, if within that range that marks as pairs - There must be another number which is this number pairs - Same Digit - The number of pairs within a range = Num of itm in range * (Num of Digit - 1), e.g. 1111~2222 => (2222-1111+1) * (4-1) = 3336. - Since n<m - All Digit same cannot be count: 1111, 2222... so 3336 - 2 = 3334 - if 4321 should not map 3214. 2 pairs is recycle if and only if al = br && ar=bl && al within Al,Bl ar within Ar,Br therefore, all number that left witin A,B and right within A,B will be recycle number With each mid, you may count the number of itm for left, and number of itm for right */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.Scanner; import java.util.Arrays; /** * * @author CuteCoke */ public class C3 { //final String TASK_NAME = "C-small-attempt0"; final String TASK_NAME = "C-large"; //final String TASK_NAME = "sample"; final String IN_FILE = TASK_NAME+".in"; final String OUT_FILE = TASK_NAME+".out"; private boolean contains(int[] arr, int tar){ for(int a: arr){ if (a==tar) return true; } return false; } public int solve(int A, int B){ int res = 0; String s=A+""; int len =s.length(); int[] al = new int[len]; int[] ar = new int[len]; int[] bl = new int[len]; int[] br = new int[len]; for(int i=1; i<len; i++){ int tn = (int)Math.pow(10,i); al[i] = A / tn; ar[i] = A % tn; bl[i] = B / tn; br[i] = B % tn; } for(int i=A; i<=B; i++){ String sTmp = i+""; if ("".equals(sTmp.replaceAll(sTmp.charAt(0)+"",""))) continue; int[] used = new int[len]; int usedcnt = 0; for(int j=1; j<len; j++){ int tn = (int)Math.pow(10,j); int l = i / tn; int r = i % tn; int k = len-j; if (l==r) continue; if ((r+"").length() != j) continue; if ((l+"").length() != (len-j)) continue; int tn2 = (int)Math.pow(10,len-j); int nw = r*tn2+l; if (i>=nw) continue; if (r>al[k] && r<bl[k]){ if (!contains(used, nw)){ res++; used[usedcnt++]=nw; //System.out.println("j="+j+"("+l+","+r+"); add1("+i+") nw="+nw); } }else{ if (nw>=A && nw<=B){ if (!contains(used, nw)){ res++; used[usedcnt++]=nw; //System.out.println("j="+j+"("+l+","+r+"); add2("+i+") nw="+nw); } } } } } return res; } public void doMain() throws Exception{ try{ Scanner sc1 = null; BufferedReader br = new BufferedReader(new FileReader(IN_FILE)); BufferedWriter bw = new BufferedWriter(new FileWriter(OUT_FILE)); int T = Integer.parseInt(br.readLine()); for (int a=0; a<T; a++){ bw.write("Case #"+(a+1)+": "); sc1 = new Scanner(br.readLine()); int A = sc1.nextInt(); int B = sc1.nextInt(); int ans = solve(A, B); bw.write(ans+"\n"); } br.close(); bw.close(); }catch(FileNotFoundException e){ System.err.println("In File: "+(new File(IN_FILE)).getAbsolutePath()); System.err.println("Out File: "+(new File(OUT_FILE)).getAbsolutePath()); e.printStackTrace(System.err); } } public static void main(String[] s) throws Exception{ try{ C3 test = new C3(); test.doMain(); }catch(Exception e){ e.printStackTrace(System.err); } } }
A20490
A20472
0
/** * */ package hu.herba.codejam; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; /** * Base functionality, helper functions for CodeJam problem solver utilities. * * @author csorbazoli */ public abstract class AbstractCodeJamBase { private static final String EXT_OUT = ".out"; protected static final int STREAM_TYPE = 0; protected static final int FILE_TYPE = 1; protected static final int READER_TYPE = 2; private static final String DEFAULT_INPUT = "test_input"; private static final String DEFAULT_OUTPUT = "test_output"; private final File inputFolder; private final File outputFolder; public AbstractCodeJamBase(String[] args, int type) { String inputFolderName = AbstractCodeJamBase.DEFAULT_INPUT; String outputFolderName = AbstractCodeJamBase.DEFAULT_OUTPUT; if (args.length > 0) { inputFolderName = args[0]; } this.inputFolder = new File(inputFolderName); if (!this.inputFolder.exists()) { this.showUsage("Input folder '" + this.inputFolder.getAbsolutePath() + "' not exists!"); } if (args.length > 1) { outputFolderName = args[1]; } this.outputFolder = new File(outputFolderName); if (this.outputFolder.exists() && !this.outputFolder.canWrite()) { this.showUsage("Output folder '" + this.outputFolder.getAbsolutePath() + "' not writeable!"); } else if (!this.outputFolder.exists() && !this.outputFolder.mkdirs()) { this.showUsage("Could not create output folder '" + this.outputFolder.getAbsolutePath() + "'!"); } File[] inputFiles = this.inputFolder.listFiles(); for (File inputFile : inputFiles) { this.processInputFile(inputFile, type); } } /** * @return the inputFolder */ public File getInputFolder() { return this.inputFolder; } /** * @return the outputFolder */ public File getOutputFolder() { return this.outputFolder; } /** * @param input * input reader * @param output * output writer * @throws IOException * in case input or output fails * @throws IllegalArgumentException * in case the given input is invalid */ @SuppressWarnings("unused") protected void process(BufferedReader reader, PrintWriter pw) throws IOException, IllegalArgumentException { System.out.println("NEED TO IMPLEMENT (reader/writer)!!!"); System.exit(-2); } /** * @param input * input file * @param output * output file (will be overwritten) * @throws IOException * in case input or output fails * @throws IllegalArgumentException * in case the given input is invalid */ protected void process(File input, File output) throws IOException, IllegalArgumentException { System.out.println("NEED TO IMPLEMENT (file/file)!!!"); System.exit(-2); } /** * @param input * input stream * @param output * output stream * @throws IOException * in case input or output fails * @throws IllegalArgumentException * in case the given input is invalid */ protected void process(InputStream input, OutputStream output) throws IOException, IllegalArgumentException { System.out.println("NEED TO IMPLEMENT (stream/stream)!!!"); System.exit(-2); } /** * @param type * @param input * @param output */ private void processInputFile(File input, int type) { long starttime = System.currentTimeMillis(); System.out.println("Processing '" + input.getAbsolutePath() + "'..."); File output = new File(this.outputFolder, input.getName() + AbstractCodeJamBase.EXT_OUT); if (type == AbstractCodeJamBase.STREAM_TYPE) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(input); os = new FileOutputStream(output); this.process(is, os); } catch (FileNotFoundException e) { this.showUsage("FileNotFound: " + e.getLocalizedMessage()); } catch (IllegalArgumentException excIA) { this.showUsage(excIA.getLocalizedMessage()); } catch (Exception exc) { System.out.println("Program failed: " + exc.getLocalizedMessage()); exc.printStackTrace(System.out); } finally { if (is != null) { try { is.close(); } catch (IOException e) { System.out.println("Failed to close input: " + e.getLocalizedMessage()); } } if (os != null) { try { os.close(); } catch (IOException e) { System.out.println("Failed to close output: " + e.getLocalizedMessage()); } } } } else if (type == AbstractCodeJamBase.READER_TYPE) { BufferedReader reader = null; PrintWriter pw = null; try { reader = new BufferedReader(new FileReader(input)); pw = new PrintWriter(output); this.process(reader, pw); } catch (FileNotFoundException e) { this.showUsage("FileNotFound: " + e.getLocalizedMessage()); } catch (IllegalArgumentException excIA) { this.showUsage(excIA.getLocalizedMessage()); } catch (Exception exc) { System.out.println("Program failed: " + exc.getLocalizedMessage()); exc.printStackTrace(System.out); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { System.out.println("Failed to close input: " + e.getLocalizedMessage()); } } if (pw != null) { pw.close(); } } } else if (type == AbstractCodeJamBase.FILE_TYPE) { try { this.process(input, output); } catch (IllegalArgumentException excIA) { this.showUsage(excIA.getLocalizedMessage()); } catch (Exception exc) { System.out.println("Program failed: " + exc.getLocalizedMessage()); exc.printStackTrace(System.out); } } else { this.showUsage("Unknown type given: " + type + " (accepted values: 0,1)"); } System.out.println(" READY (" + (System.currentTimeMillis() - starttime) + " ms)"); } /** * Read a single number from input * * @param reader * @param purpose * What is the purpose of given data * @return * @throws IOException * @throws IllegalArgumentException */ protected int readInt(BufferedReader reader, String purpose) throws IOException, IllegalArgumentException { int ret = 0; String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException("Invalid input: line is empty, it should be an integer (" + purpose + ")!"); } try { ret = Integer.parseInt(line); } catch (NumberFormatException excNF) { throw new IllegalArgumentException("Invalid input: the first line '" + line + "' should be an integer (" + purpose + ")!"); } return ret; } /** * Read array of integers * * @param reader * @param purpose * @return */ protected int[] readIntArray(BufferedReader reader, String purpose) throws IOException { int[] ret = null; String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException("Invalid input: line is empty, it should be an integer list (" + purpose + ")!"); } String[] strArr = line.split("\\s"); int len = strArr.length; ret = new int[len]; for (int i = 0; i < len; i++) { try { ret[i] = Integer.parseInt(strArr[i]); } catch (NumberFormatException excNF) { throw new IllegalArgumentException("Invalid input: line '" + line + "' should be an integer list (" + purpose + ")!"); } } return ret; } /** * Read array of strings * * @param reader * @param purpose * @return */ protected String[] readStringArray(BufferedReader reader, String purpose) throws IOException { String[] ret = null; String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException("Invalid input: line is empty, it should be a string list (" + purpose + ")!"); } ret = line.split("\\s"); return ret == null ? new String[0] : ret; } /** * Basic usage pattern. Can be overwritten by current implementation * * @param message * Short message, describing the problem with given program * arguments */ protected void showUsage(String message) { if (message != null) { System.out.println(message); } System.out.println("Usage:"); System.out.println("\t" + this.getClass().getName() + " program"); System.out.println("\tArguments:"); System.out.println("\t\t<input folder>:\tpath of input folder (default: " + AbstractCodeJamBase.DEFAULT_INPUT + ")."); System.out.println("\t\t \tAll files will be processed in the folder"); System.out.println("\t\t<output folder>:\tpath of output folder (default: " + AbstractCodeJamBase.DEFAULT_OUTPUT + ")"); System.out.println("\t\t \tOutput file name will be the same as input"); System.out.println("\t\t \tinput with extension '.out'"); System.exit(-1); } }
import java.io.File; import java.io.IOException; import java.util.Scanner; public class QuestionB { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { File fileread = new File("B-large.in.txt"); File filewrite = new File(QuestionB.class.getName() + "output4Big.txt"); GCIFileReader fr = new GCIFileReader(fileread); GCIFileWriter fw = new GCIFileWriter(filewrite); GCIResult res = new GCIResult(); String s = fr.getLine(); int n = Integer.parseInt(s); for (int i=0; i < n ; i++) { String l = fr.getLine(); Scanner sc = new Scanner(l); int con = sc.nextInt(); int spe = sc.nextInt(); int p = sc.nextInt(); int countOk = 0; int countOKSpe = 0; for (int j = 0 ; j < con ; j++) { int acon = sc.nextInt(); if (acon >= p) { if ((acon / 3.0) >= (p)) { countOk++; continue; } if (Double.compare((acon / 3.0),(Math.abs(p - 0.7))) >= 0) { countOk++; continue; } if (Double.compare((acon / 3.0),(Math.abs(p - 2 + 0.5 ))) >=0 ) { countOKSpe++; continue; } } } int finalOkSpe = countOKSpe > spe ? spe : countOKSpe; int tres = countOk + finalOkSpe; res.addCase(String.valueOf(tres)); } fw.writeResult(res); } }
B10858
B11026
0
package be.mokarea.gcj.common; public abstract class TestCaseReader<T extends TestCase> { public abstract T nextCase() throws Exception; public abstract int getMaxCaseNumber(); }
package org.moriraaca.codejam; public enum OutputDestination { STDOUT, FILE; }
B10485
B12727
0
import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import java.io.File; import java.io.IOException; import java.io.FileWriter; import java.io.BufferedWriter; public class Recycle { public static void main(String[] args) { /* Set<Integer> perms = getPermutations(123456); for(Integer i: perms) System.out.println(i);*/ try { Scanner s = new Scanner(new File("recycle.in")); BufferedWriter w = new BufferedWriter(new FileWriter(new File("recycle.out"))); int numCases = s.nextInt(); s.nextLine(); for(int n = 1;n <= numCases; n++) { int A = s.nextInt(); int B = s.nextInt(); int count = 0; for(int k = A; k <= B; k++) { count += getNumPairs(k, B); } w.write("Case #" + n + ": " + count + "\n"); } w.flush(); w.close(); } catch (IOException e) { e.printStackTrace(); } } public static int getNumPairs(int n, int B) { Set<Integer> possibles = getPermutations(n); int count = 0; for(Integer i : possibles) if(i > n && i <= B) count++; return count; } public static Set<Integer> getPermutations(int n) { Set<Integer> perms = new TreeSet<Integer>(); char[] digits = String.valueOf(n).toCharArray(); for(int firstPos = 1; firstPos < digits.length; firstPos++) { String toBuild = ""; for(int k = 0; k < digits.length; k++) toBuild += digits[(firstPos + k) % digits.length]; perms.add(Integer.parseInt(toBuild)); } return perms; } }
package com.develog; import java.io.IOException; public class Runner { public static void main(String args[]) throws IOException{ new C(); } }
B21968
B21866
0
import java.util.*; import java.io.*; public class recycled_numbers { public static void main(String[]a) throws Exception{ Scanner f = new Scanner(new File(a[0])); int result=0; int A,B; String n,m; HashSet<String> s=new HashSet<String>(); int T=f.nextInt(); //T total case count for (int t=1; t<=T;t++){//for each case t s.clear(); result=0; //reset A=f.nextInt();B=f.nextInt(); //get values for next case if (A==B)result=0;//remove case not meeting problem limits else{ for(int i=A;i<=B;i++){//for each int in range n=Integer.toString(i); m=new String(n); //System.out.println(n); for (int j=1;j<n.length();j++){//move each digit to the front & test m = m.substring(m.length()-1)+m.substring(0,m.length()-1); if(m.matches("^0+[\\d]+")!=true && Integer.parseInt(m)<=B && Integer.parseInt(n)<Integer.parseInt(m)){ s.add(new String(n+","+m)); //result++; //System.out.println(" matched: "+m); } } } result = s.size(); } //display output System.out.println("Case #" + t + ": " + result); } } }
package jam2012.numbers; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import commons.FileUtilities; public class Recycle { public static void main(String[] args) throws IOException { List<String> strings = FileUtilities.readFile(new File("C-large.in")); int number = Integer.parseInt(strings.get(0)); List<String> result = new LinkedList<String>(); for (int i = 1; i <= number; i++) { Scanner s = new Scanner(strings.get(i)); int lower = s.nextInt(); int upper = s.nextInt(); int[] lowerArray = createArray(lower); int[] upperArray = createArray(upper); int tresult = 0; for (int j = lower; j <= upper; j++) { int[] test = createArray(j); LinkedList<Integer> poss = new LinkedList<Integer>(); for (int k = 1; k < test.length; k++) { if (isBigger(test, k, lowerArray, 0) == 1 && isBigger(test, k, upperArray, 0) <= 0 && isBigger(test, k, test, 0) == 1) { boolean dup = false; for (int l : poss) { if (isBigger(test, k, test, l) == 0) { dup = true; } } if (!dup) { tresult++; poss.add(k); } } } } result.add(Integer.toString(tresult)); } FileUtilities.writeFile(result, new File("C-large.out")); } private static int isBigger(int[] a, int aStart, int[] b, int bStart) { for (int i = 0; i < a.length; i++) { int aPtr = a[(i+aStart)%a.length]; int bPtr = b[(i+bStart)%b.length]; if (aPtr > bPtr) { return 1; } else if (aPtr < bPtr) { return -1; } } return 0; } private static int[] createArray(int i) { String iS = Integer.toString(i); int[] iA = new int[iS.length()]; for (int j = 0; j < iA.length; j++) { iA[j] = Character.getNumericValue(iS.charAt(j)); } return iA; } }
B20006
B22209
0
import java.io.*; import java.math.BigInteger; import java.util.*; import org.jfree.data.function.PowerFunction2D; public class r2a { Map numMap = new HashMap(); int output = 0; /** * @param args */ public static void main(String[] args) { r2a mk = new r2a(); try { FileInputStream fstream = new FileInputStream("d:/cjinput.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String str; int i = 0; while ((str = br.readLine()) != null) { int begin=0,end = 0; i++; if (i == 1) continue; mk.numMap = new HashMap(); StringTokenizer strTok = new StringTokenizer(str, " "); while (strTok.hasMoreTokens()) { begin = Integer.parseInt(((String) strTok.nextToken())); end = Integer.parseInt(((String) strTok.nextToken())); } mk.evaluate(i, begin, end); } in.close(); } catch (Exception e) { System.err.println(e); } } private void evaluate(int rowNum, int begin, int end) { output=0; for (int i = begin; i<= end; i++) { if(numMap.containsKey(Integer.valueOf(i))) continue; List l = getPairElems(i); if (l.size() > 0) { Iterator itr = l.iterator(); int ctr = 0; ArrayList tempList = new ArrayList(); while (itr.hasNext()) { int next = ((Integer)itr.next()).intValue(); if (next <= end && next > i) { numMap.put(Integer.valueOf(next), i); tempList.add(next); ctr++; } } ctr = getCounter(ctr+1,2); /* if (tempList.size() > 0 || ctr > 0) System.out.println("DD: " + i + ": " + tempList +" ; ctr = " + ctr);*/ output = output + ctr; } } String outputStr = "Case #" + (rowNum -1) + ": " + output; System.out.println(outputStr); } private int getCounter(int n, int r) { int ret = 1; int nfactorial =1; for (int i = 2; i<=n; i++) { nfactorial = i*nfactorial; } int nrfact =1; for (int i = 2; i<=n-r; i++) { nrfact = i*nrfact; } return nfactorial/(2*nrfact); } private ArrayList getPairElems(int num) { ArrayList retList = new ArrayList(); int temp = num; if (num/10 == 0) return retList; String str = String.valueOf(num); int arr[] = new int[str.length()]; int x = str.length(); while (temp/10 > 0) { arr[x-1] = temp%10; temp=temp/10; x--; } arr[0]=temp; int size = arr.length; for (int pos = size -1; pos >0; pos--) { if(arr[pos] == 0) continue; int pairNum = 0; int multiplier =1; for (int c=0; c < size-1; c++) { multiplier = multiplier*10; } pairNum = pairNum + (arr[pos]*multiplier); for(int ctr = pos+1, i=1; i < size; i++,ctr++) { if (ctr == size) ctr=0; if (multiplier!=1) multiplier=multiplier/10; pairNum = pairNum + (arr[ctr]*multiplier); } if (pairNum != num) retList.add(Integer.valueOf(pairNum)); } return retList; } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import junit.framework.TestCase; public class RecycledNumbers extends TestCase { public void testMain() throws IOException { RecycledNumbers.main(null); } public static void main(String[] args) throws IOException { setStandardIO(); setFileIO("recyclednumbers"); readLine(); int T = nextInt(); for (int t = 1; t <= T; ++t) { readLine(); int A = nextInt(); int B = nextInt(); int N = String.valueOf(A).length() - 1; if (N == 0) println("Case #" + t + ": " + 0); else { Set<Pair> pairs = new TreeSet<Pair>(); for (int i = A; i <= B; ++i) { for (int j = 0; j < N; ++j) { String x = String.valueOf(i); String y = x.substring(N - j) + x.substring(0, N - j); if (y.charAt(0) == '0') continue; int X = Integer.valueOf(x); int Y = Integer.valueOf(y); if (X == Y) continue; if (Y < A) continue; if (Y > B) continue; if (X < Y) pairs.add(new Pair(X, Y)); else pairs.add(new Pair(Y, X)); } } println("Case #" + t + ": " + pairs.size()); } } flush(); } //~ ---------------------------------------------------------------------------------------------------------------- //~ - Auxiliary code ----------------------------------------------------------------------------------------------- //~ ---------------------------------------------------------------------------------------------------------------- static BufferedReader in; static PrintWriter out; static StringTokenizer st; private static void setStandardIO() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); } private static void setFileIO(String fileName) throws FileNotFoundException, IOException { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(new BufferedWriter(new FileWriter(fileName + ".out"))); } public static void readLine() throws IOException { st = new StringTokenizer(in.readLine()); } public static int nextInt() { return Integer.parseInt(st.nextToken()); } public static long nextLong() { return Long.parseLong(st.nextToken()); } public static String nextString() { return st.nextToken(); } public static List<String> nextStrings() { List<String> strings = new ArrayList<String>(); while (st.hasMoreTokens()) strings.add(st.nextToken()); return strings; } public static void flush() { out.flush(); } public static void println(Object object) { out.println(object); } public static void print(Object object) { out.print(object); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static class Pair implements Comparable<Pair>{ public int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Pair [x=" + x + ", y=" + y + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (x ^ (x >>> 32)); result = prime * result + (int) (y ^ (y >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } @Override public int compareTo(Pair o) { if (x < o.x) return -1; if (x > o.x) return 1; return y - o.y; } } }
B21752
B21633
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(); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.*; import java.util.ArrayList; import java.util.Scanner; /** * * @author Ka */ public class Recy { private File file; private int aantal; private ArrayList<String> cases; private ArrayList<Integer> max; public Recy(File f) throws FileNotFoundException { file = f; Scanner scanner = new Scanner(new FileReader(file)); aantal = scanner.nextInt(); cases = new ArrayList<String>(aantal); max = new ArrayList<Integer>(aantal); scanner.nextLine(); for(int i =0; i < aantal ; i++) { String s = scanner.nextLine(); cases.add(s); } System.out.println(cases); } public void scores() { for(String s : cases) { int counter = 0; ArrayList<Integer> nb = new ArrayList<Integer>(); String sb = ""; while(counter < s.length()) { if(s.charAt(counter)!= ' ') { sb = sb + s.charAt(counter); } if(s.charAt(counter) == ' '&& counter != s.length()-1) { int n = Integer.parseInt(sb); nb.add(n); sb = ""; } counter++; } if(counter == s.length()) { int n = Integer.parseInt(sb); nb.add(n); sb = ""; } System.out.println(nb); options(nb); } } public void options(ArrayList<Integer>nr) { int n = nr.get(0), m = nr.get(1),amount=0; if(n < 10 && m < 10) amount = 0; else if(n >= 10 && n < 100&& n % 10 < 10) { for(int i = n ; i < m ; i++) { String s = Integer.toString(i); int g = Integer.parseInt(s); String s1 = s.charAt(1)+""+ s.charAt(0)+""; int r = Integer.parseInt(s1); if(g >= n && g <= m && r >= n && r <= m && g < r ) amount++; } } else if(n >= 100 && n < 1000) { for(int i = n ; i < m ; i++) { String s = Integer.toString(i); int g = Integer.parseInt(s); String s1 = s.charAt(2)+""+ s.charAt(0)+""+s.charAt(1); String s2 = s.charAt(1)+""+ s.charAt(2)+""+s.charAt(0); int r = Integer.parseInt(s1); int r1 = Integer.parseInt(s2); if(g >= n && g <= m && r >= n && r <= m && g < r ) amount++; if(r != r1) { if(g >= n && g <= m && r1 >= n && r1 <= m && g < r1 ) amount++; } } } else if(n >= 1000 && n < 10000) { for(int i = n ; i < m ; i++) { String s = Integer.toString(i); int g = Integer.parseInt(s); String s1 = s.charAt(3)+""+s.charAt(0)+""+ s.charAt(1)+""+s.charAt(2); String s2 = s.charAt(2)+""+s.charAt(3)+""+ s.charAt(0)+""+s.charAt(1); String s3 = s.charAt(1)+""+s.charAt(2)+""+ s.charAt(3)+""+s.charAt(0); int r = Integer.parseInt(s1); int r1 = Integer.parseInt(s2); int r2 = Integer.parseInt(s3); if(g >= n && g <= m && r >= n && r <= m && g < r ) amount++; if(r != r1 && r1 != r2 && r != r2) { if(g >= n && g <= m && r1 >= n && r1 <= m && g < r1 ) amount++; if(g >= n && g <= m && r2 >= n && r2 <= m && g <= r2 ) amount++; } } } else if(n >= 10000 && n < 100000) { for(int i = n ; i < m ; i++) { String s = Integer.toString(i); int g = Integer.parseInt(s); String s1 = s.charAt(4)+""+s.charAt(0)+""+s.charAt(1)+""+ s.charAt(2)+""+s.charAt(3); String s2 = s.charAt(3)+""+s.charAt(4)+""+s.charAt(0)+""+ s.charAt(1)+""+s.charAt(2); String s3 = s.charAt(2)+""+s.charAt(3)+""+s.charAt(4)+""+ s.charAt(0)+""+s.charAt(1); String s4 = s.charAt(1)+""+s.charAt(2)+""+s.charAt(3)+""+ s.charAt(4)+""+s.charAt(0); int r = Integer.parseInt(s1); int r1 = Integer.parseInt(s2); int r2 = Integer.parseInt(s3); int r3 = Integer.parseInt(s4); if(g >= n && g <= m && r >= n && r <= m && g < r ) amount++; if(r != r1 || r1 != r2 || r != r2 || r != r3 || r2 != r3) { if(g >= n && g <= m && r1 >= n && r1 <= m && g < r1 ) amount++; if(g >= n && g <= m && r2 >= n && r2 <= m && g <= r2 ) amount++; if(g >= n && g <= m && r3 >= n && r3 <= m && g <= r3 ) amount++; } } } else if(n >= 1000000 && n < 10000000) { for(int i = n ; i < m ; i++) { String s = Integer.toString(i); int g = Integer.parseInt(s); String s1 = s.charAt(5)+""+s.charAt(0)+""+s.charAt(1)+""+s.charAt(2)+""+ s.charAt(3)+""+s.charAt(4); String s2 = s.charAt(4)+""+s.charAt(5)+""+s.charAt(0)+""+s.charAt(1)+""+ s.charAt(2)+""+s.charAt(3); String s3 = s.charAt(3)+""+s.charAt(4)+""+s.charAt(5)+""+s.charAt(0)+""+ s.charAt(1)+""+s.charAt(2); String s4 = s.charAt(2)+""+s.charAt(3)+""+s.charAt(4)+""+s.charAt(5)+""+ s.charAt(0)+""+s.charAt(1); String s5 = s.charAt(1)+""+s.charAt(2)+""+s.charAt(3)+""+s.charAt(4)+""+ s.charAt(5)+""+s.charAt(0); int r = Integer.parseInt(s1); int r1 = Integer.parseInt(s2); int r2 = Integer.parseInt(s3); int r3 = Integer.parseInt(s4); int r4 = Integer.parseInt(s5); if(g >= n && g <= m && r >= n && r <= m && g < r ) amount++; if(r != r1 || r1 != r2 || r != r2 || r != r3 || r2 != r3 || r != r4 || r2 != r4 || r3 != r4) { if(g >= n && g <= m && r1 >= n && r1 <= m && g < r1 ) amount++; if(g >= n && g <= m && r2 >= n && r2 <= m && g <= r2 ) amount++; if(g >= n && g <= m && r3 >= n && r3 <= m && g <= r3 ) amount++; if(g >= n && g <= m && r4 >= n && r4 <= m && g <= r4 ) amount++; } } } max.add(amount); } public void output(BufferedWriter out) throws FileNotFoundException, IOException { int counter = 1; for(Integer s : max ) { out.write("Case #" + counter + ": "); out.write(s+"\n"); counter++; } out.close(); } }
A22378
A21945
0
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class CodeJam { // public static final String INPUT_FILE_PATH = "D://CodeJamInput.txt"; public static final String INPUT_FILE_PATH = "D://B-large.in"; public static final String OUTPUT_FILE_PATH = "D://CodeJamOutput.txt"; public static List<String> readInput() { List<String> list = new ArrayList<String>(); try { BufferedReader input = new BufferedReader(new FileReader( INPUT_FILE_PATH)); try { String line = null; while ((line = input.readLine()) != null) { list.add(line); } } finally { input.close(); } } catch (IOException ex) { ex.printStackTrace(); } return list; } public static void writeOutput(List<String> output) { PrintWriter writer = null; try { writer = new PrintWriter(new FileWriter(OUTPUT_FILE_PATH)); for (String line : output) { writer.println(line); } writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) writer.close(); } } public static void main(String[] args) { List<DanceFloor> danceFloors = DanceFloor.parseFromFile(CodeJam.readInput()); List<String> output = new ArrayList<String>(); for(int i = 0; i < danceFloors.size(); i++) { System.out.println(danceFloors.get(i)); String line = ""; line += "Case #" + (i + 1) + ": " + danceFloors.get(i).calculate(); output.add(line); } CodeJam.writeOutput(output); } } class DanceFloor { private List<Integer> tripletsTotalCounts; private int surpriseCount; private int targetScore; private int dancersCount; public DanceFloor(List<Integer> tripletsTotalCounts, int surpriseCount, int targetScore, int dancersCount) { this.tripletsTotalCounts = tripletsTotalCounts; this.surpriseCount = surpriseCount; this.targetScore = targetScore; this.dancersCount = dancersCount; } public int calculate() { int result = 0; if (targetScore == 0) return dancersCount; for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if (total < (targetScore * 3 - 4)) { tripletsTotalCounts.remove(i--); } else if (total == 0) { tripletsTotalCounts.remove(i--); } } for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if ((surpriseCount > 0) && (total == targetScore * 3 - 4)) { result++; surpriseCount--; tripletsTotalCounts.remove(i--); } else if ((surpriseCount == 0) && (total == targetScore * 3 - 4)) { tripletsTotalCounts.remove(i--); } } for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if ((surpriseCount > 0) && (total == targetScore * 3 - 3)) { result++; surpriseCount--; tripletsTotalCounts.remove(i--); } else if ((surpriseCount == 0) && (total == targetScore * 3 - 3)) { tripletsTotalCounts.remove(i--); } } result += tripletsTotalCounts.size(); return result; } public static List<DanceFloor> parseFromFile(List<String> readInput) { List<DanceFloor> result = new ArrayList<DanceFloor>(); int testCaseCount = Integer.parseInt(readInput.get(0)); for (int i = 0; i < testCaseCount; i++) { String line[] = readInput.get(i + 1).split(" "); List<Integer> totalCounts = new ArrayList<Integer>(); for (int j = 0; j < Integer.parseInt(line[0]); j++) { totalCounts.add(Integer.parseInt(line[3 + j])); } result.add(new DanceFloor(totalCounts, Integer.parseInt(line[1]), Integer.parseInt(line[2]), Integer.parseInt(line[0]))); } return result; } @Override public String toString() { return "dancersCount = " + dancersCount + "; surpriseCount = " + surpriseCount + "; targetScore = " + targetScore + "; tripletsTotalCounts" + tripletsTotalCounts.toString(); } }
import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int numCases = Integer.parseInt(br.readLine()); for(int i = 0; i < numCases; i++) { solveCase(i+1, br.readLine()); } } private static void solveCase(int caseNum, String line) { String[] parts = line.split(" "); int numGooglers = Integer.parseInt(parts[0]); int numSurprising = Integer.parseInt(parts[1]); int minScore = Integer.parseInt(parts[2]); ArrayList<Integer> scores = new ArrayList<Integer>(numGooglers); for(int i = 0 ;i < numGooglers; i++) { scores.add(Integer.parseInt(parts[i+3])); } //System.out.println(numSurprising +" surprising"); //System.out.println("scores: "+ scores); System.out.println("Case #"+caseNum+": "+solve(minScore, scores, 0, numSurprising, 0)); } private static int solve(int minScore, ArrayList<Integer> scores, int index, int surprisesRemaining, int result) { if(index == scores.size()) { return result; } if(solveWithoutSurprise(minScore, scores.get(index))) { result++; } else if(surprisesRemaining > 0 && solveWithSurprise(minScore, scores.get(index))) { result++; surprisesRemaining--; } return solve(minScore, scores, index + 1, surprisesRemaining, result); } private static boolean solveWithoutSurprise(int minScore, int totalScore) { if(minScore ==0) { return true; } if(totalScore == 0) { return false; } int scoresTo = totalScore - 1; int each = scoresTo / 3; if(each + 1 >= minScore) { return true; } return false; } private static boolean solveWithSurprise(int minScore, int totalScore) { if(totalScore == 0) { return false; } int scoresTo = totalScore - 2; // if total score was < 2, would have been true from WithoutSurprise int each = scoresTo / 3; int remainder = scoresTo % 3; if(remainder == 0 || remainder == 1) { if(each + 2 >= minScore) { return true; } return false; } else { // remainder ==2 //System.out.println("totalScore="+totalScore+": SHOULD NEVER HAPPEN!!!!!!!!!!!! SHOULD ALWAYS BE ABLE TO SOLVE WIHTOUT SURPIRSE!!!"); } return false; } }
B10231
B10152
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.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; import java.util.Scanner; public class RecycledNumbers { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub //System.setOut(new PrintStream(new File("RecycledNumbers.txt"))); Scanner scanner = new Scanner(System.in); int testcasenum = Integer.valueOf(scanner.next()); scanner.nextLine(); for (int testcase = 0; testcase < testcasenum; testcase++) { System.out.print("Case #"); System.out.print(testcase+1); System.out.print(": "); int from = scanner.nextInt(); int to = scanner.nextInt(); int count = 0; boolean table[] = new boolean[to+1]; for (int num = from; num <= to; num++) { if (!table[num]){ int len = String.valueOf(num).length(); int shift = num; table[num] = true; int pair = 1; for (int i = 0;i < len-1;i++){ shift = shiftLeft(shift, len); if (shift >= from && shift <= to&& !table[shift]){ pair++; table[shift] = true; } } count += pair*(pair-1)/2; } } System.out.println(count); } } public static int shiftLeft(int num, int len) { int digit = num % 10; num = num / 10; return num += Math.pow(10, len-1)*digit; } public static int getUniqueDigits(int num){ boolean digits[] = new boolean[10]; while (num != 0) { int digit = (num % 10); digits[digit] = true; num = num / 10; } int count = 0; for (int i = 0;i < 10;i++){ count += digits[i]?1:0; } return count; } }
B10245
B10204
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.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; public class JamInputReader { int numItem; String thisLine = null; BufferedReader in; StringTokenizer tokenizer; public JamInputReader(String fileName) { try { in = new BufferedReader(new FileReader(fileName)); /* String text = in.readLine(); numItem = Integer.parseInt(text);*/ readNextLine(); tokenizer = new StringTokenizer(thisLine, " "); } catch (FileNotFoundException e) { e.printStackTrace(); } } void readNextLine() { try { thisLine = in.readLine(); } catch (IOException e) { e.printStackTrace(); } } int getNumItems() { numItem = Integer.parseInt(tokenizer.nextToken()); return numItem; } String getNextItem() { if(false == tokenizer.hasMoreTokens()) { readNextLine(); tokenizer = new StringTokenizer(thisLine, " "); } return tokenizer.nextToken(); } String getNextLine() { readNextLine(); return thisLine; } int getNextInt() { return Integer.parseInt(getNextItem()); } long getNextLong() { return Long.parseLong(getNextItem()); } byte[] getNextLineByte() { readNextLine(); return thisLine.getBytes(); } }
B20734
B21831
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 qualification; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedList; import java.util.Scanner; public class C { public static void main(String[] Args) throws IOException { Scanner sc = new Scanner(new FileReader("C-small.in")); PrintWriter pw = new PrintWriter(new FileWriter("output.txt")); int caseCnt = sc.nextInt(); // int caseCnt=1; for (int caseNum=1; caseNum <= caseCnt; caseNum++) { System.out.println(caseNum); int A=sc.nextInt(); int B=sc.nextInt(); // int A = 1234567; // int B =1234567; HashMap<Integer, LinkedList<Integer>> visited = new HashMap<Integer, LinkedList<Integer>>(); long total=0; for(int i=A;i<=B;i++){ if(!visited.containsKey(i)) visited.put(i, new LinkedList<Integer>()); String stringI=String.valueOf(i); for(int j=1;j<stringI.length();j++) { String test = stringI.substring(j)+stringI.substring(0, j); int testInt = Integer.parseInt(test); if(testInt>=A && testInt<=B && testInt!=i){ if(!visited.containsKey(testInt)) visited.put(testInt, new LinkedList<Integer>()); if(!visited.get(testInt).contains(i)) { total++; visited.get(testInt).add(i); visited.get(i).add(testInt); } } } } System.out.println(total); pw.println("Case #" + caseNum + ": " + total); } pw.flush(); pw.close(); sc.close(); } }
B11696
B11323
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycled; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.TreeSet; /** * * @author Alfred */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream("C-small-attempt0.in"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter outFile = new FileWriter("out.txt"); PrintWriter out = new PrintWriter(outFile); String line; line = br.readLine(); int cases = Integer.parseInt(line); for (int i=1; i<=cases;i++){ line = br.readLine(); String[] values = line.split(" "); int A = Integer.parseInt(values[0]); int B = Integer.parseInt(values[1]); int total=0; for (int n=A; n<=B;n++){ TreeSet<String> solutions = new TreeSet<String>(); for (int k=1;k<values[1].length();k++){ String m = circshift(n,k); int mVal = Integer.parseInt(m); if(mVal<=B && mVal!=n && mVal> n && !m.startsWith("0") && m.length()==Integer.toString(n).length() ) { solutions.add(m); } } total+=solutions.size(); } out.println("Case #"+i+": "+total); } in.close(); out.close(); } catch (Exception e) {//Catch exception if any System.err.println("Error: " + e.getMessage()); } } private static String circshift(int n, int k) { String nString=Integer.toString(n); int len=nString.length(); String m = nString.substring(len-k)+nString.subSequence(0, len-k); //System.out.println(n+" "+m); return m; } }
import java.util.*; import java.io.*; import static java.lang.Math.*; public class A { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader in = new BufferedReader(new FileReader("C-small-attempt0.in")); FileWriter fw = new FileWriter("output.out"); /*BufferedReader in = new BufferedReader(new FileReader("A-large.in")); FileWriter fw = new FileWriter("A-large.out");*/ int N = new Integer(in.readLine()); String[] output = new String[N]; int[] trueCount = new int[N]; for (int cases = 0; cases < N; cases++) { int CaseNo = cases+1; output[cases] = ""; StringTokenizer G = new StringTokenizer(in.readLine()); int W = G.countTokens(); int[] a = new int[2]; String[] b = new String[W]; for (int j = 0; j < a.length; j++) { a[j] = new Integer(G.nextToken()); } int counter = 1; int A =a[0]; int B =a[1]; int C = a[0]; System.out.println(A + " x " +B); int lengthA = Integer.toString(A).length(); if (lengthA == 1){ trueCount[cases] = 0; } else{ int range = B - A + 1; int[] rangeA = new int[range]; rangeA[0] = A; while (A<B){ A = A+1; rangeA[counter] = A; counter=counter+1; } for (int ii=0;ii<range;ii++){ int currentN = rangeA[ii]; int currentM = rangeA[ii]; int length = Integer.toString(rangeA[ii]).length(); String curM = Integer.toString(currentM); for (int jj=0; jj<length;jj++){ curM = curM.charAt(length-1) + curM.substring(0, length-1); currentM = Integer.parseInt(curM); if (currentM <= B && currentM > currentN && currentM >= C){ trueCount[cases]+=1; } } } } fw.write("Case #"+CaseNo+": "+ trueCount[cases]+ "\n"); } fw.flush(); fw.close(); } }
A11201
A11171
0
package CodeJam.c2012.clasificacion; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * Problem * * You're watching a show where Googlers (employees of Google) dance, and then * each dancer is given a triplet of scores by three judges. Each triplet of * scores consists of three integer scores from 0 to 10 inclusive. The judges * have very similar standards, so it's surprising if a triplet of scores * contains two scores that are 2 apart. No triplet of scores contains scores * that are more than 2 apart. * * For example: (8, 8, 8) and (7, 8, 7) are not surprising. (6, 7, 8) and (6, 8, * 8) are surprising. (7, 6, 9) will never happen. * * The total points for a Googler is the sum of the three scores in that * Googler's triplet of scores. The best result for a Googler is the maximum of * the three scores in that Googler's triplet of scores. Given the total points * for each Googler, as well as the number of surprising triplets of scores, * what is the maximum number of Googlers that could have had a best result of * at least p? * * For example, suppose there were 6 Googlers, and they had the following total * points: 29, 20, 8, 18, 18, 21. You remember that there were 2 surprising * triplets of scores, and you want to know how many Googlers could have gotten * a best result of 8 or better. * * With those total points, and knowing that two of the triplets were * surprising, the triplets of scores could have been: * * 10 9 10 6 6 8 (*) 2 3 3 6 6 6 6 6 6 6 7 8 (*) * * The cases marked with a (*) are the surprising cases. This gives us 3 * Googlers who got at least one score of 8 or better. There's no series of * triplets of scores that would give us a higher number than 3, so the answer * is 3. * * Input * * The first line of the input gives the number of test cases, T. T test cases * follow. Each test case consists of a single line containing integers * separated by single spaces. The first integer will be N, the number of * Googlers, and the second integer will be S, the number of surprising triplets * of scores. The third integer will be p, as described above. Next will be N * integers ti: the total points of the Googlers. * * Output * * For each test case, output one line containing "Case #x: y", where x is the * case number (starting from 1) and y is the maximum number of Googlers who * could have had a best result of greater than or equal to p. * * Limits * * 1 ≤ T ≤ 100. 0 ≤ S ≤ N. 0 ≤ p ≤ 10. 0 ≤ ti ≤ 30. At least S of the ti values * will be between 2 and 28, inclusive. * * Small dataset * * 1 ≤ N ≤ 3. * * Large dataset * * 1 ≤ N ≤ 100. * * Sample * * Input Output 4 Case #1: 3 3 1 5 15 13 11 Case #2: 2 3 0 8 23 22 21 Case #3: 1 * 2 1 1 8 0 Case #4: 3 6 2 8 29 20 8 18 18 21 * * @author Leandro Baena Torres */ public class B { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader("B.in")); String linea; int numCasos, N, S, p, t[], y, minSurprise, minNoSurprise; linea = br.readLine(); numCasos = Integer.parseInt(linea); for (int i = 0; i < numCasos; i++) { linea = br.readLine(); String[] aux = linea.split(" "); N = Integer.parseInt(aux[0]); S = Integer.parseInt(aux[1]); p = Integer.parseInt(aux[2]); t = new int[N]; y = 0; minSurprise = p + ((p - 2) >= 0 ? (p - 2) : 0) + ((p - 2) >= 0 ? (p - 2) : 0); minNoSurprise = p + ((p - 1) >= 0 ? (p - 1) : 0) + ((p - 1) >= 0 ? (p - 1) : 0); for (int j = 0; j < N; j++) { t[j] = Integer.parseInt(aux[3 + j]); if (t[j] >= minNoSurprise) { y++; } else { if (t[j] >= minSurprise) { if (S > 0) { y++; S--; } } } } System.out.println("Case #" + (i + 1) + ": " + y); } } }
import java.io.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.logging.Level; import java.util.logging.Logger; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author aliakbars */ public class Googlers { public static void main(String[] args) { Googlers gr = new Googlers(); FileInputStream fstream = null; FileWriter fwrite; int jml; int s; int p; int okay; try { fstream = new FileInputStream("B-small-attempt7.in"); fwrite = new FileWriter("B-small-attempt7.out"); BufferedWriter ofile = new BufferedWriter(fwrite); DataInputStream ifile = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(ifile)); String num = br.readLine(); for (int i = 0; i < Integer.parseInt(num); i++) { String[] input = br.readLine().split(" "); jml = Integer.parseInt(input[0]); s = Integer.parseInt(input[1]); p = Integer.parseInt(input[2]); okay = 0; for (int j = 0; j < jml; j++) { int x = Integer.parseInt(input[3+j]); if (x / 3 >= p) { okay++; } else { if (x / 3 + 1 >= p && x != 0) { if (x - (x / 3) * 3 + (x / 3) >= p) { okay++; } else { if (s > 0) { okay++; s--; } } } else if (x / 3 + 2 >= p && x != 0) { if ((x / 3) * 3 + 2 == x) { if (s > 0) { okay++; s--; } } } } } try { ofile.write("Case #" + (i + 1) + ": " + okay); ofile.newLine(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } System.out.println("Case #" + (i + 1) + ": " + okay); } ofile.close(); } catch (IOException ex) { Logger.getLogger(Googlerese.class.getName()).log(Level.SEVERE, null, ex); } finally { try { fstream.close(); } catch (IOException ex) { Logger.getLogger(Tutorial.class.getName()).log(Level.SEVERE, null, ex); } } } }
A12460
A10032
0
/** * */ package pandit.codejam; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Scanner; /** * @author Manu Ram Pandit * */ public class DancingWithGooglersUpload { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { FileInputStream fStream = new FileInputStream( "input.txt"); Scanner scanner = new Scanner(new BufferedInputStream(fStream)); Writer out = new OutputStreamWriter(new FileOutputStream("output.txt")); int T = scanner.nextInt(); int N,S,P,ti; int counter = 0; for (int count = 1; count <= T; count++) { N=scanner.nextInt(); S = scanner.nextInt(); counter = 0; P = scanner.nextInt(); for(int i=1;i<=N;i++){ ti=scanner.nextInt(); if(ti>=(3*P-2)){ counter++; continue; } else if(S>0){ if(P>=2 && ((ti==(3*P-3)) ||(ti==(3*P-4)))) { S--; counter++; continue; } } } // System.out.println("Case #" + count + ": " + counter); out.write("Case #" + count + ": " + counter + "\n"); } fStream.close(); out.close(); } }
import java.io.*; import java.util.*; public class GoogleDancing { public static void main(String[] args) throws IOException { BufferedReader read = new BufferedReader(new FileReader("B-small-attempt3.in.txt")); int T = Integer.parseInt(read.readLine()); for(int i = 1; i <= T; i++){ StringTokenizer st = new StringTokenizer(read.readLine()); int N = Integer.parseInt(st.nextToken()); int S = Integer.parseInt(st.nextToken()); int P = Integer.parseInt(st.nextToken()); if(P == 0) { System.out.println("Case #" + i + ": " + N); continue; } int total = 0; for(int j = 0; j < N; j++) { int temp = Integer.parseInt(st.nextToken()); if(temp == 0) continue; int q = temp/3 + ((temp%3 == 0)? 0:1); if(P <= q) total++; else if(temp%3 != 1) { if(P <= q+1 && S > 0) { total++; S--; } } } System.out.println("Case #" + i + ": " + total); } } }
A12544
A10561
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.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.*; public class B { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("B.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("B.out"))); int C = sc.nextInt(); for(int i=1;i<=C;i++){ int N = sc.nextInt(); int S = sc.nextInt(); int B = sc.nextInt(); boolean[] pass = new boolean[N]; boolean[] wierd = new boolean[N]; troll:for(int a=0;a<N;a++){ int P = sc.nextInt(); for(int b=0;b<=10;b++){ for(int c=b-2;c<=b+2;c++){ if(c>10||c<0)continue; for(int d=b-2;d<=b+2;d++){ if(d>10||d<0)continue; if(b+c+d!=P)continue; int small = Math.min(Math.min(b,c),d); int big = Math.max(Math.max(b,c),d); // System.out.println(b+" "+c+" "+d); if(big>=B){ if(big-small==2){ // System.out.println(b+" "+c+" "+d); wierd[a]=true; } else if(big-small<2){ pass[a]=true; // System.out.println(b+" "+c+" "+d); continue troll; } } } } } } // System.out.println(Arrays.toString(pass)); // System.out.println(Arrays.toString(wierd)); int ans = 0; int used = 0; for(int a=0;a<N;a++){ if(pass[a]){ ans++; continue; } if(wierd[a]){ if(used<S)ans++; used++; } } out.println("Case #"+i+": "+ans); } out.close(); } }
B12941
B10433
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(); } }
package codejam2012; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; /** * * @author devashish */ public class ProblemC { private static Set<PairedNumber> pairedNumbers = new HashSet<PairedNumber>(); private static Map<PairedNumber, Integer> pairedNumbersMap = new HashMap<PairedNumber, Integer>(); public static void main(String[] args) { StringTokenizer st = null; BufferedReader in; PrintWriter out = null; try { in = new BufferedReader(new FileReader(new File("E:/c.in"))); out = new PrintWriter(new FileWriter(new File("E:/c.out"))); while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } int t = Integer.parseInt(st.nextToken()); for (int i = 1; i <= t; i++) { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int outputLine = new ProblemC().getNumberOfRecycledPairs(A, B); out.print("Case #" + i + ": " + outputLine + "\n"); } } catch (IOException e) { } out.flush(); } private int getNumberOfRecycledPairs(int A, int B) { pairedNumbers = new HashSet<PairedNumber>(); pairedNumbersMap = new HashMap<PairedNumber, Integer>(); String strB = B + ""; //System.out.println("Count from " + A + " to " + B); if (strB.length() == 1) { return 0; } for (int i = A; i <= B; i++) { if (isPalindrome(i)) { continue; } if (isSameDigits(i)) { continue; } PairedNumber pairedNumber = new PairedNumber(i); boolean added = pairedNumbers.add(pairedNumber); //System.out.println("i = " + i + ", added: " + added); if (!added) { int occurence = 2; if (pairedNumbersMap.containsKey(pairedNumber)) { occurence = pairedNumbersMap.get(pairedNumber) + 1; } pairedNumbersMap.put(pairedNumber, occurence); } } int finalCount = 0; Iterator it = pairedNumbersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); // System.out.println(pairs.getKey() + " = " + pairs.getValue()); it.remove(); int val = (Integer) pairs.getValue(); finalCount += (val * (val - 1)) / 2; } return finalCount; } private boolean isPalindrome(int number) { int reversedNumber = 0; while (number > 0) { int temp = number % 10; number = number / 10; reversedNumber = reversedNumber * 10 + temp; } if (number == reversedNumber) { return true; } return false; } private boolean isSameDigits(int num) { String str = num + ""; char ch = str.charAt(0); String check = ""; for (int i = 0; i < str.length(); i++) { check += ch; } if (str.equals(check)) { return true; } return false; } public Set<Integer> getPermutations(Integer num, int A, int B) { Set<Integer> perms = new HashSet<Integer>(); int length = (num == 0) ? 1 : (int) Math.log10(num) + 1; String numString = num + ""; for (int i = 1; i < length; i++) { String str = numString.substring(i) + numString.substring(0, i); //System.out.println(str); perms.add(Integer.parseInt(str)); } //perms.add(num); return perms; } class PairedNumber { private String pairedNumber = ""; public PairedNumber(int number) { this.pairedNumber = number + ""; } public Set<Integer> getPermutations(Integer num) { Set<Integer> perms = new HashSet<Integer>(); int length = (num == 0) ? 1 : (int) Math.log10(num) + 1; String numString = num + ""; for (int i = 1; i < length; i++) { String str = numString.substring(i) + numString.substring(0, i); perms.add(Integer.parseInt(str)); } return perms; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PairedNumber other = (PairedNumber) obj; Set<Integer> perms = getPermutations(Integer.parseInt(this.pairedNumber)); if (perms.contains(Integer.parseInt(other.pairedNumber))) { return true; } else { return false; } } @Override public int hashCode() { int hash = 5; hash = 13 * hash + (this.pairedNumber != null ? this.pairedNumber.length() : 0); return hash; } @Override public String toString() { return "PairedNumber{" + "pairedNumber=" + pairedNumber + '}'; } } }
B10155
B10222
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.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.PrintStream; import java.util.Scanner; //javac C.java && java C x.in x.out public class C { public static void main(String[] args) throws FileNotFoundException { InputStream in = System.in; if(args.length>0) in = new FileInputStream(args[0]); PrintStream out = System.out; if(args.length>1) out = new PrintStream(args[1]); Solver s = new Solver(new Scanner(in),out); //Multiple case input s.cases(); //Single case input //s.go(); } } class Solver { Scanner in; PrintStream out; public Solver(Scanner scanner, PrintStream printStream) { in = scanner; out = printStream; } public void cases() { int numCases = in.nextInt(); in.nextLine(); for(int i=0;i<numCases;i++) { out.print("Case #"+(i+1)+": "); go(); } } public void go() { int A = in.nextInt(); int B = in.nextInt(); int ans = 0; int mod = 1; int a = A; int digs = 0; while(a>0) { a/=10; mod*=10; digs++; } for(int n = A; n <= B; n++) { for(int m = n+1; m <= B; m++) { int nn=n; for(int i = 0; i < digs; i++) { nn=(nn+mod*(nn%10))/10; if(nn==m) { ans++; break; } } } } out.println(ans); } }
B22190
B20775
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(); } }
package CodeJam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.HashSet; import java.util.Set; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader("D:\\workspace\\GoogleCodeJam\\data\\C-large.in")); String line; BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\workspace\\GoogleCodeJam\\data\\C-large.out")); line=reader.readLine(); int c = Integer.parseInt(line); int i = 1; while ((line=reader.readLine()) != null) { String[] ints = line.split(" "); int a,b; a = Integer.parseInt(ints[0]); b = Integer.parseInt(ints[1]); int cnt = countNumber(a,b); writer.write(String.format("Case #%s: %s", i, cnt)); System.out.println(String.format("Case #%s: %s", i, cnt)); if (i<c) writer.newLine(); i++; } writer.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static int countNumber(int a, int b) { int cnt = 0; for (int i=a;i<b;i++) { String is = String.valueOf(i); Set<String> dup = new HashSet<String>(); for (int j = 1; j < is.length(); j++) { String s = is.substring(j) + is.substring(0,j); if (dup.contains(s)) continue; else dup.add(s); if (Integer.parseInt(s)>i && Integer.parseInt(s)<=b) { cnt++; } } } return cnt; } }
B20006
B21174
0
import java.io.*; import java.math.BigInteger; import java.util.*; import org.jfree.data.function.PowerFunction2D; public class r2a { Map numMap = new HashMap(); int output = 0; /** * @param args */ public static void main(String[] args) { r2a mk = new r2a(); try { FileInputStream fstream = new FileInputStream("d:/cjinput.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String str; int i = 0; while ((str = br.readLine()) != null) { int begin=0,end = 0; i++; if (i == 1) continue; mk.numMap = new HashMap(); StringTokenizer strTok = new StringTokenizer(str, " "); while (strTok.hasMoreTokens()) { begin = Integer.parseInt(((String) strTok.nextToken())); end = Integer.parseInt(((String) strTok.nextToken())); } mk.evaluate(i, begin, end); } in.close(); } catch (Exception e) { System.err.println(e); } } private void evaluate(int rowNum, int begin, int end) { output=0; for (int i = begin; i<= end; i++) { if(numMap.containsKey(Integer.valueOf(i))) continue; List l = getPairElems(i); if (l.size() > 0) { Iterator itr = l.iterator(); int ctr = 0; ArrayList tempList = new ArrayList(); while (itr.hasNext()) { int next = ((Integer)itr.next()).intValue(); if (next <= end && next > i) { numMap.put(Integer.valueOf(next), i); tempList.add(next); ctr++; } } ctr = getCounter(ctr+1,2); /* if (tempList.size() > 0 || ctr > 0) System.out.println("DD: " + i + ": " + tempList +" ; ctr = " + ctr);*/ output = output + ctr; } } String outputStr = "Case #" + (rowNum -1) + ": " + output; System.out.println(outputStr); } private int getCounter(int n, int r) { int ret = 1; int nfactorial =1; for (int i = 2; i<=n; i++) { nfactorial = i*nfactorial; } int nrfact =1; for (int i = 2; i<=n-r; i++) { nrfact = i*nrfact; } return nfactorial/(2*nrfact); } private ArrayList getPairElems(int num) { ArrayList retList = new ArrayList(); int temp = num; if (num/10 == 0) return retList; String str = String.valueOf(num); int arr[] = new int[str.length()]; int x = str.length(); while (temp/10 > 0) { arr[x-1] = temp%10; temp=temp/10; x--; } arr[0]=temp; int size = arr.length; for (int pos = size -1; pos >0; pos--) { if(arr[pos] == 0) continue; int pairNum = 0; int multiplier =1; for (int c=0; c < size-1; c++) { multiplier = multiplier*10; } pairNum = pairNum + (arr[pos]*multiplier); for(int ctr = pos+1, i=1; i < size; i++,ctr++) { if (ctr == size) ctr=0; if (multiplier!=1) multiplier=multiplier/10; pairNum = pairNum + (arr[ctr]*multiplier); } if (pairNum != num) retList.add(Integer.valueOf(pairNum)); } return retList; } }
import java.io.File; import java.io.FileNotFoundException; import java.util.Formatter; import java.util.HashSet; import java.util.Scanner; public class RecycledNumbers { private static String solve(int A, int B) { int count = 0; final HashSet<Integer> seen = new HashSet<Integer>(10); for (int n = A; n < B; n++) { // Find number of decimal digits. int nTemp = n, digits = 0, unit = 1; while (nTemp > 0) { digits++; nTemp /= 10; unit *= 10; } unit /= 10; int m = n; seen.clear(); for (int i = 1; i < digits; i++) { if (m % 10 == 0) { // Don't process because there will be a leading zero. m /= 10; } else { m = (unit * (m % 10)) + (m / 10); if (m > n && m <= B && !seen.contains(m)) { seen.add(m); count++; } } } } return "" + count; } public static void main(String[] args) throws FileNotFoundException { //String filename = "C-test.in"; //String filename = "C-small-attempt0.in"; String filename = "C-large.in"; assert filename.endsWith(".in"); Scanner in = new Scanner(new File(filename)); Formatter out = new Formatter(new File(filename.replace(".in", ".out"))); assert in.hasNext(); int T = in.nextInt(); in.nextLine(); for (int t = 0; t < T; t++) { int A = in.nextInt(); int B = in.nextInt(); String ans = solve(A, B); String result; if (t < T - 1) result = String.format("Case #%d: %s%n", t + 1, ans); else result = String.format("Case #%d: %s", t + 1, ans); out.format(result); System.out.format(result); } out.flush(); out.close(); } }
A22642
A20197
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; } } } }
import java.io.*; import java.util.*; public class DG { private static String fileName = DG.class.getSimpleName().replaceFirst("_.*", ""); private static String inputFileName = "D:\\cj12\\"+fileName + ".in"; private static String outputFileName = "D:\\cj12\\"+fileName + ".out"; private static Scanner in; private static PrintWriter out; public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); if (args.length >= 2) { inputFileName = args[0]; outputFileName = args[1]; } in = new Scanner(new FileReader(inputFileName)); out = new PrintWriter(outputFileName); int tests = in.nextInt(); //in.nextLine(); for (int t = 1; t <= tests; t++) { int n = in.nextInt(); int s = in.nextInt(); int p = in.nextInt(); int res = 0; for(int i=0;i<n;i++) { int tot = in.nextInt(); if(tot >= ((3*p)-2)) res++; else if(tot > 0 && s > 0 && (tot >= ((3*p)-4))) { res++; s--; } } System.out.println("Case #" + t + ": "+res); out.println("Case #" + t + ": "+res); } in.close(); out.close(); } }
B10702
B10027
0
import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class Recycle { private static HashMap<Integer, HashSet<Integer>> map = new HashMap<Integer, HashSet<Integer>>(); private static HashSet<Integer> toSkip = new HashSet<Integer>(); /** * @param args */ public static void main(String[] args) { Scanner reader = new Scanner(System.in); int T = reader.nextInt(); for (int tc = 1; tc <= T; tc++) { int a = reader.nextInt(); int b = reader.nextInt(); long before = System.currentTimeMillis(); int res = doit(a, b); System.out.printf("Case #%d: %d\n", tc, res); long after = System.currentTimeMillis(); // System.out.println("time taken: " + (after - before)); } } private static int doit(int a, int b) { int count = 0; HashSet<Integer> skip = new HashSet<Integer>(toSkip); for (int i = a; i <= b; i++) { if (skip.contains(i)) continue; HashSet<Integer> arr = generate(i); // if(arr.size() > 1) { // map.put(i, arr); // } // System.out.println(i + " --> " + // Arrays.deepToString(arr.toArray())); int temp = 0; if (arr.size() > 1) { for (int x : arr) { if (x >= a && x <= b) { temp++; skip.add(x); } } count += temp * (temp - 1) / 2; } // System.out.println("not skipping " + i + " gen: " + arr.size()+ " " + (temp * (temp - 1) / 2)); } return count; } private static HashSet<Integer> generate(int num) { if(map.containsKey(num)) { HashSet<Integer> list = map.get(num); return list; } HashSet<Integer> list = new HashSet<Integer>(); String s = "" + num; list.add(num); int len = s.length(); for (int i = 1; i < len; i++) { String temp = s.substring(i) + s.substring(0, i); // System.out.println("temp: " + temp); if (temp.charAt(0) == '0') continue; int x = Integer.parseInt(temp); if( x <= 2000000) { list.add(x); } } if(list.size() > 1) { map.put(num, list); } else { toSkip.add(num); } return list; } }
import java.io.BufferedReader; import java.io.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="B-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(); } } }
B21049
B20759
0
package it.simone.google.code.jam2012; import java.util.HashSet; import java.util.Set; public class RecycledNumber implements GoogleCodeExercise { int a = 0; int b = 0; Set<Couple> distinctCouple = null; long maxTime = 0; private class Couple { int x = 0; int y = 0; public Couple(int x, int y) { this.x = x; this.y = y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Couple other = (Couple) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (x == other.x && y == other.y) return true; if (x == other.y && y == other.x) return true; return false; } private RecycledNumber getOuterType() { return RecycledNumber.this; } } @Override public String execute(String line) { int result = 0; String[] data = line.split(" "); a = Integer.parseInt(data[0]); b = Integer.parseInt(data[1]); initialize(); int n = a; // while (n <= b) { result += analize(n); n++; // if (n % 1000 == 0) // System.out.println(n); } System.out.println(result); return "" + result; } @Override public void initialize() { distinctCouple = new HashSet<Couple>(); } private int analize(int number) { String numString = "" + number; initialize(); for (int i = 1; i < numString.length(); i++) { int m = shift(numString, i); if (a <= number && number < m && m <= b) { Couple couple=new Couple(number,m); if (!distinctCouple.contains(couple)) distinctCouple.add(couple); } } return distinctCouple.size(); } private int shift(String numString, int posx) { String result = null; result = "" + numString.substring(posx) + numString.substring(0, posx); return Integer.parseInt(result.toString()); } }
package codejam; public class DirConsts { public static final String // INPUT_DIR = "/home/luke/Downloads", // OUTPUT_DIR = "/home/luke/Downloads/CodeJam"; }
A10996
A10961
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 br.com; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Scanner; public class ProblemaB { static String caminho = "/home/mateus/"; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File(caminho + "entrada.txt")); FileWriter writer = new FileWriter(new File("/home/mateus/saida.txt"), false); int cases = sc.nextInt(); for (int i = 1; i <= cases; i++) { if (i == 3) { System.out.println(""); } int n = sc.nextInt(); int s = sc.nextInt(); int p = sc.nextInt(); int resposta = 0; ArrayList<Tripla> triplas = new ArrayList<Tripla>(); for (int j = 0; j < n; j++) { triplas.add(new Tripla(sc.nextInt())); } for (int w = triplas.size() - 1; w >= 0; w--) { if (triplas.get(w).maximaPontuacao() >= p) { resposta++; triplas.remove(w); } } for (int w = 0; w < triplas.size() && s > 0; w++) { if (triplas.get(w).maximaPontuacaoEspecial() >= p) { s--; resposta++; } } writer.append(criarCase(i, resposta + "")); } writer.flush(); writer.close(); } public static String criarCase(int i, String s) { return "Case #" + i + ": " + s + "\n"; } }
B21207
B22187
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.*; import java.math.BigInteger; import java.util.*; public class GC { String s = null; String[] sp = null; public void run() throws Exception{ BufferedReader br = new BufferedReader(new FileReader("C-large.in")); BufferedWriter bw = new BufferedWriter(new FileWriter("OUTPUT.txt")); s = br.readLine(); int T = Integer.parseInt(s); int t = 1; while(t <= T){ s = br.readLine(); sp = s.split(" "); long ans = 0; int a = Integer.parseInt(sp[0]); int b = Integer.parseInt(sp[1]); if(a < 10){ a = 10; } while(a < b){ String sa = Integer.toString(a); Set<String> set = new HashSet<String>(); for(int i = 1; i < sa.length(); i++){ String f = sa.substring(0, i); String ba = sa.substring(i); String ns = ba + f; if(set.contains(ns)){ continue; } set.add(ns); int nb = Integer.parseInt(ns); if(nb > a && nb <= b){ ans++; } } a++; } bw.write("Case #" + t + ": " + ans + "\n"); t++; } bw.close(); } public static void main(String[] args) throws Exception { GC b = new GC(); b.run(); } }
A21010
A20324
0
package codejam; import fixjava.Pair; public class Utils { public static long minLong(long firstVal, long... otherVals) { long minVal = firstVal; for (int i = 0; i < otherVals.length; i++) minVal = Math.min(firstVal, otherVals[i]); return minVal; } public static int minInt(int firstVal, int... otherVals) { int minVal = firstVal; for (int i = 0; i < otherVals.length; i++) minVal = Math.min(firstVal, otherVals[i]); return minVal; } public static float minFloat(float firstVal, float... otherVals) { float minVal = firstVal; for (int i = 0; i < otherVals.length; i++) minVal = Math.min(firstVal, otherVals[i]); return minVal; } /** * ArgMin returned as a Pair<Integer, Integer>(index, value). Array must * have at least one value. */ public static Pair<Integer, Integer> argMin(int[] arr) { int min = arr[0]; int argMin = 0; for (int i = 1; i < arr.length; i++) { if (arr[i] < min) { min = arr[i]; argMin = i; } } return new Pair<Integer, Integer>(argMin, min); } /** * ArgMax returned as a Pair<Integer, Integer>(index, value). Array must * have at least one value. */ public static Pair<Integer, Integer> argMax(int[] arr) { int max = arr[0]; int argMax = 0; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; argMax = i; } } return new Pair<Integer, Integer>(argMax, max); } }
import java.io.*; import java.util.*; public class GoogleDancer { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new FileReader("Dancer.in")); PrintWriter pw = new PrintWriter(new FileWriter("Dancer.out"), true); int T = sc.nextInt(); for (int c = 1; c<=T; c++) { int N = sc.nextInt(); int S = sc.nextInt(); int p = sc.nextInt(); int[] points = new int[N]; for (int d = 0; d < N; d++) { points[d] = sc.nextInt(); } int num = calc(N, S, p, points); String x = String.format("Case #%d: %d", c, num); pw.println(x); } pw.close(); } public static int calc(int N, int S, int p, int[] points) { int total = 0; int min = ((p-2)<0? 0 : p-2)*2 + p; for (Integer n : points) { if (n < min) continue; int avg = n/3; if (n%3 == 0) { if (avg >= p) total++; else if ((avg+1) >= p && S>0) { total++; S--; } }else if (n%3 == 1) { if ((avg+1) >= p)total++; }else { if ((avg+1) >= p) total++; else if ((avg+2)>= p && S > 0) { total++; S--; } } } return total; } }
B10485
B11048
0
import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import java.io.File; import java.io.IOException; import java.io.FileWriter; import java.io.BufferedWriter; public class Recycle { public static void main(String[] args) { /* Set<Integer> perms = getPermutations(123456); for(Integer i: perms) System.out.println(i);*/ try { Scanner s = new Scanner(new File("recycle.in")); BufferedWriter w = new BufferedWriter(new FileWriter(new File("recycle.out"))); int numCases = s.nextInt(); s.nextLine(); for(int n = 1;n <= numCases; n++) { int A = s.nextInt(); int B = s.nextInt(); int count = 0; for(int k = A; k <= B; k++) { count += getNumPairs(k, B); } w.write("Case #" + n + ": " + count + "\n"); } w.flush(); w.close(); } catch (IOException e) { e.printStackTrace(); } } public static int getNumPairs(int n, int B) { Set<Integer> possibles = getPermutations(n); int count = 0; for(Integer i : possibles) if(i > n && i <= B) count++; return count; } public static Set<Integer> getPermutations(int n) { Set<Integer> perms = new TreeSet<Integer>(); char[] digits = String.valueOf(n).toCharArray(); for(int firstPos = 1; firstPos < digits.length; firstPos++) { String toBuild = ""; for(int k = 0; k < digits.length; k++) toBuild += digits[(firstPos + k) % digits.length]; perms.add(Integer.parseInt(toBuild)); } return perms; } }
package com.clausewitz.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public abstract class Solver { protected BufferedReader fileIn = null; protected String outFilename = "output.out"; protected int numOfTestCase = -1; protected String answer[] = null; public void openFile(String filename) { try { fileIn = new BufferedReader(new FileReader(filename)); if(filename.substring(filename.length()-3,filename.length()).equals(".in")) outFilename = filename.substring(0, filename.length()-3) + ".out"; } catch (IOException e) { System.out.println("Cannot open file: " + e.getMessage()); } } public void closeFile() { try { if(fileIn!=null) fileIn.close(); } catch (IOException e) { System.out.println("Cannot close file: " + e.getMessage()); } } public void setOutFilename(String filename) { this.outFilename = filename; } public int readNumber(int defaultValue) { int result = defaultValue; try { result = Integer.parseInt(fileIn.readLine()); } catch (Exception e) { System.out.println("Cannot read a number from file: " + e.getMessage()); } return result; } public void prepareAnswers() { answer = new String[numOfTestCase]; } public abstract void readProblem() throws IOException; public abstract void algorithm(int idx); public void printAnswer() { try { BufferedWriter fileOut = new BufferedWriter(new FileWriter(this.outFilename)); for(int i=0;i<numOfTestCase;++i) { String output = "Case #" + (i+1) + ": " + answer[i] + "\n"; System.out.print(output); fileOut.write(output); } fileOut.close(); } catch (IOException e) { System.out.println("Exception to print answers: " + e.getMessage()); } } public void solve(String filename) { openFile(filename); numOfTestCase = readNumber(-1); prepareAnswers(); for(int i=0;i<numOfTestCase;++i) { try { readProblem(); algorithm(i); } catch (IOException e) { System.out.println("Exception at reading problem #" + (i+1) + ": " + e.getMessage()); } } printAnswer(); closeFile(); } }
B21968
B20098
0
import java.util.*; import java.io.*; public class recycled_numbers { public static void main(String[]a) throws Exception{ Scanner f = new Scanner(new File(a[0])); int result=0; int A,B; String n,m; HashSet<String> s=new HashSet<String>(); int T=f.nextInt(); //T total case count for (int t=1; t<=T;t++){//for each case t s.clear(); result=0; //reset A=f.nextInt();B=f.nextInt(); //get values for next case if (A==B)result=0;//remove case not meeting problem limits else{ for(int i=A;i<=B;i++){//for each int in range n=Integer.toString(i); m=new String(n); //System.out.println(n); for (int j=1;j<n.length();j++){//move each digit to the front & test m = m.substring(m.length()-1)+m.substring(0,m.length()-1); if(m.matches("^0+[\\d]+")!=true && Integer.parseInt(m)<=B && Integer.parseInt(n)<Integer.parseInt(m)){ s.add(new String(n+","+m)); //result++; //System.out.println(" matched: "+m); } } } result = s.size(); } //display output System.out.println("Case #" + t + ": " + result); } } }
package codejam2012; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class ProblemC { public static void main(String[] args) throws FileNotFoundException, IOException { int T, n, A, B, recycle, lastN = 0, lastM = 1; ProblemC c = new ProblemC(); Scanner sc = new Scanner(new FileReader("C-large.in.txt")); PrintWriter pw = new PrintWriter(new FileWriter("outputPC.txt")); T = sc.nextInt(); for(int i = 0; i < T; i++){ A = sc.nextInt(); B = sc.nextInt(); recycle = 0; for(n = A; n < B; n++){ int digits = Integer.toString(n).length(); if(digits > 1){ char[] num = new char[digits]; for(int j = 0; j < digits; j++){ num[j] = Integer.toString(n).charAt(j); } for(int j = 0; j < digits - 1; j++){ c.rotateNum(num); if(Integer.parseInt(c.charToString(num)) <= B && Integer.parseInt(c.charToString(num)) > n){ if(lastN == n && lastM == Integer.parseInt(c.charToString(num))){ recycle--; } lastN = n; lastM = Integer.parseInt(c.charToString(num)); recycle++; } } } } pw.print("Case #" + (i + 1) + ": "); pw.println(recycle); } pw.flush(); pw.close(); sc.close(); } public String charToString(char[] c){ String result = ""; for(int i = 0; i < c.length; i++){ result += c[i]; } return result; } public void rotateNum(char[] c){ char aux = c[c.length - 1]; for(int i = c.length - 1; i > 0; i--){ c[i] = c[i - 1]; } c[0] = aux; } }
A10793
A11860
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.FileReader; import java.util.ArrayList; public class Run2 { public static void main(String[] args) { String path = "files/B-small-attempt1.in"; int T = 0; ArrayList<ArrayList<Integer>> googlers = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> surprisings = new ArrayList<Integer>(); ArrayList<Integer> leasts = new ArrayList<Integer>(); try { boolean isFirstLine = true; FileReader FR = new FileReader(path); BufferedReader BR = new BufferedReader(FR); String str = ""; while((str=BR.readLine())!=null) { if (isFirstLine) { T = Integer.parseInt(str); isFirstLine = false; } else { String[] temp = str.split(" "); surprisings.add(Integer.parseInt(temp[1])); leasts.add(Integer.parseInt(temp[2])); ArrayList<Integer> score = new ArrayList<Integer>(); for(int i = 3; i < temp.length; i++) { score.add(Integer.parseInt(temp[i])); } googlers.add(score); } } } catch (Exception e) { e.printStackTrace(); } for(int i = 0; i < T; i++) { ArrayList<Integer> googler = googlers.get(i); int surprising = surprisings.get(i); int least = leasts.get(i); int number = 0; int dontSurprising = 0; int isSurprising = 0; for(int j = 0; j < googler.size(); j++) { int score = googler.get(j); int surprisingBounds = least+(least-2)*2; int dontSurprisingBounds = least+(least-1)*2; if (least < 2) { surprisingBounds = least; dontSurprisingBounds = least; } if (score >= surprisingBounds && score < dontSurprisingBounds) { isSurprising++; } else if (score >= dontSurprisingBounds) { dontSurprising++; } } number = dontSurprising+isSurprising+((surprising-isSurprising)>=0?0:(surprising-isSurprising)); System.out.println("Case #"+(i+1)+": "+number); } } }
A12113
A12268
0
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class B { static int[][] memo; static int[] nums; static int p; public static void main(String[] args)throws IOException { Scanner br=new Scanner(new File("B-small-attempt0.in")); PrintWriter out=new PrintWriter(new File("b.out")); int cases=br.nextInt(); for(int c=1;c<=cases;c++) { int n=br.nextInt(),s=br.nextInt(); p=br.nextInt(); nums=new int[n]; for(int i=0;i<n;i++) nums[i]=br.nextInt(); memo=new int[n][s+1]; for(int[] a:memo) Arrays.fill(a,-1); out.printf("Case #%d: %d\n",c,go(0,s)); } out.close(); } public static int go(int index,int s) { if(index>=nums.length) return 0; if(memo[index][s]!=-1) return memo[index][s]; int best=0; for(int i=0;i<=10;i++) { int max=i; for(int j=0;j<=10;j++) { if(Math.abs(i-j)>2) continue; max=Math.max(i,j); thisone: for(int k=0;k<=10;k++) { int ret=0; if(Math.abs(i-k)>2||Math.abs(j-k)>2) continue; max=Math.max(max,k); int count=0; if(Math.abs(i-k)==2) count++; if(Math.abs(i-j)==2) count++; if(Math.abs(j-k)==2) count++; if(i+j+k==nums[index]) { boolean surp=(count>=1); if(surp&&s>0) { if(max>=p) ret++; ret+=go(index+1,s-1); } else if(!surp) { if(max>=p) ret++; ret+=go(index+1,s); } best=Math.max(best,ret); } else if(i+j+k>nums[index]) break thisone; } } } return memo[index][s]=best; } }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; public class Dancing { /** * @param args */ public static void main(String[] args) { try { System.setIn(new FileInputStream("../B-small-attempt0.in")); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(0); } InputStreamReader inp = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(inp); String line = ""; int inputs = 0; try{ line = br.readLine(); inputs = Integer.parseInt( line ); } catch(Exception x){ System.err.println(x); System.exit(1); } String[] stringdata = {}; for(int i=0; i < inputs; i++){ try{ line = br.readLine(); stringdata = line.split(" "); } catch(Exception x){ System.err.println(x); System.exit(1); } int[] data = new int[stringdata.length]; for(int j=0; j < stringdata.length; j++){ data[j] = Integer.parseInt(stringdata[j]); } int n = data[0]; int s = data[1]; int p = data[2]; int count = 0; for(int k=3; k < data.length; k++){ int score = data[k]; //double x = Math.ceil(score / 3.0); if(score >= p && score >= (p*3)-2){ count++; } else if(score >= p && score >= (p*3)-4 && s > 0){ s--; count++; } } System.out.println("Case #" + (i+1) + ": " + count); } } }
B10702
B10317
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.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; public class Recycled { private File file = new File("D:\\Sources\\GoogleCodeJam\\files\\C-small-attempt0.in"); private File outFile = new File("D:\\Sources\\GoogleCodeJam\\files\\result.out"); private Long[] results; private Integer solved = 0; public void readData() { boolean first = true; Scanner scanner; try { scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); Scanner scan = new Scanner(line); if (first) { results = new Long[scan.nextInt()]; first = false; } else { long min = scan.nextLong(); long max = scan.nextLong(); results[solved] = solveProblem(min, max); solved++; } } printResult(); } catch (Exception e) { e.printStackTrace(); } } private Long solveProblem(long min, long max) { long sum = 0; TreeSet<Double> res = new TreeSet<Double>(); for (long val = min; val <= max; val++) { res.clear(); String number = String.valueOf(val); int len = number.length(); for (int i = 1; i < number.length(); i++) { String newVal = number.substring(i, len) + number.substring(0, i); long recycled = Long.valueOf(newVal); if(recycled > val && recycled <= max && res.add(val + recycled * Math.pow(10, len))) { sum++; } } } return sum; } private void printResult() { try { FileWriter fstream = new FileWriter(outFile); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < results.length; i++) { out.write("Case #" + (i + 1) + ": " + results[i]); out.newLine(); } out.close(); } catch (Exception e) { e.printStackTrace(); } } }
A12113
A12627
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 q2; import java.util.Scanner; public class DWG { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int _t = 0; _t < t; _t++) { int n = sc.nextInt(); int s = sc.nextInt(); int p = sc.nextInt(); int floor, sfloor; if (p == 0){ floor = 0; } else { floor = p+(2*(p-1)); } if (p == 1){ sfloor = 1; } else { sfloor = p+(2*(p-2)); } int y = 0; for (int _n=0; _n<n; _n++){ int ti = sc.nextInt(); if (ti >= floor) { y++; } else if (ti >= sfloor && s > 0 && sfloor >= 0) { y++; s--; } } System.out.printf("Case #%d: %d\n",_t+1,y); } } }
B12082
B12041
0
package jp.funnything.competition.util; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import org.apache.commons.io.IOUtils; public class QuestionReader { private final BufferedReader _reader; public QuestionReader( final File input ) { try { _reader = new BufferedReader( new FileReader( input ) ); } catch ( final FileNotFoundException e ) { throw new RuntimeException( e ); } } public void close() { IOUtils.closeQuietly( _reader ); } public String read() { try { return _reader.readLine(); } catch ( final IOException e ) { throw new RuntimeException( e ); } } public BigDecimal[] readBigDecimals() { return readBigDecimals( " " ); } public BigDecimal[] readBigDecimals( final String separator ) { final String[] tokens = readTokens( separator ); final BigDecimal[] values = new BigDecimal[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = new BigDecimal( tokens[ index ] ); } return values; } public BigInteger[] readBigInts() { return readBigInts( " " ); } public BigInteger[] readBigInts( final String separator ) { final String[] tokens = readTokens( separator ); final BigInteger[] values = new BigInteger[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = new BigInteger( tokens[ index ] ); } return values; } public int readInt() { final int[] values = readInts(); if ( values.length != 1 ) { throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" ); } return values[ 0 ]; } public int[] readInts() { return readInts( " " ); } public int[] readInts( final String separator ) { final String[] tokens = readTokens( separator ); final int[] values = new int[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = Integer.parseInt( tokens[ index ] ); } return values; } public long readLong() { final long[] values = readLongs(); if ( values.length != 1 ) { throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" ); } return values[ 0 ]; } public long[] readLongs() { return readLongs( " " ); } public long[] readLongs( final String separator ) { final String[] tokens = readTokens( separator ); final long[] values = new long[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = Long.parseLong( tokens[ index ] ); } return values; } public String[] readTokens() { return readTokens( " " ); } public String[] readTokens( final String separator ) { return read().split( separator ); } }
import java.io.*; import java.util.Set; import java.util.HashSet; public class recycled { public static int A,B; public static int[] t = {1,10,100,1000,10000,100000,1000000}; public static int solve(){ if(B<10) return 0; int DB=0,kit,m,n; int lg = 0; while(lg < 6 && A >= t[lg+1]) lg++; //System.out.println(A+" "+lg); for(n = A; n <B; n++){ kit = 1; Set H = new HashSet(); while(t[kit] < n){ m = t[lg-kit+1]*(n%t[kit])+(n/t[kit]); //System.out.println("testing >>> "+n+" - "+m); if( n < m && m <= B && (n%t[kit])*10>=t[kit] && !H.contains(m)) { DB++; H.add(m); //System.out.println("OK >>> "+n+" - "+m+" DB= "+DB); } kit++; } } return DB; } public static void main (String args[]) throws IOException{ BufferedReader be = new BufferedReader(new FileReader("C-small.in")); int T = Integer.parseInt(be.readLine()); for(int i=1; i<=T; i++){ String s = be.readLine(); A = Integer.parseInt(s.split(" ")[0]); B = Integer.parseInt(s.split(" ")[1]); System.out.println("Case #"+i+": "+solve()); } be.close(); } }
A11277
A12270
0
package googlers; import java.util.Scanner; import java.util.PriorityQueue; import java.util.Comparator; public class Googlers { public static void main(String[] args) { int n,s,p,count=0,t; Scanner sin=new Scanner(System.in); t=Integer.parseInt(sin.nextLine()); int result[]=new int[t]; int j=0; if(t>=1 && t<=100) { for (int k = 0; k < t; k++) { count=0; String ip = sin.nextLine(); String[]tokens=ip.split(" "); n=Integer.parseInt(tokens[0]); s=Integer.parseInt(tokens[1]); p=Integer.parseInt(tokens[2]); if( (s>=0 && s<=n) && (p>=0 && p<=10) ) { int[] total=new int[n]; for (int i = 0; i < n; i++) { total[i] = Integer.parseInt(tokens[i+3]); } Comparator comparator=new PointComparator(); PriorityQueue pq=new PriorityQueue<Point>(1, comparator); for (int i = 0; i < n; i++) { int x=total[i]/3; int r=total[i]%3; if(x>=p) count++; else if(x<(p-2)) continue; else { //System.out.println("enter "+x+" "+(p-2)); if(p-x==1) { Point temp=new Point(); temp.q=x; temp.r=r; pq.add(temp); } else // p-x=2 { if(r==0) continue; else { Point temp=new Point(); temp.q=x; temp.r=r; pq.add(temp); } } } //System.out.println("hi "+pq.size()); } while(pq.size()!=0) { Point temp=(Point)pq.remove(); if(p-temp.q==1 && temp.q!=0) { if(temp.r>=1) count++; else { if(s!=0) { s--; count++; } } } else if(p-temp.q==2) { if(s!=0 && (temp.q+temp.r)>=p) { s--; count++; } } } //System.out.println(p); result[j++]=count; } } for (int i = 0; i < t; i++) { System.out.println("Case #"+(i+1)+": "+result[i]); } } } /*Point x=new Point(); x.q=8; Point y=new Point(); y.q=6; Point z=new Point(); z.q=7; pq.add(x); pq.add(y); pq.add(z); */ } class PointComparator implements Comparator<Point> { @Override public int compare(Point x, Point y) { // Assume neither string is null. Real code should // probably be more robust if (x.q < y.q) { return 1; } if (x.q > y.q) { return -1; } return 0; } } class Point { int q,r; public int getQ() { return q; } public void setQ(int q) { this.q = q; } public int getR() { return r; } public void setR(int r) { this.r = r; } }
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; public class Solution { static final boolean DBG = false; // x x x s= 3x // x x x+1 s= 3x +1 // x x x-1 s= 3x -1 // x x+1 x+1 s= 3x +2 // x x-1 x-1 s= 3x-2 public static void main(String[] args) { AllNormal allNormal = new AllNormal(); AllSurprising allSurprising = new AllSurprising(); Scanner sc = new Scanner(System.in); long dStart = System.currentTimeMillis(); StringBuilder sbout = new StringBuilder(); int T = sc.nextInt(); for (int i = 1; i <= T; i++) { Task one = new Task(sc, allNormal, allSurprising); int res = one.getSolution(); sbout.append("Case #"); sbout.append(i); sbout.append(": "); sbout.append(res); sbout.append('\n'); } if (DBG) { sbout.append("time :"); sbout.append(System.currentTimeMillis() - dStart); } System.out.print(sbout.toString()); } static class Task { int N; // number of people int S; // Surprising Triplets; int p; // ? of N with best result >= p ArrayList<OnePerson> persons = new ArrayList<OnePerson>(); String original = ""; public Task(Scanner sc, AllNormal allNormal, AllSurprising allSurprising) { N = sc.nextInt(); S = sc.nextInt(); p = sc.nextInt(); original = N + " " + S + " " + p + ", "; for (int i = 0; i < N; i++) { OnePerson one = new OnePerson(sc.nextInt()); one.setHowItCan(allNormal, allSurprising, p); persons.add(one); original += " " + one.sum; } } int getSolution() { int canNormal = 0; int canWithSurprising = 0; for (OnePerson one : persons) { if (one.canHaveWithNormal) { canNormal++; } else { if (one.canWithSurprising) canWithSurprising++; } } return canNormal + Math.min(canWithSurprising, S); } } static class OnePerson { int sum = 0; boolean canHaveWithNormal = false; // can have best >= p without // surprising rating boolean canWithSurprising = false; public OnePerson(int sum) { this.sum = sum; } void setHowItCan(AllNormal allNormal, AllSurprising allSurprising, int p) { canHaveWithNormal = (allNormal.all.get(this.sum).best >= p); canWithSurprising = allSurprising.canBeSurprisingWithBestGreater( this.sum, p); } } static class AllNormal { HashMap<Integer, NormalRating> all = new HashMap<Integer, Solution.NormalRating>(); public AllNormal() { for (int i = 0; i <= 10; i++) { addOne(new NormalRating(3 * i, i, i)); addOne(new NormalRating(3 * i + 1, i + 1, i)); addOne(new NormalRating(3 * i - 1, i, i - 1)); addOne(new NormalRating(3 * i + 2, i + 1, i)); addOne(new NormalRating(3 * i - 2, i, i - 1)); } } void addOne(NormalRating one) { if (one.isValid() && !all.containsKey(one.sum)) { all.put(one.sum, one); } } void printAll() { ArrayList<NormalRating> vals = new ArrayList<Solution.NormalRating>(); vals.addAll(all.values()); Collections.sort(vals); for (NormalRating one : vals) { one.printLn(); } } } static class NormalRating implements Comparable<NormalRating> { int sum = 0; int best = 0; int min = 0; public NormalRating(int sum, int best, int min) { this.sum = sum; this.best = best; this.min = min; } boolean isValid() { return (sum >= 0) && (best >= 0) && (min >= 0) && (best <= 10); } void printLn() { System.out.println("s: " + sum + " b: " + best + " m: " + min); } @Override public int compareTo(NormalRating other) { return (new Integer(sum)).compareTo(new Integer(other.sum)); } } static class AllSurprising { ArrayList<SurprisingRating> items = new ArrayList<Solution.SurprisingRating>(); public AllSurprising() { for (int i = 0; i <= 8; i++) { addOne(new SurprisingRating(3 * i + 2, i + 2)); addOne(new SurprisingRating(3 * i + 3, i + 2)); addOne(new SurprisingRating(3 * i + 4, i + 2)); } } void addOne(SurprisingRating one) { items.add(one); } boolean canBeSurprisingWithBestGreater(int withsum, int p) { for (SurprisingRating rating : items) { if (rating.sum == withsum) { return (rating.best >= p); } } return false; } } // x x+2 x = 3x +2 // x x+2 x+1 = 3x +3 // x x+2 x+2 = 3x +4 static class SurprisingRating { int sum = 0; int best = 0; public SurprisingRating(int sum, int best) { this.sum = sum; this.best = best; } } }
B20856
B21789
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.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class RecycledNumbers { public static void main(String[] args) { try { File dataFile = new File(args[0]); File outputFile = new File(args[1]); if (dataFile.exists()) { BufferedReader reader = new BufferedReader(new FileReader(dataFile)); FileWriter writer = new FileWriter(outputFile, false); int maxIteration = Integer.valueOf(reader.readLine()); int currentLine = 0; String line; while ((line = reader.readLine()) != null && currentLine < maxIteration) { int result = 0; HashMap<Integer, List<Integer>> recycled = new HashMap<Integer, List<Integer>>(); String[] AB = line.split(" "); for (int min = Integer.valueOf(AB[0]), max = Integer.valueOf(AB[1]), i = min ; i < max ; i++) { String currVal = String.valueOf(i); String rotatedVal = currVal; for (int j = 0; j < currVal.length() - 1; j++){ rotatedVal = rotateRight(rotatedVal); if (String.valueOf(Integer.valueOf(rotatedVal)).length() != String.valueOf(Integer.valueOf(currVal)).length()) continue; int iVal = Integer.valueOf(rotatedVal); if (iVal >= min && iVal <= max && iVal != i) { int key, val; if (i < iVal) { key = i; val = iVal; } else { key = iVal; val = i; } if (recycled.containsKey(key)) { List<Integer> allVal = recycled.get(key); if (allVal != null) { if (!allVal.contains(val)) { allVal.add(val); result++; } } } else { List<Integer> addedVal = new ArrayList<Integer>(); addedVal.add(val); recycled.put(key, addedVal); result++; } } } } writer.write("Case #" + ++currentLine + ": " + result + "\n"); } reader.close(); writer.close(); } } catch (Exception exc) { exc.printStackTrace(); } } private static String rotateRight(String sInput) { int len = sInput.length(); char[] outstring = sInput.toCharArray(); char ch = outstring[len - 1]; for (int j = len -1; j > 0; j--) { outstring[j] = outstring[j - 1]; } outstring[0] = ch; return String.valueOf(outstring); } }
B12669
B10582
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package year_2012.qualification; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; /** * * @author paul * @date 14 Apr 2012 */ public class QuestionC { private static Set<Integer> getCycle(int x) { String s = Integer.toString(x); Set<Integer> set = new HashSet<Integer>(); set.add(x); for (int c = 1; c < s.length(); c++) { String t = s.substring(c).concat(s.substring(0, c)); set.add(Integer.parseInt(t)); } return set; } private static Set<Integer> mask(Set<Integer> set, int a, int b) { Set<Integer> result = new HashSet<Integer>(); for (int x : set) { if (x >= a && x <= b) { result.add(x); } } return result; } public static void main(String[] args) throws FileNotFoundException, IOException { String question = "C"; // String name = "large"; String name = "small-attempt0"; // String name = "test"; String filename = String.format("%s-%s", question, name); BufferedReader input = new BufferedReader( new FileReader(String.format("/home/paul/Documents/code-jam/2012/qualification/%s.in", filename))); String firstLine = input.readLine(); PrintWriter pw = new PrintWriter(new File( String.format("/home/paul/Documents/code-jam/2012/qualification/%s.out", filename))); int T = Integer.parseInt(firstLine); // Loop through test cases. for (int i = 0; i < T; i++) { // Read data. String[] tokens = input.readLine().split(" "); // int N = Integer.parseInt(input.readLine()); int A = Integer.parseInt(tokens[0]); int B = Integer.parseInt(tokens[1]); // System.out.format("%d, %d\n", A, B); boolean[] used = new boolean[B+1]; int total = 0; for (int n = A; n <= B; n++) { if (!used[n]) { Set<Integer> set = mask(getCycle(n), A, B); int k = set.size(); total += (k * (k-1))/2; for (int m : set) { used[m] = true; } } } pw.format("Case #%d: %d\n", i + 1, total); } pw.close(); } }
package codeJam; import java.util.ArrayList; import utilities.FileReadWrite; public class RecycledNumbers { public static ArrayList<int[]> myDic; public static void main(String[] args) { FileReadWrite myFile = new FileReadWrite(); String outputString =""; ArrayList<String> lines = myFile.readFile(); int N = Integer.parseInt(lines.get(0)); int A, B, counter; for (int i = 1; i < lines.size(); i++) { counter=0; String[] w= lines.get(i).split(" "); A = Integer.parseInt(w[0]); B = Integer.parseInt(w[1]); System.out.println("A="+A+" B="+B); String tempLine = "Case #"+(i)+": "; myDic = new ArrayList<int[]>(); for (int j = A; j <= B; j++) { if(!RecycledNumbers.hasSameDigits(j)) { int[] h = RecycledNumbers.getOtherNumbers(j); for (int k = 0; k < h.length; k++) { if(h[k]<=B && h[k]>=A && j<h[k]) { // System.out.println(j + " " + h[k]); int[] g = new int[2]; g[0]=j; g[1]=h[k]; if(!RecycledNumbers.exist(g)) { myDic.add(g); counter++; } } } } } System.out.println("counter="+counter); System.out.println("myDic.size()="+myDic.size()); System.out.println(); outputString = outputString + tempLine + counter + "\n"; } System.out.println(outputString); myFile.writeFile(outputString); } public static boolean hasSameDigits(int x) { String str = Integer.toString(x); if(str.length()==1) return true; if(str.length()>1) { int c = 0; int d = 0; for (int i = 1; i < str.length(); i++) { if(str.charAt(i)=='0') c++; if(str.charAt(i)==str.charAt(0)) d++; } if(c==str.length()-1) { return true; } else { if(d==str.length()-1) return true; else return false; } } return true; } public static int[] getOtherNumbers (int x) { // System.out.println("x="+x); // System.out.println(); String str = Integer.toString(x); int length = str.length(); int[] y = new int[length-1]; int counter = 0; String temp1, temp2, temp3; for (int i = 0; i < str.length(); i++) { counter = i+1; // System.out.println("counter="+counter); if(counter==str.length()) continue; temp1 = str.substring(counter); // System.out.println("temp1="+temp1); temp2 = str.substring(0, counter); // System.out.println("temp2="+temp2); temp3 = temp1 + temp2; // System.out.println("temp3="+temp3); if(temp3.charAt(0)=='0') temp3=RecycledNumbers.excludeLeadingzeros(temp3); y[i]=Integer.parseInt(temp3); } return y; } public static String excludeLeadingzeros (String str) { for (int i = 0; i < str.length(); i++) if(str.charAt(i)!='0') { str = str.substring(i); break; } return str; } public static boolean exist (int[] g) { for (int i = 0; i < myDic.size(); i++) { int[] j = myDic.get(i); if(j[0]==g[0] && j[1]==g[1]) return true; } return false; } }
B11318
B13027
0
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); int casos=1, a, b, n, m, cont; while(t!=0){ a=sc.nextInt(); b=sc.nextInt(); if(a>b){ int aux=a; a=b; b=aux; } System.out.printf("Case #%d: ",casos++); if(a==b){ System.out.printf("%d\n",0); }else{ cont=0; for(n=a;n<b;n++){ for(m=n+1;m<=b;m++){ if(isRecycled(n,m)) cont++; } } System.out.printf("%d\n",cont); } t--; } } public static boolean isRecycled(int n1, int n2){ String s1, s2, aux; s1 = String.valueOf( n1 ); s2 = String.valueOf( n2 ); boolean r = false; for(int i=0;i<s1.length();i++){ aux=""; aux=s1.substring(i,s1.length())+s1.substring(0,i); // System.out.println(aux); if(aux.equals(s2)){ r=true; break; } } return r; } }
import java.io.*; class qu3{ public static void main(String arg[])throws Exception { File f=new File("/Users/rishabhsonthalia/Downloads/C-small-attempt0.in.txt"); FileInputStream fin=new FileInputStream(f); File fo=new File("opt.txt"); FileOutputStream fout=new FileOutputStream(fo); BufferedWriter bwr=new BufferedWriter(new OutputStreamWriter(fout)); BufferedReader br=new BufferedReader(new InputStreamReader(fin)); String g=""; long len=Long.parseLong(br.readLine()); long ca=1; long a,b; String e=""; long n,m; while(--len >=0) { long count=0; g=br.readLine(); a=Long.parseLong(g.substring(0,g.indexOf(" ")) ); b=Long.parseLong( g.substring(g.indexOf(" ")+1,g.length())) ; for(long i=a;i<=b;i++) { n=i; for(long j=0 ; j<(i+"").length()-1; j++) { m=shift(n); if(m>-1 & i<m & m <=b) {count++; } n=m; } } bwr.write("Case #"+(ca++)+": "+count); bwr.newLine(); bwr.flush(); }//while } public static long shift(long x) { String s; if(x<0) s="0"+(-x)+""; else s=x+""; String ss=s.charAt(s.length()-1)+s.substring(0,s.length()-1); if(x%10==0) return(-Long.parseLong(ss)); return (Long.parseLong(ss)); } }
B12941
B12978
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.FileWriter; import java.io.IOException; public class OutputPrinter { public OutputPrinter() { try { m_writer = new FileWriter("C:/AHK/output.txt"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } FileWriter m_writer; int m_case = 1; public void print(String result) { try { m_writer.write("Case #"+ (m_case++)+": " + result + "\n"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
A22360
A20335
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 codejam; import java.util.*; import java.io.*; public class DancingWithTheGooglers { 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 N = Integer.parseInt(parts[0]); int S = Integer.parseInt(parts[1]); int p = Integer.parseInt(parts[2]); int[] scores = new int[N]; for (int i = 0; i < N; ++i) scores[i] = Integer.parseInt(parts[3 + i]); Arrays.sort(scores); int cnt = 0; for (int i = N - 1; i >= N - S; --i) { int mod = scores[i] % 3; int score = scores[i] / 3; if (mod == 1 || mod == 2) ++score; if (scores[i] > 1 && (mod == 0 || mod == 2)) ++score; score = Math.min(score, 10); if (score >= p) ++cnt; //System.out.println(score); } out.println("Case #" + t + ": " + cnt); } in.close(); out.close(); System.exit(0); } }
A10793
A12675
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 y2012; import java.io.File; import java.io.PrintWriter; import java.util.Scanner; public class QR2 { public static void main(String[] args) throws Exception { Scanner inputFile=new Scanner(new File(args[0])); PrintWriter outputFile=new PrintWriter(new File(args[1])); int t=Integer.parseInt(inputFile.nextLine()); for(int i=0;i<t;i++){ int result = 0; String[] aCase = inputFile.nextLine().split(" "); int numGooglers = Integer.parseInt(aCase[0]); int numSurprising = Integer.parseInt(aCase[1]); int p = Integer.parseInt(aCase[2]); int[][] scoreboard = new int[numGooglers][5]; for(int j=0; j<numGooglers; j++) { scoreboard[j][0] = Integer.parseInt(aCase[3+j]); } for(int j=0; j<numGooglers;j++) { int avg = scoreboard[j][0]/3; int mod = scoreboard[j][0]%3; scoreboard[j][1] = mod; switch(mod) { case 0: scoreboard[j][2] = avg; scoreboard[j][3] = avg; scoreboard[j][4] = avg; break; case 1: scoreboard[j][2] = avg+1; scoreboard[j][3] = avg; scoreboard[j][4] = avg; break; case 2: scoreboard[j][2] = avg+1; scoreboard[j][3] = avg+1; scoreboard[j][4] = avg; break; } } for(int j=0; j<numGooglers;j++) { if(scoreboard[j][2] >= p) { result = result + 1; } else if( scoreboard[j][2] == p-1 //diff with 1 score && numSurprising > 0 //still has suprise quota && scoreboard[j][1] != 1 //suprise-able? && (scoreboard[j][0] >= 3 && scoreboard[j][0] <= 27) //suprise-able? ) { result = result + 1; numSurprising = numSurprising - 1; } } outputFile.println("Case #"+(i+1)+": " + result); System.out.println("Case #"+(i+1)+": " + result); } inputFile.close(); outputFile.close(); } }
B22190
B21675
0
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class Recycled { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for (int i = 0; i < t; i++) { String[] str = br.readLine().split(" "); int a = Integer.parseInt(str[0]); int b = Integer.parseInt(str[1]); System.out.println("Case #" + (i + 1) + ": " + find(a, b)); } } catch (IOException e) { e.printStackTrace(); } } private static int find(int a, int b) { HashSet<Long> used = new HashSet<Long>(); int digits = String.valueOf(a).length(); if (digits == 1) return 0; for (int i = a; i <= b; i++) { int s = 10; int m = (int) Math.pow(10, digits-1); for (int j = 0; j < digits-1; j++) { int r = i % s; if (r < s/10) continue; int q = i / s; int rn = r * m + q; s *= 10; m /= 10; if (i != rn && rn >= a && rn <= b) { long pp; if (rn < i) pp = (long)rn << 30 | i; else pp = (long)i << 30 | rn; if (!used.contains(pp)) { used.add(pp); } } } } return used.size(); } }
import java.io.*; import java.util.*; public class C{ public static void main(String[] args){ try{ String inputFile = "C-large.in"; String outputFile = "C-large.out"; Scanner sc = new Scanner(new File(inputFile)); FileWriter fwStream = new FileWriter( outputFile ); BufferedWriter bwStream = new BufferedWriter( fwStream ); PrintWriter pwStream = new PrintWriter( bwStream ); int numCase = sc.nextInt(); for(int i = 0; i < numCase; i++){ int answer = 0; int min = sc.nextInt(); int max = sc.nextInt(); for(int j = min; j <= max; j++){ String a = String.valueOf(j); int length = a.length(); int temp = ((j % 10) * (int)(Math.pow(10,length-1))) + (j /10); while(temp != j){ if(temp >= min && temp <= max && temp > j){ answer++; } temp = ((temp % 10) * (int)(Math.pow(10,length-1))) + (temp /10); } } pwStream.print("Case #"+(i+1)+ ": "); pwStream.print(answer); pwStream.println(); } pwStream.close(); sc.close(); } catch(Exception e){e.printStackTrace();} } }
A12460
A13151
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.*; import java.io.*; public class dancing { private static Reader in; private static PrintWriter out; public static final String NAME = "B-small-attempt1"; private static void main2() throws IOException { int N = in.nextInt(), S = in.nextInt(), p = in.nextInt(); int [] arr = new int [N + 1]; for (int i = 1; i <= N; i++) arr [i] = in.nextInt(); int [][] dp = new int [N + 1][S + 1]; dp [0][0] = 0; for (int i = 1; i <= N; i++) { int curscore = (arr [i] + 2) / 3, nscore = (arr [i] + 4) / 3; if (arr [i] == 0) curscore = nscore = 0; dp [i][0] = dp [i - 1][0]; if (curscore >= p) dp [i][0] = dp [i - 1][0] + 1; for (int j = 1; j <= S; j++) { dp [i][j] = Math.max (dp [i - 1][j - 1], dp [i - 1][j]); if (curscore >= p) dp [i][j] = Math.max (dp [i][j], dp [i - 1][j] + 1); if (nscore >= p) dp [i][j] = Math.max (dp [i][j], dp [i - 1][j - 1] + 1); } } out.println (dp [N][S]); } public static void main(String[] args) throws IOException { in = new Reader(NAME + ".in"); out = new PrintWriter(new BufferedWriter(new FileWriter(NAME + ".out"))); int numCases = in.nextInt(); for (int test = 1; test <= numCases; test++) { out.print("Case #" + test + ": "); main2(); } out.close(); System.exit(0); } /** Faster input **/ static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1024]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; else return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; else return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); } if (neg) return -ret; else return ret; } public char nextChar() throws IOException { char ret = 0; byte c = read(); while (c <= ' ') c = read(); return (char) c; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
B20566
B20219
0
import java.util.Scanner; import java.io.*; import java.lang.Math; public class C{ public static int recycle(String str){ String[] numbers = str.split(" "); int min = Integer.parseInt(numbers[0]); int max = Integer.parseInt(numbers[1]); int ret = 0; for(int i = min; i < max; i++){ String num = i + ""; int len = num.length(); int k = i; for(int j = 1; j < len; j++){ k = (k/10) + (int)java.lang.Math.pow(10.0,(double)(len-1))*(k%10); if (k > i && k <= max) ret++; else if(k == i) break; } } return ret; } public static void main(String[] args){ Scanner sc = null; String next; int out; try{ sc = new Scanner(new File("C-large.in")); int cases = Integer.parseInt(sc.nextLine()); int current = 0; FileWriter fs = new FileWriter("output.txt"); BufferedWriter buff = new BufferedWriter(fs); while(current < cases){ next = sc.nextLine(); current++; out = recycle(next); buff.write("Case #" + current + ": " + out + "\n"); } buff.close(); } catch(Exception ex){} } }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class C { static int[] a = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000 }; static class Pair implements Comparable<Pair> { int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } public int hashCode() { return a | b << 22; } public boolean equals(Object o) { Pair p = (Pair) o; return p.a == a && p.b == b; } @Override public int compareTo(Pair o) { if (a != o.a) return a - o.a; if (b != o.b) return b - o.b; return 0; } } public static int digitCount(int i) { int c = 0; while (i != 0) { c++; i /= 10; } return c; } public static Pair getMin(int i) { int nd = digitCount(i); int[] arr = new int[nd]; int l = i; for (int j = 0; j < arr.length; j++) { arr[j] = l; l = l % 10 * a[nd - 1] + l / 10; } Arrays.sort(arr); return new Pair(arr[0], nd); } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream("C.in"))); PrintWriter out = new PrintWriter("C.out"); int tc = Integer.parseInt(in.readLine()); for (int cc = 1; cc <= tc; cc++) { StringTokenizer strtok = new StringTokenizer(in.readLine(), " "); int a = Integer.parseInt(strtok.nextToken()); int b = Integer.parseInt(strtok.nextToken()); int[][] count = new int[digitCount(b) + 1][b + 1]; long res = 0; for (int i = a; i <= b; i++) { Pair p = getMin(i); res += count[p.b][p.a]; count[p.b][p.a]++; } out.printf("Case #%d: %d\n", cc, res); } out.close(); } }
A10568
A12712
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 qualifiers; import java.io.*; import java.util.*; import java.util.concurrent.*; public class QualifierB { class Task implements Runnable { private int num; private String line; public Task(int num, String line) { this.num = num; this.line = line; } @Override public void run() { String result = null; // BEGIN RESULT COMPUTATION // ------------------------------------------------------------ String[] split_line = line.split(" "); int num_googlers = Integer.parseInt(split_line[0]); int num_surprising = Integer.parseInt(split_line[1]); int best_points = Integer.parseInt(split_line[2]); int count = 0; for (int j = 0; j < num_googlers; ++j) { int total_points = Integer.parseInt(split_line[j + 3]); total_points -= best_points; if (total_points < 0) { continue; } if (best_points * 2 - 2 <= total_points) { ++count; continue; } if (num_surprising > 0) { if ((best_points - 2) * 2 <= total_points && total_points <= (best_points + 2) * 2) { ++count; --num_surprising; } } } result = String.valueOf(count); // END RESULT COMPUTATION // ------------------------------------------------------------ System.out.println(result); reportResult(num, result); } } public static final int NUM_THREADS = 1; private String file_name; private ArrayList<String> results; public QualifierB(String file_name) { this.file_name = file_name; } public ArrayList<String> calculate() throws IOException, InterruptedException { results = new ArrayList<String>(); ThreadPoolExecutor tpe = new ThreadPoolExecutor(NUM_THREADS, NUM_THREADS, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); FileReader fr = new FileReader(file_name); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); System.out.println("Header: " + line); String[] ints = line.split(" "); // BEGIN HEADER PARSING // -------------------------------------------------------------------- int total_num = Integer.parseInt(ints[0]); // END HEADER PARSING // -------------------------------------------------------------------- for (int i = 0; i < total_num; ++i) { results.add(""); // BEGIN READING CASE // ---------------------------------------------------------------- line = br.readLine(); tpe.execute(new Task(i, line)); // END READING CASE // ---------------------------------------------------------------- } br.close(); fr.close(); tpe.shutdown(); tpe.awaitTermination(8, TimeUnit.MINUTES); return results; } public synchronized void reportResult(int num, String result) { results.set(num, result); } public static void main(String[] args) throws IOException, InterruptedException { long time0 = System.currentTimeMillis(); if (args.length < 1) { System.out.println("Remember command line argument"); System.exit(1); } QualifierB runner = new QualifierB(args[0]); ArrayList<String> results = runner.calculate(); System.out.println("Run time: " + (System.currentTimeMillis() - time0) / 1000 + "s\n"); FileWriter fw = new FileWriter("results.txt"); BufferedWriter bw = new BufferedWriter(fw); for (int i = 0; i < results.size(); ++i) { System.out.println("Case #" + (i + 1) + ": " + results.get(i)); bw.write("Case #" + (i + 1) + ": " + results.get(i) + "\n"); } bw.close(); fw.close(); } }
A12570
A11006
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.awt.image.BufferStrategy; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Scanner; public class DancingGooglers { public static void main(String[] args) { File file = new File("C:\\Users\\aadi\\Desktop\\DancingGooglers\\B-small-attempt0.in"); try{ FileWriter fstream = new FileWriter("C:\\Users\\aadi\\Desktop\\DancingGooglers\\out.txt"); BufferedWriter out = new BufferedWriter(fstream); Scanner scanner = new Scanner(file); int numOfCases = Integer.parseInt(scanner.nextLine()); for(int i =0 ;i< numOfCases ; i++){ int sCount= 0; int non_sCount = 0; String line = scanner.nextLine(); Scanner scanner2 = new Scanner(line); scanner2.useDelimiter(" "); int n = scanner2.nextInt(); int s = scanner2.nextInt(); int p = scanner2.nextInt(); while(scanner2.hasNext()){ int tot = scanner2.nextInt(); if(tot>=Math.max((p*3-2), 0)){ non_sCount++; }else if(tot>=(p + Math.max((p-2),0) + Math.max((p-2),0)) ){ sCount++; } } out.write("Case #"+(i+1)+": "); if(sCount<s){ //System.out.println(non_sCount+sCount); out.write(""+(non_sCount+sCount)); }else{ //System.out.println(non_sCount+s); out.write(""+(non_sCount+s)); } //System.out.println(""); out.write(System.getProperty("line.separator")); } out.close(); }catch(FileNotFoundException f){ f.printStackTrace(); }catch(Exception e){ e.printStackTrace(); } } }
B12669
B10659
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package year_2012.qualification; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; /** * * @author paul * @date 14 Apr 2012 */ public class QuestionC { private static Set<Integer> getCycle(int x) { String s = Integer.toString(x); Set<Integer> set = new HashSet<Integer>(); set.add(x); for (int c = 1; c < s.length(); c++) { String t = s.substring(c).concat(s.substring(0, c)); set.add(Integer.parseInt(t)); } return set; } private static Set<Integer> mask(Set<Integer> set, int a, int b) { Set<Integer> result = new HashSet<Integer>(); for (int x : set) { if (x >= a && x <= b) { result.add(x); } } return result; } public static void main(String[] args) throws FileNotFoundException, IOException { String question = "C"; // String name = "large"; String name = "small-attempt0"; // String name = "test"; String filename = String.format("%s-%s", question, name); BufferedReader input = new BufferedReader( new FileReader(String.format("/home/paul/Documents/code-jam/2012/qualification/%s.in", filename))); String firstLine = input.readLine(); PrintWriter pw = new PrintWriter(new File( String.format("/home/paul/Documents/code-jam/2012/qualification/%s.out", filename))); int T = Integer.parseInt(firstLine); // Loop through test cases. for (int i = 0; i < T; i++) { // Read data. String[] tokens = input.readLine().split(" "); // int N = Integer.parseInt(input.readLine()); int A = Integer.parseInt(tokens[0]); int B = Integer.parseInt(tokens[1]); // System.out.format("%d, %d\n", A, B); boolean[] used = new boolean[B+1]; int total = 0; for (int n = A; n <= B; n++) { if (!used[n]) { Set<Integer> set = mask(getCycle(n), A, B); int k = set.size(); total += (k * (k-1))/2; for (int m : set) { used[m] = true; } } } pw.format("Case #%d: %d\n", i + 1, total); } pw.close(); } }
import java.io.*; public class google3 { void main()throws IOException { try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("C-small-attempt0.in.txt"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; strLine=br.readLine(); int a=Integer.parseInt(strLine);//Read File Line By Line String b[]=new String[a]; int i=0; while ((strLine = br.readLine()) != null) { // Print the content on the console b[i]=strLine;i++; } in.close(); FileOutputStream out = new FileOutputStream(new File("output.txt")); int g=0;for(int l=0;l<a;l++) {g=l+1;byte[] s = ("Case #"+g+": "+check(b[l])+"\n").getBytes(); out.write(s); } } catch(Exception e){} } int check(String a){ String[] parts = a.split(" "); int[] numbers = new int[parts.length]; int count=0; for(int i = 0; i < parts.length; i++) { numbers[i] = Integer.parseInt(parts[i].trim()); } for(int i=numbers[0];i<=numbers[1];i++) {for(int j=i+1;j<=numbers[1];j++) { count+=ret(i,j); } } return count; } int ret(int a,int b) { String c=Integer.toString(a); String d=Integer.toString(b); for(int i=0;i<c.length();i++) { if((c.substring(i,c.length())+c.substring(0,i)).equals(d)) {return 1;} } return 0; } }
B20734
B20590
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 be.mokarea.gcj.common; import java.io.FileWriter; import java.io.PrintWriter; import java.io.Writer; public abstract class GoogleCodeJamBase<T extends TestCase> { protected abstract Transformation<T> createTransformation(TestCaseReader<T> testCaseReader, PrintWriter outputWriter) throws Exception; protected abstract String getOutputFileName() throws Exception; protected abstract TestCaseReader<T> getTestCaseReader() throws Exception; public void execute() { try { PrintWriter outputWriter = null; try { outputWriter = new PrintWriter(new FileWriter(getOutputFileName())); Transformation<T> transformation = createTransformation(getTestCaseReader(),outputWriter); transformation.transformAll(); outputWriter.flush(); } finally { closeQuietly(outputWriter); } } catch (Throwable t) { t.printStackTrace(); } } private void closeQuietly(Writer outputWriter) { if (outputWriter != null) { try { outputWriter.close(); } catch (Throwable t) { t.printStackTrace(); } } } }
B10899
B11803
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; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam.qualification.recyclednumbers; import java.util.HashSet; import java.util.List; import java.util.Set; import util.BaseResolver; import util.Util; /** * * @author bohmd */ public class RecycledNumbers extends BaseResolver { int cases; public static void main(String[] args) throws Exception { if (args.length == 0 || args[0].equals("")) { throw new Exception("The first parameter must be the input file name without extension."); } else { new RecycledNumbers(args[0]).resolve(); } } public RecycledNumbers(String file) { super(file); } @Override protected void executeLine(String line) throws Exception { if (getLineNum() == 0) { cases = Util.getInt(line); } else { List<Integer> lineCase = Util.getIntList(line); write(resolveCase(lineCase.get(0), lineCase.get(1))); } } protected String resolveCase(int min, int max) { Set<Pair> pairSet= new HashSet<Pair>(); for(int i=min; i<=max; i++) { String n = i+""; for(int j=0; j<n.length(); j++) { String m = n.substring(j)+n.substring(0,j); int mInt=Integer.parseInt(m); if(mInt>i && mInt<=max) { pairSet.add(new Pair(i, mInt)); } } } return " "+pairSet.size(); } private class Pair { int m; int n; public Pair(int n, int m) { this.m = m; this.n = n; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Pair other = (Pair) obj; return (this.n == other.n && this.m == other.m) || (this.n == other.m && this.m == other.n); } @Override public int hashCode() { int hash = 7; hash = 11 * hash + this.m + this.n; return hash; } } }
B10155
B10200
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.util.HashSet; import java.util.Scanner; import java.util.Set; public class Q3 { public static void main (String[] args) { Scanner s = new Scanner(System.in); int numTests = s.nextInt(); for (int test = 0; test < numTests; test++) { int a = s.nextInt(); int b = s.nextInt(); int count = 0; for (int i = a; i < b; i++) { String si = String.valueOf(i); Set<Integer> found = new HashSet<Integer>(); for (int j = 0; j < si.length(); j++) { String sj = si.substring(j) + si.substring(0, j); int other = Integer.parseInt(sj); if (!found.contains(other) && other > i && other <= b) { found.add(other); count++; } } } System.out.println("Case #" + (test+1) + ": " + count); } } }
B11696
B11959
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycled; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.TreeSet; /** * * @author Alfred */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream("C-small-attempt0.in"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter outFile = new FileWriter("out.txt"); PrintWriter out = new PrintWriter(outFile); String line; line = br.readLine(); int cases = Integer.parseInt(line); for (int i=1; i<=cases;i++){ line = br.readLine(); String[] values = line.split(" "); int A = Integer.parseInt(values[0]); int B = Integer.parseInt(values[1]); int total=0; for (int n=A; n<=B;n++){ TreeSet<String> solutions = new TreeSet<String>(); for (int k=1;k<values[1].length();k++){ String m = circshift(n,k); int mVal = Integer.parseInt(m); if(mVal<=B && mVal!=n && mVal> n && !m.startsWith("0") && m.length()==Integer.toString(n).length() ) { solutions.add(m); } } total+=solutions.size(); } out.println("Case #"+i+": "+total); } in.close(); out.close(); } catch (Exception e) {//Catch exception if any System.err.println("Error: " + e.getMessage()); } } private static String circshift(int n, int k) { String nString=Integer.toString(n); int len=nString.length(); String m = nString.substring(len-k)+nString.subSequence(0, len-k); //System.out.println(n+" "+m); return m; } }
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.IOException; import java.util.InputMismatchException; import java.math.BigInteger; public class Recycled { static InputReader in; static PrintWriter out; public static void main(String[] args) { try { System.setIn(new FileInputStream(args[0])); System.setOut(new PrintStream(new FileOutputStream(args[0].replace(".in",".out")))); } catch (FileNotFoundException e) { throw new RuntimeException(); } in = new InputReader(System.in); out = new PrintWriter(System.out); int T = in.readInt(); for (int t = 0; t < T; t++) { int A = in.readInt(); int B = in.readInt(); int count = 0; for (int i = A; i <= B; i++) { String A_s = Integer.toString(i); int n = A_s.length(); for (int j = 0; j < n - 1; j++) { A_s = A_s.substring(1) + A_s.charAt(0); int temp = Integer.parseInt(A_s); if (temp > i && temp <= B) { count++; // System.out.println("("+i+", "+temp+")"); } } } out.print("Case #"+(t+1)+": "); out.println("" + count); } out.close(); } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } }
B11318
B10848
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 codejam; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.LinkedList; import java.util.Queue; public class RecycledNumbers { public static void main(String[] args) throws IOException { String fileName = "C-small-attempt1"; Queue<String> queue = file("input/"+fileName+".in"); File outputFile = new File("result/"+fileName+".out"); if(!outputFile.exists()) outputFile.createNewFile(); FileOutputStream output = new FileOutputStream(outputFile); int TestCases = Integer.parseInt(queue.poll()); for(int i=0; i < TestCases; i++) { output.write(("Case #"+(i+1)+": ").getBytes()); int[] input = parseLine(queue.poll()); int A = input[0]; int B = input[1]; int base = (int)Math.log10(A); int count = 0; if(base > 0) { int zeros = (int)Math.pow(10, base); for(int n=A; n <= B; n++) { int m = n; for(int k=0; k < base; k++) { m = m/10 + (m%10)*zeros; if(n < m && m <= B) count++; } } } output.write(Integer.toString(count).getBytes()); output.write('\n'); } } public static int recycleRoutine(int n, int m, int digits) { int count = 0; int base = (int)Math.pow(10, digits-1); for(int i=0; i < digits; i++) { n = n/10 + (n%10)*base; for(int j=0; j < digits; j++) { m = m/10 + (m%10)*base; if(m >= n) count++; } } return count; } public static int[] parseLine(String line) { String[] array = line.split("\\s"); int[] result = new int[array.length]; for(int i=0; i < result.length; i++) result[i] = Integer.parseInt(array[i]); return result; } /* given a file name ... fetches the file from war folder */ public static byte[] getFile(String fileName) throws IOException { FileInputStream in = new FileInputStream(fileName); int size = in.available(); byte[] imageBytes = new byte[size]; /* read the whole image into array */ int read = 0; while(read < size) read += in.read(imageBytes, read, size-read); return imageBytes; } /* mimic php functions */ public static Queue<String> file(String filename) throws IOException { byte[] fileBytes = getFile(filename); Queue<String> queue = new LinkedList(); StringBuilder builder = new StringBuilder(); for(int i=0; i < fileBytes.length; i++) { if(fileBytes[i] == '\n') { queue.add(builder.toString()); builder.delete(0, builder.length()); continue; } if(fileBytes[i] == '\r') continue; builder.append((char)fileBytes[i]); } return queue; } }
B12074
B12774
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 ); } }
public class UniqueList { private int[] number; private int totalSize, size; public UniqueList(int allocatedSize) { totalSize = allocatedSize; number = new int[totalSize]; size = 0; } public void add(int n) { for (int i = 0; i < size; i++) { if (number[i] == n) return; } number[size ++] = n; } public int getSize() { return size; } }
A20934
A22983
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; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; /** * * @author akila */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here ArrayList<String> testCases = new ArrayList<String>(); boolean isCaseNo = true; int testCount = 0; FileReader fr = new FileReader("B-large.in"); BufferedReader br = new BufferedReader(fr); String s; while ((s = br.readLine()) != null) { if (isCaseNo) { testCount = Integer.parseInt(s); isCaseNo = false; } else { testCases.add(s); } } fr.close(); Solve(testCount, testCases); } public static void Solve(int testCount, ArrayList<String> testCases) throws IOException { FileWriter fstream = new FileWriter("out.txt"); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < testCount; i++) { ArrayList<Googler> googlers = new ArrayList<Googler>(); String s = testCases.get(i); String[] ar = s.split(" "); int noOfGooglers = 0, sup = 0, min = -1, count = 0; noOfGooglers = Integer.parseInt(ar[0]); sup = Integer.parseInt(ar[1]); min = Integer.parseInt(ar[2]); for (int j = 3; j < noOfGooglers + 3; j++) { Googler g = new Googler(); googlers.add(g); for (int a = 0; a <= 10; a++) { if (a > Integer.parseInt(ar[j])) { break; } for (int b = 0; b <= 10; b++) { if (a + b > Integer.parseInt(ar[j])) { break; } for (int c = 0; c <= 10; c++) { if (a + b + c == Integer.parseInt(ar[j])) { if ((Math.abs(a - b) <= 2) && (Math.abs(a - c) <= 2) && (Math.abs(b - c) <= 2)) { if ((Math.abs(a - b) == 2) || (Math.abs(a - c) == 2) || (Math.abs(b - c) == 2)) { Scores sc = new Scores(); sc.A = a; sc.B = b; sc.C = c; g.sup.add(sc); g.hasSup = true; } else { Scores sc = new Scores(); sc.A = a; sc.B = b; sc.C = c; g.normal.add(sc); } } } else if (a + b + c > Integer.parseInt(ar[j])) { break; } } } } } ArrayList<Googler> removed = new ArrayList<Googler>(); for (int j = 0; j < googlers.size(); j++) { Googler googler = googlers.get(j); if (googler.hasSup && googler.normal.isEmpty() && sup > 0) { if (googler.hasMinInSup(min)) { count++; } sup--; removed.add(googler); } } googlers.removeAll(removed); for (int j = 0; j < googlers.size(); j++) { Googler googler = googlers.get(j); if (googler.hasMinInNorm(min)) { count++; } else if (sup > 0 && googler.hasMinInSup(min)) { count++; sup--; } } out.write("Case #" + (i + 1) + ": " + count + "\n"); } out.close(); } } class Scores { public int A = -1, B = -1, C = -1; public boolean hasMin(int min) { return A >= min || B >= min || C >= min; } } class Googler { public ArrayList<Scores> normal = new ArrayList<Scores>(); public ArrayList<Scores> sup = new ArrayList<Scores>(); public boolean hasSup = false; public boolean hasMinInSup(int min) { for (int i = 0; i < sup.size(); i++) { if (sup.get(i).hasMin(min)) return true; } return false; } public boolean hasMinInNorm(int min) { for (int i = 0; i < normal.size(); i++) { if (normal.get(i).hasMin(min)) return true; } return false; } }
B10899
B10529
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 recyclednumbers; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; /** * @author Emmanuel JS Hoarau - Google Code Jam 2012 */ public class RecycledNumbers { String executeLine(final String line) { String words[] = line.split(" "); String sa = words[0], sb = words[1]; int a = Integer.parseInt(sa); int b = Integer.parseInt(sb); int result = 0; for (int n = a; n <= b; ++n) { HashSet<String> matches = new HashSet<String>(); String s = Integer.toString(n); String ss = s + s.substring(0, s.length()-1); int l = s.length(); for (int j = 1; j < l; ++j) { if (ss.charAt(j) != '0') { String r = ss.substring(j, j+l); if ((r.compareTo(s) > 0) && (r.compareTo(sa) >= 0) && (r.compareTo(sb) <= 0) && !matches.contains(r)) { matches.add(r); ++result; } } } } return Integer.toString(result); } void execute() { try { InputStreamReader stream = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(stream); String line = reader.readLine(); int lines = Integer.parseInt(line); for (int i = 1; i <= lines; ++i) { line = reader.readLine(); StringBuilder out = new StringBuilder(); out.append("Case #"); out.append(i); out.append(": "); out.append(executeLine(line)); System.out.println(out.toString()); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new RecycledNumbers().execute(); } }
B22190
B20706
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(); } }
package org.moriraaca.codejam; import java.io.File; import java.io.InputStream; import java.io.PrintStream; public abstract class AbstractSolver<TC extends TestCase> { protected final String RESOURCE_FOLDER = "src/main/resources/"; /* Config */ protected final String defaultInputFileName; protected final OutputDestination outputDestination; protected final DebugOutputLevel debugOutputLevel; protected final Class<? extends AbstractDataParser> dataParserClass; protected PrintStream output; protected PrintStream getOutput() { if (output == null) { try { switch (outputDestination) { case STDOUT: output = System.out; break; case FILE: output = new PrintStream(new File( defaultInputFileName.replaceAll("\\.in", "\\.out"))); default: break; } } catch (Exception rethrow) { throw new Error("Fatal error on initialization of output", rethrow); } } return output; } public AbstractSolver() { try { SolverConfiguration config = getClass().getAnnotation( SolverConfiguration.class); debugOutputLevel = config.debugOutputLevel(); outputDestination = config.outputDestination(); defaultInputFileName = config.inputFileName(); dataParserClass = config.parser(); } catch (Exception log) { log.printStackTrace(); throw new Error("Fatal error on initialization", log); } } public void write(String msg, DebugOutputLevel level) { if (level.ordinal() <= debugOutputLevel.ordinal()) { getOutput().print(msg); } } public final String solve() { return solve(defaultInputFileName); } @SuppressWarnings("unchecked") public final String solve(String fileName) { try { AbstractDataParser dataParser = dataParserClass.getConstructor( InputStream.class).newInstance( getClass().getClassLoader().getResourceAsStream(fileName)); StringBuilder result = new StringBuilder(); for (int i = 0; i < dataParser.getTestCases().length; i++) { result.append("Case #") .append(i + 1) .append(": ") .append(solveTestCase((TC) dataParser.getTestCases()[i])) .append("\n"); } return result.toString(); } catch (Exception e) { throw new Error("Fatal error on solve", e); } } public final void getSolution() { write(solve(), DebugOutputLevel.SOLUTION); } protected abstract String solveTestCase(TC testCase); }
A22992
A22769
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.menzus.gcj._2012.qualification.b; import com.menzus.gcj.common.Processor; public class BMain { private static String SMALL_FILE_NAME = "src/main/resources/com/menzus/gcj/_2012/qualification/b/B-small-attempt0.in.txt"; public static void main(String[] args) throws Exception { Processor smallFileProcessor = new BProcessorFactory(SMALL_FILE_NAME).createProcessor(); smallFileProcessor.process(); System.out.println("done."); } }
A12544
A12980
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.*; import java.util.Arrays; public class Main{ public static void main(String[] args) throws Exception { int t = Integer.parseInt(finB.readLine()); int test = 1; while(test <= t){ int n = fnextInt(); int s = fnextInt(); int p = fnextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++){ a[i] = fnextInt(); } print(n + " " + s + " " + p + " "); for(int i = 0; i < n; i++){ print(a[i] + " "); } int[] max = new int[n]; for(int i = 0; i < n; i++){ if(a[i] / 3 == 0){ if(p == 2 && a[i] == 2 && s > 0){ max[i] = a[i]; s--; continue; } else if(a[i] == 2) max[i] = 1; else max[i] = a[i]; continue; } if(a[i] % 3 == 0 && a[i] / 3 < p){ if(s > 0 && a[i] / 3 + 1 == p){ max[i] = a[i] / 3 + 1; s--; continue; } } if(a[i] % 3 == 2 && a[i] / 3 + 1 < p){ if(s > 0 && a[i] / 3 + 2 == p){ max[i] = a[i] / 3 + 2; s--; continue; } } max[i] = a[i] % 3 > 0 ? a[i] / 3 + 1 : a[i] / 3; } int ans = 0; for(int i = 0; i < n; i++){ if(max[i] >= p) ans++; } fout.println("Case #" + test + ": " + ans); println("Case #" + test + ": " + ans); test++; } fout.flush(); } private static PrintWriter out; private static BufferedReader inB; private static BufferedReader finB; private static PrintWriter fout; static { try { finB = new BufferedReader(new InputStreamReader(new FileInputStream("input.in"))); fout = new PrintWriter(new FileOutputStream("output.txt")); out = new PrintWriter(System.out); inB = new BufferedReader(new InputStreamReader(System.in)); } catch(Exception e) {e.printStackTrace();} } private static StreamTokenizer in = new StreamTokenizer(inB); private static StreamTokenizer fin = new StreamTokenizer(finB); private static void exit(Object o) throws Exception { out.println(o); out.flush(); System.exit(0); } private static void println(Object o) throws Exception{ out.println(o); out.flush(); } private static void print(Object o) throws Exception{ out.print(o); out.flush(); } private static int fnextInt() throws Exception { fin.nextToken(); return (int)fin.nval; } private static int nextInt() throws Exception { in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception { in.nextToken(); return in.sval; } }
A20490
A21245
0
/** * */ package hu.herba.codejam; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; /** * Base functionality, helper functions for CodeJam problem solver utilities. * * @author csorbazoli */ public abstract class AbstractCodeJamBase { private static final String EXT_OUT = ".out"; protected static final int STREAM_TYPE = 0; protected static final int FILE_TYPE = 1; protected static final int READER_TYPE = 2; private static final String DEFAULT_INPUT = "test_input"; private static final String DEFAULT_OUTPUT = "test_output"; private final File inputFolder; private final File outputFolder; public AbstractCodeJamBase(String[] args, int type) { String inputFolderName = AbstractCodeJamBase.DEFAULT_INPUT; String outputFolderName = AbstractCodeJamBase.DEFAULT_OUTPUT; if (args.length > 0) { inputFolderName = args[0]; } this.inputFolder = new File(inputFolderName); if (!this.inputFolder.exists()) { this.showUsage("Input folder '" + this.inputFolder.getAbsolutePath() + "' not exists!"); } if (args.length > 1) { outputFolderName = args[1]; } this.outputFolder = new File(outputFolderName); if (this.outputFolder.exists() && !this.outputFolder.canWrite()) { this.showUsage("Output folder '" + this.outputFolder.getAbsolutePath() + "' not writeable!"); } else if (!this.outputFolder.exists() && !this.outputFolder.mkdirs()) { this.showUsage("Could not create output folder '" + this.outputFolder.getAbsolutePath() + "'!"); } File[] inputFiles = this.inputFolder.listFiles(); for (File inputFile : inputFiles) { this.processInputFile(inputFile, type); } } /** * @return the inputFolder */ public File getInputFolder() { return this.inputFolder; } /** * @return the outputFolder */ public File getOutputFolder() { return this.outputFolder; } /** * @param input * input reader * @param output * output writer * @throws IOException * in case input or output fails * @throws IllegalArgumentException * in case the given input is invalid */ @SuppressWarnings("unused") protected void process(BufferedReader reader, PrintWriter pw) throws IOException, IllegalArgumentException { System.out.println("NEED TO IMPLEMENT (reader/writer)!!!"); System.exit(-2); } /** * @param input * input file * @param output * output file (will be overwritten) * @throws IOException * in case input or output fails * @throws IllegalArgumentException * in case the given input is invalid */ protected void process(File input, File output) throws IOException, IllegalArgumentException { System.out.println("NEED TO IMPLEMENT (file/file)!!!"); System.exit(-2); } /** * @param input * input stream * @param output * output stream * @throws IOException * in case input or output fails * @throws IllegalArgumentException * in case the given input is invalid */ protected void process(InputStream input, OutputStream output) throws IOException, IllegalArgumentException { System.out.println("NEED TO IMPLEMENT (stream/stream)!!!"); System.exit(-2); } /** * @param type * @param input * @param output */ private void processInputFile(File input, int type) { long starttime = System.currentTimeMillis(); System.out.println("Processing '" + input.getAbsolutePath() + "'..."); File output = new File(this.outputFolder, input.getName() + AbstractCodeJamBase.EXT_OUT); if (type == AbstractCodeJamBase.STREAM_TYPE) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(input); os = new FileOutputStream(output); this.process(is, os); } catch (FileNotFoundException e) { this.showUsage("FileNotFound: " + e.getLocalizedMessage()); } catch (IllegalArgumentException excIA) { this.showUsage(excIA.getLocalizedMessage()); } catch (Exception exc) { System.out.println("Program failed: " + exc.getLocalizedMessage()); exc.printStackTrace(System.out); } finally { if (is != null) { try { is.close(); } catch (IOException e) { System.out.println("Failed to close input: " + e.getLocalizedMessage()); } } if (os != null) { try { os.close(); } catch (IOException e) { System.out.println("Failed to close output: " + e.getLocalizedMessage()); } } } } else if (type == AbstractCodeJamBase.READER_TYPE) { BufferedReader reader = null; PrintWriter pw = null; try { reader = new BufferedReader(new FileReader(input)); pw = new PrintWriter(output); this.process(reader, pw); } catch (FileNotFoundException e) { this.showUsage("FileNotFound: " + e.getLocalizedMessage()); } catch (IllegalArgumentException excIA) { this.showUsage(excIA.getLocalizedMessage()); } catch (Exception exc) { System.out.println("Program failed: " + exc.getLocalizedMessage()); exc.printStackTrace(System.out); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { System.out.println("Failed to close input: " + e.getLocalizedMessage()); } } if (pw != null) { pw.close(); } } } else if (type == AbstractCodeJamBase.FILE_TYPE) { try { this.process(input, output); } catch (IllegalArgumentException excIA) { this.showUsage(excIA.getLocalizedMessage()); } catch (Exception exc) { System.out.println("Program failed: " + exc.getLocalizedMessage()); exc.printStackTrace(System.out); } } else { this.showUsage("Unknown type given: " + type + " (accepted values: 0,1)"); } System.out.println(" READY (" + (System.currentTimeMillis() - starttime) + " ms)"); } /** * Read a single number from input * * @param reader * @param purpose * What is the purpose of given data * @return * @throws IOException * @throws IllegalArgumentException */ protected int readInt(BufferedReader reader, String purpose) throws IOException, IllegalArgumentException { int ret = 0; String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException("Invalid input: line is empty, it should be an integer (" + purpose + ")!"); } try { ret = Integer.parseInt(line); } catch (NumberFormatException excNF) { throw new IllegalArgumentException("Invalid input: the first line '" + line + "' should be an integer (" + purpose + ")!"); } return ret; } /** * Read array of integers * * @param reader * @param purpose * @return */ protected int[] readIntArray(BufferedReader reader, String purpose) throws IOException { int[] ret = null; String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException("Invalid input: line is empty, it should be an integer list (" + purpose + ")!"); } String[] strArr = line.split("\\s"); int len = strArr.length; ret = new int[len]; for (int i = 0; i < len; i++) { try { ret[i] = Integer.parseInt(strArr[i]); } catch (NumberFormatException excNF) { throw new IllegalArgumentException("Invalid input: line '" + line + "' should be an integer list (" + purpose + ")!"); } } return ret; } /** * Read array of strings * * @param reader * @param purpose * @return */ protected String[] readStringArray(BufferedReader reader, String purpose) throws IOException { String[] ret = null; String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException("Invalid input: line is empty, it should be a string list (" + purpose + ")!"); } ret = line.split("\\s"); return ret == null ? new String[0] : ret; } /** * Basic usage pattern. Can be overwritten by current implementation * * @param message * Short message, describing the problem with given program * arguments */ protected void showUsage(String message) { if (message != null) { System.out.println(message); } System.out.println("Usage:"); System.out.println("\t" + this.getClass().getName() + " program"); System.out.println("\tArguments:"); System.out.println("\t\t<input folder>:\tpath of input folder (default: " + AbstractCodeJamBase.DEFAULT_INPUT + ")."); System.out.println("\t\t \tAll files will be processed in the folder"); System.out.println("\t\t<output folder>:\tpath of output folder (default: " + AbstractCodeJamBase.DEFAULT_OUTPUT + ")"); System.out.println("\t\t \tOutput file name will be the same as input"); System.out.println("\t\t \tinput with extension '.out'"); System.exit(-1); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package qualb; import java.util.Scanner; /** * * @author marcin */ public class QualB { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = Integer.parseInt(in.nextLine()); for (int ci = 1; ci <= T; ++ci) { int N = in.nextInt(); int S = in.nextInt(); int p = in.nextInt(); int certains = 0; int possibles = 0; for (int i = 0; i < N; ++i) { int total = in.nextInt(); int temp = total - (3 * p); if (temp >= 0) { ++certains; } else { if ((p - 1 >= 0) && (temp >= -2)) { ++certains; } else if ((p - 2 >= 0) && (temp >= -4)) { ++possibles; } } } int optional = S > possibles ? possibles : S; int answer = certains + optional; System.out.println("Case #" + ci + ": " + answer); } } }
B10485
B10107
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.HashSet; import java.util.Scanner; import java.util.Set; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for (int i = 0; i < n; i++) { int a = sc.nextInt(); int b = sc.nextInt(); long output = solve(a, b); System.out.println("Case #" + (i + 1) + ": " + output); } } private static long solve(int a, int b) { if (b <= 10) return 0; int start = a; if(a <= 10) start = 11; int count = 0; Set<Integer> found = new HashSet<Integer>(); for(int i = start; i < b; i++){ String toshift = String.valueOf(i); int len = toshift.length(); for(int j =1; j<len;j++){ String shifted = shift(toshift, j); int v = Integer.valueOf(shifted); if(v <= b && v >a && i < v && !found.contains(v) && !shifted.startsWith("0")) { found.add(v); count++; } } found.clear(); } return count; } private static String shift(String toshift, int j) { String pre = toshift.substring(0, j); String post = toshift.substring(j); return post.concat(pre); } }
A22378
A20811
0
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class CodeJam { // public static final String INPUT_FILE_PATH = "D://CodeJamInput.txt"; public static final String INPUT_FILE_PATH = "D://B-large.in"; public static final String OUTPUT_FILE_PATH = "D://CodeJamOutput.txt"; public static List<String> readInput() { List<String> list = new ArrayList<String>(); try { BufferedReader input = new BufferedReader(new FileReader( INPUT_FILE_PATH)); try { String line = null; while ((line = input.readLine()) != null) { list.add(line); } } finally { input.close(); } } catch (IOException ex) { ex.printStackTrace(); } return list; } public static void writeOutput(List<String> output) { PrintWriter writer = null; try { writer = new PrintWriter(new FileWriter(OUTPUT_FILE_PATH)); for (String line : output) { writer.println(line); } writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) writer.close(); } } public static void main(String[] args) { List<DanceFloor> danceFloors = DanceFloor.parseFromFile(CodeJam.readInput()); List<String> output = new ArrayList<String>(); for(int i = 0; i < danceFloors.size(); i++) { System.out.println(danceFloors.get(i)); String line = ""; line += "Case #" + (i + 1) + ": " + danceFloors.get(i).calculate(); output.add(line); } CodeJam.writeOutput(output); } } class DanceFloor { private List<Integer> tripletsTotalCounts; private int surpriseCount; private int targetScore; private int dancersCount; public DanceFloor(List<Integer> tripletsTotalCounts, int surpriseCount, int targetScore, int dancersCount) { this.tripletsTotalCounts = tripletsTotalCounts; this.surpriseCount = surpriseCount; this.targetScore = targetScore; this.dancersCount = dancersCount; } public int calculate() { int result = 0; if (targetScore == 0) return dancersCount; for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if (total < (targetScore * 3 - 4)) { tripletsTotalCounts.remove(i--); } else if (total == 0) { tripletsTotalCounts.remove(i--); } } for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if ((surpriseCount > 0) && (total == targetScore * 3 - 4)) { result++; surpriseCount--; tripletsTotalCounts.remove(i--); } else if ((surpriseCount == 0) && (total == targetScore * 3 - 4)) { tripletsTotalCounts.remove(i--); } } for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if ((surpriseCount > 0) && (total == targetScore * 3 - 3)) { result++; surpriseCount--; tripletsTotalCounts.remove(i--); } else if ((surpriseCount == 0) && (total == targetScore * 3 - 3)) { tripletsTotalCounts.remove(i--); } } result += tripletsTotalCounts.size(); return result; } public static List<DanceFloor> parseFromFile(List<String> readInput) { List<DanceFloor> result = new ArrayList<DanceFloor>(); int testCaseCount = Integer.parseInt(readInput.get(0)); for (int i = 0; i < testCaseCount; i++) { String line[] = readInput.get(i + 1).split(" "); List<Integer> totalCounts = new ArrayList<Integer>(); for (int j = 0; j < Integer.parseInt(line[0]); j++) { totalCounts.add(Integer.parseInt(line[3 + j])); } result.add(new DanceFloor(totalCounts, Integer.parseInt(line[1]), Integer.parseInt(line[2]), Integer.parseInt(line[0]))); } return result; } @Override public String toString() { return "dancersCount = " + dancersCount + "; surpriseCount = " + surpriseCount + "; targetScore = " + targetScore + "; tripletsTotalCounts" + tripletsTotalCounts.toString(); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Dancing { public static void main(String[] args) { int numTestCases; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { numTestCases = Integer.parseInt(in.readLine()); for (int i = 0; i < numTestCases; i++) { String line = in.readLine(); String[] ints = line.split(" "); int numGooglers = Integer.parseInt(ints[0]); int numSurprising = Integer.parseInt(ints[1]); int p = Integer.parseInt(ints[2]); int numSuccess = 0; for (int j = 3; j < ints.length; j++) { int score = Integer.parseInt(ints[j]); // special case if (score == 0 && p > 0) { continue; } // trivial case if (score/3 >= p) { numSuccess++; continue; } int remainingTwoScoresSum = score - p; if (remainingTwoScoresSum >= (p-1)*2) { numSuccess++; continue; } if (remainingTwoScoresSum >= (p-2)*2 && numSurprising > 0) { numSuccess++; numSurprising--; continue; } } System.out.println("Case #"+(i+1)+": "+numSuccess); } } catch (IOException e) { // System.out.println("oh noes"); } } }
A22078
A23066
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.BufferedReader; import java.io.InputStreamReader; class DWtG { public static BufferedReader br = null; public static int numCases; public static int numDancers; public static int numSurprises; public static int p; // p is given by the problem as the "best score" public static String[] input; public static void main(String[] args) { try { br = new BufferedReader(new InputStreamReader(System.in)); numCases = Integer.parseInt(br.readLine().trim()); for(int i = 0; i < numCases; i++) { input = br.readLine().split(" "); numDancers = Integer.parseInt(input[0]); numSurprises = Integer.parseInt(input[1]); p = Integer.parseInt(input[2]); int maxDancers = 0; for(int j = 3; j < input.length; j++) { if(maxReg(Integer.parseInt(input[j])) >= p) maxDancers++; else if(numSurprises > 0 && maxSpecial(Integer.parseInt(input[j])) >= p) { maxDancers++; numSurprises--; } } System.out.println("Case #" + (i+1) + ": " + maxDancers); } } catch(Exception e) { e.getMessage(); e.printStackTrace(); } } public static int maxReg(int n) { if(n == 0) return 0; else if(n == 1) return 1; else if(n == 2) return 1; else if(n % 3 == 0) return (n / 3); else if(n % 3 == 1) return (n / 3) + 1; else if(n % 3 == 2) return (n / 3) + 1; return -1; } public static int maxSpecial(int n) { if(n == 0) return 0; else if(n == 1) return 1; else if(n == 2) return 2; else if(n % 3 == 0) return (n / 3) + 1; else if(n % 3 == 1) return (n / 3) + 1; else if(n % 3 == 2) return (n / 3) + 2; return -1; } }
A11502
A12367
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.util.*; public class QualB12 { /** * @param args */ 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 g = 0; for (int j = 1; j <= N; j++) { int a = in.nextInt(); if (a/3 >= p) ++g; else if (a/3 >= p-2) { if (a/3 == p-1) { if (a%3 == 2) { ++g; } else if (a%3 == 1) { ++g; } else if (a%3 == 0) { if (S > 0 && a/3 > 0) { ++g; --S; } } } else if (a/3 == p-2) { if (a%3 == 2) { if (S > 0){ ++g; --S; } } } else { System.out.println("a is " + a + " and p is " + p); assert false; } } } System.out.println("Case #" + i + ": " + g); } } /* Self-Made Test Cases 4 3 0 5 0 0 0 3 1 6 14 13 12 2 0 10 30 30 4 1 5 13 12 11 11 Case #1: 0 Case #2: 1 Case #3: 2 Case #4: 2 */ }
B11327
B13174
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]); } } }
package recycle; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; public class Recycle { public static void main(String[] args) throws Exception { FileInputStream fr=new FileInputStream("/home/priyankle/Desktop/recycle.txt"); StreamTokenizer st=new StreamTokenizer(fr); st.eolIsSignificant(false); st.whitespaceChars(0,32); int i=1,j=0,cases=0,count=0; int A[]=null; int B[]=null; File file=new File("output.txt"); FileWriter fileWritter = new FileWriter(file.getName(),true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); int learn=0,flag=0; while(true) { flag++; learn=st.nextToken(); if(learn==StreamTokenizer.TT_EOF) break; if(learn==StreamTokenizer.TT_NUMBER&&flag==1) { cases=(int)st.nval; A= new int[cases+1]; B= new int[cases+1]; } if(learn==StreamTokenizer.TT_NUMBER&&flag==2) A[i]=(int)st.nval; else if(learn==StreamTokenizer.TT_NUMBER&&flag==3) { B[i]=(int)st.nval; flag=1; i++; } } int resultant=0; int y1=0,y2=0,y3=0,temp=0; for(j=1;j<=cases;j++) { count=0; for(i=A[j];i<=B[j];i++) { y1=i/100; temp=i%100; y2=temp/10; y3=temp%10; if(y1==0&&y2==0&&y3==0) { count=0; } else if(y1==0&&y2!=0) { if(y3>y2) { resultant=y3*10+y2; if(resultant<=B[j]) count++; } } else { if((y2>y1)||(y2==y1&&y2<y3)) { resultant=y2*100+y3*10+y1; if(resultant<=B[j]) count++; } if((y3>y1)||(y3==y1&&y3>y2)) { resultant=y3*100+y1*10+y2; if(resultant<=B[j]) count++; } } } bufferWritter.write("Case #"+j+": "+count+"\n"); } bufferWritter.close(); } }
A12544
A10082
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; } }
package qualificationRound; public class Dancing { /** * * @param N * Number of Googlers * @param S * number of surprising triplets of scores * @param P * * @param Ti * the total points of the Googlers * * @return what is the maximum number of Googlers that could have had a best * result of at least p */ public static int howMany(int N, int S, int P, int[] Ti) { if (0 == P) return N; int count = 0; int specials = 0; for (int t : Ti) { if (0 == t) continue; int mod = t % 3; int div = t / 3; int max = -1; int maxSpecial = -1; switch (mod) { case 0: max = div; maxSpecial = div + 1; break; case 1: max = div + 1; // same as 'maxSpecial' break; case 2: max = div + 1; maxSpecial = div + 2; break; } if (max >= P) count++; else if (maxSpecial >= P) specials++; } if (specials > S) count += S; else count += specials; return count; } }
B21270
B21859
0
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; public class CopyOfCopyOfMain { static int ndigits(int n) { return (int) (Math.log10(n) + 1); } static int rot(int n, int dig) { return (int) ((n % 10) * Math.pow(10, dig - 1)) + (int) (n / 10); } public static void main(String[] args) throws FileNotFoundException { String file = "C-large"; Scanner in = new Scanner(new File(file + ".in")); PrintWriter out = new PrintWriter(new File(file + ".out")); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int A = in.nextInt(); int B = in.nextInt(); int c = 0; int[] list = new int[ndigits(B)]; numbers: for (int i = A; i <= B; i++) { int digs = ndigits(i); int rot = i; int pairs = 0; Arrays.fill(list, -1); list[0] = i; digits: for (int j = 1; j <= digs + 1; j++) { rot = rot(rot, digs); if(rot < i) continue; if (A <= rot && rot <= B) { for (int k = 0; k < j; k++) { if (list[k] == rot) { continue digits; } } pairs++; list[j] = rot; } } //c += pairs * (pairs + 1) / 2; c += pairs ; // c+=digs; } out.println("Case #" + t + ": " + c); } in.close(); out.close(); } }
import java.io.*; import java.util.*; public class Revn{ static int bt[]={0,10,100,1000,10000,100000,1000000},gl[]=new int[2000001];; public static void main(String args[])throws Exception{ BufferedReader br=new BufferedReader(new FileReader("ginp.txt")); PrintWriter pr=new PrintWriter("Revn.txt"); int i=0,j=0,k=0,a=0,b=0,tc=Integer.parseInt(br.readLine());long co=0; StringTokenizer st=null; for(k=1;k<=tc;k++) {st=new StringTokenizer(br.readLine()); a=Integer.parseInt(st.nextToken()); b=Integer.parseInt(st.nextToken()); co=0; for(i=a;i<b;i++) co=co+get(i,b); pr.println("Case #"+k+": "+co); } pr.close(); } public static int get(int x,int y) { String s1=""+x; int i=0,j=0,l=s1.length()-1,t=bt[l],ty=x,ry=0,gp[]=new int[l]; for(i=0;i<l;i++) {ty=(ty%t)*10+ty/t; ry=ty>x&&ty<=y&&gl[ty]==0?ry+1:ry; if(ty<y){ gl[ty]=1; gp[i]=ty;} } for(i=0;i<l;i++) gl[gp[i]]=0; return ry; } }
A11502
A11133
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.*; import java.util.*; class Source3 { public static void main(String[] args) throws IOException { String s,word,buffer; FileReader input = new FileReader("B-small.in"); BufferedReader in = new BufferedReader(input); File file = new File("B-small.out"); BufferedWriter out = new BufferedWriter(new FileWriter(file)); s = in.readLine(); int count= Integer.parseInt(s); int i=1; while ((s = in.readLine()) != null && s.length() != 0) { out.write("Case #"+(i++)+": "); Scanner scan =new Scanner(s); int N =Integer.parseInt(scan.next()); int S=Integer.parseInt(scan.next()); int p=Integer.parseInt(scan.next()); int[] t =new int[200]; for(int x=0;x<N;x++) { t[x]= Integer.parseInt(scan.next()); } int ans = perform(N,S,p,t); out.write(ans+"\n"); } out.close(); } public static int perform(int N,int S ,int p ,int[] t) { int count=0; int surprise=0; boolean pass=false; int staticP=p; for(int x=0;x<N;x++) { pass=false; p=staticP; while(p<=10&&!pass) { //System.out.println("SCORE : "+t[x]); int remain = t[x]-p; int[][] possibleNS = {{p,p},{p+1,p+1},{p,p+1},{p,p-1},{p-1,p-1} }; int[][] possibleS = {{p+2,p+2},{p,p+2},{p+1,p+2},{p-2,p-2},{p-2,p-1},{p-2,p} }; //System.out.print("TRI: "+p); if(equalpair(remain,possibleNS)) { count++; pass=true; } else if(equalpair(remain,possibleS)) { if(surprise<S) { count++; surprise++; pass=true; } } p++; } } return count; } public static boolean equalpair(int num,int[][] pair) { boolean check=false; for(int i=0;i<pair.length;i++) { if(num==(pair[i][0]+pair[i][1])) { if(pair[i][0]>=0&&pair[i][0]<=10&&pair[i][1]>=0&&pair[i][1]<=10) { check=true; //System.out.println(" "+pair[i][0]+" "+pair[i][1]); } } } return check; } }
A22992
A22960
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package IO; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; /** * * @author dannocz */ public class InputReader { public static Input readFile(String filename){ try { /* Sets up a file reader to read the file passed on the command 77 line one character at a time */ FileReader input = new FileReader(filename); /* Filter FileReader through a Buffered read to read a line at a time */ BufferedReader bufRead = new BufferedReader(input); String line; // String that holds current file line int count = 0; // Line number of count ArrayList<String> cases= new ArrayList<String>(); // Read first line line = bufRead.readLine(); int noTestCases=Integer.parseInt(line); count++; // Read through file one line at time. Print line # and line while (count<=noTestCases){ //System.out.println("Reading. "+count+": "+line); line = bufRead.readLine(); cases.add(line); count++; } bufRead.close(); return new Input(noTestCases,cases); }catch (ArrayIndexOutOfBoundsException e){ /* If no file was passed on the command line, this expception is generated. A message indicating how to the class should be called is displayed */ e.printStackTrace(); }catch (IOException e){ // If another exception is generated, print a stack trace e.printStackTrace(); } return null; }// end main }
import java.util.Scanner; import java.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 */ public class Main { public static void main(String[] args) { InputStream inputStream; try { inputStream = new FileInputStream("B-large.in"); } catch (IOException e) { throw new RuntimeException(e); } OutputStream outputStream; try { outputStream = new FileOutputStream("gcj2.out"); } catch (IOException e) { throw new RuntimeException(e); } Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); GCJ2 solver = new GCJ2(); solver.solve(1, in, out); out.close(); } } class GCJ2 { public void solve(int testNumber, Scanner in, PrintWriter out) { int cases = in.nextInt(); for(int caseNum =0;caseNum<cases;caseNum++) { int res = 0; int N = in.nextInt(); int S = in.nextInt(); int p = in.nextInt(); int normal = Math.max(p,p*3-2); int surprise = Math.max(p,p*3-4); for(int i=0;i<N;i++) { int score = in.nextInt(); if(score>=normal)res++; else if(score>=surprise && S>0) { res++; S--; } } out.println("Case #"+(caseNum+1)+": "+res); } } }
B10361
B11372
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.*; import static java.lang.System.*; public class C { // small input version public static String next(String x) { return x.substring(1)+x.charAt(0); } public static void main(String[] args) { Scanner sc = new Scanner(in); int t = sc.nextInt(); boolean[][] match = new boolean[1001][1001]; for (int i = 1; i <= 1000; i++) { String str = Integer.toString(i); for (int j = 0; j < 4; j++) { str = next(str); int k = Integer.parseInt(str); match[Math.min(i,k)][Math.max(i,k)] = true; } } for (int c = 1; c <= t; c++) { int u = sc.nextInt(); int v = sc.nextInt(); int ctr = 0; for (int i = u; i <= v; i++) { for (int j = i+1; j <= v; j++) { if (match[i][j]) { ctr++; } } } out.printf("Case #%d: %d\n", c, ctr); } } }
B20006
B20321
0
import java.io.*; import java.math.BigInteger; import java.util.*; import org.jfree.data.function.PowerFunction2D; public class r2a { Map numMap = new HashMap(); int output = 0; /** * @param args */ public static void main(String[] args) { r2a mk = new r2a(); try { FileInputStream fstream = new FileInputStream("d:/cjinput.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String str; int i = 0; while ((str = br.readLine()) != null) { int begin=0,end = 0; i++; if (i == 1) continue; mk.numMap = new HashMap(); StringTokenizer strTok = new StringTokenizer(str, " "); while (strTok.hasMoreTokens()) { begin = Integer.parseInt(((String) strTok.nextToken())); end = Integer.parseInt(((String) strTok.nextToken())); } mk.evaluate(i, begin, end); } in.close(); } catch (Exception e) { System.err.println(e); } } private void evaluate(int rowNum, int begin, int end) { output=0; for (int i = begin; i<= end; i++) { if(numMap.containsKey(Integer.valueOf(i))) continue; List l = getPairElems(i); if (l.size() > 0) { Iterator itr = l.iterator(); int ctr = 0; ArrayList tempList = new ArrayList(); while (itr.hasNext()) { int next = ((Integer)itr.next()).intValue(); if (next <= end && next > i) { numMap.put(Integer.valueOf(next), i); tempList.add(next); ctr++; } } ctr = getCounter(ctr+1,2); /* if (tempList.size() > 0 || ctr > 0) System.out.println("DD: " + i + ": " + tempList +" ; ctr = " + ctr);*/ output = output + ctr; } } String outputStr = "Case #" + (rowNum -1) + ": " + output; System.out.println(outputStr); } private int getCounter(int n, int r) { int ret = 1; int nfactorial =1; for (int i = 2; i<=n; i++) { nfactorial = i*nfactorial; } int nrfact =1; for (int i = 2; i<=n-r; i++) { nrfact = i*nrfact; } return nfactorial/(2*nrfact); } private ArrayList getPairElems(int num) { ArrayList retList = new ArrayList(); int temp = num; if (num/10 == 0) return retList; String str = String.valueOf(num); int arr[] = new int[str.length()]; int x = str.length(); while (temp/10 > 0) { arr[x-1] = temp%10; temp=temp/10; x--; } arr[0]=temp; int size = arr.length; for (int pos = size -1; pos >0; pos--) { if(arr[pos] == 0) continue; int pairNum = 0; int multiplier =1; for (int c=0; c < size-1; c++) { multiplier = multiplier*10; } pairNum = pairNum + (arr[pos]*multiplier); for(int ctr = pos+1, i=1; i < size; i++,ctr++) { if (ctr == size) ctr=0; if (multiplier!=1) multiplier=multiplier/10; pairNum = pairNum + (arr[ctr]*multiplier); } if (pairNum != num) retList.add(Integer.valueOf(pairNum)); } return retList; } }
package ulohy; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class codejam_3 { static byte cases; static int A, B; static List<Integer> l1 = new ArrayList<Integer>(); static List<Integer> l2 = new ArrayList<Integer>(); static int[] pairs; static int[] rotated_array = new int[10]; public static void read_input() { Scanner s = null; try { s = new Scanner(new FileReader("./src/ulohy/C-small-attempt1.in")); } catch (FileNotFoundException e) { e.printStackTrace(); } cases = s.nextByte(); pairs = new int[cases]; for (int i = 0; i < cases; i++) { l1.add(s.nextInt()); l2.add(s.nextInt()); } s.close(); } public static void write_output() { FileWriter outFile; try { outFile = new FileWriter("./src/ulohy/output"); PrintWriter out = new PrintWriter(outFile); for (int i = 1; i <= cases; i++) { out.println("Case #"+i+": "+pairs[i-1]); } out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static int rotateNumber(int number, int mul) { return number / 10 + mul * (number % 10); } public static void main(String args[]) { int rotated; read_input(); for (int i = 0; i < cases; i++) { int numdigits = (int) Math.log10((double)l1.get(i)); // would return numdigits - 1 int multiplier = (int) Math.pow(10.0, (double)numdigits); for (int j = l1.get(i); j <= l2.get(i); j++) { rotated = rotateNumber(j, multiplier); for (int k = 0; k <= numdigits; k++) { if (j < rotated && rotated <= l2.get(i)) { for (int k2 = 0; k2 < k; k2++) { if (rotated == rotated_array[k2]) { pairs[i]--; } } pairs[i]++; } rotated_array[k] = rotated; rotated = rotateNumber(rotated, multiplier); } } } write_output(); } }
A22378
A21371
0
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class CodeJam { // public static final String INPUT_FILE_PATH = "D://CodeJamInput.txt"; public static final String INPUT_FILE_PATH = "D://B-large.in"; public static final String OUTPUT_FILE_PATH = "D://CodeJamOutput.txt"; public static List<String> readInput() { List<String> list = new ArrayList<String>(); try { BufferedReader input = new BufferedReader(new FileReader( INPUT_FILE_PATH)); try { String line = null; while ((line = input.readLine()) != null) { list.add(line); } } finally { input.close(); } } catch (IOException ex) { ex.printStackTrace(); } return list; } public static void writeOutput(List<String> output) { PrintWriter writer = null; try { writer = new PrintWriter(new FileWriter(OUTPUT_FILE_PATH)); for (String line : output) { writer.println(line); } writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) writer.close(); } } public static void main(String[] args) { List<DanceFloor> danceFloors = DanceFloor.parseFromFile(CodeJam.readInput()); List<String> output = new ArrayList<String>(); for(int i = 0; i < danceFloors.size(); i++) { System.out.println(danceFloors.get(i)); String line = ""; line += "Case #" + (i + 1) + ": " + danceFloors.get(i).calculate(); output.add(line); } CodeJam.writeOutput(output); } } class DanceFloor { private List<Integer> tripletsTotalCounts; private int surpriseCount; private int targetScore; private int dancersCount; public DanceFloor(List<Integer> tripletsTotalCounts, int surpriseCount, int targetScore, int dancersCount) { this.tripletsTotalCounts = tripletsTotalCounts; this.surpriseCount = surpriseCount; this.targetScore = targetScore; this.dancersCount = dancersCount; } public int calculate() { int result = 0; if (targetScore == 0) return dancersCount; for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if (total < (targetScore * 3 - 4)) { tripletsTotalCounts.remove(i--); } else if (total == 0) { tripletsTotalCounts.remove(i--); } } for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if ((surpriseCount > 0) && (total == targetScore * 3 - 4)) { result++; surpriseCount--; tripletsTotalCounts.remove(i--); } else if ((surpriseCount == 0) && (total == targetScore * 3 - 4)) { tripletsTotalCounts.remove(i--); } } for (int i = 0; i < tripletsTotalCounts.size(); i++) { int total = tripletsTotalCounts.get(i); if ((surpriseCount > 0) && (total == targetScore * 3 - 3)) { result++; surpriseCount--; tripletsTotalCounts.remove(i--); } else if ((surpriseCount == 0) && (total == targetScore * 3 - 3)) { tripletsTotalCounts.remove(i--); } } result += tripletsTotalCounts.size(); return result; } public static List<DanceFloor> parseFromFile(List<String> readInput) { List<DanceFloor> result = new ArrayList<DanceFloor>(); int testCaseCount = Integer.parseInt(readInput.get(0)); for (int i = 0; i < testCaseCount; i++) { String line[] = readInput.get(i + 1).split(" "); List<Integer> totalCounts = new ArrayList<Integer>(); for (int j = 0; j < Integer.parseInt(line[0]); j++) { totalCounts.add(Integer.parseInt(line[3 + j])); } result.add(new DanceFloor(totalCounts, Integer.parseInt(line[1]), Integer.parseInt(line[2]), Integer.parseInt(line[0]))); } return result; } @Override public String toString() { return "dancersCount = " + dancersCount + "; surpriseCount = " + surpriseCount + "; targetScore = " + targetScore + "; tripletsTotalCounts" + tripletsTotalCounts.toString(); } }
import java.util.*; public class Dancing { public static void main( String[] args ) { Scanner scan = new Scanner(System.in); int cases = scan.nextInt(); for (int i = 0; i < cases; i++) { int count = 0; int n = scan.nextInt(); int s = scan.nextInt(); int p = scan.nextInt(); for( int j = 0; j < n; j++) { int score = scan.nextInt(); if( reg(score) >= p ) { count++; } else if( s > 0 && spec(score) >= p ) { count++; s--; } } System.out.println("Case #" + (i+1) + ": " + count); } } public static int reg(int n) { if( n == 0) { return 0; } else if(n == 2 || n == 1) { return 1; } else if( (n%3) == 0) { return (n/3); } else if( (n%3) == 1) { return (n/3) + 1; } else if( (n%3) == 2) { return (n/3)+1; } return 0; } public static int spec(int n) { if( n== 0 ) { return 0; } else if(n == 1) { return 1; } else if(n == 2) { return 2; } else if( (n%3) == 0) { return (n/3)+1; } else if( (n%3) == 1) { return (n/3) + 1; } else if( (n%3) == 2) { return (n/3)+2; } return 0; } }