F1
stringlengths
6
6
F2
stringlengths
6
6
label
stringclasses
2 values
text_1
stringlengths
149
20.2k
text_2
stringlengths
48
42.7k
B22190
B21916
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 Tres { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("tres.txt")); int T = Integer.parseInt(in.readLine()); for(int t = 0; t < T; t++) { String[] temp = in.readLine().split(" "); int A = Integer.parseInt(temp[0]); int B = Integer.parseInt(temp[1]); HashMap<String, Integer> matches = new HashMap<String, Integer>(); for(int i = A; i <= B; i++) { String s = new Integer(i).toString(); int j; for(j = 0; j < s.length(); j++) { String stemp = s.substring(j) + s.substring(0,j); if(matches.containsKey(stemp)) { matches.put(stemp, matches.get(stemp)+1); //System.out.println(s + " matched with " + stemp); break; } } if(j == s.length()) matches.put(s, 1); } int answer = 0; for(String s : matches.keySet()) { int itemp = matches.get(s); answer += itemp*(itemp-1)/2; } System.out.println("Case #" + (t+1) + ": " + answer); } in.close(); } }
A22771
A22741
0
package com.menzus.gcj._2012.qualification.b; import com.menzus.gcj.common.InputBlockParser; import com.menzus.gcj.common.OutputProducer; import com.menzus.gcj.common.impl.AbstractProcessorFactory; public class BProcessorFactory extends AbstractProcessorFactory<BInput, BOutputEntry> { public BProcessorFactory(String inputFileName) { super(inputFileName); } @Override protected InputBlockParser<BInput> createInputBlockParser() { return new BInputBlockParser(); } @Override protected OutputProducer<BInput, BOutputEntry> createOutputProducer() { return new BOutputProducer(); } }
package GCJ_2012.QualifiactionRound; import java.io.*; import java.util.Arrays; import java.util.Scanner; public class B { static int[] scores; static int p; static int[][] dp; static int inf = 10000000; public static int solve(int idx, int remSurprising) { if (idx == scores.length) { if (remSurprising == 0) return 0; return -inf; } if (dp[idx][remSurprising] != -1) return dp[idx][remSurprising]; if (scores[idx] % 3 == 0) { if (remSurprising > 0 && scores[idx] / 3 != 0) { int maxOpt1 = scores[idx] / 3 + 1; int maxOpt2 = scores[idx] / 3; int opt1, opt2; if (maxOpt1 >= p) { opt1 = 1 + solve(idx + 1, remSurprising - 1); } else { opt1 = solve(idx + 1, remSurprising - 1); } if (maxOpt2 >= p) { opt2 = 1 + solve(idx + 1, remSurprising); } else { opt2 = solve(idx + 1, remSurprising); } return dp[idx][remSurprising] = Math.max(opt1, opt2); } else { int max = scores[idx] / 3; if (max >= p) { return dp[idx][remSurprising] = 1 + solve(idx + 1, remSurprising); } else { return dp[idx][remSurprising] = solve(idx + 1, remSurprising); } } } else if (scores[idx] % 3 == 1) { if (remSurprising > 0 && scores[idx] / 3 != 0) { int maxOpt1 = scores[idx] / 3 + 1; int maxOpt2 = scores[idx] / 3 + 1; int opt1, opt2; if (maxOpt1 >= p) { opt1 = 1 + solve(idx + 1, remSurprising - 1); } else { opt1 = solve(idx + 1, remSurprising - 1); } if (maxOpt2 >= p) { opt2 = 1 + solve(idx + 1, remSurprising); } else { opt2 = solve(idx + 1, remSurprising); } return dp[idx][remSurprising] = Math.max(opt1, opt2); } else { int max = scores[idx] / 3 + 1; if (max >= p) { return dp[idx][remSurprising] = 1 + solve(idx + 1, remSurprising); } else { return dp[idx][remSurprising] = solve(idx + 1, remSurprising); } } } else { if (remSurprising > 0) { int maxOpt1 = scores[idx] / 3 + 2; int maxOpt2 = scores[idx] / 3 + 1; int opt1, opt2; if (maxOpt1 >= p) { opt1 = 1 + solve(idx + 1, remSurprising - 1); } else { opt1 = solve(idx + 1, remSurprising - 1); } if (maxOpt2 >= p) { opt2 = 1 + solve(idx + 1, remSurprising); } else { opt2 = solve(idx + 1, remSurprising); } return dp[idx][remSurprising] = Math.max(opt1, opt2); } else { int max = scores[idx] / 3 + 1; if (max >= p) { return dp[idx][remSurprising] = 1 + solve(idx + 1, remSurprising); } else { return dp[idx][remSurprising] = solve(idx + 1, remSurprising); } } } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new FileReader("C:/Users/Mostafa/Downloads/B-large.in")); //Scanner sc = new Scanner(System.in); FileWriter fw = new FileWriter("D:/output.txt"); PrintWriter out = new PrintWriter(System.out); int cases = sc.nextInt(); for (int i = 0; i < cases; i++) { int N = sc.nextInt(); int S = sc.nextInt(); p = sc.nextInt(); scores = new int[N]; for (int j = 0; j < N; j++) { scores[j] = sc.nextInt(); } dp = new int[N][S + 1]; for (int j = 0; j < N; j++) Arrays.fill(dp[j], -1); int res = solve(0, S); fw.write("Case #" + (i + 1) + ": " + res + "\n"); out.print("Case #" + (i + 1) + ": " + res + "\n"); } fw.flush(); out.flush(); } }
B11327
B11392
0
package recycledNumbers; public class OutputData { private int[] Steps; public int[] getSteps() { return Steps; } public OutputData(int [] Steps){ this.Steps = Steps; for(int i=0;i<this.Steps.length;i++){ System.out.println("Test "+(i+1)+": "+Steps[i]); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author root */ public class Recycled { public static void main(String args[]) { int T; ArrayList a = reader("c:\\inp.in"); ArrayList out = new ArrayList(); String st = (String) a.get(0); T = Integer.parseInt(st); int ans; int i1, i2; for (int i = 0; i < T; i++) { st = (String) a.get(i + 1); Scanner sc = new Scanner(st); i1 = sc.nextInt(); i2 = sc.nextInt(); ans = findNoOfRecycle(i1, i2); out.add(ans); } writer("c:\\output.txt", out); } public static ArrayList reader(String filename) { FileInputStream fis = null; ArrayList a = new ArrayList(); String line = ""; try { fis = new FileInputStream(filename); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); while ((line = br.readLine()) != null) { a.add(line); } } catch (IOException ex) { } finally { try { fis.close(); } catch (IOException ex) { } } return a; } private static int findNoOfRecycle(int a, int b) { HashSet<Integer> done = new HashSet<Integer>(); int noOfMatches = 0, l, localmatches = 0; String sb, sbs, sbe; sbs = Integer.toString(a); sbe = Integer.toString(b); for (int i = a; i <= b; i++) { if (!done.contains(i)) { sb = Integer.toString(i); localmatches = 0; l = sb.length(); boolean flag = true; for (int k = 0; k < l - 1; k++) { if (sb.charAt(k) != sb.charAt(k + 1)) { flag = false; k = l; } } if (!flag) { for (int j = 0; j < l - 1; j++) { sb = sb.charAt(l - 1) + sb.substring(0, l - 1); if(sb.charAt(0)!='0') if (sb.compareTo(sbs) >= 0 && sb.compareTo(sbe) <= 0) { done.add(Integer.parseInt(sb)); localmatches++; } } } noOfMatches = noOfMatches + (localmatches * (localmatches + 1)) / 2; } } return noOfMatches; } private static void writer(String file, ArrayList out) { FileOutputStream fos = null; try { fos = new FileOutputStream(file); for (int i = 0; i < out.size(); i++) { try { String output = "Case #" + Integer.toString(i + 1) + ": " + out.get(i) + "\n"; fos.write(output.getBytes()); System.out.print(output); } catch (IOException ex) { Logger.getLogger(BotTrust.class.getName()).log(Level.SEVERE, null, ex); } } } catch (FileNotFoundException ex) { } finally { try { fos.close(); } catch (IOException ex) { } } } }
A11201
A12382
0
package CodeJam.c2012.clasificacion; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * Problem * * You're watching a show where Googlers (employees of Google) dance, and then * each dancer is given a triplet of scores by three judges. Each triplet of * scores consists of three integer scores from 0 to 10 inclusive. The judges * have very similar standards, so it's surprising if a triplet of scores * contains two scores that are 2 apart. No triplet of scores contains scores * that are more than 2 apart. * * For example: (8, 8, 8) and (7, 8, 7) are not surprising. (6, 7, 8) and (6, 8, * 8) are surprising. (7, 6, 9) will never happen. * * The total points for a Googler is the sum of the three scores in that * Googler's triplet of scores. The best result for a Googler is the maximum of * the three scores in that Googler's triplet of scores. Given the total points * for each Googler, as well as the number of surprising triplets of scores, * what is the maximum number of Googlers that could have had a best result of * at least p? * * For example, suppose there were 6 Googlers, and they had the following total * points: 29, 20, 8, 18, 18, 21. You remember that there were 2 surprising * triplets of scores, and you want to know how many Googlers could have gotten * a best result of 8 or better. * * With those total points, and knowing that two of the triplets were * surprising, the triplets of scores could have been: * * 10 9 10 6 6 8 (*) 2 3 3 6 6 6 6 6 6 6 7 8 (*) * * The cases marked with a (*) are the surprising cases. This gives us 3 * Googlers who got at least one score of 8 or better. There's no series of * triplets of scores that would give us a higher number than 3, so the answer * is 3. * * Input * * The first line of the input gives the number of test cases, T. T test cases * follow. Each test case consists of a single line containing integers * separated by single spaces. The first integer will be N, the number of * Googlers, and the second integer will be S, the number of surprising triplets * of scores. The third integer will be p, as described above. Next will be N * integers ti: the total points of the Googlers. * * Output * * For each test case, output one line containing "Case #x: y", where x is the * case number (starting from 1) and y is the maximum number of Googlers who * could have had a best result of greater than or equal to p. * * Limits * * 1 ≤ T ≤ 100. 0 ≤ S ≤ N. 0 ≤ p ≤ 10. 0 ≤ ti ≤ 30. At least S of the ti values * will be between 2 and 28, inclusive. * * Small dataset * * 1 ≤ N ≤ 3. * * Large dataset * * 1 ≤ N ≤ 100. * * Sample * * Input Output 4 Case #1: 3 3 1 5 15 13 11 Case #2: 2 3 0 8 23 22 21 Case #3: 1 * 2 1 1 8 0 Case #4: 3 6 2 8 29 20 8 18 18 21 * * @author Leandro Baena Torres */ public class B { public static void main(String[] args) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader("B.in")); String linea; int numCasos, N, S, p, t[], y, minSurprise, minNoSurprise; linea = br.readLine(); numCasos = Integer.parseInt(linea); for (int i = 0; i < numCasos; i++) { linea = br.readLine(); String[] aux = linea.split(" "); N = Integer.parseInt(aux[0]); S = Integer.parseInt(aux[1]); p = Integer.parseInt(aux[2]); t = new int[N]; y = 0; minSurprise = p + ((p - 2) >= 0 ? (p - 2) : 0) + ((p - 2) >= 0 ? (p - 2) : 0); minNoSurprise = p + ((p - 1) >= 0 ? (p - 1) : 0) + ((p - 1) >= 0 ? (p - 1) : 0); for (int j = 0; j < N; j++) { t[j] = Integer.parseInt(aux[3 + j]); if (t[j] >= minNoSurprise) { y++; } else { if (t[j] >= minSurprise) { if (S > 0) { y++; S--; } } } } System.out.println("Case #" + (i + 1) + ": " + y); } } }
package codeJam; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuffer pal; ArrayList<Integer> puntajes= new ArrayList(); int test= sc.nextInt(), N, S, P, rare, num, count; for (int i=1; i<=test; i++){ N= sc.nextInt(); S= sc.nextInt(); P= sc.nextInt(); count=0; P=3*P-2; rare= P-2; if (P==1) rare =1; System.out.print("Case #"+i+": "); for (int j=0; j<N; j++){ num=sc.nextInt(); if (num>=P){ count++; } else if ((S>0) && (num>=rare)){ S--; count++; } } System.out.println(count); } } }
B12115
B11966
0
package qual; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { new RecycledNumbers().run(); } private void run() { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int t = 0; t < T; t++) { int A = sc.nextInt(); int B = sc.nextInt(); int result = solve(A, B); System.out.printf("Case #%d: %d\n", t + 1, result); } } public int solve(int A, int B) { int result = 0; for (int i = A; i <= B; i++) { int dig = (int) Math.log10(A/*same as B*/) + 1; int aa = i; for (int d = 0; d < dig - 1; d++) { aa = (aa % 10) * (int)Math.pow(10, dig - 1) + (aa / 10); if (i == aa) { break; } if (i < aa && aa <= B) { // System.out.printf("(%d, %d) ", i, aa); result++; } } } return result; } }
package com.my; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { try { RecycledNumbers r = new RecycledNumbers(); String fileLocation = "C://Training//Google//RecycledNumbers//src//com//my//smallInput.txt"; BufferedReader reader = r.getInputFile(fileLocation); String line = reader.readLine(); int count =1; while ( ( line = reader.readLine()) != null ) { String inputs[] = line.split(" " ); int numCount = r.recycle(Integer.parseInt(inputs[0]),Integer.parseInt(inputs[1])); System.out.println("Case #" + count + ": " + numCount); ++count; } //System.out.println(r.recycle(100,999)); } catch (Exception e) { // TODO: handle exception } } } class RecycledNumbers { public BufferedReader getInputFile(String fileLocation) throws Exception{ BufferedReader reader = new BufferedReader(new FileReader(new File(fileLocation))); return reader; } int recycle(int first, int second) throws Exception{ int count = 0; for( int i=first; i<=second; ++i) { String str = Integer.toString(i); Set set = new HashSet(); int div = 1; for( int j =0 ; j<str.length()-1; ++j) { div = div*10; int trail = i % div ; String s = str.substring(0,str.length()- (j+1)); int newNum = Integer.parseInt(trail + s); if( i < newNum && newNum <= second) { if( !set.contains(newNum)) { set.add(newNum); ++count; } } } } return count; } }
B11318
B11900
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 gcj2012; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.LinkedList; public class RecycledNumbers { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader reader = new BufferedReader(new FileReader(new File("C:\\Users\\GAUTAM\\Downloads\\GCJ2012Inputs\\C-small-attempt0.in"))); int noOfInput = Integer.parseInt(reader.readLine()); StringBuilder finalOutput = new StringBuilder(); for(int i=1;i<=noOfInput;i++) { String input = reader.readLine(); String[] range = input.split(" "); finalOutput.append("Case #"+i + ": " + result(Integer.parseInt(range[0]),Integer.parseInt(range[1]))+"\n"); } reader.close(); BufferedWriter writer = new BufferedWriter(new FileWriter(new File("C:\\Users\\GAUTAM\\Downloads\\GCJ2012Outputs\\C-small.out"))); writer.write(finalOutput.toString()); writer.close(); } public static int result(int A, int B) { HashSet<String> result = new HashSet<String>(); for(int i = A; i <= B;i++) { LinkedList<String> digits = digits(i); for(int k =0 ; k < digits.size()-1; k++) { int m = rightshift(digits,k); if(m >= A && m <= B && digits.size() == digits(m).size() && m != i) { if(!result.contains(String.valueOf(i) + "-" + String.valueOf(m)) && !result.contains(String.valueOf(m) + "-" + String.valueOf(i))) { result.add(String.valueOf(i) + "-" + String.valueOf(m)); } } } } return result.size(); } public static LinkedList<String> digits(int num) { LinkedList<String> digits = new LinkedList<String>(); while (num > 0 ){ int r = num % 10; digits.addFirst(String.valueOf(r)); num = num / 10; } return digits; } public static int getNum(LinkedList<String> digits) { StringBuilder builder = new StringBuilder(); for(String a : digits) { builder.append(a); } return Integer.parseInt(builder.toString()); } public static int rightshift(LinkedList<String> digits,int noOfDig) { LinkedList<String> newList = new LinkedList<String>(); int k = 0; for(int i = digits.size()-noOfDig-1; i < digits.size();i++ ) { newList.add(k, digits.get(i)); k++; } for(int i = 0; i < digits.size()-noOfDig-1;i++ ) { newList.add(k, digits.get(i)); k++; } return getNum(newList); } }
B13196
B11522
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Q3M { public static void main(String[] args) throws Exception { compute(); } private static void compute() throws Exception { BufferedReader br = new BufferedReader(new FileReader(new File( "C:\\work\\Q3\\C-small-attempt0.in"))); String line = null; int i = Integer.parseInt(br.readLine()); List l = new ArrayList(); for (int j = 0; j < i; j++) { line = br.readLine(); String[] nums = line.split(" "); l.add(calculate(nums)); } writeOutput(l); } private static int calculate(String[] nums) { int min = Integer.parseInt(nums[0]); int max = Integer.parseInt(nums[1]); int count = 0; List l = new ArrayList(); for (int i = min; i <= max; i++) { for (int times = 1; times < countDigits(i); times++) { int res = shiftNum(i, times); if (res <= max && i < res) { if ((!l.contains((i + ":" + res)))) { l.add(i + ":" + res); l.add(res + ":" + i); count++; } } } } return count; } private static boolean checkZeros(int temp, int res) { if (temp % 10 == 0 || res % 10 == 0) return false; return true; } private static int shiftNum(int n, int times) { int base = (int) Math.pow(10, times); int temp2 = n / base; int placeHolder = (int) Math.pow((double) 10, (double) countDigits(temp2)); int res = placeHolder * (n % base) + temp2; if (countDigits(res) == countDigits(n)) { return res; } else { return 2000001; } } public static int countDigits(int x) { if (x < 10) return 1; else { return 1 + countDigits(x / 10); } } private static void writeOutput(List l) throws Exception { StringBuffer b = new StringBuffer(); int i = 1; BufferedWriter br = new BufferedWriter(new FileWriter(new File( "C:\\work\\Q3\\ans.txt"))); for (Iterator iterator = l.iterator(); iterator.hasNext();) { br.write("Case #" + i++ + ": " + iterator.next()); br.newLine(); } br.close(); } }
import java.io.*; import java.math.*; import java.util.*; import java.text.*; import java.util.regex.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.lang.Integer.*; import static java.lang.Double.*; import static java.lang.Character.*; public class C { static class Pair { int a, b; public Pair(int a, int b) { super(); this.a = a; this.b = b; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (a != other.a) return false; if (b != other.b) return false; return true; } } Object solve() { String As = sc.next(); int l = As.length(); int A = parseInt(As); int B = sc.nextInt(); int ml = (int)pow(10,l-1); HashSet<Pair> used = new HashSet<Pair>(); for (int n = A; n < B; n++) { int m = n; for (int i = 0; i < l; i++) { m = m/10 + (m%10)*ml; if (n < m && m <= B) used.add(new Pair(n,m)); } } return used.size(); } private static Scanner sc; private static PrintWriter fw; public static void main(String[] args) throws Exception { String inFile; // inFile = "input.txt"; inFile = "C-small-attempt0.in"; // inFile = "A-large.in"; // sc = new Scanner(System.in); sc = new Scanner(new FileInputStream(inFile)); fw = new PrintWriter(new FileWriter("output.txt", false)); int N = sc.nextInt(); sc.nextLine(); for (int cas = 1; cas <= N; cas++) { fw.print("Case #" + cas + ": "); // fw.println("Case #" + cas + ": "); Object res = new C().solve(); if (res instanceof Double) fw.printf("%.10f\n", res); else fw.printf("%s\n", res); fw.flush(); } fw.close(); sc.close(); } }
B10858
B10572
0
package be.mokarea.gcj.common; public abstract class TestCaseReader<T extends TestCase> { public abstract T nextCase() throws Exception; public abstract int getMaxCaseNumber(); }
package practice; import java.util.*; public class Recycled { public static void main(String args[]){ Scanner sc = new Scanner(System.in); int cases = sc.nextInt(); for(int i = 0; i<cases;i++){ int caseCounter = i+1; int firstNum = sc.nextInt(); int secondNum = sc.nextInt(); int result=0; List<Integer> resultList = new ArrayList<Integer>(); for(int j = firstNum;j<=secondNum;j++){ String first = Integer.toString(j); for(int k = 0; k<first.length()-1; k++){ String modified = first.substring(first.length()-k-1)+first.substring(0, first.length()-k-1); int newNumber = Integer.parseInt(modified); if(newNumber<=secondNum && newNumber>j && newNumber>=firstNum){ result++; } } } System.out.println("Case #"+caseCounter+": "+result); } } }
B10361
B11440
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); } }
//Kholofelo Moyaba //Problem C codejam //14 April 2012 import java.util.Scanner; class RecycledNumbers { public static void main(String[] args) { Scanner input = new Scanner(System.in); int cases = input.nextInt(); for(int i=1;i<=cases;i++) { int a = input.nextInt(); int b = input.nextInt(); int digits = (a+"").length()-1;//number of digits -1 int factor = 1;//factor in order of a and b for(int j=0;j<digits;j++,factor*=10);//factor=10^digit int result = 0; for(int n=a;n<b;n++){ int[] buffer = new int[digits];//current pairs int m = n;//rotation of n into m for(int j=0;j<digits;j++){ m = m/10 + (m%10)*factor;//rotate if(m<=b && n<m)//recycled pair {//check if duplicate boolean distinct = true; for(int k=0;k<j;k++) if(buffer[k]==m) { distinct = false; break; } if(distinct) { result++; buffer[j] = m; } } } } System.out.println("Case #"+i+": "+result); } } }
A11502
A12224
0
package template; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class TestCase { private boolean isSolved; private Object solution; private Map<String, Integer> intProperties; private Map<String, ArrayList<Integer>> intArrayProperties; private Map<String, ArrayList<ArrayList<Integer>>> intArray2DProperties; private Map<String, Double> doubleProperties; private Map<String, ArrayList<Double>> doubleArrayProperties; private Map<String, ArrayList<ArrayList<Double>>> doubleArray2DProperties; private Map<String, String> stringProperties; private Map<String, ArrayList<String>> stringArrayProperties; private Map<String, ArrayList<ArrayList<String>>> stringArray2DProperties; private Map<String, Boolean> booleanProperties; private Map<String, ArrayList<Boolean>> booleanArrayProperties; private Map<String, ArrayList<ArrayList<Boolean>>> booleanArray2DProperties; private Map<String, Long> longProperties; private Map<String, ArrayList<Long>> longArrayProperties; private Map<String, ArrayList<ArrayList<Long>>> longArray2DProperties; private int ref; private double time; public TestCase() { initialise(); } private void initialise() { isSolved = false; intProperties = new HashMap<>(); intArrayProperties = new HashMap<>(); intArray2DProperties = new HashMap<>(); doubleProperties = new HashMap<>(); doubleArrayProperties = new HashMap<>(); doubleArray2DProperties = new HashMap<>(); stringProperties = new HashMap<>(); stringArrayProperties = new HashMap<>(); stringArray2DProperties = new HashMap<>(); booleanProperties = new HashMap<>(); booleanArrayProperties = new HashMap<>(); booleanArray2DProperties = new HashMap<>(); longProperties = new HashMap<>(); longArrayProperties = new HashMap<>(); longArray2DProperties = new HashMap<>(); ref = 0; } public void setSolution(Object o) { solution = o; isSolved = true; } public Object getSolution() { if (!isSolved) { Utils.die("getSolution on unsolved testcase"); } return solution; } public void setRef(int i) { ref = i; } public int getRef() { return ref; } public void setTime(double d) { time = d; } public double getTime() { return time; } public void setInteger(String s, Integer i) { intProperties.put(s, i); } public Integer getInteger(String s) { return intProperties.get(s); } public void setIntegerList(String s, ArrayList<Integer> l) { intArrayProperties.put(s, l); } public void setIntegerMatrix(String s, ArrayList<ArrayList<Integer>> l) { intArray2DProperties.put(s, l); } public ArrayList<Integer> getIntegerList(String s) { return intArrayProperties.get(s); } public Integer getIntegerListItem(String s, int i) { return intArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Integer>> getIntegerMatrix(String s) { return intArray2DProperties.get(s); } public ArrayList<Integer> getIntegerMatrixRow(String s, int row) { return intArray2DProperties.get(s).get(row); } public Integer getIntegerMatrixItem(String s, int row, int column) { return intArray2DProperties.get(s).get(row).get(column); } public ArrayList<Integer> getIntegerMatrixColumn(String s, int column) { ArrayList<Integer> out = new ArrayList(); for(ArrayList<Integer> row : intArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setDouble(String s, Double i) { doubleProperties.put(s, i); } public Double getDouble(String s) { return doubleProperties.get(s); } public void setDoubleList(String s, ArrayList<Double> l) { doubleArrayProperties.put(s, l); } public void setDoubleMatrix(String s, ArrayList<ArrayList<Double>> l) { doubleArray2DProperties.put(s, l); } public ArrayList<Double> getDoubleList(String s) { return doubleArrayProperties.get(s); } public Double getDoubleListItem(String s, int i) { return doubleArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Double>> getDoubleMatrix(String s) { return doubleArray2DProperties.get(s); } public ArrayList<Double> getDoubleMatrixRow(String s, int row) { return doubleArray2DProperties.get(s).get(row); } public Double getDoubleMatrixItem(String s, int row, int column) { return doubleArray2DProperties.get(s).get(row).get(column); } public ArrayList<Double> getDoubleMatrixColumn(String s, int column) { ArrayList<Double> out = new ArrayList(); for(ArrayList<Double> row : doubleArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setString(String s, String t) { stringProperties.put(s, t); } public String getString(String s) { return stringProperties.get(s); } public void setStringList(String s, ArrayList<String> l) { stringArrayProperties.put(s, l); } public void setStringMatrix(String s, ArrayList<ArrayList<String>> l) { stringArray2DProperties.put(s, l); } public ArrayList<String> getStringList(String s) { return stringArrayProperties.get(s); } public String getStringListItem(String s, int i) { return stringArrayProperties.get(s).get(i); } public ArrayList<ArrayList<String>> getStringMatrix(String s) { return stringArray2DProperties.get(s); } public ArrayList<String> getStringMatrixRow(String s, int row) { return stringArray2DProperties.get(s).get(row); } public String getStringMatrixItem(String s, int row, int column) { return stringArray2DProperties.get(s).get(row).get(column); } public ArrayList<String> getStringMatrixColumn(String s, int column) { ArrayList<String> out = new ArrayList(); for(ArrayList<String> row : stringArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setBoolean(String s, Boolean b) { booleanProperties.put(s, b); } public Boolean getBoolean(String s) { return booleanProperties.get(s); } public void setBooleanList(String s, ArrayList<Boolean> l) { booleanArrayProperties.put(s, l); } public void setBooleanMatrix(String s, ArrayList<ArrayList<Boolean>> l) { booleanArray2DProperties.put(s, l); } public ArrayList<Boolean> getBooleanList(String s) { return booleanArrayProperties.get(s); } public Boolean getBooleanListItem(String s, int i) { return booleanArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Boolean>> getBooleanMatrix(String s) { return booleanArray2DProperties.get(s); } public ArrayList<Boolean> getBooleanMatrixRow(String s, int row) { return booleanArray2DProperties.get(s).get(row); } public Boolean getBooleanMatrixItem(String s, int row, int column) { return booleanArray2DProperties.get(s).get(row).get(column); } public ArrayList<Boolean> getBooleanMatrixColumn(String s, int column) { ArrayList<Boolean> out = new ArrayList(); for(ArrayList<Boolean> row : booleanArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setLong(String s, Long b) { longProperties.put(s, b); } public Long getLong(String s) { return longProperties.get(s); } public void setLongList(String s, ArrayList<Long> l) { longArrayProperties.put(s, l); } public void setLongMatrix(String s, ArrayList<ArrayList<Long>> l) { longArray2DProperties.put(s, l); } public ArrayList<Long> getLongList(String s) { return longArrayProperties.get(s); } public Long getLongListItem(String s, int i) { return longArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Long>> getLongMatrix(String s) { return longArray2DProperties.get(s); } public ArrayList<Long> getLongMatrixRow(String s, int row) { return longArray2DProperties.get(s).get(row); } public Long getLongMatrixItem(String s, int row, int column) { return longArray2DProperties.get(s).get(row).get(column); } public ArrayList<Long> getLongMatrixColumn(String s, int column) { ArrayList<Long> out = new ArrayList(); for(ArrayList<Long> row : longArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class DWiGoogler { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("B-small-attempt0.in")); BufferedWriter out = new BufferedWriter(new FileWriter("out.txt")); int T = Integer.parseInt(in.readLine()); int cnt = 0; while(T > 0){ T--; cnt++; int result = 0; String str1 = in.readLine(); String[] str2= str1.split(" "); int n = Integer.parseInt(str2[0]); int s = Integer.parseInt(str2[1]); int p = Integer.parseInt(str2[2]); int [] x = new int[n]; for(int i=0; i<n; i++){ int score = Integer.parseInt(str2[i+3]); int min = score / 3; int rest = score%3; if(min>=p){ result++; }else if(p-min==1 && rest>0){ result++; }else if((s>0 && rest==0 && p-min==1 && min != 0) || (s>0 && rest==2 && p-min==2 && min !=0)){ result++; s--; } } out.write("Case #"+ cnt +": " + result+"\n"); } in.close(); out.close(); } }
B11318
B10334
0
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); int casos=1, a, b, n, m, cont; while(t!=0){ a=sc.nextInt(); b=sc.nextInt(); if(a>b){ int aux=a; a=b; b=aux; } System.out.printf("Case #%d: ",casos++); if(a==b){ System.out.printf("%d\n",0); }else{ cont=0; for(n=a;n<b;n++){ for(m=n+1;m<=b;m++){ if(isRecycled(n,m)) cont++; } } System.out.printf("%d\n",cont); } t--; } } public static boolean isRecycled(int n1, int n2){ String s1, s2, aux; s1 = String.valueOf( n1 ); s2 = String.valueOf( n2 ); boolean r = false; for(int i=0;i<s1.length();i++){ aux=""; aux=s1.substring(i,s1.length())+s1.substring(0,i); // System.out.println(aux); if(aux.equals(s2)){ r=true; break; } } return r; } }
import java.util.HashSet; public class CSolver extends SolverModule { @Override String processLine(String line) { int[] lines = toIntegers(line.split(" ")); int A = lines[0]; int B = lines[1]; HashSet<String> hashSet = new HashSet<String>(); for (int i = A; i < B; i++) { int length = String.valueOf(A).length(); for (int j = 1; j < length; j++) { int a = rightMove(i, length - j); int b = leftMove(i, j) - leftMove(rightMove(i, (length - j)), length); int total = a + b; if (total >= A && total <= B && total > i) { hashSet.add(i + "," + total); } } } return String.valueOf(hashSet.size()); } private int leftMove(int number, int count) { number = number * (int) (Math.pow(10, count)); return number; } private int rightMove(int number, int count) { if (count == 0) { return number; } number = (number / (int) (Math.pow(10, count))); return number; } }
A22771
A22231
0
package com.menzus.gcj._2012.qualification.b; import com.menzus.gcj.common.InputBlockParser; import com.menzus.gcj.common.OutputProducer; import com.menzus.gcj.common.impl.AbstractProcessorFactory; public class BProcessorFactory extends AbstractProcessorFactory<BInput, BOutputEntry> { public BProcessorFactory(String inputFileName) { super(inputFileName); } @Override protected InputBlockParser<BInput> createInputBlockParser() { return new BInputBlockParser(); } @Override protected OutputProducer<BInput, BOutputEntry> createOutputProducer() { return new BOutputProducer(); } }
package trupti; import java.io.*; import java.util.*; public class Main2 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // char c[]; int count=0; try { FileOutputStream out=new FileOutputStream("out8.out"); Scanner inFIle=new Scanner(new FileReader("B-large.in") ); int t=inFIle.nextInt(); while (t!=0) { count++; int a=0,b=0; int n=inFIle.nextInt(); int s=inFIle.nextInt(); int p=inFIle.nextInt(); int ti[]=new int[n]; int m[][]=new int[n][3]; int cn=0; for(int i=0;i<n;i++) { ti[i]=inFIle.nextInt(); m[i][0]=ti[i]/3; m[i][1]=ti[i]/3; m[i][2]=ti[i]/3; //System.out.println(m[i][0]+" "+m[i][3]+" "+m[i][2]); if((ti[i]%3)==2) { m[i][0]++; m[i][1]++; } if((ti[i]%3)==1) m[i][0]++; if((m[i][0]<p) &(m[i][0]>=1)) { a=p-m[i][0]; /*if(a==2 & s>0) if((m[i][0]==m[i][1])&(m[i][1]==m[i][2])) { m[i][0]+=2; m[i][1]--; m[i][2]--; s--; }*/ if(a==1 & s>0) { if((m[i][0]==m[i][1])&(m[i][1]==m[i][2])) { m[i][0]+=1; m[i][1]--; // m[i][2]--; s--; } else { if((m[i][0]==m[i][1])&((m[i][1]-m[i][2])==1)) { m[i][0]+=1; m[i][1]--; // m[i][2]--; s--; } } } } System.out.println(m[i][0]); if(m[i][0]>=p) cn++; } out.write(("Case #"+count+": "+cn+"\n").getBytes()); System.out.print("case #"+count+": "+cn+"\n"); //System.out.println(str); t--; } } catch (Exception e) { // TODO: handle exception } } }
B11696
B12354
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recycled; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.TreeSet; /** * * @author Alfred */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream("C-small-attempt0.in"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter outFile = new FileWriter("out.txt"); PrintWriter out = new PrintWriter(outFile); String line; line = br.readLine(); int cases = Integer.parseInt(line); for (int i=1; i<=cases;i++){ line = br.readLine(); String[] values = line.split(" "); int A = Integer.parseInt(values[0]); int B = Integer.parseInt(values[1]); int total=0; for (int n=A; n<=B;n++){ TreeSet<String> solutions = new TreeSet<String>(); for (int k=1;k<values[1].length();k++){ String m = circshift(n,k); int mVal = Integer.parseInt(m); if(mVal<=B && mVal!=n && mVal> n && !m.startsWith("0") && m.length()==Integer.toString(n).length() ) { solutions.add(m); } } total+=solutions.size(); } out.println("Case #"+i+": "+total); } in.close(); out.close(); } catch (Exception e) {//Catch exception if any System.err.println("Error: " + e.getMessage()); } } private static String circshift(int n, int k) { String nString=Integer.toString(n); int len=nString.length(); String m = nString.substring(len-k)+nString.subSequence(0, len-k); //System.out.println(n+" "+m); return m; } }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class C { public static void main(String[] args) throws Throwable { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int numCases = Integer.parseInt(reader.readLine()); for (int c = 1; c <= numCases; c++) { System.out.println("Case #" + c + ": " + solveCase(reader.readLine())); } } private static int solveCase(String line) { String[] tokens = line.split(" "); int a = Integer.parseInt(tokens[0]); int b = Integer.parseInt(tokens[1]); Set<String> alreadyFound; int count = 0; if (b > 9) { for (int n = a; n <= b; n++) { String nstr = String.valueOf(n); int nlen = nstr.length(); alreadyFound = new HashSet<String>(); for (int index = 1; index < nlen; index++) { String mstr = nstr.substring(index, nlen) + nstr.substring(0, index); int m = Integer.parseInt(mstr); mstr = String.valueOf(m); if (mstr.length() == nlen && alreadyFound.add(mstr)) { if (m > n && m >=a && m <= b) { count++; } } } } } return count; } }
B11361
B12985
0
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class C{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int caze, T; int A, B; void run(){ T=sc.nextInt(); for(caze=1; caze<=T; caze++){ A=sc.nextInt(); B=sc.nextInt(); solve(); } } void solve(){ int ans=0; for(int n=A; n<=B; n++){ int digit=(int)(log10(n)+EPS); int d=(int)pow(10, digit); // debug("n", n); for(int m=rot(n, d); m!=n; m=rot(m, d)){ // debug("m", m); if(n<m&&m<=B){ ans++; } } } answer(ans+""); } int rot(int n, int d){ return n/10+n%10*d; } void answer(String s){ println("Case #"+caze+": "+s); } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(deepToString(os)); } public static void main(String[] args){ try{ System.setIn(new FileInputStream("dat/C-small.in")); System.setOut(new PrintStream(new FileOutputStream("dat/C-small.out"))); }catch(Exception e){} new C().run(); System.out.flush(); System.out.close(); } }
package qualification_2012; import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class C { public void run() { try { Scanner in = new Scanner(new File("C.in")); PrintWriter out = new PrintWriter(new File("C.txt")); int T = in.nextInt(); for (int TC = 1; TC <= T; TC++) { int A = in.nextInt(); int B = in.nextInt(); long counter = 0; HashSet<String> set = new HashSet<String>(); for (int n = A; n < B; n++) { for (int i = 10; i < n; i*=10) { String p1 = (n/i) + ""; p1 = (n%i) + p1; int m = Integer.parseInt(p1); String t = n+"-"+m; if (m > n && m <= B && !set.contains(t)) { set.add(t); counter++; } } } System.out.println("Case #" + TC + ": " + counter); out.println("Case #" + TC + ": " + counter); } out.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new C().run(); } }
B10231
B12177
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.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Scanner; public class RecycledNumbers { static Scanner sc; public static void main(String a[]) throws FileNotFoundException { int n,i; int res; sc= new Scanner(new FileInputStream("d:\\test\\a.in")); PrintStream out=new PrintStream(new FileOutputStream("d:\\test\\a.out")); n=sc.nextInt(); sc.nextLine(); for(i=1;i<=n;i++) { res=process(); out.println("Case #"+i+": "+res); } } static int process() { int res=0; int low,high,i; low=sc.nextInt(); high=sc.nextInt(); for(i=low;i<=high;i++) res+=value(i,low,high); res=res/2; return res; } static int value(int a,int low,int high) { int i,res=0,n=1,p=10,q,val,prev=0; if(a<10) return 0; if(a<100) { n=2; q=10; } else if(a<1000) { n=3; q=100; } else if(a<10000) { n=4; q=1000; } else if(a<100000) { n=5; q=10000; } else if(a<1000000) { n=6; q=100000; } else { n=7; q=1000000; } for(i=1;i<n;i++) { val = ((a%p)*q)+(a/p); if(val>=low && val<=high && val!=a && val!=prev) { prev=val; res++; } p=p*10; q=q/10; } return res; } }
A11917
A10049
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 QualificationRound.dancingwiththegooglers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Scoring { private List<String> inputLines = new ArrayList<String>(); private List<String> outputLines = new ArrayList<String>(); private static final String INPUT_FILE_NAME = "B-small-attempt0.in"; private static final String OUTPUT_FILE_NAME = "output.txt"; private List<SingleCase> cases = new ArrayList<Scoring.SingleCase>(); public static void main(String[] args) { Scoring s = new Scoring(); s.readLines(); s.parseLines(); s.generateOutput(); s.outputLines(); } private void readLines() { try { BufferedReader reader = new BufferedReader(new FileReader(INPUT_FILE_NAME)); String line = reader.readLine(); line = reader.readLine(); while (line != null) { inputLines.add(line); line = reader.readLine(); } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void parseLines() { for (String inputLine : inputLines) { int readNumbers = 0; SingleCase singleCase = new SingleCase(); String[] split = inputLine.split(" "); for (String s : split) { switch (readNumbers) { case 0: singleCase.numberOfGooglers = Integer.parseInt(s); break; case 1: singleCase.numberOfSurprises = Integer.parseInt(s); break; case 2: singleCase.minBestResult = Integer.parseInt(s); break; default: singleCase.scores.add(Integer.parseInt(s)); } readNumbers++; } cases.add(singleCase); } } private void generateOutput() { int caseNumber = 1; for (SingleCase singleCase : cases) { outputLines.add(getOutputPrefix(caseNumber++) + singleCase.getResult()); } } private void outputLines() { try { BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE_NAME, false)); for (String line : outputLines) { writer.write(line); if (!line.equals(outputLines.get(outputLines.size() - 1))) { writer.write("\n"); } } writer.close(); } catch (IOException e) { e.printStackTrace(); } } private class SingleCase { @SuppressWarnings("unused") //unnecessary. Just use number of scores private int numberOfGooglers = 0; private int numberOfSurprises = 0; private int minBestResult = 0; private List<Integer> scores = new ArrayList<Integer>(); private int getResult() { int clearPasses = 0; int potentialSurprises = 0; //Minimum clear pass is x + x-1 + x-1 where x is the minBestResult int minForClearPass = (minBestResult * 3) - 2; //Minimum surprise pass is x + x-2 + x-2 where x is the minBestResult int minForSurprisePass = (minBestResult * 3) - 4; if (minForSurprisePass < 1) { if (minBestResult == 0) { minForSurprisePass = 0; } else { minForSurprisePass = 1; } } for (int score : scores) { if (score >= minForClearPass) { clearPasses++; } else if (score >= minForSurprisePass) { potentialSurprises++; } } return clearPasses + (Math.min(potentialSurprises, numberOfSurprises)); } } private String getOutputPrefix(int number) { return "Case #" + number + ": "; } }
A11277
A10242
0
package googlers; import java.util.Scanner; import java.util.PriorityQueue; import java.util.Comparator; public class Googlers { public static void main(String[] args) { int n,s,p,count=0,t; Scanner sin=new Scanner(System.in); t=Integer.parseInt(sin.nextLine()); int result[]=new int[t]; int j=0; if(t>=1 && t<=100) { for (int k = 0; k < t; k++) { count=0; String ip = sin.nextLine(); String[]tokens=ip.split(" "); n=Integer.parseInt(tokens[0]); s=Integer.parseInt(tokens[1]); p=Integer.parseInt(tokens[2]); if( (s>=0 && s<=n) && (p>=0 && p<=10) ) { int[] total=new int[n]; for (int i = 0; i < n; i++) { total[i] = Integer.parseInt(tokens[i+3]); } Comparator comparator=new PointComparator(); PriorityQueue pq=new PriorityQueue<Point>(1, comparator); for (int i = 0; i < n; i++) { int x=total[i]/3; int r=total[i]%3; if(x>=p) count++; else if(x<(p-2)) continue; else { //System.out.println("enter "+x+" "+(p-2)); if(p-x==1) { Point temp=new Point(); temp.q=x; temp.r=r; pq.add(temp); } else // p-x=2 { if(r==0) continue; else { Point temp=new Point(); temp.q=x; temp.r=r; pq.add(temp); } } } //System.out.println("hi "+pq.size()); } while(pq.size()!=0) { Point temp=(Point)pq.remove(); if(p-temp.q==1 && temp.q!=0) { if(temp.r>=1) count++; else { if(s!=0) { s--; count++; } } } else if(p-temp.q==2) { if(s!=0 && (temp.q+temp.r)>=p) { s--; count++; } } } //System.out.println(p); result[j++]=count; } } for (int i = 0; i < t; i++) { System.out.println("Case #"+(i+1)+": "+result[i]); } } } /*Point x=new Point(); x.q=8; Point y=new Point(); y.q=6; Point z=new Point(); z.q=7; pq.add(x); pq.add(y); pq.add(z); */ } class PointComparator implements Comparator<Point> { @Override public int compare(Point x, Point y) { // Assume neither string is null. Real code should // probably be more robust if (x.q < y.q) { return 1; } if (x.q > y.q) { return -1; } return 0; } } class Point { int q,r; public int getQ() { return q; } public void setQ(int q) { this.q = q; } public int getR() { return r; } public void setR(int r) { this.r = r; } }
package com.googlecode.contest.dancing; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class DancingGooglers { public static void main(String[] args) throws Exception { File outputFile = new File("dancing_googlers_output.txt"); FileOutputStream fos = new FileOutputStream(outputFile); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fos)); FileInputStream fis = new FileInputStream(args[0]); final String preface = "Case #"; BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis)); String numberOfTestCasesString = bufferedReader.readLine(); int numberOfTestCases = Integer.parseInt(numberOfTestCasesString); for (int i = 1; i <= numberOfTestCases; i++) { DancingTestCase testCase = parseString(i, bufferedReader.readLine()); solveTestCase(testCase); System.out.println(preface + i + ": " + testCase.getAnswer()); bufferedWriter.write(preface + i + ": " + testCase.getAnswer() ); bufferedWriter.newLine(); bufferedWriter.flush(); } } public static void solveTestCase(DancingTestCase testCase) { int possibleGooglers = 0; int target = testCase.scoreToBeat; int usedSurprises = 0; //short circuit for the easiest case if (target == 0) { testCase.setAnswer(testCase.numberOfDancers); return; } for (String score : testCase.totalScores) { int tripletScore = Integer.parseInt(score); int quotient = tripletScore/3; int modulus = tripletScore%3; if (quotient >= testCase.scoreToBeat) { System.out.println("1 processing score: " + score); possibleGooglers++; } else if (tripletScore == 0 && testCase.scoreToBeat> 0) { //continue; System.out.println("2 processing score: " + score); } else if (quotient + 2 < testCase.scoreToBeat) { //continue; System.out.println("3 processing score: " + score); } else if (quotient + 2 == testCase.scoreToBeat && modulus == 2 && usedSurprises < testCase.surprises) { possibleGooglers++; usedSurprises++; System.out.println("3A processing score: " + score); } else if (quotient + 2 == testCase.scoreToBeat ) { //continue System.out.println("4 processing score: " + score); } else if (modulus > 0) { possibleGooglers++; System.out.println("5 processing score: " + score); } else if (modulus == 0 && usedSurprises < testCase.surprises) { possibleGooglers++; usedSurprises++; System.out.println("6 processing score: " + score); } else if (modulus == 0 && usedSurprises >= testCase.surprises) { //continue System.out.println("7 processing score: " + score); } else { throw new IllegalArgumentException("couldn't handle score: " + score); } } testCase.setAnswer(possibleGooglers); } public static DancingTestCase parseString(final int testCaseNumber, final String s) { StringTokenizer tokenizer = new StringTokenizer(s); String dancerString = tokenizer.nextToken(); int numberOfDancers = Integer.parseInt(dancerString); String surpriseString = tokenizer.nextToken(); int surprises = Integer.parseInt(surpriseString); String scoreString = tokenizer.nextToken(); int scoreToBeat = Integer.parseInt(scoreString); ArrayList<String> scores = new ArrayList<String>(numberOfDancers); while (tokenizer.hasMoreTokens()) { scores.add(tokenizer.nextToken()); } return new DancingTestCase(testCaseNumber, numberOfDancers, surprises, scoreToBeat, scores ); } static class DancingTestCase implements Comparable { final int testCaseNumber; final int numberOfDancers; final int surprises; final int scoreToBeat; final List<String> totalScores; private int answer; public DancingTestCase(int testCaseNumber, int numberOfDancers, int surprises, int scoreToBeat, List<String> totalScores) { this.testCaseNumber = testCaseNumber; this.numberOfDancers = numberOfDancers; this.surprises = surprises; this.scoreToBeat = scoreToBeat; this.totalScores = totalScores; } public int compareTo(Object o) { return 0; } public int getAnswer() { return answer; } public void setAnswer(int answer) { this.answer = answer; } } }
B10899
B10699
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class ReadFile { public static void main(String[] args) throws Exception { String srcFile = "C:" + File.separator + "Documents and Settings" + File.separator + "rohit" + File.separator + "My Documents" + File.separator + "Downloads" + File.separator + "C-small-attempt1.in.txt"; String destFile = "C:" + File.separator + "Documents and Settings" + File.separator + "rohit" + File.separator + "My Documents" + File.separator + "Downloads" + File.separator + "C-small-attempt0.out"; File file = new File(srcFile); List<String> readData = new ArrayList<String>(); FileReader fileInputStream = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileInputStream); StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { readData.add(line); } stringBuilder.append(generateOutput(readData)); File writeFile = new File(destFile); if (!writeFile.exists()) { writeFile.createNewFile(); } FileWriter fileWriter = new FileWriter(writeFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(stringBuilder.toString()); bufferedWriter.close(); System.out.println("output" + stringBuilder); } /** * @param number * @return */ private static String generateOutput(List<String> number) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < number.size(); i++) { if (i == 0) { continue; } else { String tempString = number.get(i); String[] temArr = tempString.split(" "); stringBuilder.append("Case #" + i + ": "); stringBuilder.append(getRecNumbers(temArr[0], temArr[1])); stringBuilder.append("\n"); } } if (stringBuilder.length() > 0) { stringBuilder.deleteCharAt(stringBuilder.length() - 1); } return stringBuilder.toString(); } // /* This method accepts method for google code jam */ // private static String method(String value) { // int intValue = Integer.valueOf(value); // double givenExpr = 3 + Math.sqrt(5); // double num = Math.pow(givenExpr, intValue); // String valArr[] = (num + "").split("\\."); // int finalVal = Integer.valueOf(valArr[0]) % 1000; // // return String.format("%1$03d", finalVal); // // } // // /* This method accepts method for google code jam */ // private static String method2(String value) { // StringTokenizer st = new StringTokenizer(value, " "); // String test[] = value.split(" "); // StringBuffer str = new StringBuffer(); // // for (int i = 0; i < test.length; i++) { // // test[i]=test[test.length-i-1]; // str.append(test[test.length - i - 1]); // str.append(" "); // } // str.deleteCharAt(str.length() - 1); // String strReversedLine = ""; // // while (st.hasMoreTokens()) { // strReversedLine = st.nextToken() + " " + strReversedLine; // } // // return str.toString(); // } private static int getRecNumbers(String no1, String no2) { int a = Integer.valueOf(no1); int b = Integer.valueOf(no2); Set<String> dupC = new HashSet<String>(); for (int i = a; i <= b; i++) { int n = i; List<String> value = findPerm(n); for (String val : value) { if (Integer.valueOf(val) <= b && Integer.valueOf(val) >= a && n < Integer.valueOf(val)) { dupC.add(n + "-" + val); } } } return dupC.size(); } private static List<String> findPerm(int num) { String numString = String.valueOf(num); List<String> value = new ArrayList<String>(); for (int i = 0; i < numString.length(); i++) { String temp = charIns(numString, i); if (!temp.equalsIgnoreCase(numString)) { value.add(charIns(numString, i)); } } return value; } public static String charIns(String str, int j) { String begin = str.substring(0, j); String end = str.substring(j); return end + begin; } }
import java.io.*; import java.util.*; import java.math.*; public class Main implements Runnable { static int power = 1; private static String filename; public static void main(String[] args) { if (args.length>0 && args[0].equals("f")) filename = "input.txt"; else filename = ""; new Thread(new Main()).start(); } private static void debug(Object ... str) { for (Object s : str) System.out.print(s + ", "); System.out.println(); } private void check(int x, int y, int ndig) { int temp = x; int[] digx = new int[ndig]; int[] digy = new int[ndig]; for (int i = 0; i < ndig; ++i, temp = temp / 10) { digx[i] = temp % 10; } temp = y; for (int i = 0; i < ndig; ++i, temp = temp / 10) { digy[i] = temp % 10; } boolean equal = false; for (int sh = 1; !equal && sh < ndig; ++sh) { equal = true; for (int i = 0; equal && i < ndig; ++i) { if (digx[(i + sh) % ndig] != digy[i]) { equal = false; } } } if (!equal || x >= y) System.out.println("HAHAHA " + x + " " + y); } public void run() { try{ MyScanner in; Locale.setDefault(Locale.US); if (filename.length()>0) in = new MyScanner(filename); else in = new MyScanner(System.in); PrintWriter out = new PrintWriter(System.out); int T = in.nextInt(); for (int test = 0; test < T; ++test) { int a = in.nextInt(); int b = in.nextInt(); int temp = a; int ndig = 0; while (temp > 0) { temp /= 10; ndig++; } int[] dig = new int[ndig]; power = 1; for (int i = 1; i<ndig; ++i) power *= 10; int ans = 0; boolean[] was = new boolean[2000001]; int[] stack = new int[ndig]; for (int x = a; x <= b; ++x) { temp = x; for (int c = 0; c < ndig; ++c, temp = temp / 10) { dig[c] = temp % 10; if (dig[c] == 0) continue; } int stack_size = 0; int y = x / 10 + dig[0] * power; for (int c = 1; c < ndig; ++c) { if ((x < y && y <= b) && !was[y]) { ans++; stack[stack_size++] = y; was[y] = true; //check(x, y, ndig); } y = y / 10 + dig[c] * power; } for (int i = 0; i < stack_size; ++i) { was[stack[i]] = false; stack[i] = 0; } } out.println("Case #" + (1 + test) + ": " + ans); } out.close(); in.close(); }catch(Exception e) { e.printStackTrace(); } } } class MyScanner { BufferedReader in; StringTokenizer st; MyScanner(String file){ try{ in = new BufferedReader(new FileReader(new File(file))); }catch(Exception e){ e.printStackTrace(); } } MyScanner(InputStream inp){ try{ in = new BufferedReader(new InputStreamReader(inp)); }catch (Exception e){ e.printStackTrace(); } } void skipLine(){ st = null; } boolean hasMoreTokens(){ String s = null; try{ while ((st==null || !st.hasMoreTokens())&& (s=in.readLine()) != null) st = new StringTokenizer(s); if ((st==null || !st.hasMoreTokens())&& s==null) return false; }catch(IOException e){ e.printStackTrace(); } return true; } String nextToken(){ if (hasMoreTokens()){ return st.nextToken(); } return null; } int nextInt(){ return Integer.parseInt(nextToken()); } long nextLong(){ return Long.parseLong(nextToken()); } double nextDouble(){ return Double.parseDouble(nextToken()); } String nextString(){ return nextToken(); } void close(){ try{ in.close(); }catch(IOException e){ e.printStackTrace(); } } }
B12074
B13123
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.File; import java.io.FileNotFoundException; import java.util.Scanner; public class RecycledNumber { public static void main (String[] args) throws FileNotFoundException{ Scanner scan = new Scanner (new File ("input.txt")); int caseNumber = scan.nextInt(); scan.nextLine(); for(int k=0; k<caseNumber; k++){ int result = 0; int A = scan.nextInt(); int B = scan.nextInt(); for (int i = A ; i <= B ; i++){ for (int j = 1; j < numberOfDigits(i) ; j++){ if (digit(i,j)>=digit(i,numberOfDigits(i))){ if (A <= recycle(i,j) && B >= recycle(i,j) && i<recycle(i,j)){ result++; } } } } System.out.println("Case #"+(k+1)+": "+result); if (scan.hasNextLine()){ scan.nextLine(); } } } static int numberOfDigits(int number){ return ((int)Math.floor(Math.log10(number))) + 1; } static int recycle(int number, int digit){ int newPrefix = (((int)(number%Math.pow(10, digit)))*(int)Math.pow(10, (numberOfDigits(number)-digit))); int newSuffix = number/(int)(Math.pow(10, digit)) ; return newPrefix+newSuffix; } static int digit(int number, int digit){ return (number/(int)(Math.pow(10,digit-1)))%10; } }
B12669
B12196
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 qualification; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class C { private static abstract class Solver { public abstract String solveCase(String input); } public static void main(String[] args) throws IOException { solveTasks("C-small-attempt1", new Solver() { @Override public String solveCase(String input) { String[] parts = input.split(" "); int from = Integer.parseInt(parts[0]); int to = Integer.parseInt(parts[1]); int count = countRecycledBetween(from, to); return Integer.toString(count); } }); } private static void solveTasks(String name, Solver bTest) throws FileNotFoundException, IOException { BufferedReader bufferedReader = new BufferedReader(new FileReader(name + ".in")); FileWriter outputWriter = new FileWriter(name + ".out"); int inputLength = Integer.parseInt(bufferedReader.readLine()); for (int i = 0; i < inputLength; i++) { String inputLine = bufferedReader.readLine(); String output = bTest.solveCase(inputLine); String answer = "Case #" + (i + 1) + ": " + output; outputWriter.append(answer); outputWriter.append('\n'); System.out.println(answer); } bufferedReader.close(); outputWriter.close(); } private static int countRecycledBetween(int a, int b) { int recycled = 0; for (int i = a; i < b; i++) { for (int j = i + 1; j <= b; j++) { if (isRecycled(i, j)) { recycled++; } } } return recycled; } private static boolean isRecycled(int aInt, int bInt) { String aString = Integer.toString(aInt); String bString = Integer.toString(bInt); int lengthDiff = aString.length() - bString.length(); if (lengthDiff > 0) { bString = appendZeroes(lengthDiff, bString); } else if (lengthDiff < 0) { aString = appendZeroes(-lengthDiff, aString); } for (int i = 1; i < aString.length(); i++) { String shifted = shiftString(bString, i); if (aString.equals(shifted)) { return true; } } return false; } private static String appendZeroes(int zeroes, String base) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < zeroes; i++) { stringBuilder.append('0'); } stringBuilder.append(base); return stringBuilder.toString(); } private static String shiftString(String input, int steps) { StringBuilder builder = new StringBuilder(); builder.append(input.substring(steps)); builder.append(input.substring(0, steps)); return builder.toString(); } private static int[] splitDigits(int number) { String string = Integer.toString(number); int[] digits = new int[string.length()]; for (int i = 0; i < digits.length; i++) { digits[i] = string.charAt(i) - '0'; } return digits; } }
A22191
A21779
0
package com.example; import java.io.IOException; import java.util.List; public class ProblemB { enum Result { INSUFFICIENT, SUFFICIENT, SUFFICIENT_WHEN_SURPRISING } public static void main(String[] a) throws IOException { List<String> lines = FileUtil.getLines("/B-large.in"); int cases = Integer.valueOf(lines.get(0)); for(int c=0; c<cases; c++) { String[] tokens = lines.get(c+1).split(" "); int n = Integer.valueOf(tokens[0]); // N = number of Googlers int s = Integer.valueOf(tokens[1]); // S = number of surprising triplets int p = Integer.valueOf(tokens[2]); // P = __at least__ a score of P int sumSufficient = 0; int sumSufficientSurprising = 0; for(int i=0; i<n; i++) { int points = Integer.valueOf(tokens[3+i]); switch(test(points, p)) { case SUFFICIENT: sumSufficient++; break; case SUFFICIENT_WHEN_SURPRISING: sumSufficientSurprising++; break; } // uSystem.out.println("points "+ points +" ? "+ p +" => "+ result); } System.out.println("Case #"+ (c+1) +": "+ (sumSufficient + Math.min(s, sumSufficientSurprising))); // System.out.println(); // System.out.println("N="+ n +", S="+ s +", P="+ p); // System.out.println(); } } private static Result test(int n, int p) { int fac = n / 3; int rem = n % 3; if(rem == 0) { // int triplet0[] = { fac, fac, fac }; // print(n, triplet0); if(fac >= p) { return Result.SUFFICIENT; } if(fac > 0 && fac < 10) { if(fac+1 >= p) { return Result.SUFFICIENT_WHEN_SURPRISING; } // int triplet1[] = { fac+1, fac, fac-1 }; // surprising // print(n, triplet1); } } else if(rem == 1) { // int triplet0[] = { fac+1, fac, fac }; // print(n, triplet0); if(fac+1 >= p) { return Result.SUFFICIENT; } // if(fac > 0 && fac < 10) { // int triplet1[] = { fac+1, fac+1, fac-1 }; // print(n, triplet1); // } } else if(rem == 2) { // int triplet0[] = { fac+1, fac+1, fac }; // print(n, triplet0); if(fac+1 >= p) { return Result.SUFFICIENT; } if(fac < 9) { // int triplet1[] = { fac+2, fac, fac }; // surprising // print(n, triplet1); if(fac+2 >= p) { return Result.SUFFICIENT_WHEN_SURPRISING; } } } else { throw new RuntimeException("error"); } return Result.INSUFFICIENT; // System.out.println(); // System.out.println(n +" => "+ div3 +" ("+ rem +")"); } // private static void print(int n, int[] triplet) { // System.out.println("n="+ n +" ("+ (n/3) +","+ (n%3) +") => ["+ triplet[0] +","+ triplet[1] +","+ triplet[2] +"]" + (triplet[0]-triplet[2] > 1 ? " *" : "")); // } }
import java.io.*; import java.util.*; public class Main{ public static void main (String[] args) throws java.lang.Exception{ BufferedReader bfr=new BufferedReader(new InputStreamReader(System.in)); int T=Integer.parseInt(bfr.readLine()); int res[]=new int[T]; Arrays.fill(res,0); for(int i=0;i<T;i++){ String t[]=bfr.readLine().split(" "); int N=Integer.parseInt(t[0]); int S=Integer.parseInt(t[1]); int p=Integer.parseInt(t[2]); int x=3*p-4; for(int j=3;j<t.length;j++){ int q=Integer.parseInt(t[j]); if(p==1){ if(q>0){ res[i]++; } continue; } if(q>x+1){ res[i]++; } else if(q>=x && S>0){ res[i]++; S--; } } } for(int i=0;i<T;i++){ System.out.println("Case #"+(i+1)+": "+res[i]); } } }
B12669
B11785
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package year_2012.qualification; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; /** * * @author paul * @date 14 Apr 2012 */ public class QuestionC { private static Set<Integer> getCycle(int x) { String s = Integer.toString(x); Set<Integer> set = new HashSet<Integer>(); set.add(x); for (int c = 1; c < s.length(); c++) { String t = s.substring(c).concat(s.substring(0, c)); set.add(Integer.parseInt(t)); } return set; } private static Set<Integer> mask(Set<Integer> set, int a, int b) { Set<Integer> result = new HashSet<Integer>(); for (int x : set) { if (x >= a && x <= b) { result.add(x); } } return result; } public static void main(String[] args) throws FileNotFoundException, IOException { String question = "C"; // String name = "large"; String name = "small-attempt0"; // String name = "test"; String filename = String.format("%s-%s", question, name); BufferedReader input = new BufferedReader( new FileReader(String.format("/home/paul/Documents/code-jam/2012/qualification/%s.in", filename))); String firstLine = input.readLine(); PrintWriter pw = new PrintWriter(new File( String.format("/home/paul/Documents/code-jam/2012/qualification/%s.out", filename))); int T = Integer.parseInt(firstLine); // Loop through test cases. for (int i = 0; i < T; i++) { // Read data. String[] tokens = input.readLine().split(" "); // int N = Integer.parseInt(input.readLine()); int A = Integer.parseInt(tokens[0]); int B = Integer.parseInt(tokens[1]); // System.out.format("%d, %d\n", A, B); boolean[] used = new boolean[B+1]; int total = 0; for (int n = A; n <= B; n++) { if (!used[n]) { Set<Integer> set = mask(getCycle(n), A, B); int k = set.size(); total += (k * (k-1))/2; for (int m : set) { used[m] = true; } } } pw.format("Case #%d: %d\n", i + 1, total); } pw.close(); } }
package com.google.codejam.p3; import java.awt.Point; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; public class Problem3 { ArrayList<Point> cases = new ArrayList<Point>(); public void loadInput() { try{ FileInputStream fstream = new FileInputStream("input3.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); //read number of lines while ((strLine = br.readLine()) != null) { String[] info = strLine.split(" "); int A = Integer.parseInt(info[0]); int B = Integer.parseInt(info[1]); cases.add(new Point(A,B)); } in.close(); } catch (Exception e) { } } public static boolean isRecycled(int a, int b) { String s1 = Integer.toString(a); String s2 = Integer.toString(b); for (int i=0; i<s1.length(); i++) { String tmpS = s2.substring(0, s2.length()-1); char lastC = s2.charAt(s2.length()-1); s2 = lastC + tmpS; if (s2.equals(s1)) return true; } return false; } public void getOutput() { for (int x=0; x<cases.size(); x++) { int A = cases.get(x).x; int B = cases.get(x).y; int total = 0; for (int i=A; i<B; i++) for (int j=i+1; j<=B; j++) if (isRecycled(i, j)) total++; System.out.println("Case #" + (x+1) + ": " + total); } } public static void main(String[] args) { Problem3 p = new Problem3(); p.loadInput(); p.getOutput(); } }
A22992
A21045
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package IO; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; /** * * @author dannocz */ public class InputReader { public static Input readFile(String filename){ try { /* Sets up a file reader to read the file passed on the command 77 line one character at a time */ FileReader input = new FileReader(filename); /* Filter FileReader through a Buffered read to read a line at a time */ BufferedReader bufRead = new BufferedReader(input); String line; // String that holds current file line int count = 0; // Line number of count ArrayList<String> cases= new ArrayList<String>(); // Read first line line = bufRead.readLine(); int noTestCases=Integer.parseInt(line); count++; // Read through file one line at time. Print line # and line while (count<=noTestCases){ //System.out.println("Reading. "+count+": "+line); line = bufRead.readLine(); cases.add(line); count++; } bufRead.close(); return new Input(noTestCases,cases); }catch (ArrayIndexOutOfBoundsException e){ /* If no file was passed on the command line, this expception is generated. A message indicating how to the class should be called is displayed */ e.printStackTrace(); }catch (IOException e){ // If another exception is generated, print a stack trace e.printStackTrace(); } return null; }// end main }
import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; public class B { public static void main(String[] args) throws Exception { Scanner in = new Scanner(new FileReader(new File("B.in"))); PrintWriter out = new PrintWriter(new FileWriter("B.out")); int tests = in.nextInt(); int N,S,p; for (int i = 1; i <= tests; i++) { out.print("Case #" + (i) + ": "); System.out.print("Case #" + (i) + ": "); N = in.nextInt();S = in.nextInt();p = in.nextInt(); int cnt = 0,updateable = 0; for (int j = 0; j < N; j++) { int x = in.nextInt(); int y = x/3; int rem = x%3; if(rem == 0){ if(y >= p)cnt++; else if(y+1 <= x && y+1 == p)updateable++; }else if(rem == 1){ if(y+1 >= p)cnt++; }else{//rem == 2 if(y+1 >= p)cnt++; else if(y+2 == p)updateable++; } } cnt += Math.min(S,updateable); out.println(cnt); System.out.println(cnt); } out.close(); } }
B10361
B10605
0
package codejam; import java.util.*; import java.io.*; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("in.txt")); PrintWriter out = new PrintWriter(new File("out.txt")); int T = Integer.parseInt(in.readLine()); for (int t = 1; t <= T; ++t) { String[] parts = in.readLine().split("[ ]+"); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); int cnt = 0; for (int i = A; i < B; ++i) { String str = String.valueOf(i); int n = str.length(); String res = ""; Set<Integer> seen = new HashSet<Integer>(); for (int j = n - 1; j > 0; --j) { res = str.substring(j) + str.substring(0, j); int k = Integer.parseInt(res); if (k > i && k <= B) { //System.out.println("(" + i + ", " + k + ")"); if (!seen.contains(k)) { ++cnt; seen.add(k); } } } } out.println("Case #" + t + ": " + cnt); } in.close(); out.close(); System.exit(0); } }
package google.code.jam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.ListIterator; public class RecycledNumbers { final static String fileNameIn = "C-small-attempt0.in"; final static String fileNameOut = "C-small-attempt0.out"; private static int solve(int A, int B) { HashMap<String, Integer> hashMap = new HashMap<String, Integer>(); for (int i = A; i <= B; i++) { String n = new Integer(i).toString(); String key = minimum(n); if (Integer.valueOf(n) >= A && Integer.valueOf(n) <= B) { if (!hashMap.containsKey(key)) { hashMap.put(key, 1); } else { hashMap.put(key, hashMap.get(key) + 1); } } } int count = 0; for (String key : hashMap.keySet()) { Integer value = hashMap.get(key); count = count + (value * (value - 1) / 2); } return count; } private static String minimum(String input) { String min = input; for (int i = 0; i < input.length(); i++) { if (Integer.valueOf(shift(input, i)) < Integer.valueOf(min)) { min = shift(input, i); } } return min; } private static String shift(String input, int n) { return input.substring(n, input.length()) + input.substring(0, n); } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(fileNameIn)); BufferedWriter out = new BufferedWriter(new FileWriter(fileNameOut)); int testCases = Integer.parseInt(in.readLine()); for (int i = 0; i < testCases; i++) { String[] elements = in.readLine().split( new Character((char) 32).toString()); List<Integer> values = new ArrayList<Integer>(); for (String v : elements) { values.add(Integer.valueOf(v)); } ListIterator<Integer> iterator = values.listIterator(); int A = iterator.next(); int B = iterator.next(); out.write(String.format("Case #%s: %s\n", i + 1, solve(A, B))); } in.close(); out.close(); } }
B13196
B10128
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Q3M { public static void main(String[] args) throws Exception { compute(); } private static void compute() throws Exception { BufferedReader br = new BufferedReader(new FileReader(new File( "C:\\work\\Q3\\C-small-attempt0.in"))); String line = null; int i = Integer.parseInt(br.readLine()); List l = new ArrayList(); for (int j = 0; j < i; j++) { line = br.readLine(); String[] nums = line.split(" "); l.add(calculate(nums)); } writeOutput(l); } private static int calculate(String[] nums) { int min = Integer.parseInt(nums[0]); int max = Integer.parseInt(nums[1]); int count = 0; List l = new ArrayList(); for (int i = min; i <= max; i++) { for (int times = 1; times < countDigits(i); times++) { int res = shiftNum(i, times); if (res <= max && i < res) { if ((!l.contains((i + ":" + res)))) { l.add(i + ":" + res); l.add(res + ":" + i); count++; } } } } return count; } private static boolean checkZeros(int temp, int res) { if (temp % 10 == 0 || res % 10 == 0) return false; return true; } private static int shiftNum(int n, int times) { int base = (int) Math.pow(10, times); int temp2 = n / base; int placeHolder = (int) Math.pow((double) 10, (double) countDigits(temp2)); int res = placeHolder * (n % base) + temp2; if (countDigits(res) == countDigits(n)) { return res; } else { return 2000001; } } public static int countDigits(int x) { if (x < 10) return 1; else { return 1 + countDigits(x / 10); } } private static void writeOutput(List l) throws Exception { StringBuffer b = new StringBuffer(); int i = 1; BufferedWriter br = new BufferedWriter(new FileWriter(new File( "C:\\work\\Q3\\ans.txt"))); for (Iterator iterator = l.iterator(); iterator.hasNext();) { br.write("Case #" + i++ + ": " + iterator.next()); br.newLine(); } br.close(); } }
import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String[] args){ int t; Scanner s = new Scanner(System.in); t=s.nextInt(); for(int k=1;k<=t;k++){ int a,b; a=s.nextInt(); b=s.nextInt(); int al=a/10,d=1; while(al>0){ d++; al/=10; } int count=0; for(int i=a;i<=b;i++){ HashSet<Integer> hs = new HashSet<Integer>(); for(int j=1;j<d;j++){ int p=(int) (Math.pow(10,j)); int l=i/p; int r=i%p; int n=r*((int) (Math.pow(10,d-j))) + l ; if(n>=a && n<=b && n!=i) { if(!hs.contains(n)){ count++; hs.add(n); } } } } System.out.println("Case #"+k+": "+(count/2)); } } }
A10996
A11642
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 com.codejam; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ProblemB { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File("B-small-attempt0.in")); int T = sc.nextInt(); sc.nextLine(); for (int i = 0; i < T; i++) { int N = sc.nextInt(); int S = sc.nextInt(); int p = sc.nextInt(); int[] t = new int[N]; for (int j = 0; j < N; j++) { t[j] = sc.nextInt(); } System.out.println("Case #" + (i + 1) + ": " + solve(N, S, p, t)); } } private static int solve(int N, int S, int p, int[] t) { int countA = 0, countB1 = 0, countB2 = 0, countC1 = 0, countC2 = 0, count = 0; for (int i = 0; i < N; i++) { int r = t[i] % 3, d = t[i] / 3; switch (r) { case 1: if (d + 1 >= p) { countA++; } break; case 0: if (d == 0) { if (d >= p) { countB1++; } } else if (d >= 10) { if (d >= p) { countB1++; } } else if (d >= p) { countB1++; } else if (d + 1 == p && d > 0) { countB2++; } break; case 2: if (d >= 9) { if (d + 1 >= p) { countC1++; } } else if (d + 1 >= p) { countC1++; } else if (d + 2 == p) { countC2++; } break; default: break; } } count = countA + countB1 + countC1 + Math.min(countB2 + countC2, S); return count; } }
B10899
B11246
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class ReadFile { public static void main(String[] args) throws Exception { String srcFile = "C:" + File.separator + "Documents and Settings" + File.separator + "rohit" + File.separator + "My Documents" + File.separator + "Downloads" + File.separator + "C-small-attempt1.in.txt"; String destFile = "C:" + File.separator + "Documents and Settings" + File.separator + "rohit" + File.separator + "My Documents" + File.separator + "Downloads" + File.separator + "C-small-attempt0.out"; File file = new File(srcFile); List<String> readData = new ArrayList<String>(); FileReader fileInputStream = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileInputStream); StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { readData.add(line); } stringBuilder.append(generateOutput(readData)); File writeFile = new File(destFile); if (!writeFile.exists()) { writeFile.createNewFile(); } FileWriter fileWriter = new FileWriter(writeFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(stringBuilder.toString()); bufferedWriter.close(); System.out.println("output" + stringBuilder); } /** * @param number * @return */ private static String generateOutput(List<String> number) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < number.size(); i++) { if (i == 0) { continue; } else { String tempString = number.get(i); String[] temArr = tempString.split(" "); stringBuilder.append("Case #" + i + ": "); stringBuilder.append(getRecNumbers(temArr[0], temArr[1])); stringBuilder.append("\n"); } } if (stringBuilder.length() > 0) { stringBuilder.deleteCharAt(stringBuilder.length() - 1); } return stringBuilder.toString(); } // /* This method accepts method for google code jam */ // private static String method(String value) { // int intValue = Integer.valueOf(value); // double givenExpr = 3 + Math.sqrt(5); // double num = Math.pow(givenExpr, intValue); // String valArr[] = (num + "").split("\\."); // int finalVal = Integer.valueOf(valArr[0]) % 1000; // // return String.format("%1$03d", finalVal); // // } // // /* This method accepts method for google code jam */ // private static String method2(String value) { // StringTokenizer st = new StringTokenizer(value, " "); // String test[] = value.split(" "); // StringBuffer str = new StringBuffer(); // // for (int i = 0; i < test.length; i++) { // // test[i]=test[test.length-i-1]; // str.append(test[test.length - i - 1]); // str.append(" "); // } // str.deleteCharAt(str.length() - 1); // String strReversedLine = ""; // // while (st.hasMoreTokens()) { // strReversedLine = st.nextToken() + " " + strReversedLine; // } // // return str.toString(); // } private static int getRecNumbers(String no1, String no2) { int a = Integer.valueOf(no1); int b = Integer.valueOf(no2); Set<String> dupC = new HashSet<String>(); for (int i = a; i <= b; i++) { int n = i; List<String> value = findPerm(n); for (String val : value) { if (Integer.valueOf(val) <= b && Integer.valueOf(val) >= a && n < Integer.valueOf(val)) { dupC.add(n + "-" + val); } } } return dupC.size(); } private static List<String> findPerm(int num) { String numString = String.valueOf(num); List<String> value = new ArrayList<String>(); for (int i = 0; i < numString.length(); i++) { String temp = charIns(numString, i); if (!temp.equalsIgnoreCase(numString)) { value.add(charIns(numString, i)); } } return value; } public static String charIns(String str, int j) { String begin = str.substring(0, j); String end = str.substring(j); return end + begin; } }
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class cyclic { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int in = Integer.parseInt(sc.nextLine()); int i = 1; while (i <= in) { int A = sc.nextInt(); int B = Integer.parseInt(sc.nextLine().trim()); System.out.print("Case #" + i + ": "); if(i < in) System.out.println(count(A,B)); else System.out.print(count(A,B)); i++; } } public static int count(int A, int B) { boolean[] flag = new boolean[B - A + 1]; int numDigits = (int) Math.log10(A) + 1; int pairs = 0; for (int i = A; i <= B; i++) { if (!flag[i - A]) { flag[i - A] = true; int n = 1; for (int j = 1; j < numDigits; j++) { int l = (int) (i / Math.pow(10, j)); l += (i % Math.pow(10, j)) * Math.pow(10, numDigits - j); if (l >= A && l <= B && !flag[l-A]) { flag[l - A] = true; n++; } } if (n > 1) { int nC2 = 1; for (int j = 0; j < 2; j++) { nC2 = nC2 * (n - j) / (j + 1); } pairs += nC2; } } } return pairs; } }
A22191
A21277
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 ? " *" : "")); // } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Problem2; 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 NewDancers { static int in[][], out[]; 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][103]; 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()); } } } 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(); } public static void main(String[] args) throws FileNotFoundException, IOException { readFile("data"); for (int i = 0; i < in.length; i++) { int googlers = in[i][0]; int surp = in[i][1]; int p = in[i][2]; int minCountedTriplet = 3 * p - 2; int minCountedTripletWithSur = 3 * p - 4; int output = 0; for (int j = 3; j < googlers + 3; j++) { int temp = in[i][j]; if (temp >= minCountedTriplet) { output++; } else { if (surp > 0 && temp >= minCountedTripletWithSur && minCountedTripletWithSur >= 0) { output++; surp--; } } } out[i] = output; } writeOutput("output.txt"); } }
B21752
B20021
0
package Main; import com.sun.deploy.util.ArrayUtil; import org.apache.commons.lang3.ArrayUtils; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; /** * Created with IntelliJ IDEA. * User: arran * Date: 14/04/12 * Time: 3:12 PM * To change this template use File | Settings | File Templates. */ public class Round { public StringBuilder parse(BufferedReader in) throws IOException { StringBuilder out = new StringBuilder(); String lineCount = in.readLine(); for (int i = 1; i <= Integer.parseInt(lineCount); i++) { out.append("Case #"+i+": "); System.err.println("Case #"+i+": "); String line = in.readLine(); String[] splits = line.split(" "); int p1 = Integer.valueOf(splits[0]); int p2 = Integer.valueOf(splits[1]); int r = pairRecyclable(p1, p2); out.append(r); // if (i < Integer.parseInt(lineCount)) out.append("\n"); } return out; } public static int pairRecyclable(int i1, int i2) { HashSet<String> hash = new HashSet<String>(); for (int i = i1; i < i2; i++) { String istr = String.valueOf(i); if (istr.length() < 2) continue; for (int p = 0; p < istr.length() ; p++) { String nistr = istr.substring(p,istr.length()).concat(istr.substring(0,p)); if (Integer.valueOf(nistr) < i1) continue; if (Integer.valueOf(nistr) > i2) continue; if (nistr.equals(istr)) continue; String cnistr = (Integer.valueOf(nistr) > Integer.valueOf(istr)) ? istr + "," + nistr : nistr + "," + istr; hash.add(cnistr); } } return hash.size(); } public static void main(String[] args) { InputStreamReader converter = null; try { int attempt = 0; String quest = "C"; // String size = "small-attempt"; String size = "large"; converter = new InputStreamReader(new FileInputStream("src/resource/"+quest+"-"+size+".in")); BufferedReader in = new BufferedReader(converter); Round r = new Round(); String str = r.parse(in).toString(); System.out.print(str); FileOutputStream fos = new FileOutputStream(quest+"-"+size+".out"); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw); bw.write(str); bw.flush(); bw.close(); } catch (IOException e) { e.printStackTrace(); } } }
package WQ; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; public class Problem_C { /** * @param args * @throws FileNotFoundException */ public static boolean check(String s) { for (int i = 0; i < s.length() - 1; i++) { if (s.charAt(i) != s.charAt(i + 1)) return true; } return false; } public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new FileReader("C-large.in")); PrintWriter out = new PrintWriter("out1.txt"); int num = in.nextInt(); for (int CASE = 1; CASE <= num; CASE++) { int a = in.nextInt(); int b = in.nextInt(); HashSet<String> hs = new HashSet<String>(); for (int i = a; i <= b; i++) { String s = i + ""; if (check(s) && s.length() > 1) { for (int k = s.length() - 2, j = 0; k >= 0 && j < s.length() - 1; j++, k--) { String newS = s.substring(k + 1) + s.substring(0, k + 1); int newInt = Integer.parseInt(newS); if (newInt <= b && i < newInt && s.length() == (newInt + "").length() && !newS.equals(s)) { if (i < Integer.parseInt(newS)) hs.add(i + " " + newS); else hs.add(newS + " " + i); } } } } out.println("Case #" + CASE + ": " + hs.size()); } out.close(); } }
B21049
B21700
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 com.paupicas.year2012.codejam.qr; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; public class C { public static void main(String[] args) throws Exception { String filename = "C-large"; BufferedReader inputFile = new BufferedReader(new FileReader(filename + ".in")); FileWriter outputFile = new FileWriter(filename + ".out"); int casesNumber = Integer.valueOf(inputFile.readLine()); for (int cn = 1; cn <= casesNumber; cn++) { String result = "Case #" + cn + ": "; String[] tn = inputFile.readLine().split(" "); int a = Integer.valueOf(tn[0]); int b = Integer.valueOf(tn[1]); HashMap<String, Boolean> counted = new HashMap<String, Boolean>(b - a); int c = 0; for (int i = a; i <= b; i++) { String is = String.valueOf(i); for (int j = 1; j < is.length(); j++) { String ps = is.substring(j, is.length()) + is.substring(0, j); String pair = is + "," + ps; int p = Integer.valueOf(ps); if (p > i && p <= b && !counted.containsKey(pair)) { c++; counted.put(pair, true); } } } result = result + c; System.out.println(result); outputFile.write(result); if (cn < casesNumber) { outputFile.write("\n"); } } inputFile.close(); outputFile.close(); } }
A20490
A22519
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.util.Scanner; public class Dance { public static void main(String[] args) throws Throwable { Scanner scan = new Scanner(new File("dance.in")); int t = Integer.parseInt(scan.nextLine()); for (int i = 1; i <= t; i++) { String line = scan.nextLine(); Scanner token = new Scanner(line); int n = token.nextInt(); int s = token.nextInt(); int p = token.nextInt(); int counter = 0; for (int j = 0; j < n; j++) { int score = token.nextInt(); int scoreEach = score / 3; int remainder = score % 3; if (scoreEach >= p) { counter++; } else if (scoreEach + 1 == p && remainder >= 1) { counter++; } else if (scoreEach + 2 >= p && remainder == 2 && s > 0) { s--; counter++; } else if (scoreEach + 1 == p && remainder == 0 && s > 0 && score > 0) { s--; counter++; } } System.out.printf("Case #%d: %d\n", i, counter); } } }
B20734
B21309
0
package fixjava; public class StringUtils { /** Repeat the given string the requested number of times. */ public static String repeat(String str, int numTimes) { StringBuilder buf = new StringBuilder(Math.max(0, str.length() * numTimes)); for (int i = 0; i < numTimes; i++) buf.append(str); return buf.toString(); } /** * Pad the left hand side of a field with the given character. Always adds at least one pad character. If the length of str is * greater than numPlaces-1, then the output string will be longer than numPlaces. */ public static String padLeft(String str, char padChar, int numPlaces) { int bufSize = Math.max(numPlaces, str.length() + 1); StringBuilder buf = new StringBuilder(Math.max(numPlaces, str.length() + 1)); buf.append(padChar); for (int i = 1, mi = bufSize - str.length(); i < mi; i++) buf.append(padChar); buf.append(str); return buf.toString(); } /** * Pad the right hand side of a field with the given character. Always adds at least one pad character. If the length of str is * greater than numPlaces-1, then the output string will be longer than numPlaces. */ public static String padRight(String str, char padChar, int numPlaces) { int bufSize = Math.max(numPlaces, str.length() + 1); StringBuilder buf = new StringBuilder(Math.max(numPlaces, str.length() + 1)); buf.append(str); buf.append(padChar); while (buf.length() < bufSize) buf.append(padChar); return buf.toString(); } /** Intern all strings in an array, skipping null elements. */ public static String[] intern(String[] arr) { for (int i = 0; i < arr.length; i++) arr[i] = arr[i].intern(); return arr; } /** Intern a string, ignoring null */ public static String intern(String str) { return str == null ? null : str.intern(); } }
import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileOut { /** * コンストラクタ. * @param filename 書き出すファイル名 * @param s 書き出す文字列 */ public FileOut(String filename, String s) { File f = new File(filename); FileWriter fw = null; try { fw = new FileWriter(f); fw.write(s); } catch (IOException e) { e.printStackTrace(); } finally { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
B10361
B12574
0
package codejam; import java.util.*; import java.io.*; public class RecycledNumbers { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader("in.txt")); PrintWriter out = new PrintWriter(new File("out.txt")); int T = Integer.parseInt(in.readLine()); for (int t = 1; t <= T; ++t) { String[] parts = in.readLine().split("[ ]+"); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); int cnt = 0; for (int i = A; i < B; ++i) { String str = String.valueOf(i); int n = str.length(); String res = ""; Set<Integer> seen = new HashSet<Integer>(); for (int j = n - 1; j > 0; --j) { res = str.substring(j) + str.substring(0, j); int k = Integer.parseInt(res); if (k > i && k <= B) { //System.out.println("(" + i + ", " + k + ")"); if (!seen.contains(k)) { ++cnt; seen.add(k); } } } } out.println("Case #" + t + ": " + cnt); } in.close(); out.close(); System.exit(0); } }
package problem1; import java.io.*; import java.util.IllegalFormatException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /** * TextIO provides a set of static methods for reading and writing text. By default, it reads * from standard input and writes to standard output, but it is possible to redirect the input * and output to files or to other input and output streams. When the standard input and output * streams are being used, the input methods will not produce an error; instead, the user is * repeatedly prompted for input until a legal input is entered. (If standard input has been * changed externally, as by file redirection on the command line, this is not a reasonable * behavior; to handle this case, TextIO will give up after 10 consecutive illegal inputs and * will throw an IllegalArgumentException.) For the most part, any other * error will be translated into an IllegalArguementException. * <p>For writing to standard output, the output methods in this class pretty much * duplicate the functionality of System.out, and System.out can be used interchangeably with them. * <p>This class does not use optimal Java programming practices. It is designed specifically to be easily * usable even by a beginning programmer who has not yet learned about objects and exceptions. Therefore, * everything is in a single source file that compiles into a single class file, all the methods are * static methods, and none of the methods throw exceptions that would require try...catch statements. * Also for this reason, all exceptions are converted into IllegalArgumentExceptions, even when this * exception type doesn't really make sense. * <p>This class requires Java 5.0 or higher. (A previous version of TextIO required only Java 1.1; * this version should work with any source code that used the previous version, but it has some new * features, including the type of formatted output that was introduced in Java 5 and the ability to * use files and streams.) */ public class TextIO { /* Modified November 2007 to empty the TextIO input buffer when switching from one * input source to another. This fixes a bug that allows input from the previous input * source to be read after the new source has been selected. */ /** * The value returned by the peek() method when the input is at end-of-file. * (The value of this constant is (char)0xFFFF.) */ public final static char EOF = (char)0xFFFF; /** * The value returned by the peek() method when the input is at end-of-line. * The value of this constant is the character '\n'. */ public final static char EOLN = '\n'; // The value returned by peek() when at end-of-line. /** * After this method is called, input will be read from standard input (as it * is in the default state). If a file or stream was previously the input source, that file * or stream is closed. */ public static void readStandardInput() { if (readingStandardInput) return; try { in.close(); } catch (Exception e) { } emptyBuffer(); // Added November 2007 in = standardInput; inputFileName = null; readingStandardInput = true; inputErrorCount = 0; } /** * After this method is called, input will be read from inputStream, provided it * is non-null. If inputStream is null, then this method has the same effect * as calling readStandardInput(); that is, future input will come from the * standard input stream. */ public static void readStream(InputStream inputStream) { if (inputStream == null) readStandardInput(); else readStream(new InputStreamReader(inputStream)); } /** * After this method is called, input will be read from inputStream, provided it * is non-null. If inputStream is null, then this method has the same effect * as calling readStandardInput(); that is, future input will come from the * standard input stream. */ public static void readStream(Reader inputStream) { if (inputStream == null) readStandardInput(); else { if ( inputStream instanceof BufferedReader) in = (BufferedReader)inputStream; else in = new BufferedReader(inputStream); emptyBuffer(); // Added November 2007 inputFileName = null; readingStandardInput = false; inputErrorCount = 0; } } /** * Opens a file with a specified name for input. If the file name is null, this has * the same effect as calling readStandardInput(); that is, input will be read from standard * input. If an * error occurs while trying to open the file, an exception of type IllegalArgumentException * is thrown, and the input source is not changed. If the file is opened * successfully, then after this method is called, all of the input routines will read * from the file, instead of from standard input. */ public static void readFile(String fileName) { if (fileName == null) // Go back to reading standard input readStandardInput(); else { BufferedReader newin; try { newin = new BufferedReader( new FileReader(fileName) ); } catch (Exception e) { throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n" + "(Error :" + e + ")"); } if (! readingStandardInput) { // close current input stream try { in.close(); } catch (Exception e) { } } emptyBuffer(); // Added November 2007 in = newin; readingStandardInput = false; inputErrorCount = 0; inputFileName = fileName; } } /** * Puts a GUI file-selection dialog box on the screen in which the user can select * an input file. If the user cancels the dialog instead of selecting a file, it is * not considered an error, but the return value of the subroutine is false. * If the user does select a file, but there is an error while trying to open the * file, then an exception of type IllegalArgumentException is thrown. Finally, if * the user selects a file and it is successfully opened, then the return value of the * subroutine is true, and the input routines will read from the file, instead of * from standard input. If the user cancels, or if any error occurs, then the * previous input source is not changed. * <p>NOTE: Calling this method starts a GUI user interface thread, which can continue * to run even if the thread that runs the main program ends. If you use this method * in a non-GUI program, it might be necessary to call System.exit(0) at the end of the main() * routine to shut down the Java virtual machine completely. */ public static boolean readUserSelectedFile() { if (fileDialog == null) fileDialog = new JFileChooser(); fileDialog.setDialogTitle("Select File for Input"); int option = fileDialog.showOpenDialog(null); if (option != JFileChooser.APPROVE_OPTION) return false; File selectedFile = fileDialog.getSelectedFile(); BufferedReader newin; try { newin = new BufferedReader( new FileReader(selectedFile) ); } catch (Exception e) { throw new IllegalArgumentException("Can't open file \"" + selectedFile.getName() + "\" for input.\n" + "(Error :" + e + ")"); } if (!readingStandardInput) { // close current file try { in.close(); } catch (Exception e) { } } emptyBuffer(); // Added November 2007 in = newin; inputFileName = selectedFile.getName(); readingStandardInput = false; inputErrorCount = 0; return true; } /** * After this method is called, output will be written to standard output (as it * is in the default state). If a file or stream was previously open for output, it * will be closed. */ public static void writeStandardOutput() { if (writingStandardOutput) return; try { out.close(); } catch (Exception e) { } outputFileName = null; outputErrorCount = 0; out = standardOutput; writingStandardOutput = true; } /** * After this method is called, output will be sent to outputStream, provided it * is non-null. If outputStream is null, then this method has the same effect * as calling writeStandardOutput(); that is, future output will be sent to the * standard output stream. */ public static void writeStream(OutputStream outputStream) { if (outputStream == null) writeStandardOutput(); else writeStream(new PrintWriter(outputStream)); } /** * After this method is called, output will be sent to outputStream, provided it * is non-null. If outputStream is null, then this method has the same effect * as calling writeStandardOutput(); that is, future output will be sent to the * standard output stream. */ public static void writeStream(PrintWriter outputStream) { if (outputStream == null) writeStandardOutput(); else { out = outputStream; outputFileName = null; outputErrorCount = 0; writingStandardOutput = false; } } /** * Opens a file with a specified name for output. If the file name is null, this has * the same effect as calling writeStandardOutput(); that is, output will be sent to standard * output. If an * error occurs while trying to open the file, an exception of type IllegalArgumentException * is thrown. If the file is opened successfully, then after this method is called, * all of the output routines will write to the file, instead of to standard output. * If an error occurs, the output destination is not changed. * <p>NOTE: Calling this method starts a GUI user interface thread, which can continue * to run even if the thread that runs the main program ends. If you use this method * in a non-GUI program, it might be necessary to call System.exit(0) at the end of the main() * routine to shut down the Java virtual machine completely. */ public static void writeFile(String fileName) { if (fileName == null) // Go back to reading standard output writeStandardOutput(); else { PrintWriter newout; try { newout = new PrintWriter(new FileWriter(fileName)); } catch (Exception e) { throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for output.\n" + "(Error :" + e + ")"); } if (!writingStandardOutput) { try { out.close(); } catch (Exception e) { } } out = newout; writingStandardOutput = false; outputFileName = fileName; outputErrorCount = 0; } } /** * Puts a GUI file-selection dialog box on the screen in which the user can select * an output file. If the user cancels the dialog instead of selecting a file, it is * not considered an error, but the return value of the subroutine is false. * If the user does select a file, but there is an error while trying to open the * file, then an exception of type IllegalArgumentException is thrown. Finally, if * the user selects a file and it is successfully opened, then the return value of the * subroutine is true, and the output routines will write to the file, instead of * to standard output. If the user cancels, or if an error occurs, then the current * output destination is not changed. */ public static boolean writeUserSelectedFile() { if (fileDialog == null) fileDialog = new JFileChooser(); fileDialog.setDialogTitle("Select File for Output"); File selectedFile; while (true) { int option = fileDialog.showSaveDialog(null); if (option != JFileChooser.APPROVE_OPTION) return false; // user canceled selectedFile = fileDialog.getSelectedFile(); if (selectedFile.exists()) { int response = JOptionPane.showConfirmDialog(null, "The file \"" + selectedFile.getName() + "\" already exists. Do you want to replace it?", "Replace existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (response == JOptionPane.YES_OPTION) break; } else { break; } } PrintWriter newout; try { newout = new PrintWriter(new FileWriter(selectedFile)); } catch (Exception e) { throw new IllegalArgumentException("Can't open file \"" + selectedFile.getName() + "\" for output.\n" + "(Error :" + e + ")"); } if (!writingStandardOutput) { try { out.close(); } catch (Exception e) { } } out = newout; writingStandardOutput = false; outputFileName = selectedFile.getName(); outputErrorCount = 0; return true; } /** * If TextIO is currently reading from a file, then the return value is the name of the file. * If the class is reading from standard input or from a stream, then the return value is null. */ public static String getInputFileName() { return inputFileName; } /** * If TextIO is currently writing to a file, then the return value is the name of the file. * If the class is writing to standard output or to a stream, then the return value is null. */ public static String getOutputFileName() { return outputFileName; } // *************************** Output Methods ********************************* /** * Write a single value to the current output destination, using the default format * and no extra spaces. This method will handle any type of parameter, even one * whose type is one of the primitive types. */ public static void put(Object x) { out.print(x); out.flush(); if (out.checkError()) outputError("Error while writing output."); } /** * Write a single value to the current output destination, using the default format * and outputting at least minChars characters (with extra spaces added before the * output value if necessary). This method will handle any type of parameter, even one * whose type is one of the primitive types. * @param x The value to be output, which can be of any type. * @param minChars The minimum number of characters to use for the output. If x requires fewer * then this number of characters, then extra spaces are added to the front of x to bring * the total up to minChars. If minChars is less than or equal to zero, then x will be printed * in the minumum number of spaces possible. */ public static void put(Object x, int minChars) { if (minChars <= 0) out.print(x); else out.printf("%" + minChars + "s", x); out.flush(); if (out.checkError()) outputError("Error while writing output."); } /** * This is equivalent to put(x), followed by an end-of-line. */ public static void putln(Object x) { out.println(x); out.flush(); if (out.checkError()) outputError("Error while writing output."); } /** * This is equivalent to put(x,minChars), followed by an end-of-line. */ public static void putln(Object x, int minChars) { put(x,minChars); out.println(); out.flush(); if (out.checkError()) outputError("Error while writing output."); } /** * Write an end-of-line character to the current output destination. */ public static void putln() { out.println(); out.flush(); if (out.checkError()) outputError("Error while writing output."); } /** * Writes formatted output values to the current output destination. This method has the * same function as System.out.printf(); the details of formatted output are not discussed * here. The first parameter is a string that describes the format of the output. There * can be any number of additional parameters; these specify the values to be output and * can be of any type. This method will throw an IllegalArgumentException if the * format string is null or if the format string is illegal for the values that are being * output. */ public static void putf(String format, Object... items) { if (format == null) throw new IllegalArgumentException("Null format string in TextIO.putf() method."); try { out.printf(format,items); } catch (IllegalFormatException e) { throw new IllegalArgumentException("Illegal format string in TextIO.putf() method."); } out.flush(); if (out.checkError()) outputError("Error while writing output."); } // *************************** Input Methods ********************************* /** * Test whether the next character in the current input source is an end-of-line. Note that * this method does NOT skip whitespace before testing for end-of-line -- if you want to do * that, call skipBlanks() first. */ public static boolean eoln() { return peek() == '\n'; } /** * Test whether the next character in the current input source is an end-of-file. Note that * this method does NOT skip whitespace before testing for end-of-line -- if you want to do * that, call skipBlanks() or skipWhitespace() first. */ public static boolean eof() { return peek() == EOF; } /** * Reads the next character from the current input source. The character can be a whitespace * character; compare this to the getChar() method, which skips over whitespace and returns the * next non-whitespace character. An end-of-line is always returned as the character '\n', even * when the actual end-of-line in the input source is something else, such as '\r' or "\r\n". * This method will throw an IllegalArgumentException if the input is at end-of-file (which will * not ordinarily happen if reading from standard input). */ public static char getAnyChar() { return readChar(); } /** * Returns the next character in the current input source, without actually removing that * character from the input. The character can be a whitespace character and can be the * end-of-file character (specified by the constant TextIO.EOF).An end-of-line is always returned * as the character '\n', even when the actual end-of-line in the input source is something else, * such as '\r' or "\r\n". This method never causes an error. */ public static char peek() { return lookChar(); } /** * Skips over any whitespace characters, except for end-of-lines. After this method is called, * the next input character is either an end-of-line, an end-of-file, or a non-whitespace character. * This method never causes an error. (Ordinarily, end-of-file is not possible when reading from * standard input.) */ public static void skipBlanks() { char ch=lookChar(); while (ch != EOF && ch != '\n' && Character.isWhitespace(ch)) { readChar(); ch = lookChar(); } } /** * Skips over any whitespace characters, including for end-of-lines. After this method is called, * the next input character is either an end-of-file or a non-whitespace character. * This method never causes an error. (Ordinarily, end-of-file is not possible when reading from * standard input.) */ private static void skipWhitespace() { char ch=lookChar(); while (ch != EOF && Character.isWhitespace(ch)) { readChar(); if (ch == '\n' && readingStandardInput && writingStandardOutput) { out.print("? "); out.flush(); } ch = lookChar(); } } /** * Skips whitespace characters and then reads a value of type byte from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static byte getlnByte() { byte x=getByte(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type short from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static short getlnShort() { short x=getShort(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type int from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static int getlnInt() { int x=getInt(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type long from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static long getlnLong() { long x=getLong(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type float from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static float getlnFloat() { float x=getFloat(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type double from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static double getlnDouble() { double x=getDouble(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type char from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). Note that the value * that is returned will be a non-whitespace character; compare this with the getAnyChar() method. * When using standard IO, this will not produce an error. In other cases, an error can occur if * an end-of-file is encountered. */ public static char getlnChar() { char x=getChar(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads a value of type boolean from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. * <p>Legal inputs for a boolean input are: true, t, yes, y, 1, false, f, no, n, and 0; letters can be * either upper case or lower case. One "word" of input is read, using the getWord() method, and it * must be one of these; note that the "word" must be terminated by a whitespace character (or end-of-file). */ public static boolean getlnBoolean() { boolean x=getBoolean(); emptyBuffer(); return x; } /** * Skips whitespace characters and then reads one "word" from input, discarding the rest of * the current line of input (including the next end-of-line character, if any). A word is defined as * a sequence of non-whitespace characters (not just letters!). When using standard IO, * this will not produce an error. In other cases, an IllegalArgumentException will be thrown * if an end-of-file is encountered. */ public static String getlnWord() { String x=getWord(); emptyBuffer(); return x; } /** * This is identical to getln(). */ public static String getlnString() { return getln(); } /** * Reads all the characters from the current input source, up to the next end-of-line. The end-of-line * is read but is not included in the return value. Any other whitespace characters on the line are retained, * even if they occur at the start of input. The return value will be an empty string if there are no * no characters before the end-of-line. When using standard IO, this will not produce an error. * In other cases, an IllegalArgumentException will be thrown if an end-of-file is encountered. */ public static String getln() { StringBuffer s = new StringBuffer(100); char ch = readChar(); while (ch != '\n') { s.append(ch); ch = readChar(); } return s.toString(); } /** * Skips whitespace characters and then reads a value of type byte from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static byte getByte() { return (byte)readInteger(-128L,127L); } /** * Skips whitespace characters and then reads a value of type short from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static short getShort() { return (short)readInteger(-32768L,32767L); } /** * Skips whitespace characters and then reads a value of type int from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static int getInt() { return (int)readInteger(Integer.MIN_VALUE, Integer.MAX_VALUE); } /** * Skips whitespace characters and then reads a value of type long from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static long getLong() { return readInteger(Long.MIN_VALUE, Long.MAX_VALUE); } /** * Skips whitespace characters and then reads a single non-whitespace character from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error. In other cases, an IllegalArgumentException will be thrown if an end-of-file * is encountered. */ public static char getChar() { skipWhitespace(); return readChar(); } /** * Skips whitespace characters and then reads a value of type float from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static float getFloat() { float x = 0.0F; while (true) { String str = readRealString(); if (str == null) { errorMessage("Floating point number not found.", "Real number in the range " + (-Float.MAX_VALUE) + " to " + Float.MAX_VALUE); } else { try { x = Float.parseFloat(str); } catch (NumberFormatException e) { errorMessage("Illegal floating point input, " + str + ".", "Real number in the range " + (-Float.MAX_VALUE) + " to " + Float.MAX_VALUE); continue; } if (Float.isInfinite(x)) { errorMessage("Floating point input outside of legal range, " + str + ".", "Real number in the range " + (-Float.MAX_VALUE) + " to " + Float.MAX_VALUE); continue; } break; } } inputErrorCount = 0; return x; } /** * Skips whitespace characters and then reads a value of type double from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. */ public static double getDouble() { double x = 0.0; while (true) { String str = readRealString(); if (str == null) { errorMessage("Floating point number not found.", "Real number in the range " + (-Double.MAX_VALUE) + " to " + Double.MAX_VALUE); } else { try { x = Double.parseDouble(str); } catch (NumberFormatException e) { errorMessage("Illegal floating point input, " + str + ".", "Real number in the range " + (-Double.MAX_VALUE) + " to " + Double.MAX_VALUE); continue; } if (Double.isInfinite(x)) { errorMessage("Floating point input outside of legal range, " + str + ".", "Real number in the range " + (-Double.MAX_VALUE) + " to " + Double.MAX_VALUE); continue; } break; } } inputErrorCount = 0; return x; } /** * Skips whitespace characters and then reads one "word" from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. A word is defined as * a sequence of non-whitespace characters (not just letters!). When using standard IO, * this will not produce an error. In other cases, an IllegalArgumentException will be thrown * if an end-of-file is encountered. */ public static String getWord() { skipWhitespace(); StringBuffer str = new StringBuffer(50); char ch = lookChar(); while (ch == EOF || !Character.isWhitespace(ch)) { str.append(readChar()); ch = lookChar(); } return str.toString(); } /** * Skips whitespace characters and then reads a value of type boolean from input. Any additional characters on * the current line of input are retained, and will be read by the next input operation. When using standard IO, * this will not produce an error; the user will be prompted repeatedly for input until a legal value * is input. In other cases, an IllegalArgumentException will be thrown if a legal value is not found. * <p>Legal inputs for a boolean input are: true, t, yes, y, 1, false, f, no, n, and 0; letters can be * either upper case or lower case. One "word" of input is read, using the getWord() method, and it * must be one of these; note that the "word" must be terminated by a whitespace character (or end-of-file). */ public static boolean getBoolean() { boolean ans = false; while (true) { String s = getWord(); if ( s.equalsIgnoreCase("true") || s.equalsIgnoreCase("t") || s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("y") || s.equals("1") ) { ans = true; break; } else if ( s.equalsIgnoreCase("false") || s.equalsIgnoreCase("f") || s.equalsIgnoreCase("no") || s.equalsIgnoreCase("n") || s.equals("0") ) { ans = false; break; } else errorMessage("Illegal boolean input value.", "one of: true, false, t, f, yes, no, y, n, 0, or 1"); } inputErrorCount = 0; return ans; } // ***************** Everything beyond this point is private implementation detail ******************* private static String inputFileName; // Name of file that is the current input source, or null if the source is not a file. private static String outputFileName; // Name of file that is the current output destination, or null if the destination is not a file. private static JFileChooser fileDialog; // Dialog used by readUserSelectedFile() and writeUserSelectedFile() private final static BufferedReader standardInput = new BufferedReader(new InputStreamReader(System.in)); // wraps standard input stream private final static PrintWriter standardOutput = new PrintWriter(System.out); // wraps standard output stream private static BufferedReader in = standardInput; // Stream that data is read from; the current input source. private static PrintWriter out = standardOutput; // Stream that data is written to; the current output destination. private static boolean readingStandardInput = true; private static boolean writingStandardOutput = true; private static int inputErrorCount; // Number of consecutive errors on standard input; reset to 0 when a successful read occurs. private static int outputErrorCount; // Number of errors on standard output since it was selected as the output destination. private static Matcher integerMatcher; // Used for reading integer numbers; created from the integer Regex Pattern. private static Matcher floatMatcher; // Used for reading floating point numbers; created from the floatRegex Pattern. private final static Pattern integerRegex = Pattern.compile("(\\+|-)?[0-9]+"); private final static Pattern floatRegex = Pattern.compile("(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))((e|E)(\\+|-)?[0-9]+)?"); private static String buffer = null; // One line read from input. private static int pos = 0; // Position of next char in input line that has not yet been processed. private static String readRealString() { // read chars from input following syntax of real numbers skipWhitespace(); if (lookChar() == EOF) return null; if (floatMatcher == null) floatMatcher = floatRegex.matcher(buffer); floatMatcher.region(pos,buffer.length()); if (floatMatcher.lookingAt()) { String str = floatMatcher.group(); pos = floatMatcher.end(); return str; } else return null; } private static String readIntegerString() { // read chars from input following syntax of integers skipWhitespace(); if (lookChar() == EOF) return null; if (integerMatcher == null) integerMatcher = integerRegex.matcher(buffer); integerMatcher.region(pos,buffer.length()); if (integerMatcher.lookingAt()) { String str = integerMatcher.group(); pos = integerMatcher.end(); return str; } else return null; } private static long readInteger(long min, long max) { // read long integer, limited to specified range long x=0; while (true) { String s = readIntegerString(); if (s == null){ errorMessage("Integer value not found in input.", "Integer in the range " + min + " to " + max); } else { String str = s.toString(); try { x = Long.parseLong(str); } catch (NumberFormatException e) { errorMessage("Illegal integer input, " + str + ".", "Integer in the range " + min + " to " + max); continue; } if (x < min || x > max) { errorMessage("Integer input outside of legal range, " + str + ".", "Integer in the range " + min + " to " + max); continue; } break; } } inputErrorCount = 0; return x; } private static void errorMessage(String message, String expecting) { // Report error on input. if (readingStandardInput && writingStandardOutput) { // inform user of error and force user to re-enter. out.println(); out.print(" *** Error in input: " + message + "\n"); out.print(" *** Expecting: " + expecting + "\n"); out.print(" *** Discarding Input: "); if (lookChar() == '\n') out.print("(end-of-line)\n\n"); else { while (lookChar() != '\n') // Discard and echo remaining chars on the current line of input. out.print(readChar()); out.print("\n\n"); } out.print("Please re-enter: "); out.flush(); readChar(); // discard the end-of-line character inputErrorCount++; if (inputErrorCount >= 10) throw new IllegalArgumentException("Too many input consecutive input errors on standard input."); } else if (inputFileName != null) throw new IllegalArgumentException("Error while reading from file \"" + inputFileName + "\":\n" + message + "\nExpecting " + expecting); else throw new IllegalArgumentException("Error while reading from inptu stream:\n" + message + "\nExpecting " + expecting); } private static char lookChar() { // return next character from input if (buffer == null || pos > buffer.length()) fillBuffer(); if (buffer == null) return EOF; else if (pos == buffer.length()) return '\n'; else return buffer.charAt(pos); } private static char readChar() { // return and discard next character from input char ch = lookChar(); if (buffer == null) { if (readingStandardInput) throw new IllegalArgumentException("Attempt to read past end-of-file in standard input???"); else throw new IllegalArgumentException("Attempt to read past end-of-file in file \"" + inputFileName + "\"."); } pos++; return ch; } private static void fillBuffer() { // Wait for user to type a line and press return, try { buffer = in.readLine(); } catch (Exception e) { if (readingStandardInput) throw new IllegalArgumentException("Error while reading standard input???"); else if (inputFileName != null) throw new IllegalArgumentException("Error while attempting to read from file \"" + inputFileName + "\"."); else throw new IllegalArgumentException("Errow while attempting to read form an input stream."); } pos = 0; floatMatcher = null; integerMatcher = null; } private static void emptyBuffer() { // discard the rest of the current line of input buffer = null; } private static void outputError(String message) { // Report an error on output. if (writingStandardOutput) { System.err.println("Error occurred in TextIO while writing to standard output!!"); outputErrorCount++; if (outputErrorCount >= 10) { outputErrorCount = 0; throw new IllegalArgumentException("Too many errors while writing to standard output."); } } else if (outputFileName != null){ throw new IllegalArgumentException("Error occurred while writing to file \"" + outputFileName+ "\":\n " + message); } else { throw new IllegalArgumentException("Error occurred while writing to output stream:\n " + message); } } } // end of class TextIO
A10568
A12507
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.util.ArrayList; import java.util.List; import java.util.Scanner; public class Round { private int num; private int strange; private int max; private List<Integer> dancers; private int best; public Round(Scanner data){ best = 0; dancers = new ArrayList<Integer>(); num = data.nextInt(); strange = data.nextInt(); max = data.nextInt(); for(int i = 0; i < num; i++){ dancers.add(data.nextInt()); } } public int calculate(){ for(int dancer: dancers){ if(max * 3 <= dancer){ best++; }else if(dancer >= max){ int score1 = max; int temp = dancer - max; int score2 = temp / 2; if(score1 - score2 == 1){ best++; }else if(score1 - score2 == 2 && strange > 0){ best++; strange--; } } } return best; } }
A20119
A20506
0
package code12.qualification; import java.io.File; import java.io.FileWriter; import java.util.Scanner; public class B { public static String solve(int N, int S, int p, int[] t) { // 3a -> (a, a, a), *(a - 1, a, a + 1) // 3a + 1 -> (a, a, a + 1), *(a - 1, a + 1, a + 1) // 3a + 2 -> (a, a + 1, a + 1), *(a, a, a + 2) int numPNoS = 0; int numPWithS = 0; for (int i = 0; i < N; i++) { int a = (int)Math.floor(t[i] / 3); int r = t[i] % 3; switch (r) { case 0: if (a >= p) { numPNoS++; } else if (a + 1 >= p && a - 1 >= 0) { numPWithS++; } break; case 1: if (a >= p || a + 1 >= p) { numPNoS++; } break; case 2: if (a >= p || a + 1 >= p) { numPNoS++; } else if (a + 2 >= p) { numPWithS++; } break; } } return "" + (numPNoS + Math.min(S, numPWithS)); } public static void main(String[] args) throws Exception { // file name //String fileName = "Sample"; //String fileName = "B-small"; String fileName = "B-large"; // file variable File inputFile = new File(fileName + ".in"); File outputFile = new File(fileName + ".out"); Scanner scanner = new Scanner(inputFile); FileWriter writer = new FileWriter(outputFile); // problem variable int totalCase; int N, S, p; int[] t; // get total case totalCase = scanner.nextInt(); for (int caseIndex = 1; caseIndex <= totalCase; caseIndex++) { // get input N = scanner.nextInt(); S = scanner.nextInt(); p = scanner.nextInt(); t = new int[N]; for (int i = 0; i < N; i++) { t[i] = scanner.nextInt(); } String output = "Case #" + caseIndex + ": " + solve(N, S, p, t); System.out.println(output); writer.write(output + "\n"); } scanner.close(); writer.close(); } }
import java.io.*; import java.util.*; class Q2 { public static void main(String str[])throws IOException { // FileReader fr=new FileReader("B-small-attempt0.in"); FileReader fr=new FileReader("B-large.in"); BufferedReader br=new BufferedReader(fr); FileWriter fw=new FileWriter("output.txt"); BufferedWriter bw=new BufferedWriter(fw); PrintWriter pw=new PrintWriter(bw); int T=Integer.parseInt(br.readLine()); for(int i=1;i<=T;i++) { String s=br.readLine(); StringTokenizer st=new StringTokenizer(s); int N=Integer.parseInt(st.nextToken()); int S=Integer.parseInt(st.nextToken()); int p=Integer.parseInt(st.nextToken()); int Arr[][]=new int[N][4]; for(int j=0;j<N;j++) { int num=Integer.parseInt(st.nextToken()); int mod=num%3; Arr[j][0]=mod; Arr[j][3]=num; int n=num/3; if(mod==0) { Arr[j][2]=n; if(n>=p) Arr[j][1]=1; else Arr[j][1]=0; } else { Arr[j][2]=n+1; if(n+1>=p) Arr[j][1]=1; else Arr[j][1]=0; } } for(int j=0;j<N;j++) { if(S==0) break; if(Arr[j][1]==0 && (Arr[j][0]==0 || Arr[j][0]==2) && (Arr[j][2]+1)>=p && (Arr[j][2]+1)<=Arr[j][3]) { S--; Arr[j][1]=1; } } int sum=0; for(int j=0;j<N;j++) { sum+=Arr[j][1]; } pw.println("Case #"+i+": "+sum); } pw.close(); bw.close(); fw.close(); br.close(); fr.close(); } }
B12085
B13265
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gcj; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Scanner; /** * * @author daniele */ public class GCJ_C { public static void main(String[] args) throws Exception{ Scanner in = new Scanner(new File(args[0])); FileWriter out = new FileWriter("/home/daniele/Scrivania/Output"); int prove=in.nextInt(); int min,max; int cifre; int cifreaus; String temp; int aus; int count=0; ArrayList<Integer> vals = new ArrayList<Integer>(); int jcount=0; ArrayList<Integer> perm = new ArrayList<Integer>(); out.write(""); out.flush(); for(int i=1;i<=prove;i++){ out.append("Case #" +i+": ");out.flush(); min=in.nextInt(); max=in.nextInt(); for(int j=min;j<=max;j++){ if(!vals.contains(j)){ temp=""+j; cifre=temp.length(); aus=j; perm.add(j); for(int k=1;k<cifre;k++){ aus=rotateOnce(aus); temp=""+aus; cifreaus=temp.length();//elusione zeri iniziali if(aus>=min && aus<=max && aus!=j && cifreaus==cifre && nobody(vals,perm)){ perm.add(aus); jcount ++; } } while(jcount>0){count+=jcount; jcount--;} vals.addAll(perm); perm= new ArrayList<Integer>(); } } out.append(count+"\n");out.flush(); count=0; vals= new ArrayList<Integer>(); } } static public int rotateOnce(int n){ String s=""+n; if(s.length()>1){ s=s.charAt(s.length()-1) + s.substring(0,s.length()-1); n=Integer.parseInt(s); } return n; } static public boolean nobody(ArrayList<Integer> v,ArrayList<Integer> a){; for(int i=0;i<a.size();i++) if(v.contains(a.get(i))) return false; return true; } }
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class RecycledNumbers { private long low; private long high; private Map<Long, Boolean> map = new HashMap<Long, Boolean>(); private int recycycled = 0; public static void main(String[] args) throws NumberFormatException, IOException { File file = new File("C:\\Users\\xebia\\Downloads\\C-small-attempt0.in"); FileInputStream fis = new FileInputStream(file); DataInputStream in = new DataInputStream(fis); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int numberOfTestCases = new Integer(br.readLine()); for (int j = 0; j < numberOfTestCases; j++) { RecycledNumbers re = new RecycledNumbers(); String[] strings = br.readLine().split(" "); String s = strings[0]; String s2 = strings[1]; long high = new Long(s2); long low = new Long(s); int numberOfDigits = s.length(); for (long i = low; i <= high; i++) { int roundOffFigure = 1; for (int k = 0; k < numberOfDigits - 1; k++) { roundOffFigure = roundOffFigure * 10; long lastDigit = (long) (i % roundOffFigure); String str = "" + lastDigit; if (str.length() == k + 1) { long startingCombination = (long) (i / roundOffFigure); if (lastDigit == 0) { continue; } long number = (long) (lastDigit * (Math.pow(10, numberOfDigits - str.length())) + startingCombination); if (number >= low && number <= high) { if (number != i) { Boolean bool = re.map.get(number * i); if (bool == null) { re.map.put(number * i, true); re.recycycled++; } } } } } } System.out.println("Case #" + (j + 1) + ": " + re.recycycled); } } public void setLow(long low) { this.low = low; } public long getLow() { return low; } public void setHigh(long high) { this.high = high; } public long getHigh() { return high; } public void setRecycycled(int recycycled) { this.recycycled = recycycled; } public int getRecycycled() { return recycycled; } }
B10231
B12267
0
import java.io.*; class code1 { public static void main(String args[]) throws Exception { File ii = new File ("C-small-attempt1.in"); FileInputStream fis = new FileInputStream(ii); BufferedReader br = new BufferedReader(new InputStreamReader (fis)); int cases = Integer.parseInt(br.readLine()); FileOutputStream fout = new FileOutputStream ("output.txt"); DataOutputStream dout = new DataOutputStream (fout); int total=0; for(int i=0;i<cases;i++){ String temp = br.readLine(); String parts [] = temp.split(" "); int lower = Integer.parseInt(parts[0]); int upper = Integer.parseInt(parts[1]); System.out.println(lower+" "+upper); for(int j=lower;j<=upper;j++) { int abc = j;int length=0; if(j<10)continue; while (abc!=0){abc/=10;length++;} abc=j; for(int m=0;m<length-1;m++){ int shift = abc%10; abc=abc/10; System.out.println("hi "+j); abc=abc+shift*power(10,length-1); if(abc<=upper&&shift!=0&&abc>j)total++; System.out.println(total); } } dout.writeBytes("Case #"+(i+1)+ ": "+total+"\n"); total=0; }//for close } private static int power(int i, int j) { int no=1; for(int a=0;a<j;a++){no=10*no;} return no; } }
package cats; import java.io.*; import java.util.ArrayList; public class Main { public Main() throws Exception{ FileReader fr = new FileReader(new File("input.txt")); BufferedReader in = new BufferedReader(fr); File outFile = new File("output.txt"); outFile.createNewFile(); FileWriter fw = new FileWriter(outFile); BufferedWriter out = new BufferedWriter(fw); int numTests = Integer.parseInt(in.readLine()); for(int x = 0; x<numTests; x++){ String[] splitLine = in.readLine().split(" "); int min, max; min = Integer.parseInt(splitLine[0]); max = Integer.parseInt(splitLine[1]); int count = 0; ArrayList<String> found = new ArrayList<String>(); for(int n = min; n <= max; n++){ String num = n+""; found.clear(); for(int d = 0; d<num.length()-1; d++){ num = num.substring(1) + num.charAt(0); int value = Integer.parseInt(num); if(value > n && value <= max && (value+"").length() == num.length() && !found.contains(num)){ //System.out.println(n + " " + value); found.add(num); count++; } } } out.write("Case #" + (x+1) + ": " + count + "\n"); System.out.println(count); } in.close(); out.close(); } public static void main(String[] args) throws Exception{ new Main(); } }
A11277
A11241
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; } }
/** * Copyright 2012 Christopher Schmitz. All Rights Reserved. */ package com.isotopeent.codejam; import com.isotopeent.codejam.lib.SolverBase; import com.isotopeent.codejam.lib.Utils; import com.isotopeent.codejam.lib.converters.IntArrayLine; public class Solver extends SolverBase<int[]> { private static final String FILE_PATH = "C:\\codejam\\"; private static final String FILE_NAME = "B-small-attempt0"; private static final int INIT_PARAM_COUNT = 1; private static final int PARAM_COUNT = 3; private static final int MAX_ARRAY_SIZE = PARAM_COUNT + 100; // 3 params + N=100 private static final int SCORE_COUNT = 3; public static void main(String [] args) { Utils.solve(FILE_PATH, FILE_NAME, new IntArrayLine(new int[MAX_ARRAY_SIZE]), new Solver()); } public Solver() { super(INIT_PARAM_COUNT); } @Override protected String solve(int[] input) { int surprisingScores = input[1]; int scoreThreashold = input[2]; int minUnsurprisingScore = scoreThreashold * SCORE_COUNT - SCORE_COUNT + 1; int minSurprisingScore = Math.max(minUnsurprisingScore - SCORE_COUNT + 1, scoreThreashold); int count = 0; int length = input.length; for (int i = PARAM_COUNT; i < length; i++) { int score = input[i]; if (score >= minUnsurprisingScore) { count++; } else if (score >= minSurprisingScore && surprisingScores > 0) { count++; surprisingScores--; } } return Integer.toString(count); } }
B21968
B20382
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); } } }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; public class Recycled { private static int NN = 2000010; private static BufferedReader bf; private static File f; public static void main(String[] args) throws Exception { f = new File("rasdjfh.in"); FileWriter out = new FileWriter(new File("recycled.txt")); if(f.exists()) bf = new BufferedReader(new FileReader(f)); else bf = new BufferedReader(new InputStreamReader(System.in)); String line = "", pars[],s ,x; ArrayList<HashSet<Integer>> recycled = new ArrayList<HashSet<Integer>>(NN); for(int i=0;i<NN;i++) { s = ""+i; recycled.add(new HashSet<Integer>()); for(int j=1;j<s.length();j++) { x = s.substring(0, j); x = s.substring(j)+x; Integer I; if((I = Integer.parseInt(x)) > i) recycled.get(i).add(I); } } System.out.println("Ok, I'm readyÉ"); int T = Integer.parseInt(bf.readLine()), A , B; for(int t=1;t<=T;t++) { pars = bf.readLine().split("[ ]+"); A = Integer.parseInt(pars[0]); B = Integer.parseInt(pars[1]); int ans = 0; for(int i=A;i<=B;i++) { for(Integer j : recycled.get(i)) if(j >= A && j <=B) ans++; } out.write(String.format("Case #%d: %d\n",t,ans)); } out.close(); } }
A11502
A13090
0
package template; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class TestCase { private boolean isSolved; private Object solution; private Map<String, Integer> intProperties; private Map<String, ArrayList<Integer>> intArrayProperties; private Map<String, ArrayList<ArrayList<Integer>>> intArray2DProperties; private Map<String, Double> doubleProperties; private Map<String, ArrayList<Double>> doubleArrayProperties; private Map<String, ArrayList<ArrayList<Double>>> doubleArray2DProperties; private Map<String, String> stringProperties; private Map<String, ArrayList<String>> stringArrayProperties; private Map<String, ArrayList<ArrayList<String>>> stringArray2DProperties; private Map<String, Boolean> booleanProperties; private Map<String, ArrayList<Boolean>> booleanArrayProperties; private Map<String, ArrayList<ArrayList<Boolean>>> booleanArray2DProperties; private Map<String, Long> longProperties; private Map<String, ArrayList<Long>> longArrayProperties; private Map<String, ArrayList<ArrayList<Long>>> longArray2DProperties; private int ref; private double time; public TestCase() { initialise(); } private void initialise() { isSolved = false; intProperties = new HashMap<>(); intArrayProperties = new HashMap<>(); intArray2DProperties = new HashMap<>(); doubleProperties = new HashMap<>(); doubleArrayProperties = new HashMap<>(); doubleArray2DProperties = new HashMap<>(); stringProperties = new HashMap<>(); stringArrayProperties = new HashMap<>(); stringArray2DProperties = new HashMap<>(); booleanProperties = new HashMap<>(); booleanArrayProperties = new HashMap<>(); booleanArray2DProperties = new HashMap<>(); longProperties = new HashMap<>(); longArrayProperties = new HashMap<>(); longArray2DProperties = new HashMap<>(); ref = 0; } public void setSolution(Object o) { solution = o; isSolved = true; } public Object getSolution() { if (!isSolved) { Utils.die("getSolution on unsolved testcase"); } return solution; } public void setRef(int i) { ref = i; } public int getRef() { return ref; } public void setTime(double d) { time = d; } public double getTime() { return time; } public void setInteger(String s, Integer i) { intProperties.put(s, i); } public Integer getInteger(String s) { return intProperties.get(s); } public void setIntegerList(String s, ArrayList<Integer> l) { intArrayProperties.put(s, l); } public void setIntegerMatrix(String s, ArrayList<ArrayList<Integer>> l) { intArray2DProperties.put(s, l); } public ArrayList<Integer> getIntegerList(String s) { return intArrayProperties.get(s); } public Integer getIntegerListItem(String s, int i) { return intArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Integer>> getIntegerMatrix(String s) { return intArray2DProperties.get(s); } public ArrayList<Integer> getIntegerMatrixRow(String s, int row) { return intArray2DProperties.get(s).get(row); } public Integer getIntegerMatrixItem(String s, int row, int column) { return intArray2DProperties.get(s).get(row).get(column); } public ArrayList<Integer> getIntegerMatrixColumn(String s, int column) { ArrayList<Integer> out = new ArrayList(); for(ArrayList<Integer> row : intArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setDouble(String s, Double i) { doubleProperties.put(s, i); } public Double getDouble(String s) { return doubleProperties.get(s); } public void setDoubleList(String s, ArrayList<Double> l) { doubleArrayProperties.put(s, l); } public void setDoubleMatrix(String s, ArrayList<ArrayList<Double>> l) { doubleArray2DProperties.put(s, l); } public ArrayList<Double> getDoubleList(String s) { return doubleArrayProperties.get(s); } public Double getDoubleListItem(String s, int i) { return doubleArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Double>> getDoubleMatrix(String s) { return doubleArray2DProperties.get(s); } public ArrayList<Double> getDoubleMatrixRow(String s, int row) { return doubleArray2DProperties.get(s).get(row); } public Double getDoubleMatrixItem(String s, int row, int column) { return doubleArray2DProperties.get(s).get(row).get(column); } public ArrayList<Double> getDoubleMatrixColumn(String s, int column) { ArrayList<Double> out = new ArrayList(); for(ArrayList<Double> row : doubleArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setString(String s, String t) { stringProperties.put(s, t); } public String getString(String s) { return stringProperties.get(s); } public void setStringList(String s, ArrayList<String> l) { stringArrayProperties.put(s, l); } public void setStringMatrix(String s, ArrayList<ArrayList<String>> l) { stringArray2DProperties.put(s, l); } public ArrayList<String> getStringList(String s) { return stringArrayProperties.get(s); } public String getStringListItem(String s, int i) { return stringArrayProperties.get(s).get(i); } public ArrayList<ArrayList<String>> getStringMatrix(String s) { return stringArray2DProperties.get(s); } public ArrayList<String> getStringMatrixRow(String s, int row) { return stringArray2DProperties.get(s).get(row); } public String getStringMatrixItem(String s, int row, int column) { return stringArray2DProperties.get(s).get(row).get(column); } public ArrayList<String> getStringMatrixColumn(String s, int column) { ArrayList<String> out = new ArrayList(); for(ArrayList<String> row : stringArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setBoolean(String s, Boolean b) { booleanProperties.put(s, b); } public Boolean getBoolean(String s) { return booleanProperties.get(s); } public void setBooleanList(String s, ArrayList<Boolean> l) { booleanArrayProperties.put(s, l); } public void setBooleanMatrix(String s, ArrayList<ArrayList<Boolean>> l) { booleanArray2DProperties.put(s, l); } public ArrayList<Boolean> getBooleanList(String s) { return booleanArrayProperties.get(s); } public Boolean getBooleanListItem(String s, int i) { return booleanArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Boolean>> getBooleanMatrix(String s) { return booleanArray2DProperties.get(s); } public ArrayList<Boolean> getBooleanMatrixRow(String s, int row) { return booleanArray2DProperties.get(s).get(row); } public Boolean getBooleanMatrixItem(String s, int row, int column) { return booleanArray2DProperties.get(s).get(row).get(column); } public ArrayList<Boolean> getBooleanMatrixColumn(String s, int column) { ArrayList<Boolean> out = new ArrayList(); for(ArrayList<Boolean> row : booleanArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setLong(String s, Long b) { longProperties.put(s, b); } public Long getLong(String s) { return longProperties.get(s); } public void setLongList(String s, ArrayList<Long> l) { longArrayProperties.put(s, l); } public void setLongMatrix(String s, ArrayList<ArrayList<Long>> l) { longArray2DProperties.put(s, l); } public ArrayList<Long> getLongList(String s) { return longArrayProperties.get(s); } public Long getLongListItem(String s, int i) { return longArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Long>> getLongMatrix(String s) { return longArray2DProperties.get(s); } public ArrayList<Long> getLongMatrixRow(String s, int row) { return longArray2DProperties.get(s).get(row); } public Long getLongMatrixItem(String s, int row, int column) { return longArray2DProperties.get(s).get(row).get(column); } public ArrayList<Long> getLongMatrixColumn(String s, int column) { ArrayList<Long> out = new ArrayList(); for(ArrayList<Long> row : longArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } }
package y2012.quals; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class B { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File("B.in")); PrintWriter out = new PrintWriter(new File("B.out")); int nTestCase = in.nextInt(); for (int testCase = 0; testCase < nTestCase; testCase++) { int n = in.nextInt(); int s = in.nextInt(); int p = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); int res = 0; int rl = p + p - 1 + p - 1, sl = p + p - 2 + p - 2; if (p == 0) { rl = 0; sl = 0; } else if (p == 1) sl = 1; for (int i = 0; i < n; i++) if (a[i] >= rl) res++; else if (a[i] >= sl && s > 0) { res++; s--; } out.println("Case #" + (testCase + 1) + ": " + res); } in.close(); out.close(); } }
A22378
A22110
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.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; public class Dancing_with_the_Googlers { public static void main(String[] args) throws IOException { FileInputStream fis; try { fis = new FileInputStream("B-large.in"); InputStreamReader ir = new InputStreamReader(fis); BufferedReader br = new BufferedReader(ir); String s;int i=0; br.readLine(); while (br.ready()) { i++; s = br.readLine(); System.out.print("Case #"+i+": "); tran(s); System.out.print("\r"); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } //tran(a); } static void tran(String a) { String num=""; int count=0;int N=0;int S=0;int P=0; int[] score=new int[9999]; for(int i=0;i<a.length();i++) { if(Character.isDigit(a.charAt(i))&&i!=a.length()-1) { num=num+a.charAt(i); } else if(count==0) { N=Integer.parseInt(num); num=""; count++; } else if(count==1) { S=Integer.parseInt(num); num=""; count++; } else if(count==2) { P=Integer.parseInt(num); num=""; count++; } else if(i==(a.length()-1)) { num=num+a.charAt(i); score[count-3]=Integer.parseInt(num); } else { score[count-3]=Integer.parseInt(num); num=""; count++; } } //System.out.print(N+" "+S+" "+P+" "); //for(int i=0;i<N;i++){System.out.print(score[i]+" ");} int ans1=0,ans2=0,fin=0; for(int i=0;i<N;i++) { if(score[i]>=P*3-2&&score[i]>=P){ans1++;} else if(score[i]>=P*3-4&&score[i]>=P){ans2++;} } if(ans2<=S){fin=ans2+ans1;} else{fin=S+ans1;} System.out.print(fin); } }
B11421
B12838
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Recycled { public static void main(String[] args) throws Exception{ String inputFile = "C-small-attempt0.in"; BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output"))); long num_cases = Long.parseLong(input.readLine()); int current_case = 0; while (current_case < num_cases){ current_case++; String[] fields = input.readLine().split(" "); int A = Integer.parseInt(fields[0]); int B = Integer.parseInt(fields[1]); int total = 0; for (int n = A; n < B; n++){ for (int m = n+1; m <= B; m++){ if (isRecycled(n,m)) total++; } } System.out.println("Case #" + current_case + ": " + total); output.write("Case #" + current_case + ": " + total + "\n"); } output.close(); } private static boolean isRecycled(int n, int m) { String sn = ""+n; String sm = ""+m; if (sn.length() != sm.length()) return false; int totaln = 0, totalm = 0; for (int i = 0; i < sn.length(); i++){ totaln += sn.charAt(i); totalm += sm.charAt(i); } if (totaln != totalm) return false; for (int i = 0; i < sn.length()-1; i++){ sm = sm.charAt(sm.length() - 1) + sm.substring(0, sm.length() - 1); if (sm.equals(sn)) return true; } return false; } }
/* ID: 14vikra1 LANG: JAVA TASK: recycled */ import java.io.*; import java.util.*; class recycled { public static void main (String [] args) throws IOException { long start = System.currentTimeMillis(); BufferedReader br = new BufferedReader(new FileReader("recycled.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("recycled.out"))); int T = Integer.parseInt(br.readLine()); for (int i = 0; i < T; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int pairs = 0; int size = (int)(Math.floor(Math.log(A)/Math.log(10)))+1; for (int j = A; j < B; j++) { pairs += checkPairs(j, A, B, size); } out.println("Case #" + (i+1) + ": " + pairs); } long end = System.currentTimeMillis(); System.out.println(end-start); out.close(); System.exit(0); } public static int checkPairs(int num, int A, int B, int size) { int numpairs = 0; ArrayList used = new ArrayList(); for (int i = 1; i < size; i++) { int move = (int)(num%Math.pow(10, i)); int test = (int)((num)/Math.pow(10,size-i+1)); if (move >= test) { int newnum = (int)((num - move)/Math.pow(10,i)); newnum = newnum + move*(int)(Math.pow(10,size-i)); if (newnum > num && newnum <= B && !used.contains(newnum)) { numpairs++; used.add(newnum); } } } return numpairs; } }
B12570
B10516
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.IOException; import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class QuestionC { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { File fileread = new File("C-small-attempt0.in.txt"); File filewrite = new File(QuestionC.class.getName() + "output.txt"); GCIFileReader fr = new GCIFileReader(fileread); GCIFileWriter fw = new GCIFileWriter(filewrite); GCIResult res = new GCIResult(); String s = fr.getLine(); int n = Integer.parseInt(s); List<Integer> m = new LinkedList<Integer>(); for (int i=0; i < n ; i++) { String l = fr.getLine(); Scanner sc = new Scanner(l); int tres = 0; int tn = 0; int tm = 0; int newnum = 0; int A = sc.nextInt(); int B = sc.nextInt(); int length = Integer.toString(A).length(); length--; for(int j=A ; j <= B ; j++) { int tlength = length; m.clear(); while(tlength>0) { tn = (int) (j % (Math.pow(10,tlength))); tm = (int) (j / (Math.pow(10,tlength))); newnum = (int) (tn*(Math.pow(10, Integer.toString(tm).length())) + tm); if (!m.contains(newnum) &&newnum <= B && j < newnum && Integer.toString(tn).length() == tlength && Integer.toString(tm).length() == (length+1 - tlength)) if (newnum <= B && tn!=0 && j < newnum) { tres++; m.add(newnum); } tlength--; } } res.addCase(String.valueOf(tres)); } fw.writeResult(res); } }
A22642
A21928
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.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Created with IntelliJ IDEA. * User: andraz * Date: 14.4.12 * Time: 13:25 * To change this template use File | Settings | File Templates. */ public class Dancing { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for(int rep=0; rep<t; rep++) { String line[] = br.readLine().split(" "); int n = Integer.parseInt(line[0]); int s = Integer.parseInt(line[1]); int p = Integer.parseInt(line[2]); int count = 0; for(int i=0; i< n; i++) { int total = Integer.parseInt(line[3+i]); if(total>=3*p - 2) { count++; } else if ((total >= 3*p - 4) && (total>=p) && (s>0)) { count++; s--; } } System.out.printf("Case #%d: %d\n", rep+1, count); } } }
B11327
B11087
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 fixjava; import java.util.Iterator; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; public class ParallelWorkQueue<I, O> implements Iterable<Future<O>> { public interface CallableFactory<I, O> { public Callable<O> newInstance(I input); } private ExecutorService threadPool; private LinkedBlockingQueue<Future<O>> workQueue; private Future<O> poisonPill = null; public ParallelWorkQueue(final int numThreads, final Iterable<I> inputs, final CallableFactory<I, O> callableFactory) { threadPool = Executors.newFixedThreadPool(numThreads); // Keep a max of (100x the number of threads) items in the work queue at a time workQueue = new LinkedBlockingQueue<>(numThreads * 100); // Create work-producer thread new Thread() { public void run() { try { for (final I input : inputs) workQueue.put(threadPool.submit(callableFactory.newInstance(input))); // poisonPill was null until now, and null can never be put in the queue, so // the barrier can't be triggered. Now set poisonPill to another value that it // can only attain once, a NOP work unit. workQueue.put(poisonPill = threadPool.submit(new Callable<O>() { @Override public O call() throws Exception { return null; } })); // Shut down threads after last callable invoked threadPool.shutdown(); } catch (InterruptedException e) { throw new RuntimeException(e); } }; }.start(); } @Override public Iterator<Future<O>> iterator() { return new Iterator<Future<O>>() { Future<O> next = null; boolean nextConsumed = true; @Override public boolean hasNext() { if (nextConsumed) { try { next = workQueue.take(); } catch (InterruptedException e) { throw new RuntimeException(e); } nextConsumed = false; } // Check for poison pill if (next == poisonPill) { try { // Get result of poison pill Future so thread exits next.get(); } catch (Exception e) { throw new RuntimeException(e); } return false; // at end } else { return true; } } @Override public Future<O> next() { if (nextConsumed) throw new RuntimeException("Can't call next() twice without calling hasNext()"); nextConsumed = true; return next; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * Return an Iterable<Integer> that iterates from 0 to n-1 inclusive. Can be * passed into the "inputs" parameter of ParallelWorkQueue. */ public static Iterable<Integer> makeIntRangeIterable(final int n) { return new Iterable<Integer>() { private final int max = n; @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { int num = 0; @Override public boolean hasNext() { return num < max; } @Override public Integer next() { return num++; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } }
A22360
A21562
0
import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; public class Dancing_With_the_Googlers { /** * The first line of the input gives the number of test cases, T. * T test cases follow. * Each test case consists of a single line containing integers separated by single spaces. * The first integer will be N, the number of Googlers, and the second integer will be S, the number of surprising triplets of scores. * The third integer will be p, as described above. Next will be N integers ti: the total points of the Googlers. * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // Reading the input file Scanner in = new Scanner(new File("B-large.in")); // writting the input file FileOutputStream fos = new FileOutputStream("B-large.out"); PrintStream out = new PrintStream(fos); //Close the output stream int testCase=Integer.parseInt(in.nextLine()); for(int i=0;i<testCase;i++) { out.print("Case #" + (i + 1) + ":\t"); int NoOfGooglers= in.nextInt(); int NoOfSurprisingResults = in.nextInt(); int atLeastP=in.nextInt(); ArrayList<Integer> scores= new ArrayList<Integer>(); int BestResults=0; int Surprising=0; for(int j=0;j<NoOfGooglers;j++) { scores.add(in.nextInt()); //System.out.print(scores.get(j)); int modulus=scores.get(j)%3; int temp = scores.get(j); switch (modulus) { case 0: if (((temp / 3) >= atLeastP)) { BestResults++; } else { if (((((temp / 3) + 1) >= atLeastP) && ((temp / 3) >= 1)) && (Surprising < NoOfSurprisingResults)) { BestResults++; Surprising++; } System.out.println("Case 0"+"itr:"+i+" surprising:"+temp); } break; case 1: if ((temp / 3) + 1 >= atLeastP) { BestResults++; continue; } break; case 2: if ((temp / 3) + 1 >= atLeastP) { BestResults++; } else { if (((temp / 3) + 2 >= atLeastP) && (Surprising < NoOfSurprisingResults)) { BestResults++; Surprising++; } System.out.println("Case 2"+"itr:"+i+" surprising:"+temp); } break; default: System.out.println("Error"); } }// Internal for out.println(BestResults); // System.out.println(BestResults); System.out.println(Surprising); BestResults = 0; }// for in.close(); out.close(); fos.close(); } }
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; public class Dancing { public static void main(String[] args){ Dancing d = new Dancing(); try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("B-large.in"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line int numOfTests = Integer.parseInt(br.readLine()); int N,S,p; for(int i=1; i<=numOfTests; i++){ String itemString =br.readLine(); String[] items = itemString.split(" "); System.out.print("Case #"+i+": "); N=Integer.parseInt(items[0]); S=Integer.parseInt(items[1]); p=Integer.parseInt(items[2]); int[] scores = new int[N]; for(int j=3; j<N+3; j++){ scores[j-3]=Integer.parseInt(items[j]); } d.getMaxGooglers(N, S, p, scores); System.out.println(); } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } private void getMaxGooglers(int N, int S, int p, int[] scores) { int count =0; for(int i=0; i<N; i++){ if(scores[i]==0){ if(p==0){ count++; continue; } else continue; } int rem = scores[i]%3; int div = scores[i]/3; if(rem ==0){ if(div>=p) count++; else{ if(S>0 && ((div+1)>=p)){ count++; S--; } } } else if (rem==1){ if(div+1>=p) count++; } else if (rem==2){ if(div+1 >=p) count++; else if (S>0 && ((div+2)>=p)){ count++; S--; } } else; } System.out.print(count); } }
B21790
B21333
0
import java.io.*; import java.util.*; public class C { void solve() throws IOException { in("C-large.in"); out("C-large.out"); long tm = System.currentTimeMillis(); boolean[] mask = new boolean[2000000]; int[] r = new int[10]; int t = readInt(); for (int cs = 1; cs <= t; ++cs) { int a = readInt(); int b = readInt(); int ans = 0; for (int m = a + 1; m <= b; ++m) { char[] d = String.valueOf(m).toCharArray(); int c = 0; for (int i = 1; i < d.length; ++i) { if (d[i] != '0' && d[i] <= d[0]) { int n = 0; for (int j = 0; j < d.length; ++j) { int jj = i + j; if (jj >= d.length) jj -= d.length; n = n * 10 + (d[jj] - '0'); } if (n >= a && n < m && !mask[n]) { ++ans; mask[n] = true; r[c++] = n; } } } for (int i = 0; i < c; ++i) { mask[r[i]] = false; } } println("Case #" + cs + ": " + ans); //System.out.println(cs); } System.out.println("time: " + (System.currentTimeMillis() - tm)); exit(); } void in(String name) throws IOException { if (name.equals("__std")) { in = new BufferedReader(new InputStreamReader(System.in)); } else { in = new BufferedReader(new FileReader(name)); } } void out(String name) throws IOException { if (name.equals("__std")) { out = new PrintWriter(System.out); } else { out = new PrintWriter(name); } } void exit() { out.close(); System.exit(0); } int readInt() throws IOException { return Integer.parseInt(readToken()); } long readLong() throws IOException { return Long.parseLong(readToken()); } double readDouble() throws IOException { return Double.parseDouble(readToken()); } String readLine() throws IOException { st = null; return in.readLine(); } String readToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } boolean eof() throws IOException { return !in.ready(); } void print(String format, Object ... args) { out.println(new Formatter(Locale.US).format(format, args)); } void println(String format, Object ... args) { out.println(new Formatter(Locale.US).format(format, args)); } void print(Object value) { out.print(value); } void println(Object value) { out.println(value); } void println() { out.println(); } StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) throws IOException { new C().solve(); } }
import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class RN { public static Set<Pair<Integer, Integer>> RNPair = new HashSet<Pair<Integer, Integer>>(); public static class Pair<L,R> { private final L left; private final R right; public Pair(L left, R right) { this.left = left; this.right = right; } public L getLeft() { return left; } public R getRight() { return right; } @Override public int hashCode() { return left.hashCode() ^ right.hashCode(); } @Override public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof Pair)) return false; Pair pairo = (Pair) o; return this.left.equals(pairo.getLeft()) && this.right.equals(pairo.getRight()); } } public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int T = scnr.nextInt(); for (int t = 1; t <= T; t++) { RNPair.removeAll(RNPair); Integer first = scnr.nextInt(); Integer last = scnr.nextInt(); int ans = 0; for (int i = first; i < last; i++) { ans += check(first, last, i); } //ans /= 2; System.out.println("Case #" + t + ": " +RNPair.size()); } } public static int check(Integer start, Integer end, Integer num) { String numStr = num.toString(); int l = numStr.length(); int count = 0; for (int i = 0; i < l - 1; i++) { String rotStr = numStr.substring(l - i - 1) + numStr.substring(0, l - i - 1); int rotStrNum = Integer.parseInt(rotStr); if (rotStrNum < start || rotStrNum > end) continue; if (rotStrNum <= num) continue; if (num.toString().length() != Integer.toString(rotStrNum).length()) continue; if ((start <= num) && (num < rotStrNum) && (rotStrNum <= end)) { count++; Pair<Integer, Integer> p = new Pair<Integer, Integer>(num, rotStrNum); RNPair.add(p); //System.out.println(num + " " + rotStrNum); } } return count; } }
A11135
A10561
0
/** * Created by IntelliJ IDEA. * User: Administrator * Date: 3/3/12 * Time: 11:00 AM * To change this template use File | Settings | File Templates. */ import SRMLib.MathLibrary; import SRMLib.TestSRMLib; import com.sun.org.apache.bcel.internal.generic.F2D; import java.io.*; import java.util.*; import java.util.zip.Inflater; public class SRM { public static void main(String[] args) throws IOException { //TestSRMLib.run(); codeJam1.main(); return; } } class codeJam1 { public static void main() throws IOException { String inputPath = "E:\\input.txt"; String outputPath = "E:\\output.txt"; BufferedReader input = new BufferedReader(new FileReader(inputPath)); BufferedWriter output = new BufferedWriter(new FileWriter(outputPath)); String line; line = input.readLine(); int T = Integer.parseInt(line); for (int i = 1; i <= T; ++i) { line = input.readLine(); String[] words = line.split(" "); int N = Integer.parseInt(words[0]); int S = Integer.parseInt(words[1]); int p = Integer.parseInt(words[2]); int n = 0; int res = 0; for (int j = 3; j < words.length; ++j) { if (p == 0) { res++; continue; } int t = Integer.parseInt(words[j]); if (p == 1) { if (t > 0) res++; continue; } if (t >= 3 * p - 2) res++; else if (t >= 3 * p - 4) n++; } res += Math.min(n, S); output.write("Case #" + i + ": " + res); output.newLine(); } input.close(); output.close(); } }
import java.io.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(); } }
B21227
B20074
0
import java.util.HashSet; import java.util.Scanner; public class C { static HashSet p = new HashSet(); static int low; static int high; int count = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int no = sc.nextInt(); for (int i = 1; i <= no; i++) { p.clear(); low = sc.nextInt(); high = sc.nextInt(); for (int l = low; l <= high; l++) { recycle(l); } System.out.println("Case #" + i + ": " + p.size()); } } public static void recycle(int no) { String s = Integer.toString(no); for (int i = 0; i < s.length(); i++) { String rec = s.substring(i) + s.substring(0, i); int r = Integer.parseInt(rec); if (r != no && r >= low && r <= high) { int min = Math.min(r, no); int max = Math.max(r, no); String a = Integer.toString(min) + "" + Integer.toString(max); p.add(a); } } } }
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; import java.util.StringTokenizer; class roundThree { public static void main(String[] args) { String text = ""; if( args.length > 0) { text = args[0]; } else { try { FileInputStream fos = new FileInputStream( "text3.txt"); Scanner scanner = new Scanner(new FileInputStream("text3.txt")); try { while (scanner.hasNextLine()){ text += scanner.nextLine() + "\n"; } } finally{ scanner.close(); } try { fos.read(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } StringTokenizer st = new StringTokenizer(text, "[\r\n]+", false); int cases = Integer.parseInt(st.nextToken()); for (int x=1; x<= cases; x++) { StringTokenizer st2 = new StringTokenizer(st.nextToken(), "[ ]+", false); int small = Integer.parseInt(st2.nextToken()); int large = Integer.parseInt(st2.nextToken()); ArrayList keep_track = new ArrayList<Integer>(); String small_int = "" + small; int count = 0; int small_length = small_int.length(); for( int i = small; i < large; i++) { String number1 = "" + i; keep_track.clear(); for( int j = 1; j < small_length; j++) { String sub_2 = number1.substring(0,j); String sub_1 = number1.substring(j,small_length); int variation = Integer.parseInt( sub_1 + sub_2 ); if( variation > i && variation <= large && !keep_track.contains(variation)) { keep_track.add(variation); count++; } } } System.out.println( "Case #" + x + ": " + count); } } }
B21752
B21925
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(); } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; /** * * @author Anirban */ public class RecycledNumbersLarge { static int MAXN = 2000000; static int arr[] = new int[MAXN + 1]; public static boolean check(String n, String m, int len){ for(int i = 0; i < len; i++){ if(m.compareTo(n.substring(i, i + len)) == 0) return true; } return false; } public static void main(String [] args)throws IOException{ InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); int tc = 1; //int T = 50; int T = Integer.parseInt(br.readLine()); while(T-- > 0){ int count = 0; StringTokenizer st = new StringTokenizer(br.readLine(), " "); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); //int A = 1; //int B = 2000000; ArrayList <Integer> L = new ArrayList<Integer>(); String b = B + ""; for(int i = A; i <= B; i++){ String n = i + ""; String x = n; int len = n.length(); n += n; L.clear(); for(int j = 0; j < len; j++){ String m = n.substring(j, j + len); int mm = Integer.parseInt(m); if(!L.contains(mm)){ m = mm + ""; if(i < mm && x.length() == m.length() && B >= mm){ count++; //System.out.println(n.substring(0, len) + " " + m); } L.add(mm); } } } System.out.printf("Case #%d: %d", tc, count); System.out.println(); tc++; } } }
B20006
B21740
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 inam.qual; import java.io.File; import java.io.FileInputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class C { public void go() { Scanner in = new Scanner(System.in); int cc = in.nextInt(); for (int c = 1; c <= cc; c++) { int val = 0; int a = in.nextInt(); int b = in.nextInt(); Set<String> set = new HashSet<String>(); for (int i = a; i <= b; i++) { String str = String.valueOf(i); for (int j = 1; j < str.length(); j++) { String re = str.substring(j, str.length()) + str.substring(0, j); if (str.equals(re) || re.startsWith("0") || Integer.parseInt(re) > b || a > Integer.parseInt(re)) { continue; } String key = ""; if (Integer.parseInt(str) < Integer.parseInt(re)) { key = str + " " + re; } else { key = re + " " + str; } set.add(key); } } val = set.size(); System.out.println("Case #" + c + ": " + val); } } public static void main(String[] args) { try { String p = "C-large"; String r = "qual"; System.setIn(new FileInputStream(new File(r, p + ".in"))); if (1 == 1) { System.setOut(new PrintStream(new File(r, p + ".out"))); } new C().go(); } catch (Exception e) { e.printStackTrace(); } } }
A11277
A13007
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.*; import java.io.*; public class DancingWithTheGooglers{ public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Formatter formatter = new Formatter(System.out); int T = Integer.parseInt(br.readLine()); String[] dataStr; int[] data; int lineNum=1; while(T-->0){ dataStr = br.readLine().split("\\s"); data=new int[dataStr.length-3]; for(int i=0;i<data.length;i++){ data[i]=Integer.parseInt(dataStr[i+3]); } formatter.format("Case #%d: %d\n",lineNum++, solve(Integer.parseInt(dataStr[0]),Integer.parseInt(dataStr[1]), Integer.parseInt(dataStr[2]),data)); } formatter.close(); } private static int solve(int N, int S,int p, int[] dances){ int best=0; int maybe=0; int div3=0; for(int i=0;i<N;i++){ div3=dances[i]/3; if(div3>=p || (div3==p-1 && dances[i] % 3>=1)) { best++; continue; } if((div3 == p - 1 && div3>=1) || (div3==p-2 && dances[i]%3==2)){ maybe++; continue; } } return best+Math.min(S,maybe); } }
B12115
B10053
0
package qual; import java.util.Scanner; public class RecycledNumbers { public static void main(String[] args) { new RecycledNumbers().run(); } private void run() { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int t = 0; t < T; t++) { int A = sc.nextInt(); int B = sc.nextInt(); int result = solve(A, B); System.out.printf("Case #%d: %d\n", t + 1, result); } } public int solve(int A, int B) { int result = 0; for (int i = A; i <= B; i++) { int dig = (int) Math.log10(A/*same as B*/) + 1; int aa = i; for (int d = 0; d < dig - 1; d++) { aa = (aa % 10) * (int)Math.pow(10, dig - 1) + (aa / 10); if (i == aa) { break; } if (i < aa && aa <= B) { // System.out.printf("(%d, %d) ", i, aa); result++; } } } return result; } }
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Recycle2 { /** * @param args */ public static void main(String[] args) throws Exception { Scanner in = new Scanner(new BufferedReader(new FileReader("/Users/sunny/Desktop/C-small-attempt0.in"))); PrintWriter out=new PrintWriter(new FileWriter("/Users/sunny/Desktop/1.out")); int n = in.nextInt(); String i1, i2, line ; for( int i = 1 ; i <= n ; i++){ i1 = in.next() ; i2 = in.next() ; line = "Case #"+i+": "+findN(i1, i2); System.out.println(line); out.println(line); } out.close() ; } private static int findN(String i1, String i2) { Integer n = new Integer(i1), m = new Integer(i2); int count = 0 ; for(int i = n ; i <= m ; i++) { count += getRotateCount(i+"", n, m); } return count/2; } private static int getRotateCount(String x, int n, int m) { Set<String> pairs = new HashSet<String>(); int j, count=0, xI = Integer.parseInt(x); for(int i=1 ; i < x.length() ; i++ ) { j = Integer.parseInt(x.substring(i)+x.substring(0,i)); if(j <= m && j >=n && j !=xI ) { if(!pairs.contains(xI+"-"+j)) { pairs.add(xI+"-"+j); count++; } } } return count ; } }
A10568
A10874
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 Test1; import java.io.BufferedReader; import java.io.InputStreamReader; public class Test1 { static String[] orig = {"ejp mysljylc kd kxveddknmc re jsicpdrysi", "rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd","de kr kd eoya kw aej tysr re ujdr lkgc jv"}; static String[] target = {"our language is impossible to understand","there are twenty six factorial possibilities","so it is okay if you want to just give up"}; static int[] map = new int[26]; static int[] hash = new int[26]; public static void main(String[] args) { int n,s,p,T; int[] t = new int[31]; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ; try { String str = in.readLine(); int result,vaildp,tempmax; n = Integer.parseInt(str.trim()); for (int i = 1; i <= n; i++) { str = in.readLine(); String[] temp = str.split(" "); T = Integer.parseInt(temp[0]); s = Integer.parseInt(temp[1]); p = Integer.parseInt(temp[2]); result = 0; vaildp = 0; for (int j=3; j<temp.length;j++){ int numtemp = Integer.parseInt(temp[j]); int max = numtemp / 3; if (numtemp % 3 != 0) max++; if (max >= p) result++; else { tempmax = numtemp / 3; if (numtemp % 3 == 1) tempmax = tempmax +1; else if (numtemp % 3 == 2) tempmax = tempmax +2; else if (tempmax > 0) tempmax = tempmax + 1; if (tempmax >= p) vaildp++; } //System.out.println("num="+numtemp+";max="+max+";vild="+vaildp); } if (vaildp > s) vaildp = s; result = result + vaildp; if (result > T) result = T; System.out.println("Case #"+i+": "+result); //System.out.println(""); } } catch (Exception e) { } } }
A22078
A21576
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); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.common; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; /** * * @author jim */ public class FileLoader { public FileLoader() { } public ArrayList<String> loadFile(String fileName) throws IOException { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); String in; ArrayList<String> lines = new ArrayList<String>(); while ((in = br.readLine()) != null) { lines.add(in); } return lines; } }
B12074
B12107
0
package jp.funnything.competition.util; import java.math.BigInteger; /** * Utility for BigInteger */ public class BI { public static BigInteger ZERO = BigInteger.ZERO; public static BigInteger ONE = BigInteger.ONE; public static BigInteger add( final BigInteger x , final BigInteger y ) { return x.add( y ); } public static BigInteger add( final BigInteger x , final long y ) { return add( x , v( y ) ); } public static BigInteger add( final long x , final BigInteger y ) { return add( v( x ) , y ); } public static int cmp( final BigInteger x , final BigInteger y ) { return x.compareTo( y ); } public static int cmp( final BigInteger x , final long y ) { return cmp( x , v( y ) ); } public static int cmp( final long x , final BigInteger y ) { return cmp( v( x ) , y ); } public static BigInteger div( final BigInteger x , final BigInteger y ) { return x.divide( y ); } public static BigInteger div( final BigInteger x , final long y ) { return div( x , v( y ) ); } public static BigInteger div( final long x , final BigInteger y ) { return div( v( x ) , y ); } public static BigInteger mod( final BigInteger x , final BigInteger y ) { return x.mod( y ); } public static BigInteger mod( final BigInteger x , final long y ) { return mod( x , v( y ) ); } public static BigInteger mod( final long x , final BigInteger y ) { return mod( v( x ) , y ); } public static BigInteger mul( final BigInteger x , final BigInteger y ) { return x.multiply( y ); } public static BigInteger mul( final BigInteger x , final long y ) { return mul( x , v( y ) ); } public static BigInteger mul( final long x , final BigInteger y ) { return mul( v( x ) , y ); } public static BigInteger sub( final BigInteger x , final BigInteger y ) { return x.subtract( y ); } public static BigInteger sub( final BigInteger x , final long y ) { return sub( x , v( y ) ); } public static BigInteger sub( final long x , final BigInteger y ) { return sub( v( x ) , y ); } public static BigInteger v( final long value ) { return BigInteger.valueOf( value ); } }
package com.renoux.gael.codejam.utils; import java.io.Closeable; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class Output implements Closeable { private static String lineSeparator = System.getProperty("line.separator"); private FileWriter writer; private Output(File file) { try { writer = new FileWriter(file); } catch (IOException e) { throw new TechnicalException(e); } } public static Output open(File file) { System.out.println("======== " + file); return new Output(file); } public void writeLine(String text) { System.out.println(text); try { writer.write(text); writer.write(lineSeparator); } catch (IOException e) { throw new TechnicalException(e); } } public void write(String text) { System.out.print(text); try { writer.write(text); } catch (IOException e) { throw new TechnicalException(e); } } public void writeLine(Object... text) { try { for (Object s : text) { System.out.print(s); writer.write(s.toString()); } System.out.println(); writer.write(lineSeparator); } catch (IOException e) { throw new TechnicalException(e); } } public void write(Object... text) { try { for (Object s : text) { System.out.print(s); writer.write(s.toString()); } } catch (IOException e) { throw new TechnicalException(e); } } public void close() { System.out.println("================ closed"); try { writer.close(); } catch (IOException e) { throw new TechnicalException(e); } } }
B10899
B12048
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class ReadFile { public static void main(String[] args) throws Exception { String srcFile = "C:" + File.separator + "Documents and Settings" + File.separator + "rohit" + File.separator + "My Documents" + File.separator + "Downloads" + File.separator + "C-small-attempt1.in.txt"; String destFile = "C:" + File.separator + "Documents and Settings" + File.separator + "rohit" + File.separator + "My Documents" + File.separator + "Downloads" + File.separator + "C-small-attempt0.out"; File file = new File(srcFile); List<String> readData = new ArrayList<String>(); FileReader fileInputStream = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileInputStream); StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { readData.add(line); } stringBuilder.append(generateOutput(readData)); File writeFile = new File(destFile); if (!writeFile.exists()) { writeFile.createNewFile(); } FileWriter fileWriter = new FileWriter(writeFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(stringBuilder.toString()); bufferedWriter.close(); System.out.println("output" + stringBuilder); } /** * @param number * @return */ private static String generateOutput(List<String> number) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < number.size(); i++) { if (i == 0) { continue; } else { String tempString = number.get(i); String[] temArr = tempString.split(" "); stringBuilder.append("Case #" + i + ": "); stringBuilder.append(getRecNumbers(temArr[0], temArr[1])); stringBuilder.append("\n"); } } if (stringBuilder.length() > 0) { stringBuilder.deleteCharAt(stringBuilder.length() - 1); } return stringBuilder.toString(); } // /* This method accepts method for google code jam */ // private static String method(String value) { // int intValue = Integer.valueOf(value); // double givenExpr = 3 + Math.sqrt(5); // double num = Math.pow(givenExpr, intValue); // String valArr[] = (num + "").split("\\."); // int finalVal = Integer.valueOf(valArr[0]) % 1000; // // return String.format("%1$03d", finalVal); // // } // // /* This method accepts method for google code jam */ // private static String method2(String value) { // StringTokenizer st = new StringTokenizer(value, " "); // String test[] = value.split(" "); // StringBuffer str = new StringBuffer(); // // for (int i = 0; i < test.length; i++) { // // test[i]=test[test.length-i-1]; // str.append(test[test.length - i - 1]); // str.append(" "); // } // str.deleteCharAt(str.length() - 1); // String strReversedLine = ""; // // while (st.hasMoreTokens()) { // strReversedLine = st.nextToken() + " " + strReversedLine; // } // // return str.toString(); // } private static int getRecNumbers(String no1, String no2) { int a = Integer.valueOf(no1); int b = Integer.valueOf(no2); Set<String> dupC = new HashSet<String>(); for (int i = a; i <= b; i++) { int n = i; List<String> value = findPerm(n); for (String val : value) { if (Integer.valueOf(val) <= b && Integer.valueOf(val) >= a && n < Integer.valueOf(val)) { dupC.add(n + "-" + val); } } } return dupC.size(); } private static List<String> findPerm(int num) { String numString = String.valueOf(num); List<String> value = new ArrayList<String>(); for (int i = 0; i < numString.length(); i++) { String temp = charIns(numString, i); if (!temp.equalsIgnoreCase(numString)) { value.add(charIns(numString, i)); } } return value; } public static String charIns(String str, int j) { String begin = str.substring(0, j); String end = str.substring(j); return end + begin; } }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; public class User { private static final String FILENAME = "C-small-attempt0.in"; private static final String OUTFILENAME = "C-small-attempt0.out"; public static String newline = System.getProperty("line.separator"); public static void main(String[] args) throws Exception { // System.out.println(decoder.keySet()); // System.out.println(decoder.values()); PrintWriter out = new PrintWriter(new FileWriter(OUTFILENAME)); // PrintStream out = System.out; FileReader fr = null; try { fr = new FileReader(FILENAME); } catch (FileNotFoundException e) { e.printStackTrace(); } BufferedReader input = new BufferedReader(fr); String[] line; String n; int digCount; String m; int recycledPairs = 0; int T = Integer.parseInt(input.readLine()); for (int t=0; t<T; t++){ HashMap<String, TreeSet<Integer>> digitMap = new HashMap<String, TreeSet<Integer>> (); recycledPairs = 0; line = input.readLine().split(" "); n = line[0]; m = line[1]; int nInt = Integer.parseInt(n); int mInt = Integer.parseInt(m); for (int i = nInt; i<=mInt; i++){ String myChars = findChars(i); if (digitMap.containsKey(myChars)){ digitMap.get(myChars).add(i); // System.out.println ("adding "+ i + " to "+ myChars + " new size is " + digitMap.get(myChars).size()); } else { TreeSet<Integer> myTreeSet = new TreeSet<Integer>(); myTreeSet.add(i); digitMap.put(myChars, myTreeSet); // System.out.println ("adding "+ i + " to "+ myChars + " new size is " + digitMap.get(myChars).size()); } } for (TreeSet<Integer> myTreeSet : digitMap.values()){ if (myTreeSet.size()>1){ Integer[] setArray = myTreeSet.toArray(new Integer[0]); int saLen = setArray.length; for (int i = 0; i<saLen; i++) for (int j = i+1; j<saLen;j++) if(recycled(setArray[i], setArray[j])) recycledPairs++; } } /* for (int i = 0; i<7; i++) for (int j = 0; j<magSet.get(i).size(); j++) for (int k = j+1; k<magSet.get(i).size();k++) if(recycled(magSet.get(i).get(j), magSet.get(i).get(k))) recycledPairs++; */ out.println("Case #" + (t+1) + ": "+recycledPairs); } input.close(); fr.close(); out.close(); } private static boolean recycled(Integer n, Integer m) { //System.out.println("recycling: " + n + "; "+ m); String nStr = n.toString(); int strLen = nStr.length(); String mStr = m.toString(); for (int i=0; i < strLen-1; i++){ nStr = moveDigit(nStr); // System.out.println("comparing: " + nStr + "; "+ mStr); if (nStr.equals(mStr)) return true; } return false; } private static String findChars(int i) { char[] myCharArray= Integer.toString(i).toCharArray(); Arrays.sort(myCharArray); return new String(myCharArray); } private static int countDigits(String next) { // TODO Auto-generated method stub return next.length(); } private static String moveDigit(String n){ StringBuffer nString = new StringBuffer(n); if (nString.length() == 1) return n; StringBuffer resultString = new StringBuffer(); resultString.append(nString.charAt(nString.length()-1)); resultString.append(nString.substring(0, nString.length()-1)); return new String(resultString); } private static int countDigits (int i){ StringBuffer nString = new StringBuffer(Integer.toString(i)); return nString.length(); } }
B13196
B10066
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Q3M { public static void main(String[] args) throws Exception { compute(); } private static void compute() throws Exception { BufferedReader br = new BufferedReader(new FileReader(new File( "C:\\work\\Q3\\C-small-attempt0.in"))); String line = null; int i = Integer.parseInt(br.readLine()); List l = new ArrayList(); for (int j = 0; j < i; j++) { line = br.readLine(); String[] nums = line.split(" "); l.add(calculate(nums)); } writeOutput(l); } private static int calculate(String[] nums) { int min = Integer.parseInt(nums[0]); int max = Integer.parseInt(nums[1]); int count = 0; List l = new ArrayList(); for (int i = min; i <= max; i++) { for (int times = 1; times < countDigits(i); times++) { int res = shiftNum(i, times); if (res <= max && i < res) { if ((!l.contains((i + ":" + res)))) { l.add(i + ":" + res); l.add(res + ":" + i); count++; } } } } return count; } private static boolean checkZeros(int temp, int res) { if (temp % 10 == 0 || res % 10 == 0) return false; return true; } private static int shiftNum(int n, int times) { int base = (int) Math.pow(10, times); int temp2 = n / base; int placeHolder = (int) Math.pow((double) 10, (double) countDigits(temp2)); int res = placeHolder * (n % base) + temp2; if (countDigits(res) == countDigits(n)) { return res; } else { return 2000001; } } public static int countDigits(int x) { if (x < 10) return 1; else { return 1 + countDigits(x / 10); } } private static void writeOutput(List l) throws Exception { StringBuffer b = new StringBuffer(); int i = 1; BufferedWriter br = new BufferedWriter(new FileWriter(new File( "C:\\work\\Q3\\ans.txt"))); for (Iterator iterator = l.iterator(); iterator.hasNext();) { br.write("Case #" + i++ + ": " + iterator.next()); br.newLine(); } br.close(); } }
package codejam; import java.io.*; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class C { static String str = "C:\\carl\\fileC.txt"; static String text = ""; static int A, B, T, cnt; static HashMap hm; public static void main(String[] args) { try { int count = 0; hm = new HashMap(); File file = new File(str); BufferedReader br = new BufferedReader(new FileReader(file)); PrintWriter outer = new PrintWriter(new FileWriter("C:\\carl\\outC.txt")); while((text = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(text); if(count == 0) { T = Integer.parseInt(st.nextToken()); count++; } else { A = Integer.parseInt(st.nextToken()); int n = A; B = Integer.parseInt(st.nextToken()); while (n != B) { char[] temp = Integer.toString(n).toCharArray(); scramble(temp, n); n++; } outer.println("Case #" + count + ": " + hm.entrySet().size()); //System.out.println(hm.entrySet().size()); hm.clear(); count++; } } outer.close(); } catch(IOException ex) { System.out.println("Error with IO you foooool"); } catch(Exception ex) { System.out.println("Generic Error. Noob."); ex.printStackTrace(); } } public static void scramble(char[] temp, int n) { Integer[] no = new Integer[temp.length]; for(int i=0; i<temp.length;i++) { no[i] = Integer.parseInt( Character.toString(temp[i]) ); } //Integer[] test = {1, 2, 3, 4, 5}; for (int i = 0; i < temp.length - 1; i++) { Collections.rotate(Arrays.asList(no), -1); int m = trans(no); //System.out.println(n + " " + m); if( n < m && m <= B && no[0] != 0 ) { if( !hm.containsKey(n + " " + m)) { hm.put(n + " " + m, n + " " + m); //System.out.println(n + ", " + m); } //System.out.println(b); } } } public static int trans(Integer[] a) { String s = ""; for(int i : a) { s = s + i; } //System.out.println(" @@ " + s); return Integer.parseInt(s); } }
B11361
B12945
0
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class C{ Scanner sc=new Scanner(System.in); int INF=1<<28; double EPS=1e-9; int caze, T; int A, B; void run(){ T=sc.nextInt(); for(caze=1; caze<=T; caze++){ A=sc.nextInt(); B=sc.nextInt(); solve(); } } void solve(){ int ans=0; for(int n=A; n<=B; n++){ int digit=(int)(log10(n)+EPS); int d=(int)pow(10, digit); // debug("n", n); for(int m=rot(n, d); m!=n; m=rot(m, d)){ // debug("m", m); if(n<m&&m<=B){ ans++; } } } answer(ans+""); } int rot(int n, int d){ return n/10+n%10*d; } void answer(String s){ println("Case #"+caze+": "+s); } void println(String s){ System.out.println(s); } void print(String s){ System.out.print(s); } void debug(Object... os){ System.err.println(deepToString(os)); } public static void main(String[] args){ try{ System.setIn(new FileInputStream("dat/C-small.in")); System.setOut(new PrintStream(new FileOutputStream("dat/C-small.out"))); }catch(Exception e){} new C().run(); System.out.flush(); System.out.close(); } }
package lt.kasrud.gcj.ex3; import lt.kasrud.gcj.common.IO; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Main { public static void main(String[] args) throws IOException { IO.Data data = IO.readFile("C-small-attempt0.in"); IO.writeFile("out3.txt", process(data)); } private static List<Integer> process(IO.Data data) { List<Integer> result = new ArrayList<Integer>(data.getInt(0, 0)); for(IO.Record r : data.getRecords(1)){ Integer c = calculate(r.getInt(0), r.getInt(1)); result.add(c); } return result; } private static Integer calculate(Integer a, Integer b) { int cnt = 0; Set<Integer> ms = new HashSet<Integer>(); for (int n=a; n<=b; n++){ ms.clear(); String ns = String.valueOf(n); for (int i = 1; i< ns.length(); i++){ int m = rotate(ns, i); if (m > n && m <= b){ ms.add(m); } } cnt += ms.size(); } return cnt; } private static int rotate(String ns, int i){ String ms = ns.substring(i, ns.length()) + ns.substring(0, i); return Integer.valueOf(ms); } }
B10149
B10390
0
import java.io.FileInputStream; import java.util.HashMap; import java.util.Scanner; import java.util.TreeSet; // Recycled Numbers // https://code.google.com/codejam/contest/1460488/dashboard#s=p2 public class C { private static String process(Scanner in) { int A = in.nextInt(); int B = in.nextInt(); int res = 0; int len = Integer.toString(A).length(); for(int n = A; n < B; n++) { String str = Integer.toString(n); TreeSet<Integer> set = new TreeSet<Integer>(); for(int i = 1; i < len; i++) { int m = Integer.parseInt(str.substring(i, len) + str.substring(0, i)); if ( m > n && m <= B && ! set.contains(m) ) { set.add(m); res++; } } } return Integer.toString(res); } public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in.available() > 0 ? System.in : new FileInputStream(Thread.currentThread().getStackTrace()[1].getClassName() + ".practice.in")); int T = in.nextInt(); for(int i = 1; i <= T; i++) System.out.format("Case #%d: %s\n", i, process(in)); } }
package gcj2012; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbersClean { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner( new File( "/Users/olvitole/Dropbox/workspace/Googe Code/src/gcj2012/files/C-small-attempt1.in")); int t = Integer.parseInt(in.nextLine()); OutputStream outStr = new FileOutputStream( "/Users/olvitole/Dropbox/workspace/Googe Code/src/gcj2012/files/C1s-output.txt"); PrintStream printOut = new PrintStream(outStr); for (int zz = 1; zz <= t; zz++) { ArrayList<String> record = new ArrayList<String>(); String input = in.nextLine().trim(); String parts[] = input.split(" "); int A = Integer.parseInt(parts[0]); int B = Integer.parseInt(parts[1]); int count = 0; if (!(B <= 9)) { int iFliped = 0; String iFlipedString = ""; String iString = ""; for (int i = A; i <= B; i++) { iString = i + ""; int first = 0; int second = 0; for (int j = 1; j < iString.length(); j++) { System.out.println(); first = (int) (i / (Math.pow(10, j))); second = (int) (i % (Math.pow(10, j))); iFlipedString = "" + second + "" + first; iFliped = Integer.parseInt(iFlipedString); if (iFliped <= B && iFliped > i && !iString.equals(iFlipedString) && !record.contains(iString + iFlipedString)) { count++; record.add(iString + iFlipedString); } } } } String output = count + ""; printOut.append("Case #" + zz + ": " + output + "\n"); } System.setOut(printOut); } }
B21270
B20511
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.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.*; public class main { static int numberPeriod(int n, int len) { if (len == 2 && n / 10 == n % 10) return 1; if (len == 4 && n % 100 == n / 100) return 2; if (len == 6 && n % 100 == n / 10000 && n % 100 == n / 100 % 100) return 2; if (len == 6 && n % 1000 == n / 1000) return 3; return len; } static int numberLength(int n) { int len = 0; while (n > 0) { n /= 10; len++; } return len; } public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File("C-large.in")); PrintWriter out = new PrintWriter("result.txt"); int tests = sc.nextInt(); for (int t = 1; t <= tests; t++) { int a = sc.nextInt(), b = sc.nextInt(), length = numberLength(a), tt = (int) Math.pow(10, length - 1), res = 0; for (int j = a; j <= b; j++) { int cur = j; int val = j; int per = numberPeriod(j, length); for (int k = 0; k < per; k++) { int c = val % 10; val = val / 10 + c * tt; if (val > cur && val <= b) { res++; } } } out.printf("Case #%d: %d\n",t,res); } out.flush(); } }
B20023
B21579
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class GoogleC { public String szamol(String input){ String result=""; String a=input; Integer min=Integer.parseInt(a.substring(0,a.indexOf(' '))); a=a.substring(a.indexOf(' ')+1); Integer max=Integer.parseInt(a); Long count=0l; for(Integer i=min; i<=max; i++){ String e1=i.toString(); Set<Integer> db=new HashSet<Integer>(); for (int j=1; j<e1.length();j++){ String e2=e1.substring(j)+e1.substring(0,j); Integer k=Integer.parseInt(e2); if (k>i && k<=max){ db.add(k); //System.out.println(e1+"\t"+e2); } } count+=db.size(); } return count.toString(); } public static void main(String[] args) { GoogleC a=new GoogleC(); //String filename="input.txt"; //String filename="C-small-attempt0.in"; String filename="C-large.in"; String thisLine; try { BufferedReader br = new BufferedReader(new FileReader(filename)); BufferedWriter bw= new BufferedWriter(new FileWriter(filename+".out")); thisLine=br.readLine(); Integer tnum=Integer.parseInt(thisLine); for(int i=0;i<tnum;i++) { // while loop begins here thisLine=br.readLine(); System.out.println(thisLine); System.out.println("Case #"+(i+1)+": "+a.szamol(thisLine)+"\n"); bw.write("Case #"+(i+1)+": "+a.szamol(thisLine)+"\n"); } // end while // end try br.close(); bw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new FileReader("input.txt")); PrintWriter pw = new PrintWriter(new FileWriter("output.txt")); int tn = sc.nextInt(); sc.nextLine(); for(int i = 0; i < tn; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int res = 0; for(int t = a; t <= b; t++) { String oppa = t + ""; int len = (t + "").length(); for (int u = 0; u + 1 < len; u++) { if(oppa.charAt(u + 1) != '0') { int v = Integer.parseInt(oppa.substring(u + 1, len) + oppa.substring(0, u + 1)); if (t == v) break; if (a <= v && v <= b) { res++; } } } } pw.print("Case #" + (i + 1) + ": " + (res / 2)); pw.println(); } pw.close(); } }
A21396
A20641
0
import java.util.*; public class Test { public static void main(String[] args){ Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int i = 1; i<=T; i++) { int n = in.nextInt(); int s = in.nextInt(); int p = in.nextInt(); int result = 0; for(int j = 0; j<n; j++){ int x = canAddUp(in.nextInt(), p); if(x == 0) { result++; } else if (x==1 && s > 0) { result++; s--; } } System.out.println("Case #"+i+": "+result); } } public static int canAddUp(int sum, int limit) { boolean flag = false; for(int i = 0; i<=sum; i++) { for(int j = 0; i+j <= sum; j++) { int k = sum-(i+j); int a = Math.abs(i-j); int b = Math.abs(i-k); int c = Math.abs(j-k); if(a > 2 || b > 2 || c> 2){ continue; } if (i>=limit || j>=limit || k>=limit) { if(a < 2 && b < 2 && c < 2) { return 0; }else{ flag = true; } } } } return (flag) ? 1 : 2; } }
import java.io.PrintWriter; import java.util.Scanner; public class ProblemB { public static void main(String[] args) { final Scanner in = new Scanner(System.in); final PrintWriter out = new PrintWriter(System.out); final int t = in.nextInt(); for (int tt = 0; tt < t; tt++) { final int n = in.nextInt(); final int s = in.nextInt(); final int p = in.nextInt(); int surprisesLeft = s; int googlersCount = 0; for (int nn = 0; nn < n; nn++) { final int totalScore = in.nextInt(); if (canAchieveScoreIfNormal(totalScore, p)) { googlersCount++; } else if (surprisesLeft > 0 && canAchieveScoreIfSurprising(totalScore, p)) { googlersCount++; surprisesLeft--; } } out.write("Case #" + (tt + 1) + ": " + googlersCount + "\n"); } out.flush(); } private static boolean canAchieveScoreIfNormal(int totalScore, int score) { return totalScore >= (3 * score - 2); } private static boolean canAchieveScoreIfSurprising(int totalScore, int score) { if (score == 1) return totalScore >= 1; else return totalScore >= (3 * score - 4); } }
A13029
A11439
0
import java.util.List; public class Case implements Runnable { private int id; private String output; private int n; private int s; private int p; private List<Integer> g; public Case(int id) { this.id = id; } public Case(int id, int n, int s, int p, List<Integer> g) { super(); this.id = id; this.n = n; this.s = s; this.p = p; this.g = g; } public String solve() { int res = 0; for (int googler : g) { int b = googler / 3; boolean div = googler % 3 == 0; if (b >= p) { res++; continue; } if (p == b+1) { if (div && s > 0 && b > 0) { res++; s--; continue; } if (!div) { res++; continue; } } if (p == b+2) { if (3*b+2 == googler && s > 0) { res++; s--; } } } return String.valueOf(res); } @Override public void run() { output = solve(); } @Override public String toString() { return "Case #" + id + ": " + output; } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class Main { public static HashMap<Character,Character> mapp = new HashMap<Character,Character>(); public static void main(String[] args) throws Exception { PrintWriter writer = new PrintWriter(new FileWriter("output.txt")); BufferedReader input = new BufferedReader(new FileReader("B-small-attempt0.in")); int size=Integer.parseInt(input.readLine()); for(int i=0; i<size; i++) { String testCase = input.readLine(); String tokens[] = testCase.split(" "); int N = Integer.parseInt(tokens[0]); int S = Integer.parseInt(tokens[1]); int p = Integer.parseInt(tokens[2]); int count=0; //ArrayList<Integer> google = new ArrayList<Integer>(); for(int j=3; j<N+3; j++) { int testNum = Integer.parseInt(tokens[j]); if((testNum - p) >= 2*(p-1) && (testNum-p)>=0) { count++; } else if((testNum - p) < 2*(p-1) && (testNum-p)>=0) { if(S!=0 && (testNum - p) >= 2*(p-2) ) { count++; S--; } } } writer.println("Case #"+(i+1)+": "+count); } writer.close(); input.close(); } }
B11421
B12012
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Recycled { public static void main(String[] args) throws Exception{ String inputFile = "C-small-attempt0.in"; BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output"))); long num_cases = Long.parseLong(input.readLine()); int current_case = 0; while (current_case < num_cases){ current_case++; String[] fields = input.readLine().split(" "); int A = Integer.parseInt(fields[0]); int B = Integer.parseInt(fields[1]); int total = 0; for (int n = A; n < B; n++){ for (int m = n+1; m <= B; m++){ if (isRecycled(n,m)) total++; } } System.out.println("Case #" + current_case + ": " + total); output.write("Case #" + current_case + ": " + total + "\n"); } output.close(); } private static boolean isRecycled(int n, int m) { String sn = ""+n; String sm = ""+m; if (sn.length() != sm.length()) return false; int totaln = 0, totalm = 0; for (int i = 0; i < sn.length(); i++){ totaln += sn.charAt(i); totalm += sm.charAt(i); } if (totaln != totalm) return false; for (int i = 0; i < sn.length()-1; i++){ sm = sm.charAt(sm.length() - 1) + sm.substring(0, sm.length() - 1); if (sm.equals(sn)) return true; } return false; } }
import java.util.*; import java.io.*; public class C { public static int computeDigits(int x){ if(x<10){ return 1; }else{ return 1+computeDigits(x/10); } } public static boolean recycled(int x, int y){ int n = computeDigits(x); for(int i = 1;i<n;i++){ int c = (int)Math.pow(10,i); int number = x/c; int mod = x%c; int newNumber = (mod*(int)Math.pow(10,n-i))+number; //System.out.println(newNumber); if(newNumber == y) return true; } return false; } public static void main(String []args){ Scanner input = new Scanner(System.in); int cases = input.nextInt(); int []result = new int[cases]; //input.nextLine(); for(int i = 0; i < cases ;i++){ int a = input.nextInt(); int b = input.nextInt(); if(a<10 || b<10){ result[i]=0; }else{ for(int j = a; j<b;j++){ for(int k=a+1;k<=b;k++){ if(j<k && recycled(j,k)) result[i]++; } } } } try { BufferedWriter output = new BufferedWriter(new FileWriter("outfilename.txt")); for(int i = 1; i<=cases ;i++){ System.out.println("Case #"+i+": "+result[i-1]); output.write("Case #"+i+": "+result[i-1]+"\n"); } output.close(); } catch (IOException e) { } } }
A10793
A12242
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 cats; import java.io.*; import java.util.ArrayList; import java.util.Collections; public class Main { public Main() throws Exception{ FileReader fr = new FileReader(new File("input.txt")); BufferedReader in = new BufferedReader(fr); File outFile = new File("output.txt"); outFile.createNewFile(); FileWriter fw = new FileWriter(outFile); BufferedWriter out = new BufferedWriter(fw); int numTests = Integer.parseInt(in.readLine()); for(int x = 0; x<numTests; x++){ System.out.println("Working on case " + x + " of " + numTests); String[] split = in.readLine().split(" "); int numPeople, surprises, scoreToBeat; numPeople = Integer.parseInt(split[0]); surprises = Integer.parseInt(split[1]); scoreToBeat = Integer.parseInt(split[2]); ArrayList<Integer> totals = new ArrayList<Integer>(numPeople); for(int p = 0; p<numPeople; p++){ totals.add(Integer.parseInt(split[3+p])); } Collections.sort(totals); Collections.reverse(totals); int count = 0; int surprisesLeft = surprises; for(int t: totals){ if(t == 0){ if(scoreToBeat == 0) count++; else break; }else if(t >= scoreToBeat+(scoreToBeat-1)*2){ count++; }else if(t >= scoreToBeat+(scoreToBeat-2)*2 && surprisesLeft > 0){ surprisesLeft--; count++; }else break; } out.write("Case #" + (x+1) + ": " + count + "\n"); } in.close(); out.close(); } public static void main(String[] args) throws Exception{ new Main(); } }
A11917
A10386
0
package com.silverduner.codejam; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.HashMap; public class Dancing { public static void main(String[] args) throws Exception { File input = new File("B-small-attempt0.in"); BufferedReader in = new BufferedReader(new FileReader(input)); File output = new File("1.out"); BufferedWriter out = new BufferedWriter(new FileWriter(output)); // parse input int N = Integer.parseInt(in.readLine()); for(int i=0;i<N;i++) { String str = in.readLine(); out.write("Case #"+(i+1)+": "); System.out.println("-------"); String[] words = str.split(" "); int n = Integer.parseInt(words[0]); int suprise = Integer.parseInt(words[1]); int threshold = Integer.parseInt(words[2]); int[] scores = new int[n]; for(int j=0;j<n;j++) { scores[j] = Integer.parseInt(words[3+j]); } int count = 0; for(int score : scores) { int a,b,c; boolean find = false; boolean sfind = false; for(a = 10; a>=0 && !find; a--) { if(3*a-4>score) continue; for(b = a; b>=0 && b >=a-2 && !find; b--) { for(c = b; c>=0 && c >=b-2 && c >=a-2 && !find; c--) { System.out.println(a+","+b+","+c); if(a+b+c==score) { if(a >= threshold) { if(a-c <= 1){ count++; find = true; System.out.println("find!"); } else if(a-c == 2){ sfind = true; System.out.println("suprise!"); } } } } } } if(!find && sfind && suprise > 0) { count++; suprise --; } } int maxCount = count; out.write(maxCount+"\n"); } out.flush(); out.close(); in.close(); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Dancing { private static BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { String line = bufferedReader.readLine(); int cases = Integer.parseInt(line); for (int i = 1; i <= cases; i++) { line = bufferedReader.readLine(); String[] split = line.split(" "); int googlers = Integer.parseInt(split[0]); int surprises = Integer.parseInt(split[1]); int p = Integer.parseInt(split[2]); int[] totals = new int[googlers]; for (int j = 0; j < googlers; j++) { totals[j] = Integer.parseInt(split[3 + j]); } Arrays.sort(totals); int answer = 0; int usedSurprises = 0; for (int j = 0; j < googlers; j++) { if (p == 0) { answer++; } else if (totals[j] >= p + 2 * (p - 1) && p >= 1) { answer++; } else if (usedSurprises < surprises) { if (totals[j] >= p + 2 * (p - 2) && p >= 2) { answer++; usedSurprises++; } } } System.out.println("Case #" + i + ": " + answer); } } }
A11917
A13074
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.vp.iface; public interface Problem{ public static int SPEAKGOOGLERESE = 1; public static int DANCINGWITHGOOGLERS = 2; public String solve(String dataset[]); }
B11421
B10236
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Recycled { public static void main(String[] args) throws Exception{ String inputFile = "C-small-attempt0.in"; BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output"))); long num_cases = Long.parseLong(input.readLine()); int current_case = 0; while (current_case < num_cases){ current_case++; String[] fields = input.readLine().split(" "); int A = Integer.parseInt(fields[0]); int B = Integer.parseInt(fields[1]); int total = 0; for (int n = A; n < B; n++){ for (int m = n+1; m <= B; m++){ if (isRecycled(n,m)) total++; } } System.out.println("Case #" + current_case + ": " + total); output.write("Case #" + current_case + ": " + total + "\n"); } output.close(); } private static boolean isRecycled(int n, int m) { String sn = ""+n; String sm = ""+m; if (sn.length() != sm.length()) return false; int totaln = 0, totalm = 0; for (int i = 0; i < sn.length(); i++){ totaln += sn.charAt(i); totalm += sm.charAt(i); } if (totaln != totalm) return false; for (int i = 0; i < sn.length()-1; i++){ sm = sm.charAt(sm.length() - 1) + sm.substring(0, sm.length() - 1); if (sm.equals(sn)) return true; } return false; } }
import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class prob2 { public static void main(String[] args) { BufferedReader inputStream = null; try { inputStream = new BufferedReader(new FileReader( "C:/Users/vpamarty.SYMPHONY/Downloads/C-small-attempt1.in")); String lineRead = inputStream.readLine(); int noCases = Integer.valueOf(lineRead).intValue(); for (int i = 0; i < noCases; i++) { lineRead = inputStream.readLine(); String[] splitString = lineRead.split(" "); int numA = Integer.valueOf(splitString[0]).intValue(); int numB = Integer.valueOf(splitString[1]).intValue(); int distinctRps = computeDisRps(numA, numB); System.out.println("Case #"+(i+1)+": "+distinctRps); } inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } public static int computeDisRps(int num1, int num2) { int numPairs = 0; for (int numCons = num1; numCons < num2; numCons++) { int numLength = (String.valueOf(numCons)).length(); ArrayList<String> numArr = new ArrayList<String>(); numArr.add(String.valueOf(numCons)); for (int i = 1; i < numLength; i++) { String numString = String.valueOf(numCons); String newNumString = numString.substring(numLength - i) + numString.substring(0, numLength - i); if (!numArr.contains(newNumString)) { numArr.add(newNumString); if (Integer.valueOf(newNumString).intValue() > numCons && Integer.valueOf(newNumString).intValue() <= num2) numPairs++; } } } return numPairs; } }
A12544
A10724
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 home.lviv; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class Main { public static void proA(BufferedReader reader, BufferedWriter writer) throws NumberFormatException, IOException { Map<Character, Character> map = new HashMap<Character, Character>(32); String text = "zejp mysljylc kd kxveddknmc re jsicpdrysi" + "rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd" + "de kr kd eoya kw aej tysr re ujdr lkgc jvq", mapping = "qour language is impossible to understand" + "there are twenty six factorial possibilities" + "so it is okay if you want to just give upz"; for (int i = 0; i < text.length(); i++) { map.put(Character.valueOf(text.charAt(i)), Character.valueOf(mapping.charAt(i))); } int T; T = Integer.parseInt(reader.readLine()); for (int t = 0; t < T; t++) { String in, out = ""; in = reader.readLine(); for (int i = 0; i < in.length(); i++) { if (map.get(in.charAt(i)) == null) { System.out.println("null is " + in.charAt(i)); } out += map.get(in.charAt(i)); } writer.write("Case #" + (t + 1) + ": " + out + "\n"); } } public static void proB(BufferedReader reader, BufferedWriter writer) throws NumberFormatException, IOException { int T = Integer.parseInt(reader.readLine()); for (int t = 0; t < T; t++) { String[] temp = reader.readLine().split(" "); int N = Integer.parseInt(temp[0]), S = Integer.parseInt(temp[1]), p = Integer .parseInt(temp[2]), G = 0; int[] n = new int[N]; ArrayList<Integer> integers = new ArrayList<Integer>(N); for (int i = 0; i < N; i++) { n[i] = Integer.parseInt(temp[3 + i]); if (((n[i] / 3) >= p)) { G++; continue; } else { if (((n[i] / 3) >= p - 1) && (n[i] > 0) && (n[i] % 3 > 0)) { G++; continue; } if (((n[i] / 3) >= p - 1) && (n[i] > 0) && (S > 0)) { G++; S--; continue; } if (((n[i] / 3) >= p - 2) && (n[i] > 0) && (n[i] % 3 > 1) && (S > 0)) { G++; S--; continue; } } } writer.write("Case #" + (t + 1) + ": " + (G) + "\n"); } } public static void main(String[] args) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader( new FileInputStream("/home/taras/codejam/data.in"))); BufferedWriter output = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("/home/taras/codejam/data.out"))); proB(input, output); input.close(); output.close(); } }
A20382
A20641
0
package dancinggooglers; import java.io.File; import java.util.Scanner; public class DanceScoreCalculator { public static void main(String[] args) { if(args.length <= 0 || args[0] == null) { System.out.println("You must enter a file to read"); System.out.println("Usage: blah <filename>"); System.exit(0); } File argFile = new File(args[0]); try { Scanner googleSpeakScanner = new Scanner(argFile); String firstLine = googleSpeakScanner.nextLine(); Integer linesToScan = new Integer(firstLine); for(int i = 1; i <= linesToScan; i++) { String googleDancerLine = googleSpeakScanner.nextLine(); DanceScoreCase danceCase = new DanceScoreCase(googleDancerLine); System.out.println(String.format("Case #%d: %d", i, danceCase.maxDancersThatCouldPass())); } } catch (Exception e) { e.printStackTrace(); } } }
import java.io.PrintWriter; import java.util.Scanner; public class ProblemB { public static void main(String[] args) { final Scanner in = new Scanner(System.in); final PrintWriter out = new PrintWriter(System.out); final int t = in.nextInt(); for (int tt = 0; tt < t; tt++) { final int n = in.nextInt(); final int s = in.nextInt(); final int p = in.nextInt(); int surprisesLeft = s; int googlersCount = 0; for (int nn = 0; nn < n; nn++) { final int totalScore = in.nextInt(); if (canAchieveScoreIfNormal(totalScore, p)) { googlersCount++; } else if (surprisesLeft > 0 && canAchieveScoreIfSurprising(totalScore, p)) { googlersCount++; surprisesLeft--; } } out.write("Case #" + (tt + 1) + ": " + googlersCount + "\n"); } out.flush(); } private static boolean canAchieveScoreIfNormal(int totalScore, int score) { return totalScore >= (3 * score - 2); } private static boolean canAchieveScoreIfSurprising(int totalScore, int score) { if (score == 1) return totalScore >= 1; else return totalScore >= (3 * score - 4); } }
A20934
A22817
0
import java.util.*; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); B th = new B(); for (int i = 0; i < T; i++) { int n = sc.nextInt(); int s = sc.nextInt(); int p = sc.nextInt(); int[] t = new int[n]; for (int j = 0; j < n; j++) { t[j] = sc.nextInt(); } int c = th.getAnswer(s,p,t); System.out.println("Case #" + (i+1) + ": " + c); } } public int getAnswer(int s, int p, int[] t) { int A1 = p + p-1+p-1; int A2 = p + p-2+p-2; if (A1 < 0) A1 = 0; if (A2 < 0) A2 = 1; int remain = s; int count = 0; int n = t.length; for (int i = 0; i < n; i++) { if (t[i] >= A1) { count++; } else if (t[i] < A1 && t[i] >= A2) { if (remain > 0) { remain--; count++; } } } return count; } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class RQB { private static BufferedReader in; private static PrintWriter out; private static StringTokenizer input; public static void main(String[] args) throws IOException { //Initializing ... int [] maxa = new int[31];int a =0;int b =1; for (int i = 1; i <= 30; i++) { maxa[i]=b;a++;if(a==3){a=0;b++;} } int [] maxb = new int[31];a =0;b =2; for (int i = 2; i <= 30; i++) { maxb[i]=b;a++;if(a==3){a=0;b++;} } new RQB(); //------------------------------------------------------------------------- int testCases = nextInt(); int counter=0; while (testCases -- > 0){ counter++; //Here put the code..:) int n = nextInt(); int s = nextInt(); int p = nextInt(); int [] ns = new int[n]; for (int i = 0; i < ns.length; i++)ns[i]=nextInt(); Arrays.sort(ns); int ret = 0; for (int i = 0; i < ns.length; i++) { if(maxa[ns[i]]>=p){ret++;continue;} if(s>0){ if(ns[i]>=2&&ns[i]<=28){ if(maxb[ns[i]]>=p){s--;ret++;} }else{ if(maxa[ns[i]]>=p)ret++; } }else{ if(maxa[ns[i]]>=p)ret++; } } writeln("Case #"+counter+": "+ret); } //------------------------------------------------------------------------- //closing up end(); //-------------------------------------------------------------------------- } public RQB() throws IOException { //Input Output for Console to be used for trying the test samples of the problem in = new BufferedReader(new InputStreamReader(System.in)); // out = new PrintWriter(System.out); //------------------------------------------------------------------------- //Input Output for File to be used for solving the small and large test files // in = new BufferedReader(new FileReader("RQB.in")); out = new PrintWriter("RQB.txt"); //------------------------------------------------------------------------- //Initalize Stringtokenizer input input = new StringTokenizer(in.readLine()); } private static int nextInt() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Integer.parseInt(input.nextToken()); } private static long nextLong() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Long.parseLong(input.nextToken()); } private static double nextDouble() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return Double.parseDouble(input.nextToken()); } private static String nextString() throws IOException { if (!input.hasMoreTokens())input=new StringTokenizer(in.readLine()); return input.nextToken(); } private static void write(String output){ out.write(output); out.flush(); } private static void writeln(String output){ out.write(output+"\n"); out.flush(); } private static void end() throws IOException{ in.close(); out.close(); System.exit(0); } }
A22771
A20281
0
package com.menzus.gcj._2012.qualification.b; import com.menzus.gcj.common.InputBlockParser; import com.menzus.gcj.common.OutputProducer; import com.menzus.gcj.common.impl.AbstractProcessorFactory; public class BProcessorFactory extends AbstractProcessorFactory<BInput, BOutputEntry> { public BProcessorFactory(String inputFileName) { super(inputFileName); } @Override protected InputBlockParser<BInput> createInputBlockParser() { return new BInputBlockParser(); } @Override protected OutputProducer<BInput, BOutputEntry> createOutputProducer() { return new BOutputProducer(); } }
package common; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import protocols.ConfigurableStreamHandlerFactory; public class QuestionHandler { static { ConfigurableStreamHandlerFactory.Init(); } private final ISolver solver; private String newLine = System.getProperty("line.separator"); public QuestionHandler(ISolver solver) { this.solver = solver; } public void addCase(String problem, String answer) { solver.addCase(problem, answer); } public void addResource(String problemResource, String answerResource) { try { addResource(new URL(autoCompleteResourceName(problemResource)), new URL(autoCompleteResourceName(answerResource))); } catch (MalformedURLException e) { throw new RuntimeException(e); } } public void addResource(URL problemUrl, URL answerUrl) { try { BufferedReader problemReader = new BufferedReader( new InputStreamReader(problemUrl.openStream())); BufferedReader answerReader = new BufferedReader( new InputStreamReader(answerUrl.openStream())); int numberOfCases = Integer.valueOf(problemReader.readLine()); for (int i = 0; i < numberOfCases; ++i) { String answerLine = answerReader.readLine(); answerLine = answerLine.substring(answerLine.indexOf(':') + 2); solver.addCase(problemReader.readLine(), answerLine); } } catch (IOException e) { throw new RuntimeException(e); } } public void solve(String problemResource, String answerResource) { try { solve(new URL(autoCompleteResourceName(problemResource)), new URL( autoCompleteResourceName(answerResource))); } catch (MalformedURLException e) { throw new RuntimeException(e); } } public void solve(URL problemUrl, URL answerUrl) { try { String path = answerUrl.getPath().replace('\\', '/'); String curDir = System.getProperty("user.dir").replace('\\', '/') + "/"; File outFile = new File(curDir + "src/" + path); solve(problemUrl, new FileWriter(outFile), new OutputStreamWriter( System.out) { @Override public void close() throws IOException { } }); } catch (IOException e) { throw new RuntimeException(e); } } private void solve(URL problemUrl, Writer... writers) { try { BufferedReader problemReader = new BufferedReader( new InputStreamReader(problemUrl.openStream())); int numberOfCases = Integer.valueOf(problemReader.readLine()); for (int i = 0; i < numberOfCases; ++i) { String solution = "Case #" + (i + 1) + ": " + solver.solve(problemReader.readLine()); for (Writer writer : writers) { writer.write(solution); writer.write(newLine); } } for (Writer writer : writers) { writer.flush(); writer.close(); } } catch (IOException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") public <T extends ISolver> T getSolver() { return (T)solver; } private String autoCompleteResourceName(String resource) { if (resource.indexOf(":") != -1) { return resource; } return "classpath:" + solver.getClass().getPackage().getName().replace('.', '/') + "/" + resource; } }
A12211
A12662
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Dancing_improved { static int f_Superan_limites(String params){ int superan_limite=0; String[] parametros=params.split(" "); int n_participantes= Integer.parseInt(parametros[0]); int n_sorprendidos= Integer.parseInt(parametros[1]); int nota_limite= Integer.parseInt(parametros[2]); int suma_notas, resto, nota_juego; for(int i=3;i<parametros.length;i++){ // Recorro las sumas de los participantes suma_notas=Integer.parseInt(parametros[i]); resto=suma_notas%3; if(resto==0){ // el resto es el número triplicado! nota_juego=suma_notas/3; if(nota_juego>=nota_limite){ superan_limite++; }else if(nota_juego-1>=0 && n_sorprendidos>0 && ((nota_juego+1)>=nota_limite || (nota_juego+2)>=nota_limite)){ // no supera el límite pero podría hacerlo si quedan sorprendidos n_sorprendidos--; superan_limite++; } }else if((suma_notas+1)%3==0){ // Tendré que jugar con el valor en +-1 nota_juego=(suma_notas+1)/3; if(nota_juego-1>=0 && nota_juego>=nota_limite){ superan_limite++; }else if(nota_juego-1>=0 && n_sorprendidos>0 && (nota_juego+1)>=nota_limite){ n_sorprendidos--; superan_limite++; } }else if((suma_notas+2)%3==0){ // Tendré que jugar con el valor en +-2 nota_juego=(suma_notas+2)/3; if(nota_juego-1>=0 && nota_juego>=nota_limite){ superan_limite++; } } } return superan_limite; } public static void main(String[] args) throws IOException { FileReader fr = new FileReader(args[0]); BufferedReader bf = new BufferedReader(fr); int ntest=0; FileWriter fstream = new FileWriter("out.txt"); BufferedWriter out = new BufferedWriter(fstream); String lines = bf.readLine(); String liner, linew; int lines_r=0; String[] numbers; int total; while((liner = bf.readLine())!=null && lines_r<=Integer.parseInt(lines)) { ntest++; numbers=liner.split(" "); total=f_Superan_limites(liner); linew="Case #"+ntest+": "+total+"\n"; out.write(linew); lines_r++; } out.close(); fr.close(); } }
import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Iterator; import java.util.Scanner; public class DancingWithGooglers { public static class Scores { public final int S; public final int p; public final int[] t; public Scores(int S, int p, int[] t) { this.S = S; this.p = p; this.t = t; } } public static Iterator<Scores> iterator(Readable input) { final Scanner scanner = new Scanner(input); return new Iterator<Scores>() { private int cases = scanner.nextInt(); @Override public boolean hasNext() { return cases > 0; } @Override public Scores next() { int N = scanner.nextInt(); int S = scanner.nextInt(); int p = scanner.nextInt(); int[] t = new int[N]; for (int i = 0; i < N; i++) { t[i] = scanner.nextInt(); } cases--; return new Scores(S, p, t); } @Override public void remove() { throw new AbstractMethodError(); } }; } public static int maxTuples(Scores scores) { int tuples = 0; int s = scores.S; for (int i : scores.t) { int[] tuple = tuplesWithMax(i, scores.p); if (tuple.length == 3) { if (tuple[0] - tuple[2] == 2 && s > 0) { tuples++; s--; } else if (tuple[0] - tuple[2] <= 1) { tuples++; } } } return tuples; } public static int[][] tuples(int total) { if (total == 0) { return new int[][]{{0, 0, 0}}; } if (total == 30) { return new int[][]{{10, 10, 10}}; } int max = total / 3; if (total % 3 == 0) { return new int[][]{{max, max, max}, {max + 1, max, max - 1}}; } if (total % 3 == 1) { return new int[][]{{max + 1, max, max}, {max + 1, max + 1, max - 1}}; } if (max < 9) { return new int[][]{{max + 1, max + 1, max}, {max + 2, max, max}}; } return new int[][]{{max + 1, max + 1, max}}; } public static int[] tuplesWithMax(int t, int max) { for (int[] tuple : tuples(t)) { if (tuple[0] >= max) return tuple; } return new int[]{}; } public static void main(String[] args) throws FileNotFoundException { FileReader fileReader = new FileReader(args[0]); int caseId = 1; Iterator<Scores> iterator = iterator(fileReader); while (iterator.hasNext()) { int result = maxTuples(iterator.next()); System.out.format("Case #%s: %s\n", caseId, result); caseId++; } } }
A20261
A21596
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; } }
public class testCase { public testCase(int n){ T = n; cases = new String[T]; count=0; } public void addCase(String s){ if(count > T-1){ System.out.println("STOP ! too many test cases !!"); return; } cases[count++] = s; } int count; int T; String[] cases; }
A22771
A20894
0
package com.menzus.gcj._2012.qualification.b; import com.menzus.gcj.common.InputBlockParser; import com.menzus.gcj.common.OutputProducer; import com.menzus.gcj.common.impl.AbstractProcessorFactory; public class BProcessorFactory extends AbstractProcessorFactory<BInput, BOutputEntry> { public BProcessorFactory(String inputFileName) { super(inputFileName); } @Override protected InputBlockParser<BInput> createInputBlockParser() { return new BInputBlockParser(); } @Override protected OutputProducer<BInput, BOutputEntry> createOutputProducer() { return new BOutputProducer(); } }
import java.io.*; import java.math.BigInteger; import java.util.InputMismatchException; /** * Created by César Passoni */ public class TaskB implements Runnable { private InputReader in; private PrintWriter out; public static void main(String[] args) { new Thread(new TaskB()).start(); } public TaskB() { try { String fileName; // fileName = "sampleB.in"; // fileName = "B-small-attempt9.in"; fileName = "B-large.in"; System.setIn(new FileInputStream(fileName)); System.setOut(new PrintStream(new FileOutputStream(fileName.replace("in", "out")))); } catch (FileNotFoundException e) { throw new RuntimeException(); } in = new InputReader(System.in); out = new PrintWriter(System.out); } public void run() { int numTests = in.readInt(); for (int testNumber = 0; testNumber < numTests; testNumber++) { out.print("Case #" + (testNumber + 1) + ": "); int n = in.readInt(); int s = in.readInt(); int p = in.readInt(); boolean surprise = s!=0; int count = 0; int countSurprise = 0; for (int i = 0 ; i < n ; i ++) { int testCase = in.readInt(); if (testCase == 0) { if (p == 0) { count ++; } } else if (testCase >= (p*3-2)) { count ++; } else if (testCase >= (p*3-4) && surprise) { count ++; countSurprise ++; if (countSurprise >= s) { surprise = false; } } // if (testCase == 0) // { // if (s == 0) // { // count ++; // } // } // // else if (testCase%3 == 0) // { // if ((testCase/3 ) >= p) // { // count ++; // } // else if ((testCase/3 + 1) >= p && surprise) // { // count ++; // countSurprise ++; // if (countSurprise >= s) // { // surprise = false; // } // } // // } // else // { // if ((testCase/3 + 1) >= p) // { // count ++; // // } // else if ((testCase/3 + 2) >= p && surprise) // { // count ++; // countSurprise ++; // if (countSurprise >= s) // { // surprise = false; // } // } // } } // System.out.println("CASE " + (testNumber + 1) +"countSurprise " +countSurprise + " s " + s); 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; } } }
A12460
A11951
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.Arrays; import java.util.Scanner; public class B { int N; int S; int p; int[] A = new int[100]; int[][] memo = new int[100][100]; boolean[][] normal = new boolean[11][31]; boolean[][] surprise = new boolean[11][31]; B() { for (int a=0; a<=10; ++a) { for (int b=a; b<=10 && b<=a+2; ++b) { for (int c=b; c<=10 && c<=a+2; ++c) { if (c-a<=1) normal[c][a+b+c]=true; else surprise[c][a+b+c]=true; } } } Scanner in=new Scanner(System.in); for (int T=in.nextInt(),TC=1; T-->0; ++TC) { N=in.nextInt(); S=in.nextInt(); p=in.nextInt(); for (int i=0; i<N; ++i) A[i]=in.nextInt(); for (int[] m : memo) Arrays.fill(m, -1); System.out.printf("Case #%d: %d%n",TC,go(0,0)); } } int go(int at, int sur) { if (at==N) return 0; if (memo[at][sur]>-1) return memo[at][sur]; int res=0; for (int max=0; max<=10; ++max) { int add=max>=p?1:0; if (normal[max][A[at]]) res=Math.max(res,add+go(at+1,sur)); if (sur<S && surprise[max][A[at]]) res=Math.max(res,add+go(at+1,sur+1)); } return memo[at][sur]=res; } public static void main(String[] args) { new B(); } }
A22642
A21727
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.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Scanner; public class QualificationQ2 { /** * @param args */ public static void main(String[] args) throws IOException { FileWriter fstream = new FileWriter("out.txt"); BufferedWriter out = new BufferedWriter(fstream); File file = new File(args[0]); Scanner in = new Scanner(file); int T = in.nextInt(); in.nextLine(); for (int zz = 1; zz <= T; zz++) { String inputLine = in.nextLine(); String outputLine = process(inputLine); output(out,zz,outputLine); } in.close(); out.close(); } private static String process(String inputLine) { int counter = 0; String[] elements = inputLine.split(" "); int numberOfPlayers = new Integer(elements[0]); int numberOfSuprisings = new Integer(elements[1]); int score = new Integer(elements[2]); int sureCountScore = 3 * (score - 1) + 1; int surprisingCountScore = 2 * (score -2) + score; for (int i=3;i<numberOfPlayers+3;i++){ if (new Integer(elements[i])>=sureCountScore){ counter++; }else if (new Integer(elements[i])>0&&numberOfSuprisings>0&& new Integer(elements[i])>=surprisingCountScore){ counter++; numberOfSuprisings--; } } return ""+counter; } private static void output(BufferedWriter out, int zz, String formattedString) throws IOException { // TODO Auto-generated method stub String outputLine = String.format("Case #%d: %s\n", zz, formattedString); System.out.format(outputLine); out.write(outputLine); } }
A22992
A21622
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 test2; /** * * @author Student */ public class Score { private int i; private int j; private int k; private boolean surp; public Score(int i, int j, int k,boolean surp) { this.i = i; this.j = j; this.k = k; this.surp = surp; } public boolean isValid(){ return (i<=10&&j<=10&&k<=10)&&(i>=0&&j>=0&&k>=0); } public boolean isSurprising(){ return surp; } public boolean isbetter(int x){ return i>=x||j>=x||k>=x; } public String toString(){ return "("+i+","+j+","+k+")"; } }
B11318
B11549
0
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); int casos=1, a, b, n, m, cont; while(t!=0){ a=sc.nextInt(); b=sc.nextInt(); if(a>b){ int aux=a; a=b; b=aux; } System.out.printf("Case #%d: ",casos++); if(a==b){ System.out.printf("%d\n",0); }else{ cont=0; for(n=a;n<b;n++){ for(m=n+1;m<=b;m++){ if(isRecycled(n,m)) cont++; } } System.out.printf("%d\n",cont); } t--; } } public static boolean isRecycled(int n1, int n2){ String s1, s2, aux; s1 = String.valueOf( n1 ); s2 = String.valueOf( n2 ); boolean r = false; for(int i=0;i<s1.length();i++){ aux=""; aux=s1.substring(i,s1.length())+s1.substring(0,i); // System.out.println(aux); if(aux.equals(s2)){ r=true; break; } } return r; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package googlejam3; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; /** * * @author Nomeir */ public class GoogleJam3 { private String inputFile = // "C-large.in"; ".\\C-small-attempt0.in"; // ".\\test3.in"; private String outputFile = ".\\out.txt"; private String line = "start"; private FileReader reader; private BufferedReader buffer; private FileWriter writer; private BufferedWriter printer; public GoogleJam3() { try { new File(outputFile).createNewFile(); reader = new FileReader(inputFile); buffer = new BufferedReader(reader); new File(outputFile).createNewFile(); writer = new FileWriter(outputFile); printer = new BufferedWriter(writer); } catch (IOException ex) { System.out.println("The file couldn't be created ..."); } } public void endOperations() { try { if (reader != null) { reader.close(); } if (buffer != null) { buffer.close(); } if (printer != null) { printer.flush(); printer.close(); } if (writer != null) { writer.close(); } } catch (IOException ex) { ex.printStackTrace(); } } int lines; public void readInfo() { try { line = buffer.readLine(); if (line != null) { lines = Integer.valueOf(line); // int i = 0, j = 0; // L = Integer.valueOf(line.substring(0, i = line.indexOf(" "))); // D = Integer.valueOf(line.substring(++i, j = line.indexOf(" ", i))); // N = Integer.valueOf(line.substring(++j, line.length())); } } catch (FileNotFoundException ex) { System.err.println("Source file not found .. !"); } catch (IOException e) { e.printStackTrace(); } catch (StringIndexOutOfBoundsException e) { e.printStackTrace(); } } int aMinValue, bMaxValue, aMovingValue; int nMinValue, mMaxValue; String aStr, bStr; int t1, t2, searchIndex; ArrayList<Integer> keys, values; ArrayList<Integer> ab; private void readInfoLines() { try { for (int i = 0; i < lines;) { line = buffer.readLine(); ab = new ArrayList<Integer>(); recurser(line, ab); aMinValue = ab.get(0); aMovingValue = aMinValue; bMaxValue = ab.get(1); bStr = bMaxValue + ""; keys = new ArrayList<Integer>(); values = new ArrayList<Integer>(); if (bStr.length() > 1 && aMinValue < bMaxValue) { for (; aMovingValue <= bMaxValue; aMovingValue++) { aStr = aMovingValue + ""; if (aStr.length() > 1) { for (int j = 1; j < aStr.length(); j++) { nMinValue = aMovingValue; mMaxValue = Integer.parseInt(aStr.substring(j, aStr.length()) + aStr.substring(0, j)); if (mMaxValue > bMaxValue || mMaxValue < aMinValue) { continue; } if (nMinValue < mMaxValue) { searchIndex = Collections.binarySearch(keys, nMinValue); if (searchIndex >= 0 && values.get(searchIndex) == mMaxValue) { } else { keys.add(nMinValue); values.add(mMaxValue); } } } } } } printer.write("Case #" + ++i + ": " + keys.size()); printer.newLine(); } } catch (IOException ex) { ex.printStackTrace(); } } public void recurser(String s, ArrayList<Integer> links) { int i = 0, k = 0; if (s != null) { if ((i = s.indexOf(" ")) >= 0) { if (links.size() == 0) { links.add(Integer.valueOf("" + s.substring(0, i))); } if ((k = s.indexOf(" ", ++i)) >= 0) { links.add(Integer.valueOf("" + s.substring(i, k))); s = s.substring(k); recurser(s, links); } else { links.add(Integer.valueOf(s.substring(i, s.length()))); } } } } /** * @param args the command line arguments */ public static void main(String[] args) { long t = System.currentTimeMillis(); GoogleJam3 obj = new GoogleJam3(); obj.readInfo(); obj.readInfoLines(); // obj.printTestCases(); obj.endOperations(); t = System.currentTimeMillis() - t; System.out.println("Time elapsed " + t); } }
A22360
A20605
0
import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; public class Dancing_With_the_Googlers { /** * The first line of the input gives the number of test cases, T. * T test cases follow. * Each test case consists of a single line containing integers separated by single spaces. * The first integer will be N, the number of Googlers, and the second integer will be S, the number of surprising triplets of scores. * The third integer will be p, as described above. Next will be N integers ti: the total points of the Googlers. * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // Reading the input file Scanner in = new Scanner(new File("B-large.in")); // writting the input file FileOutputStream fos = new FileOutputStream("B-large.out"); PrintStream out = new PrintStream(fos); //Close the output stream int testCase=Integer.parseInt(in.nextLine()); for(int i=0;i<testCase;i++) { out.print("Case #" + (i + 1) + ":\t"); int NoOfGooglers= in.nextInt(); int NoOfSurprisingResults = in.nextInt(); int atLeastP=in.nextInt(); ArrayList<Integer> scores= new ArrayList<Integer>(); int BestResults=0; int Surprising=0; for(int j=0;j<NoOfGooglers;j++) { scores.add(in.nextInt()); //System.out.print(scores.get(j)); int modulus=scores.get(j)%3; int temp = scores.get(j); switch (modulus) { case 0: if (((temp / 3) >= atLeastP)) { BestResults++; } else { if (((((temp / 3) + 1) >= atLeastP) && ((temp / 3) >= 1)) && (Surprising < NoOfSurprisingResults)) { BestResults++; Surprising++; } System.out.println("Case 0"+"itr:"+i+" surprising:"+temp); } break; case 1: if ((temp / 3) + 1 >= atLeastP) { BestResults++; continue; } break; case 2: if ((temp / 3) + 1 >= atLeastP) { BestResults++; } else { if (((temp / 3) + 2 >= atLeastP) && (Surprising < NoOfSurprisingResults)) { BestResults++; Surprising++; } System.out.println("Case 2"+"itr:"+i+" surprising:"+temp); } break; default: System.out.println("Error"); } }// Internal for out.println(BestResults); // System.out.println(BestResults); System.out.println(Surprising); BestResults = 0; }// for in.close(); out.close(); fos.close(); } }
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; 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 Charles */ public class DancingWithGooglers { static final String FILE_NAME = "B-large"; /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { ArrayList<String> values = readFile(FILE_NAME + ".in"); int count = 1; PrintWriter outFile = new PrintWriter(new File(FILE_NAME + ".out")); for (String line : values) { String output = processAlgorithm(line, count++); System.out.println(output); outFile.println(output); } outFile.close(); } /** * Reads the CodeJam files and returns the input as a List of String. * * @param fileName The name of the file to be read * @return the list containing the contents of the file. */ public static ArrayList<String> readFile(String fileName) { ArrayList<String> results = new ArrayList<String>(); try { Scanner inFile = new Scanner(new File(fileName)); int numberOfLines = Integer.parseInt(inFile.nextLine()); while (inFile.hasNextLine()) { results.add(inFile.nextLine()); } if (numberOfLines != results.size()) { System.err.println("File size does not match..."); System.exit(0); } } catch (FileNotFoundException ex) { System.err.println("File not found..."); System.exit(0); } return results; } private static String processAlgorithm(String line, int caseNumber) { StringBuilder result = new StringBuilder("Case #" + caseNumber + ": "); Scanner scan = new Scanner(line); int numberOfDancers = scan.nextInt(); int numberOfSuprises = scan.nextInt(); int highestScore = scan.nextInt(); int usedSuprises = 0; int count = 0; Dancer current; for (int index = 0; index < numberOfDancers; index++) { current = new Dancer(scan.nextInt()); if (current.highScoreWithOutSuprise >= highestScore) { count++; } else if (current.highScoreWithSuprise >= highestScore && usedSuprises < numberOfSuprises) { usedSuprises++; count++; } } result.append(count); return result.toString(); } } class Dancer { int highScoreWithSuprise; int highScoreWithOutSuprise; public Dancer(int score) { highScoreWithOutSuprise = highScoreWithSuprise = score / 3; int mod = score % 3; if (score > 0) { switch (mod) { case 0: highScoreWithSuprise += 1; break; case 1: highScoreWithOutSuprise += 1; highScoreWithSuprise += 1; break; case 2: highScoreWithOutSuprise += 1; highScoreWithSuprise += 2; break; } } } }
A10568
A10214
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 me.stapel.kai.google.codejam2012.quali; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Locale; public class ProblemB { private static final String NL = System.getProperty("line.separator"); public ProblemB() { // nothing to do here yet } public static void main(String[] args) { ProblemB problemB = new ProblemB(); problemB.processFile("in/B-small-attempt0.in", "out/B-small.txt"); } private Object processFile(String inFileName, String outFileName) { Object obj = new Object(); File inFile = new File(inFileName); File outFile = new File(outFileName); String line = ""; int T = 1; OutputStreamWriter output; BufferedReader br; try { br = new BufferedReader(new FileReader(inFile)); output = new OutputStreamWriter(new BufferedOutputStream( new FileOutputStream(outFile)), "8859_1"); line = br.readLine(); // skipping first line line = br.readLine(); while (line != null) { String[] split = line.split(" "); int N = Integer.parseInt(split[0]); int S = Integer.parseInt( split[1]); int p = Integer.parseInt(split[2]); int[] t = new int[N]; for(int i = 0; i<N;i++) { t[i] = Integer.parseInt(split[i+3]); } int Gmax = calcGMax(N, S, p, t); output.write("Case #" + T + ": " + Gmax + NL); System.out.println("Case #" + T + ": " + Gmax); line = br.readLine(); T++; } output.flush(); output.close(); } catch (FileNotFoundException e) { System.err.println("File " + inFile.getName() + " not found. Nothing processed."); e.printStackTrace(); } catch (IOException e) { System.err.println("Error when reading file " + inFile.getName() + " or writing file " + outFile.getName() + "."); e.printStackTrace(); } return obj; } private int calcGMax(int N, int S, int p, int[] t) { int Gmax1 = 0; int Gmax2 = 0; System.out.println(Arrays.toString(t)); for(int i = 0; i < t.length; i++){ if(t[i] >= Math.max(3*p-2, p)) Gmax1++; if(t[i] >= Math.max(3*p-4, p)) Gmax2++; } return Math.min(Gmax1+S, Gmax2); } }
A12273
A12102
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Dancing * Jason Bradley Nel * 16287398 */ import java.io.*; public class Dancing { public static void main(String[] args) { In input = new In("input.txt"); int T = Integer.parseInt(input.readLine()); for (int i = 0; i < T; i++) { System.out.printf("Case #%d: ", i + 1); int N = input.readInt(); int s = input.readInt(); int p = input.readInt(); int c = 0;//counter for >=p cases //System.out.printf("N: %d, S: %d, P: %d, R: ", N, s, p); for (int j = 0; j < N; j++) { int score = input.readInt(); int q = score / 3; int m = score % 3; //System.out.printf("%2d (%d, %d) ", scores[j], q, m); switch (m) { case 0: if (q >= p) { c++; } else if (((q + 1) == p) && (s > 0) && (q != 0)) { c++; s--; } break; case 1: if (q >= p) { c++; } else if ((q + 1) == p) { c++; } break; case 2: if (q >= p) { c++; } else if ((q + 1) == p) { c++; } else if (((q + 2) == p) && (s > 0)) { c++; s--; } break; } } //System.out.printf("Best result of %d or higher: ", p); System.out.println(c); } } }
import java.io.*; public class B { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); String[] line; int N,S,p; int[][] tuple = new int[1000][3]; int[][] stuple = new int[1000][3]; int count = 0; int scount = 0; for(int i=10;i>=0;i--) { for(int j=i-2;j<=i+2;j++) { if(j<0 || j>10) continue; for(int k=i-2;k<=i+2;k++) { if(k<0 || k>10) continue; if(j-k >2 || k-j > 2) continue; int a = (i-j > 0) ? i-j : j-i; int b = (i-k > 0) ? i-k : k-i; int c = (k-j > 0) ? k-j : j-k; if(a==2 || b==2 || c==2) { stuple[scount][0] = i; stuple[scount][1] = j; stuple[scount++][2] = k; continue; } tuple[count][0] = i; tuple[count][1] = j; tuple[count++][2] = k; } } } for(int i=1;i<=T;i++) { line = br.readLine().split("\\W+"); N = Integer.parseInt(line[0]); S = Integer.parseInt(line[1]); p = Integer.parseInt(line[2]); int[] score = new int[N]; for(int j=0;j<N;j++) score[j] = Integer.parseInt(line[3+j]); int ret = 0; for(int j=0;j<N;j++) { boolean found = false; for(int k=0;k<count;k++) { if((tuple[k][0] + tuple[k][1] + tuple[k][2]) == score[j]) { if(tuple[k][0] >= p || tuple[k][1] >= p || tuple[k][2] >= p) { found = true; ret++; break; } } } if(!found && S!=0) { for(int k=0;k<scount;k++) { if((stuple[k][0] + stuple[k][1] + stuple[k][2]) == score[j]) { if(stuple[k][0] >= p || stuple[k][1] >= p || stuple[k][2] >= p) { found = true; S--; ret++; break; } } } } } System.out.println("Case #"+i+": "+ret); } } }
A11502
A10405
0
package template; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class TestCase { private boolean isSolved; private Object solution; private Map<String, Integer> intProperties; private Map<String, ArrayList<Integer>> intArrayProperties; private Map<String, ArrayList<ArrayList<Integer>>> intArray2DProperties; private Map<String, Double> doubleProperties; private Map<String, ArrayList<Double>> doubleArrayProperties; private Map<String, ArrayList<ArrayList<Double>>> doubleArray2DProperties; private Map<String, String> stringProperties; private Map<String, ArrayList<String>> stringArrayProperties; private Map<String, ArrayList<ArrayList<String>>> stringArray2DProperties; private Map<String, Boolean> booleanProperties; private Map<String, ArrayList<Boolean>> booleanArrayProperties; private Map<String, ArrayList<ArrayList<Boolean>>> booleanArray2DProperties; private Map<String, Long> longProperties; private Map<String, ArrayList<Long>> longArrayProperties; private Map<String, ArrayList<ArrayList<Long>>> longArray2DProperties; private int ref; private double time; public TestCase() { initialise(); } private void initialise() { isSolved = false; intProperties = new HashMap<>(); intArrayProperties = new HashMap<>(); intArray2DProperties = new HashMap<>(); doubleProperties = new HashMap<>(); doubleArrayProperties = new HashMap<>(); doubleArray2DProperties = new HashMap<>(); stringProperties = new HashMap<>(); stringArrayProperties = new HashMap<>(); stringArray2DProperties = new HashMap<>(); booleanProperties = new HashMap<>(); booleanArrayProperties = new HashMap<>(); booleanArray2DProperties = new HashMap<>(); longProperties = new HashMap<>(); longArrayProperties = new HashMap<>(); longArray2DProperties = new HashMap<>(); ref = 0; } public void setSolution(Object o) { solution = o; isSolved = true; } public Object getSolution() { if (!isSolved) { Utils.die("getSolution on unsolved testcase"); } return solution; } public void setRef(int i) { ref = i; } public int getRef() { return ref; } public void setTime(double d) { time = d; } public double getTime() { return time; } public void setInteger(String s, Integer i) { intProperties.put(s, i); } public Integer getInteger(String s) { return intProperties.get(s); } public void setIntegerList(String s, ArrayList<Integer> l) { intArrayProperties.put(s, l); } public void setIntegerMatrix(String s, ArrayList<ArrayList<Integer>> l) { intArray2DProperties.put(s, l); } public ArrayList<Integer> getIntegerList(String s) { return intArrayProperties.get(s); } public Integer getIntegerListItem(String s, int i) { return intArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Integer>> getIntegerMatrix(String s) { return intArray2DProperties.get(s); } public ArrayList<Integer> getIntegerMatrixRow(String s, int row) { return intArray2DProperties.get(s).get(row); } public Integer getIntegerMatrixItem(String s, int row, int column) { return intArray2DProperties.get(s).get(row).get(column); } public ArrayList<Integer> getIntegerMatrixColumn(String s, int column) { ArrayList<Integer> out = new ArrayList(); for(ArrayList<Integer> row : intArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setDouble(String s, Double i) { doubleProperties.put(s, i); } public Double getDouble(String s) { return doubleProperties.get(s); } public void setDoubleList(String s, ArrayList<Double> l) { doubleArrayProperties.put(s, l); } public void setDoubleMatrix(String s, ArrayList<ArrayList<Double>> l) { doubleArray2DProperties.put(s, l); } public ArrayList<Double> getDoubleList(String s) { return doubleArrayProperties.get(s); } public Double getDoubleListItem(String s, int i) { return doubleArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Double>> getDoubleMatrix(String s) { return doubleArray2DProperties.get(s); } public ArrayList<Double> getDoubleMatrixRow(String s, int row) { return doubleArray2DProperties.get(s).get(row); } public Double getDoubleMatrixItem(String s, int row, int column) { return doubleArray2DProperties.get(s).get(row).get(column); } public ArrayList<Double> getDoubleMatrixColumn(String s, int column) { ArrayList<Double> out = new ArrayList(); for(ArrayList<Double> row : doubleArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setString(String s, String t) { stringProperties.put(s, t); } public String getString(String s) { return stringProperties.get(s); } public void setStringList(String s, ArrayList<String> l) { stringArrayProperties.put(s, l); } public void setStringMatrix(String s, ArrayList<ArrayList<String>> l) { stringArray2DProperties.put(s, l); } public ArrayList<String> getStringList(String s) { return stringArrayProperties.get(s); } public String getStringListItem(String s, int i) { return stringArrayProperties.get(s).get(i); } public ArrayList<ArrayList<String>> getStringMatrix(String s) { return stringArray2DProperties.get(s); } public ArrayList<String> getStringMatrixRow(String s, int row) { return stringArray2DProperties.get(s).get(row); } public String getStringMatrixItem(String s, int row, int column) { return stringArray2DProperties.get(s).get(row).get(column); } public ArrayList<String> getStringMatrixColumn(String s, int column) { ArrayList<String> out = new ArrayList(); for(ArrayList<String> row : stringArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setBoolean(String s, Boolean b) { booleanProperties.put(s, b); } public Boolean getBoolean(String s) { return booleanProperties.get(s); } public void setBooleanList(String s, ArrayList<Boolean> l) { booleanArrayProperties.put(s, l); } public void setBooleanMatrix(String s, ArrayList<ArrayList<Boolean>> l) { booleanArray2DProperties.put(s, l); } public ArrayList<Boolean> getBooleanList(String s) { return booleanArrayProperties.get(s); } public Boolean getBooleanListItem(String s, int i) { return booleanArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Boolean>> getBooleanMatrix(String s) { return booleanArray2DProperties.get(s); } public ArrayList<Boolean> getBooleanMatrixRow(String s, int row) { return booleanArray2DProperties.get(s).get(row); } public Boolean getBooleanMatrixItem(String s, int row, int column) { return booleanArray2DProperties.get(s).get(row).get(column); } public ArrayList<Boolean> getBooleanMatrixColumn(String s, int column) { ArrayList<Boolean> out = new ArrayList(); for(ArrayList<Boolean> row : booleanArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } public void setLong(String s, Long b) { longProperties.put(s, b); } public Long getLong(String s) { return longProperties.get(s); } public void setLongList(String s, ArrayList<Long> l) { longArrayProperties.put(s, l); } public void setLongMatrix(String s, ArrayList<ArrayList<Long>> l) { longArray2DProperties.put(s, l); } public ArrayList<Long> getLongList(String s) { return longArrayProperties.get(s); } public Long getLongListItem(String s, int i) { return longArrayProperties.get(s).get(i); } public ArrayList<ArrayList<Long>> getLongMatrix(String s) { return longArray2DProperties.get(s); } public ArrayList<Long> getLongMatrixRow(String s, int row) { return longArray2DProperties.get(s).get(row); } public Long getLongMatrixItem(String s, int row, int column) { return longArray2DProperties.get(s).get(row).get(column); } public ArrayList<Long> getLongMatrixColumn(String s, int column) { ArrayList<Long> out = new ArrayList(); for(ArrayList<Long> row : longArray2DProperties.get(s)) { out.add(row.get(column)); } return out; } }
package codejam; import java.io.*; public class FileRead { String fileName; FileReader fr; BufferedReader br; FileRead(String fileName) { this.fileName=fileName; File f=new File("K:\\CodeJam\\Input\\"+fileName);//Create a file object FileReader fr; try { fr = new FileReader(f); br=new BufferedReader(fr); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //function to read next line. public String readNextLine(){ String text=null; try { text=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return text; } public int readNextInt(){ int n = 0; try{ n=Integer.parseInt(br.readLine().trim()); }catch(Exception e){ System.out.println("Invalid integer"); } return n; } public int [] readNextIntArray(){ int []n=null; try{ String []numarray=br.readLine().split(" "); n=new int[numarray.length]; for(int i=0;i<numarray.length;i++){ n[i]=Integer.parseInt(numarray[i].trim()); } }catch(Exception e){ System.out.println("Invalid integer"); } return n; } public void close(){ try { //fr.close(); br.close(); } catch (Exception e) { e.printStackTrace(); } } }
B12570
B12754
0
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; class RecycledNumbers{ int getcount(int small,int large){ int count = 0; for(int currnum = small; currnum < large; currnum++){ int permut = currnum; int no_of_digits = 0; while(permut > 0){ permut = permut/10; no_of_digits++; } int lastDigit = currnum % 10; permut = currnum / 10; permut = permut + lastDigit * (int)Math.pow(10, no_of_digits-1); while(permut != currnum){ if(permut >= currnum && permut <= large){ count++; } lastDigit = permut % 10; permut = permut / 10; permut = permut + lastDigit * (int)Math.pow(10, no_of_digits-1); } } return count; } public static void main(String args[]){ RecycledNumbers d = new RecycledNumbers(); int no_of_cases = 0; String input = ""; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ no_of_cases = Integer.parseInt(br.readLine()); } catch(Exception e){ System.out.println("First line is not a number"); } for(int i=1; i <= no_of_cases;i++){ try{ input = br.readLine(); } catch(Exception e){ System.out.println("Number of test cases different from the number mentioned in first line"); } System.out.print("Case #" +i+": "); StringTokenizer t = new StringTokenizer(input); int small=0,large=0; if(t.hasMoreTokens()){ small = Integer.parseInt(t.nextToken()); } if(t.hasMoreTokens()){ large = Integer.parseInt(t.nextToken()); } System.out.println(d.getcount(small,large)); } } }
package com.dagova.recycledNumbers; import java.util.TreeSet; public class RecycledNumbersSolver { private static int solution; private static int aNumber; private static int bNumber; public static int solve(String line) { solution = 0; String[] splittedLine = line.split(" "); aNumber = Integer.parseInt(splittedLine[0]); bNumber = Integer.parseInt(splittedLine[1]); for(int number = aNumber; number < bNumber-1; number++) { solution += solveNumber(number); } return solution; } public static int solveNumber(int number) { // con el treeset evita que un n de varias veces el mismo m. Antes usaba el contador recycledNumbers y por eso fallaba. TreeSet<Integer> ms = new TreeSet<Integer>(); // int recycledNumbers = 0; String numberAsString = Integer.toString(number); int numberLength = numberAsString.length(); for(int charIterator = 1; charIterator < numberLength; charIterator++) { if(numberAsString.charAt(charIterator) >= numberAsString.charAt(0)) { int recycledNumber = generateRecycledNumber(numberAsString, charIterator); if(recycledNumber <= bNumber && recycledNumber > number) { ms.add(recycledNumber); // recycledNumbers++; } } } return ms.size(); // return recycledNumbers; } public static int generateRecycledNumber(String numberAsString, int charIterator) { String prefix = numberAsString.substring(0, charIterator); String sufix = numberAsString.substring(charIterator); return Integer.parseInt(sufix.concat(prefix)); } }
B12082
B10387
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.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Prob3 { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { Scanner scan = new Scanner(new File("C-small-attempt0.in")); PrintWriter output = new PrintWriter(new File("output3.txt")); String result = ""; int tests = scan.nextInt(); for(int t = 0; t < tests; t++){ int A = scan.nextInt(); int B = scan.nextInt(); int count = 0; for(int run = A; run <= B; run++){ String m = new Integer(run).toString(); for(int i = 0; i < m.length()-1; i++){ int n = Integer.parseInt(m.substring(i+1) + m.substring(0, i+1)); if(n <= B && n >= A){ if(n == run); else{ count++; } } } } System.out.print("Case #" + (t+1) + ": " + (count/2)+"\n"); result += "Case #" + (t+1) + ": " + (count/2)+"\n"; } output.write(result); output.close(); } }
A10996
A11512
0
import java.util.Scanner; import java.io.*; class dance { public static void main (String[] args) throws IOException { File inputData = new File("B-small-attempt0.in"); File outputData= new File("Boutput.txt"); Scanner scan = new Scanner( inputData ); PrintStream print= new PrintStream(outputData); int t; int n,s,p,pi; t= scan.nextInt(); for(int i=1;i<=t;i++) { n=scan.nextInt(); s=scan.nextInt(); p=scan.nextInt(); int supTrip=0, notsupTrip=0; for(int j=0;j<n;j++) { pi=scan.nextInt(); if(pi>(3*p-3)) notsupTrip++; else if((pi>=(3*p-4))&&(pi<=(3*p-3))&&(pi>p)) supTrip++; } if(s<=supTrip) notsupTrip=notsupTrip+s; else if(s>supTrip) notsupTrip= notsupTrip+supTrip; print.println("Case #"+i+": "+notsupTrip); } } }
import java.io.*; import java.util.StringTokenizer; public class DancingWithTheGooglers { static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(String fileName) throws IOException { br = new BufferedReader(new FileReader(new File(fileName))); } public String nextToken() throws IOException, NullPointerException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public String nextString() throws IOException, NullPointerException { st = null; return br.readLine(); } public Integer nextInt() throws IOException { return Integer.parseInt(nextToken()); } void close() throws IOException { br.close(); } } public static void main(String[] args) throws IOException { final String name = "B-small-attempt0"; MyScanner in = new MyScanner(name + ".in"); PrintWriter out = new PrintWriter(name + ".txt"); int t = in.nextInt(); for (int i = 1; i <= t; i++) { int n = in.nextInt(); int s = in.nextInt(); int p = in.nextInt(); int res = 0; for (int j = 0; j < n; j++) { int q = in.nextInt(); int m = q / 3; if (q % 3 != 0) { m++; } if (m >= p) { res++; } else { if (s > 0 && q >= p) { if (q % 3 == 0 || q % 3 == 2) { m++; } if (m >= p) { s--; res++; } } } } out.println("Case #" + i + ": " + res); } in.close(); out.close(); } }
A22360
A20688
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(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication2; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; /** * * @author Mash */ public class B { public static void main(String[] args) throws IOException{ Scanner in = new Scanner(new FileReader("C:\\ima\\ans.txt")); PrintWriter out=new PrintWriter(new FileWriter("C:\\ima\\input.txt")); int T,S,p,N,G[]; T=in.nextInt(); for(int i=1;i<=T;i++){ N=in.nextInt(); G=new int[N]; S=in.nextInt(); p=in.nextInt(); for(int j=0;j<N;j++)G[j]=in.nextInt(); Arrays.sort(G); if(p>1){ int q=p*3-2; int s=p*3-4; int cnt=0; int pt=N-1; for(int j=N-1;j>=0;j--){ if(G[j]>=q){cnt++;pt--;} } while(pt>=0&&G[pt]>=s&&S>0){ cnt++;pt--;S--; } System.out.println("Case #"+i+": " +cnt); }else if(p==1){ int m=0; for(m=0;m<N;m++){ if(G[m]>0)break; } System.out.println("Case #"+i+": " +(N-m)); }else if(p==0)System.out.println("Case #"+i+": "+N); } } }
A22191
A20810
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 ? " *" : "")); // } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; /** * * @author VISHAL */ public class Googlers { public static void main(String args[]) throws IOException{ Scanner in=new Scanner(new File("H:\\in.txt")); FileWriter fout=new FileWriter("H:\\out.txt"); PrintWriter outfile=new PrintWriter(fout); // Scanner in=new Scanner(System.in); int t; t=in.nextInt(); for(int i=0;i<t;i++){ int n,p,s; n=in.nextInt(); s=in.nextInt(); p=in.nextInt(); int count=0; for(int j=0;j<n;j++){ int s1; s1=in.nextInt(); if(s1<p) continue; if(s1>=3*p-2) count++; else if(s!=0 && s1>=3*p-4) { s--; count++; } } outfile.println("Case #"+(i+1)+": "+count); } outfile.close(); } }
A12211
A11732
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Dancing_improved { static int f_Superan_limites(String params){ int superan_limite=0; String[] parametros=params.split(" "); int n_participantes= Integer.parseInt(parametros[0]); int n_sorprendidos= Integer.parseInt(parametros[1]); int nota_limite= Integer.parseInt(parametros[2]); int suma_notas, resto, nota_juego; for(int i=3;i<parametros.length;i++){ // Recorro las sumas de los participantes suma_notas=Integer.parseInt(parametros[i]); resto=suma_notas%3; if(resto==0){ // el resto es el número triplicado! nota_juego=suma_notas/3; if(nota_juego>=nota_limite){ superan_limite++; }else if(nota_juego-1>=0 && n_sorprendidos>0 && ((nota_juego+1)>=nota_limite || (nota_juego+2)>=nota_limite)){ // no supera el límite pero podría hacerlo si quedan sorprendidos n_sorprendidos--; superan_limite++; } }else if((suma_notas+1)%3==0){ // Tendré que jugar con el valor en +-1 nota_juego=(suma_notas+1)/3; if(nota_juego-1>=0 && nota_juego>=nota_limite){ superan_limite++; }else if(nota_juego-1>=0 && n_sorprendidos>0 && (nota_juego+1)>=nota_limite){ n_sorprendidos--; superan_limite++; } }else if((suma_notas+2)%3==0){ // Tendré que jugar con el valor en +-2 nota_juego=(suma_notas+2)/3; if(nota_juego-1>=0 && nota_juego>=nota_limite){ superan_limite++; } } } return superan_limite; } public static void main(String[] args) throws IOException { FileReader fr = new FileReader(args[0]); BufferedReader bf = new BufferedReader(fr); int ntest=0; FileWriter fstream = new FileWriter("out.txt"); BufferedWriter out = new BufferedWriter(fstream); String lines = bf.readLine(); String liner, linew; int lines_r=0; String[] numbers; int total; while((liner = bf.readLine())!=null && lines_r<=Integer.parseInt(lines)) { ntest++; numbers=liner.split(" "); total=f_Superan_limites(liner); linew="Case #"+ntest+": "+total+"\n"; out.write(linew); lines_r++; } out.close(); fr.close(); } }
package de.johanneslauber.codejam; import java.io.IOException; /** * * @author Johannes Lauber - [email protected] * */ public class Main { /** * @author Johannes Lauber - [email protected] * @param Args */ public static void main(String[] Args) { // solveProblem("input/A-small-practice.in", "StoreCredit"); // solveProblem("input/A-large-practice.in", "StoreCredit"); // solveProblem("input/B-small-practice.in", "ReverseWords"); // solveProblem("input/B-large-practice.in", "ReverseWords"); // solveProblem("input/C-small-practice.in", "T9Spelling"); // solveProblem("input/C-large-practice.in", "T9Spelling"); // solveProblem("input/A-small-practice.in", "SpeakinginTongues"); solveProblem("input/B-small-attempt.in", "DancingGooglers"); } /** * * @author Johannes Lauber - [email protected] * @param fileName * @param problemName */ private static void solveProblem(String fileName, String problemName) { CaseProvider caseProvider = new CaseProvider(); try { try { caseProvider.importFile( fileName, Class.forName("de.johanneslauber.codejam.model.impl." + problemName + "Case")); caseProvider.solveCases(Class .forName("de.johanneslauber.codejam.model.impl." + problemName + "Problem")); } catch (ClassNotFoundException e) { System.out.println("Error finding implemented Case: " + e.getMessage()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } catch (IOException e) { System.out.println("Error reading file: " + e.getMessage()); } } }
B10149
B10641
0
import java.io.FileInputStream; import java.util.HashMap; import java.util.Scanner; import java.util.TreeSet; // Recycled Numbers // https://code.google.com/codejam/contest/1460488/dashboard#s=p2 public class C { private static String process(Scanner in) { int A = in.nextInt(); int B = in.nextInt(); int res = 0; int len = Integer.toString(A).length(); for(int n = A; n < B; n++) { String str = Integer.toString(n); TreeSet<Integer> set = new TreeSet<Integer>(); for(int i = 1; i < len; i++) { int m = Integer.parseInt(str.substring(i, len) + str.substring(0, i)); if ( m > n && m <= B && ! set.contains(m) ) { set.add(m); res++; } } } return Integer.toString(res); } public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in.available() > 0 ? System.in : new FileInputStream(Thread.currentThread().getStackTrace()[1].getClassName() + ".practice.in")); int T = in.nextInt(); for(int i = 1; i <= T; i++) System.out.format("Case #%d: %s\n", i, process(in)); } }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Scanner; public class RecycledNumbersMain { public static void main(String[] args) { try { Scanner s=new Scanner(new BufferedReader(new FileReader("C-small-attempt0.in"))); ArrayList<RecycledNumbers> list=new ArrayList<RecycledNumbers>(); int i=0; int totalCases=Integer.parseInt(s.nextLine()); while(s.hasNextLine()){ list.add(new RecycledNumbers(++i,s.nextLine())); } for (RecycledNumbers recycledNumbers : list) { recycledNumbers.process(); } } catch (FileNotFoundException e) { System.out.println("file not found"); } } }
B10149
B11185
0
import java.io.FileInputStream; import java.util.HashMap; import java.util.Scanner; import java.util.TreeSet; // Recycled Numbers // https://code.google.com/codejam/contest/1460488/dashboard#s=p2 public class C { private static String process(Scanner in) { int A = in.nextInt(); int B = in.nextInt(); int res = 0; int len = Integer.toString(A).length(); for(int n = A; n < B; n++) { String str = Integer.toString(n); TreeSet<Integer> set = new TreeSet<Integer>(); for(int i = 1; i < len; i++) { int m = Integer.parseInt(str.substring(i, len) + str.substring(0, i)); if ( m > n && m <= B && ! set.contains(m) ) { set.add(m); res++; } } } return Integer.toString(res); } public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in.available() > 0 ? System.in : new FileInputStream(Thread.currentThread().getStackTrace()[1].getClassName() + ".practice.in")); int T = in.nextInt(); for(int i = 1; i <= T; i++) System.out.format("Case #%d: %s\n", i, process(in)); } }
public class Hehe { /** * @param args */ public static int n(int A, int B){ // TODO Auto-generated method stub int start=A; int end=B; int count=0; MyNumbers myNumbers = new MyNumbers(); MyNumbers myCheck = new MyNumbers(); for( int k = start; k<=end; k++) { int a =k; String s = Integer.valueOf(a).toString(); for(int i=0; i<s.length(); i++) { CharSequence c = s.subSequence(0, i); String s2 = s.concat(c.toString()); s2 = s2.substring(i); int n = Integer.parseInt(s2); if(n<=end && n>=start && a!=n && !myCheck.numbers.contains(n)) { //System.out.println(s+" "+s2); myNumbers.add(n); myCheck.add(a); count++; } } //myNumbers.numbers.removeAll(myCheck.numbers); } System.out.println(myNumbers.numbers.size()+" count: "+count); return count; } }
B20023
B21782
0
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class GoogleC { public String szamol(String input){ String result=""; String a=input; Integer min=Integer.parseInt(a.substring(0,a.indexOf(' '))); a=a.substring(a.indexOf(' ')+1); Integer max=Integer.parseInt(a); Long count=0l; for(Integer i=min; i<=max; i++){ String e1=i.toString(); Set<Integer> db=new HashSet<Integer>(); for (int j=1; j<e1.length();j++){ String e2=e1.substring(j)+e1.substring(0,j); Integer k=Integer.parseInt(e2); if (k>i && k<=max){ db.add(k); //System.out.println(e1+"\t"+e2); } } count+=db.size(); } return count.toString(); } public static void main(String[] args) { GoogleC a=new GoogleC(); //String filename="input.txt"; //String filename="C-small-attempt0.in"; String filename="C-large.in"; String thisLine; try { BufferedReader br = new BufferedReader(new FileReader(filename)); BufferedWriter bw= new BufferedWriter(new FileWriter(filename+".out")); thisLine=br.readLine(); Integer tnum=Integer.parseInt(thisLine); for(int i=0;i<tnum;i++) { // while loop begins here thisLine=br.readLine(); System.out.println(thisLine); System.out.println("Case #"+(i+1)+": "+a.szamol(thisLine)+"\n"); bw.write("Case #"+(i+1)+": "+a.szamol(thisLine)+"\n"); } // end while // end try br.close(); bw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package googlers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class Mainclass { String line[]; int bv=1; Mainclass(){ line=new String[50]; FileInputStream fstream; DataInputStream in; BufferedReader br; try{ fstream = new FileInputStream("in.txt"); in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); int x=Integer.parseInt(br.readLine()); for(int z=0;z<x;z++){ line[z]=br.readLine(); tranform(line[z]); } }catch(Exception e){ e.printStackTrace(); } } private void tranform(String string) { String A[]; int count=0; int z=0; A=string.split(" "); int a=Integer.parseInt(A[0]); int b=Integer.parseInt(A[1]); //System.out.println(a+ " " +b); int len=new Integer(a).toString().length(); for(int x=a;x<=b;x++){ String test=new String(x+""); String temp=test; for(int y=0;y<len-1;y++){ temp=temp.charAt(len-1)+temp.substring(0,len-1); int testn=Integer.parseInt(temp); //System.out.println(testn); if(testn==x)continue; if(testn<a||testn>b) continue; z++; } } System.out.println(z/2); String output=new String(z/2+""); try{ File file = new File("out.txt"); FileWriter fileWritter = new FileWriter(file.getName(),true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); bufferWritter.write(new String("Case #"+bv+": "+output+"\n")); System.out.println("Case #"+bv+": "+output+"\n"); bv++; bufferWritter.close(); }catch(Exception e){ e.printStackTrace(); } } public static void main(String args[]){ new Mainclass(); } }
B20856
B21283
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Happy; import java.io.*; import java.math.*; import java.lang.*; import java.util.*; import java.util.Arrays.*; import java.io.BufferedReader; //import java.io.IOException; //import java.io.InputStreamReader; //import java.io.PrintWriter; //import java.util.StringTokenizer; /** * * @author ipoqi */ public class Happy { /** * @param args the command line arguments */ public static void main(String[] args) { new Happy().haha(); } public void haha() { BufferedReader in = null; BufferedWriter out = null; try{ in = new BufferedReader(new FileReader("C-large.in")); out = new BufferedWriter(new FileWriter("LLL.out")); int T = Integer.parseInt(in.readLine()); System.out.println("T="+T); //LinkedList<Integer> mm = new LinkedList<Integer>(); //mm.add(new LinkedList<Integer>()); //int[][] mm; //for(int ii=0;ii<mm.length;ii++){ // mm[0][ii] = 1; //} for(int i=0;i<T;i++){ String[] line = in.readLine().split(" "); int A = Integer.parseInt(line[0]); int B = Integer.parseInt(line[1]); //System.out.print(" A = "+A+"\n"); //System.out.print(" B = "+B+"\n"); int ans = 0; for(int j=A;j<B;j++){ int n=j; if(n>=10){ String N = Integer.toString(n); int nlen = N.length(); List<Integer> oks = new ArrayList<Integer>(); for(int k=0;k<nlen-1;k++){ String M = ""; for(int kk=1;kk<=nlen;kk++){ M = M + N.charAt((k+kk)%nlen); } int m = Integer.parseInt(M); //System.out.print(" N = "+N+"\n"); //System.out.print(" M = "+M+"\n"); if(m>n && m<=B) { boolean isNewOne = true; for(int kkk=0;kkk<oks.size();kkk++){ //System.out.print(" KKK = "+oks.get(kkk)+"\n"); if(m==oks.get(kkk)){ isNewOne = false; } } if(isNewOne){ //System.out.print(" N = "+N+"\n"); //System.out.print(" M = "+M+"\n"); oks.add(m); ans++; } } } } } out.write("Case #"+(i+1)+": "+ans+"\n"); System.out.print("Case #"+(i+1)+": "+ans+"\n"); } in.close(); out.close(); }catch(Exception e){ e.printStackTrace(); try{ in.close(); out.close(); }catch(Exception e1){ e1.printStackTrace(); } } System.out.print("YES!\n"); } }
package com.google.code.jam2012.problemC; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; /** * Created with IntelliJ IDEA. * User: Vahid * Date: 4/14/12 * Time: 6:54 PM * To change this template use File | Settings | File Templates. */ public class ProblemC1 { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new FileInputStream("data.in")); FileOutputStream out = new FileOutputStream("C2.out"); long a, b, m,n; int lines = scanner.nextInt(); scanner.nextLine(); for (int i = 1; i<=lines; i++){ a = scanner.nextLong(); b = scanner.nextLong(); out.write(("Case #"+i+": "+ calculate(a, b)).getBytes()); out.write('\r'); out.write('\n'); if (scanner.hasNextLine()) scanner.nextLine(); } scanner.close(); out.close(); } private static long calculate(long a, long b) { long logarithm = 1; long counter = 0; int len = 1; while (logarithm * 10 <= b) { logarithm *= 10; len++; } HashSet<Long> list; for (long n = a; n<b; n++) { list = new HashSet<Long>(100); long m = n; for (int i=1; i<len; i++){ m = (m %10) *logarithm + (m/10); if ((n<m) && (m<=b) && (!list.contains(new Long(m)))) { counter++; list.add(new Long(m)); } } } return counter; } }
A12544
A13190
0
package problem1; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; public class Problem1 { public static void main(String[] args) throws FileNotFoundException, IOException{ try { TextIO.readFile("L:\\Coodejam\\Input\\Input.txt"); } catch (IllegalArgumentException e) { System.out.println("Can't open file "); System.exit(0); } FileOutputStream fout = new FileOutputStream("L:\\Coodejam\\Output\\output.txt"); PrintStream ps=new PrintStream(fout); int cases=TextIO.getInt(); int googlers=0,surprising=0,least=0; for(int i=0;i<cases;i++){ int counter=0; googlers=TextIO.getInt(); surprising=TextIO.getInt(); least=TextIO.getInt(); int score[]=new int[googlers]; for(int j=0;j<googlers;j++){ score[j]=TextIO.getInt(); } Arrays.sort(score); int temp=0; int sup[]=new int[surprising]; for(int j=0;j<googlers && surprising>0;j++){ if(biggestNS(score[j])<least && biggestS(score[j])==least){ surprising--; counter++; } } for(int j=0;j<googlers;j++){ if(surprising==0)temp=biggestNS(score[j]); else { temp=biggestS(score[j]); surprising--; } if(temp>=least)counter++; } ps.println("Case #"+(i+1)+": "+counter); } } static int biggestNS(int x){ if(x==0)return 0; if(x==1)return 1; return ((x-1)/3)+1; } static int biggestS(int x){ if(x==0)return 0; if(x==1)return 1; return ((x-2)/3)+2; } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class ProblemB { /** * @param args */ public static void main(String[] args) { BufferedReader br = null; BufferedWriter bw = null; String input[] = null; String output = null; try { br = new BufferedReader(new FileReader(new File("E:/B-small-attempt0.in"))); bw = new BufferedWriter(new FileWriter("output.txt")); int count = Integer.parseInt(br.readLine()); for (int i = 0; i < count; i++) { input = br.readLine().split(" "); int noOfScores = Integer.parseInt(input[0]); int noOfSuprises = Integer.parseInt(input[1]); int expectedScore = Integer.parseInt(input[2]); int noOfSolutions=0; int scores[]=new int[noOfScores]; for(int j=0;j<noOfScores;j++) { scores[j]=Integer.parseInt(input[j+3]); } for(int j=0;j<noOfScores;j++) { if((scores[j]%3)==1) { if(((int)(scores[j]/3)+1)>=expectedScore) { noOfSolutions++; } }else { if((scores[j]%3)==0) { int probScore=(int)(scores[j]/3); if(probScore>=expectedScore) { noOfSolutions++; } else { if(((probScore+1)>=expectedScore)&&((probScore-1)>=0)&&noOfSuprises!=0) { noOfSolutions++; noOfSuprises--; } } } else { int probScore=(int)(scores[j]/3)+1; if(probScore>=expectedScore) { noOfSolutions++; } else { if(((probScore+1)>=expectedScore)&&noOfSuprises!=0) { noOfSolutions++; noOfSuprises--; } } } } } output = new String("Case #" + (i + 1) + ": "+noOfSolutions); bw.write(output); bw.newLine(); //logic here } bw.close(); } catch (Exception e) { e.printStackTrace(); } } }
A11135
A12980
0
/** * Created by IntelliJ IDEA. * User: Administrator * Date: 3/3/12 * Time: 11:00 AM * To change this template use File | Settings | File Templates. */ import SRMLib.MathLibrary; import SRMLib.TestSRMLib; import com.sun.org.apache.bcel.internal.generic.F2D; import java.io.*; import java.util.*; import java.util.zip.Inflater; public class SRM { public static void main(String[] args) throws IOException { //TestSRMLib.run(); codeJam1.main(); return; } } class codeJam1 { public static void main() throws IOException { String inputPath = "E:\\input.txt"; String outputPath = "E:\\output.txt"; BufferedReader input = new BufferedReader(new FileReader(inputPath)); BufferedWriter output = new BufferedWriter(new FileWriter(outputPath)); String line; line = input.readLine(); int T = Integer.parseInt(line); for (int i = 1; i <= T; ++i) { line = input.readLine(); String[] words = line.split(" "); int N = Integer.parseInt(words[0]); int S = Integer.parseInt(words[1]); int p = Integer.parseInt(words[2]); int n = 0; int res = 0; for (int j = 3; j < words.length; ++j) { if (p == 0) { res++; continue; } int t = Integer.parseInt(words[j]); if (p == 1) { if (t > 0) res++; continue; } if (t >= 3 * p - 2) res++; else if (t >= 3 * p - 4) n++; } res += Math.min(n, S); output.write("Case #" + i + ": " + res); output.newLine(); } input.close(); output.close(); } }
import java.io.*; 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; } }
B10485
B12597
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 main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.HashSet; public class ProblemB { public static void main(String args[]){ try{ FileInputStream fileInputStream = new FileInputStream(args[0] + ".in"); DataInputStream in = new DataInputStream(fileInputStream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fstream = new FileWriter(args[0] + ".out"); BufferedWriter out = new BufferedWriter(fstream); String strLine; strLine = br.readLine(); int T = Integer.parseInt(strLine); for(int i = 1; i <= T; i++){ strLine = br.readLine(); String[] limits = strLine.split(" ", 2); int lowerLimit = Integer.parseInt(limits[0]); int upperLimit = Integer.parseInt(limits[1]); int count = 0; for(int j = lowerLimit; j < upperLimit; j++){ int n = j; String temp = Integer.toString(j); HashSet<String> hashSet = new HashSet<String>(); for(int k = 0; k < temp.length() - 1; k++){ temp = temp.substring(temp.length() - 1, temp.length()) + temp.substring(0, temp.length() - 1); int m = Integer.parseInt(temp); if(n < m && m <= upperLimit){ String temp1 = temp; hashSet.add(temp1); } } count = count + hashSet.size(); } System.out.println("Case #" + i + ": " + count); out.write("Case #" + i + ": " + count + "\n"); } out.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } }
B11318
B11019
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 org.moriraaca.codejam.recyclednumbers; import org.moriraaca.codejam.AbstractTest; import org.moriraaca.codejam.TestConfiguration; @TestConfiguration(solverClass = RecycledNumbersSolver.class) public class RecycledNumbers extends AbstractTest { public RecycledNumbers(String fileName) { super(fileName); } }
B11696
B10231
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.*; 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; } }
B10231
B11773
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.util.ArrayList; import java.util.List; public class RecycledNumbers { /** * @param args */ public static void main(String[] args) { List<String> inputList = FileIO.readFile("C-small-attempt0.in"); List<String> outputList = new ArrayList<String>(); int caseNo = 1 ; int testCaseCount = Integer.parseInt(inputList.get(0)); while (caseNo <= testCaseCount) { Number n = new Number(inputList.get(caseNo)); outputList.add("Case #" +caseNo +": " +n.getRecycledPairCount()); caseNo++; } FileIO.writeFile("C-small-attempt0.out", outputList); } }