F1
stringlengths 6
6
| F2
stringlengths 6
6
| label
stringclasses 2
values | text_1
stringlengths 149
20.2k
| text_2
stringlengths 48
42.7k
|
---|---|---|---|---|
A12273 | A10558 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Dancing
* Jason Bradley Nel
* 16287398
*/
import java.io.*;
public class Dancing {
public static void main(String[] args) {
In input = new In("input.txt");
int T = Integer.parseInt(input.readLine());
for (int i = 0; i < T; i++) {
System.out.printf("Case #%d: ", i + 1);
int N = input.readInt();
int s = input.readInt();
int p = input.readInt();
int c = 0;//counter for >=p cases
//System.out.printf("N: %d, S: %d, P: %d, R: ", N, s, p);
for (int j = 0; j < N; j++) {
int score = input.readInt();
int q = score / 3;
int m = score % 3;
//System.out.printf("%2d (%d, %d) ", scores[j], q, m);
switch (m) {
case 0:
if (q >= p) {
c++;
} else if (((q + 1) == p) && (s > 0) && (q != 0)) {
c++;
s--;
}
break;
case 1:
if (q >= p) {
c++;
} else if ((q + 1) == p) {
c++;
}
break;
case 2:
if (q >= p) {
c++;
} else if ((q + 1) == p) {
c++;
} else if (((q + 2) == p) && (s > 0)) {
c++;
s--;
}
break;
}
}
//System.out.printf("Best result of %d or higher: ", p);
System.out.println(c);
}
}
}
| import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class B {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("B-small-attempt1.in"));
System.setOut(new PrintStream("B-small-attempt1.out"));
int t = scan.nextInt();
for (int c = 0; c < t; c++) {
int n = scan.nextInt(); // num
int s = scan.nextInt(); // surprising
int p = scan.nextInt(); // best result cutoff
int[] totalPoints = new int[n];
for (int i = 0; i < n; i++)
totalPoints[i] = scan.nextInt();
int sUsed = 0;
int ans = 0;
for (int i = 0; i < n; i++) {
int pts = totalPoints[i];
// can it be done normal?
if (pts >= p + (p - 1) * 2)
ans++;
// can it be done surp?
else if (pts >= p + Math.max(p - 2, 0) * 2)
if (sUsed < s) {
ans++;
sUsed++;
}
}
System.out.printf("Case #%d: %d%n", c + 1, ans);
}
}
} |
B20856 | B20108 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Happy;
import java.io.*;
import java.math.*;
import java.lang.*;
import java.util.*;
import java.util.Arrays.*;
import java.io.BufferedReader;
//import java.io.IOException;
//import java.io.InputStreamReader;
//import java.io.PrintWriter;
//import java.util.StringTokenizer;
/**
*
* @author ipoqi
*/
public class Happy {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Happy().haha();
}
public void haha() {
BufferedReader in = null;
BufferedWriter out = null;
try{
in = new BufferedReader(new FileReader("C-large.in"));
out = new BufferedWriter(new FileWriter("LLL.out"));
int T = Integer.parseInt(in.readLine());
System.out.println("T="+T);
//LinkedList<Integer> mm = new LinkedList<Integer>();
//mm.add(new LinkedList<Integer>());
//int[][] mm;
//for(int ii=0;ii<mm.length;ii++){
// mm[0][ii] = 1;
//}
for(int i=0;i<T;i++){
String[] line = in.readLine().split(" ");
int A = Integer.parseInt(line[0]);
int B = Integer.parseInt(line[1]);
//System.out.print(" A = "+A+"\n");
//System.out.print(" B = "+B+"\n");
int ans = 0;
for(int j=A;j<B;j++){
int n=j;
if(n>=10){
String N = Integer.toString(n);
int nlen = N.length();
List<Integer> oks = new ArrayList<Integer>();
for(int k=0;k<nlen-1;k++){
String M = "";
for(int kk=1;kk<=nlen;kk++){
M = M + N.charAt((k+kk)%nlen);
}
int m = Integer.parseInt(M);
//System.out.print(" N = "+N+"\n");
//System.out.print(" M = "+M+"\n");
if(m>n && m<=B) {
boolean isNewOne = true;
for(int kkk=0;kkk<oks.size();kkk++){
//System.out.print(" KKK = "+oks.get(kkk)+"\n");
if(m==oks.get(kkk)){
isNewOne = false;
}
}
if(isNewOne){
//System.out.print(" N = "+N+"\n");
//System.out.print(" M = "+M+"\n");
oks.add(m);
ans++;
}
}
}
}
}
out.write("Case #"+(i+1)+": "+ans+"\n");
System.out.print("Case #"+(i+1)+": "+ans+"\n");
}
in.close();
out.close();
}catch(Exception e){
e.printStackTrace();
try{
in.close();
out.close();
}catch(Exception e1){
e1.printStackTrace();
}
}
System.out.print("YES!\n");
}
} | import java.util.Scanner;
public class RecycledNumbers {
public static int Recycled(int k,int begin,int end){
int length =String.valueOf(k).length();
int inc=0;
int con=(int) Math.pow(10,length);
int div=1;
int temp;
for(int i=1;i<length;i++){
div*=10;
con/=10;
temp=(k%div)*con+(k/div);
if(temp>k){
if(temp>=begin&&temp<=end){
inc++;
}
}
}
return inc;
}
public static int testcase(int begin,int end){
int inc=0;
for(int i=begin;i<=end;i++){
inc+=Recycled(i,begin,end);
}
return inc;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
for(int i=0;i<T;i++){
System.out.println("Case #"+(i+1)+": "+testcase(scan.nextInt(),scan.nextInt()));
}
}
}
|
A20490 | A22218 | 0 | /**
*
*/
package hu.herba.codejam;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
/**
* Base functionality, helper functions for CodeJam problem solver utilities.
*
* @author csorbazoli
*/
public abstract class AbstractCodeJamBase {
private static final String EXT_OUT = ".out";
protected static final int STREAM_TYPE = 0;
protected static final int FILE_TYPE = 1;
protected static final int READER_TYPE = 2;
private static final String DEFAULT_INPUT = "test_input";
private static final String DEFAULT_OUTPUT = "test_output";
private final File inputFolder;
private final File outputFolder;
public AbstractCodeJamBase(String[] args, int type) {
String inputFolderName = AbstractCodeJamBase.DEFAULT_INPUT;
String outputFolderName = AbstractCodeJamBase.DEFAULT_OUTPUT;
if (args.length > 0) {
inputFolderName = args[0];
}
this.inputFolder = new File(inputFolderName);
if (!this.inputFolder.exists()) {
this.showUsage("Input folder '" + this.inputFolder.getAbsolutePath() + "' not exists!");
}
if (args.length > 1) {
outputFolderName = args[1];
}
this.outputFolder = new File(outputFolderName);
if (this.outputFolder.exists() && !this.outputFolder.canWrite()) {
this.showUsage("Output folder '" + this.outputFolder.getAbsolutePath() + "' not writeable!");
} else if (!this.outputFolder.exists() && !this.outputFolder.mkdirs()) {
this.showUsage("Could not create output folder '" + this.outputFolder.getAbsolutePath() + "'!");
}
File[] inputFiles = this.inputFolder.listFiles();
for (File inputFile : inputFiles) {
this.processInputFile(inputFile, type);
}
}
/**
* @return the inputFolder
*/
public File getInputFolder() {
return this.inputFolder;
}
/**
* @return the outputFolder
*/
public File getOutputFolder() {
return this.outputFolder;
}
/**
* @param input
* input reader
* @param output
* output writer
* @throws IOException
* in case input or output fails
* @throws IllegalArgumentException
* in case the given input is invalid
*/
@SuppressWarnings("unused")
protected void process(BufferedReader reader, PrintWriter pw) throws IOException, IllegalArgumentException {
System.out.println("NEED TO IMPLEMENT (reader/writer)!!!");
System.exit(-2);
}
/**
* @param input
* input file
* @param output
* output file (will be overwritten)
* @throws IOException
* in case input or output fails
* @throws IllegalArgumentException
* in case the given input is invalid
*/
protected void process(File input, File output) throws IOException, IllegalArgumentException {
System.out.println("NEED TO IMPLEMENT (file/file)!!!");
System.exit(-2);
}
/**
* @param input
* input stream
* @param output
* output stream
* @throws IOException
* in case input or output fails
* @throws IllegalArgumentException
* in case the given input is invalid
*/
protected void process(InputStream input, OutputStream output) throws IOException, IllegalArgumentException {
System.out.println("NEED TO IMPLEMENT (stream/stream)!!!");
System.exit(-2);
}
/**
* @param type
* @param input
* @param output
*/
private void processInputFile(File input, int type) {
long starttime = System.currentTimeMillis();
System.out.println("Processing '" + input.getAbsolutePath() + "'...");
File output = new File(this.outputFolder, input.getName() + AbstractCodeJamBase.EXT_OUT);
if (type == AbstractCodeJamBase.STREAM_TYPE) {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(input);
os = new FileOutputStream(output);
this.process(is, os);
} catch (FileNotFoundException e) {
this.showUsage("FileNotFound: " + e.getLocalizedMessage());
} catch (IllegalArgumentException excIA) {
this.showUsage(excIA.getLocalizedMessage());
} catch (Exception exc) {
System.out.println("Program failed: " + exc.getLocalizedMessage());
exc.printStackTrace(System.out);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
System.out.println("Failed to close input: " + e.getLocalizedMessage());
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
System.out.println("Failed to close output: " + e.getLocalizedMessage());
}
}
}
} else if (type == AbstractCodeJamBase.READER_TYPE) {
BufferedReader reader = null;
PrintWriter pw = null;
try {
reader = new BufferedReader(new FileReader(input));
pw = new PrintWriter(output);
this.process(reader, pw);
} catch (FileNotFoundException e) {
this.showUsage("FileNotFound: " + e.getLocalizedMessage());
} catch (IllegalArgumentException excIA) {
this.showUsage(excIA.getLocalizedMessage());
} catch (Exception exc) {
System.out.println("Program failed: " + exc.getLocalizedMessage());
exc.printStackTrace(System.out);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.out.println("Failed to close input: " + e.getLocalizedMessage());
}
}
if (pw != null) {
pw.close();
}
}
} else if (type == AbstractCodeJamBase.FILE_TYPE) {
try {
this.process(input, output);
} catch (IllegalArgumentException excIA) {
this.showUsage(excIA.getLocalizedMessage());
} catch (Exception exc) {
System.out.println("Program failed: " + exc.getLocalizedMessage());
exc.printStackTrace(System.out);
}
} else {
this.showUsage("Unknown type given: " + type + " (accepted values: 0,1)");
}
System.out.println(" READY (" + (System.currentTimeMillis() - starttime) + " ms)");
}
/**
* Read a single number from input
*
* @param reader
* @param purpose
* What is the purpose of given data
* @return
* @throws IOException
* @throws IllegalArgumentException
*/
protected int readInt(BufferedReader reader, String purpose) throws IOException, IllegalArgumentException {
int ret = 0;
String line = reader.readLine();
if (line == null) {
throw new IllegalArgumentException("Invalid input: line is empty, it should be an integer (" + purpose + ")!");
}
try {
ret = Integer.parseInt(line);
} catch (NumberFormatException excNF) {
throw new IllegalArgumentException("Invalid input: the first line '" + line + "' should be an integer (" + purpose + ")!");
}
return ret;
}
/**
* Read array of integers
*
* @param reader
* @param purpose
* @return
*/
protected int[] readIntArray(BufferedReader reader, String purpose) throws IOException {
int[] ret = null;
String line = reader.readLine();
if (line == null) {
throw new IllegalArgumentException("Invalid input: line is empty, it should be an integer list (" + purpose + ")!");
}
String[] strArr = line.split("\\s");
int len = strArr.length;
ret = new int[len];
for (int i = 0; i < len; i++) {
try {
ret[i] = Integer.parseInt(strArr[i]);
} catch (NumberFormatException excNF) {
throw new IllegalArgumentException("Invalid input: line '" + line + "' should be an integer list (" + purpose + ")!");
}
}
return ret;
}
/**
* Read array of strings
*
* @param reader
* @param purpose
* @return
*/
protected String[] readStringArray(BufferedReader reader, String purpose) throws IOException {
String[] ret = null;
String line = reader.readLine();
if (line == null) {
throw new IllegalArgumentException("Invalid input: line is empty, it should be a string list (" + purpose + ")!");
}
ret = line.split("\\s");
return ret == null ? new String[0] : ret;
}
/**
* Basic usage pattern. Can be overwritten by current implementation
*
* @param message
* Short message, describing the problem with given program
* arguments
*/
protected void showUsage(String message) {
if (message != null) {
System.out.println(message);
}
System.out.println("Usage:");
System.out.println("\t" + this.getClass().getName() + " program");
System.out.println("\tArguments:");
System.out.println("\t\t<input folder>:\tpath of input folder (default: " + AbstractCodeJamBase.DEFAULT_INPUT + ").");
System.out.println("\t\t \tAll files will be processed in the folder");
System.out.println("\t\t<output folder>:\tpath of output folder (default: " + AbstractCodeJamBase.DEFAULT_OUTPUT + ")");
System.out.println("\t\t \tOutput file name will be the same as input");
System.out.println("\t\t \tinput with extension '.out'");
System.exit(-1);
}
}
| package qr2012;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
public class DancingWithTheGooglers {
public static void main(String[] args) throws Exception {
String fileName = args[0];
DancingWithTheGooglers obj = new DancingWithTheGooglers();
obj.solve(fileName);
}
public void solve(String fileName) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(fileName));
BufferedWriter bw = new BufferedWriter(
new FileWriter(fileName + ".out"));
int T = Integer.parseInt(br.readLine());
for (int i = 0; i < T; i++) {
String str = br.readLine();
StringTokenizer token = new StringTokenizer(str, " ");
int N = Integer.parseInt(token.nextToken());
int S = Integer.parseInt(token.nextToken());
int p = Integer.parseInt(token.nextToken());
int[] t = new int[N];
for (int j = 0; j < N; j++) {
t[j] = Integer.parseInt(token.nextToken());
}
// Arrays.sort(t);
int cnt = 0;
int scnt = 0;
for (int j = N - 1; j >= 0; j--) {
if (t[j] >= 3 * p - 2) {
cnt += 1;
} else if (t[j] >= 3 * p - 4 && t[j] >= 2 && scnt < S) {
cnt += 1;
scnt += 1;
}
}
bw.write("Case #" + (i + 1) + ": ");
bw.write("" + cnt);
bw.write("\r\n");
}
bw.close();
br.close();
}
}
|
A11201 | A10546 | 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 practice;
import java.util.*;
public class GoogleDance {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int cases = Integer.parseInt(sc.nextLine());
for(int i = 0; i<cases; i++){
//Case starts here
int caseCounter = i+1;
String caseLine = sc.nextLine();
String[] caseArray = caseLine.split(" ");
int googlers = Integer.parseInt(caseArray[0]);
int surprising = Integer.parseInt(caseArray[1]);
int passing = Integer.parseInt(caseArray[2]);
List<Integer> scores = new ArrayList<Integer>();
for(int j = 3; j<caseArray.length;j++){
scores.add(Integer.parseInt(caseArray[j]));
}
//Finding individual scores
int result = 0;
for(Integer score:scores){
if(score%3==0){
int individual = score/3;
if(individual==0){
if(individual>=passing){
result++;
}
}else{
if(individual>=passing){
result++;
}else if(surprising>0){
individual++;
if(individual>=passing){
result++;
surprising--;
}
}
}
}
if(score%3==1){
int individual = score/3+1;
if(individual>=passing){
result++;
}
}
if(score%3==2){
int individual = score/3+1;
if(individual>=passing){
result++;
}else if(surprising>0){
individual++;
if(individual>=passing){
result++;
surprising--;
}
}
}
}
System.out.println("Case #"+caseCounter+": " + result);
//Case ends here
}
}
}
|
A10699 | A11846 | 0 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Dancing {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// read input file
File file = new File("B-small-attempt4.in");
//File file = new File("input.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String ln = "";
int count = Integer.parseInt(br.readLine());
// write output file
File out = new File("outB.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(out));
int y = 0;
for (int i=0; i < count; i++){
ln = br.readLine();
y = getY(ln);
bw.write("Case #" + (i+1) + ": " + y);
bw.newLine();
}
bw.close();
}
private static int getY(String str) {
String[] data = str.split(" ");
int n = Integer.parseInt(data[0]);
int s = Integer.parseInt(data[1]);
int p = Integer.parseInt(data[2]);
int[] t = new int[n];
for (int i=0; i < n; i++){
t[i] = Integer.parseInt(data[i+3]);
}
int y = 0;
int base = 0;
for(int j=0; j < t.length; j++){
base = t[j] / 3;
if(base >= p) { y++; }
else if(base == p-1){
if(t[j] - (base+p) > base-1 && t[j] > 0){
y++;
} else if(s>0 && t[j] - (base+p) > base-2 && t[j] > 0){
s -= 1;
y++;
}
} else if(base == p-2){
if(s > 0 && t[j] - (base+p) > base-1 && t[j] > 0){
s -= 1;
y++;
}
}
}
return y;
}
}
|
import java.io.FileNotFoundException;
import java.util.List;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Amya
*/
public class Dancing {
public static void main(String args[]) throws FileNotFoundException{
List<String> lines = FileUtil.readFileByLine("input1");
int records = Integer.parseInt(lines.get(0));
int numOfGooglers = 0;
int numOfSurprises = 0;
int bestScore = 0;
String[] nums = null;
int eligiblesWithSurprise = 0;
int eligiblesWithoutSurprise = 0;
int onBorder = 0;
int finalEligibles = 0;
for(int i = 1; i<=records; i++){
nums = lines.get(i).split(" ");
numOfGooglers = Integer.parseInt(nums[0]);
numOfSurprises = Integer.parseInt(nums[1]);
bestScore = Integer.parseInt(nums[2]);
for(int j=3 ; j<nums.length; j++){
if(Integer.parseInt(nums[j])>=bestScore){
if(Integer.parseInt(nums[j])>=(bestScore*3 - 4)){
eligiblesWithSurprise ++;
}
if(Integer.parseInt(nums[j])>=(bestScore*3 - 2)){
eligiblesWithoutSurprise ++;
}
}
}
finalEligibles = eligiblesWithoutSurprise;
onBorder = eligiblesWithSurprise - eligiblesWithoutSurprise;
if(onBorder > numOfSurprises){
finalEligibles += numOfSurprises;
}else{
finalEligibles += onBorder;
}
if(i == records)
FileUtil.writeOutput("Case #"+i+": "+finalEligibles, true);
else
FileUtil.writeOutput("Case #"+i+": "+finalEligibles, false);
eligiblesWithSurprise = 0;
eligiblesWithoutSurprise = 0;
}
}
}
|
B12762 | B10815 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;
/**
*
* @author imgps
*/
public class C {
public static void main(String args[]) throws Exception{
int A,B;
int ctr = 0;
int testCases;
Scanner sc = new Scanner(new FileInputStream("C-small-attempt0.in "));
testCases = sc.nextInt();
int input[][] = new int[testCases][2];
for(int i=0;i<testCases;i++)
{
// System.out.print("Enter input A B: ");
input[i][0] = sc.nextInt();
input[i][1] = sc.nextInt();
}
for(int k=0;k<testCases;k++){
ctr = 0;
A = input[k][0];
B = input[k][1];
for(int i = A;i<=B;i++){
int num = i;
int nMul = 1;
int mul = 1;
int tnum = num/10;
while(tnum > 0){
mul = mul *10;
tnum= tnum/10;
}
tnum = num;
int n = 0;
while(tnum > 0 && mul >= 10){
nMul = nMul * 10;
n = (num % nMul) * mul + (num / nMul);
mul = mul / 10;
tnum = tnum / 10;
for(int m=num;m<=B;m++){
if(n == m && m > num){
ctr++;
}
}
}
}
System.out.println("Case #"+(k+1)+": "+ctr);
}
}
}
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class RecycledNumbers {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int cases = Integer.parseInt(br.readLine().trim());
for(int t=1;t<=cases;t++){
String[] inp=br.readLine().trim().split(" ");
int start=Integer.parseInt(inp[0]);
int end=Integer.parseInt(inp[1]);
System.out.println("Case #"+t+": "+getAns(start, end));
}
}
public static long getAns(int start, int end){
boolean[] visited=new boolean[end+1];
long total=0;
int max=0;
int digitCount=1;
int mult=10;
while(start/(mult) !=0){
digitCount++;
mult*=10;
}
for(int n=start;n<=end;n++){
int count=1;
if(visited[n])
continue;
visited[n]=true;
for(int s=1;s<digitCount;s++){
int o=n;
int fst=(int) Math.pow(10, s), oth=(int) Math.pow(10, digitCount-s);
int rem=o%fst;
o/=fst;
o+=(rem*oth);
if(o>=start && o<=end && !visited[o]){
if(rem/(Math.pow(10,digitCount-s-1))>0){
if(o!=n){
count++;
visited[o]=true;
}
}
}
}
total+=count*(count-1)/2;
}
return total;
}
}
|
B10149 | B11415 | 0 | import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Scanner;
import java.util.TreeSet;
// Recycled Numbers
// https://code.google.com/codejam/contest/1460488/dashboard#s=p2
public class C {
private static String process(Scanner in) {
int A = in.nextInt();
int B = in.nextInt();
int res = 0;
int len = Integer.toString(A).length();
for(int n = A; n < B; n++) {
String str = Integer.toString(n);
TreeSet<Integer> set = new TreeSet<Integer>();
for(int i = 1; i < len; i++) {
int m = Integer.parseInt(str.substring(i, len) + str.substring(0, i));
if ( m > n && m <= B && ! set.contains(m) ) {
set.add(m);
res++;
}
}
}
return Integer.toString(res);
}
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in.available() > 0 ? System.in :
new FileInputStream(Thread.currentThread().getStackTrace()[1].getClassName() + ".practice.in"));
int T = in.nextInt();
for(int i = 1; i <= T; i++)
System.out.format("Case #%d: %s\n", i, process(in));
}
}
| import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
/**
* @author Jelle Prins
*/
public class RecycledNumbers {
public static void main(String[] args) {
String input = "input.txt";
String output = "output.txt";
if (args.length >= 1) {
input = args[0];
if (args.length >= 2) {
output = args[1];
}
}
new RecycledNumbers(input, output);
}
public RecycledNumbers(String inputString, String outputString) {
init();
File input = new File(inputString);
File output = new File(outputString);
if (!input.isFile()) {
System.err.println("input file not found");
System.exit(1);
}
if (output.exists()) {
output.delete();
}
try {
String[] cases = readInput(input);
String[] results = executeCases(cases);
writeOutput(output, results);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private String[] readInput(File file) throws Exception {
Scanner scanner = new Scanner(file);
int lines = scanner.nextInt();
scanner.nextLine();
String[] cases = new String[lines];
for (int i = 0; i < lines; i++) {
cases[i] = scanner.nextLine().trim();
if (cases[i] == null) {
throw new Exception("not enough input lines");
}
}
scanner.close();
return cases;
}
private String[] executeCases(String[] cases) {
String[] output = new String[cases.length];
for (int i = 0; i < cases.length; i++) {
output[i] = executeCase(i + 1, cases[i]);
}
return output;
}
private String parseOutput(int caseID, String answer) {
String output = "Case #" + caseID + ": " + answer;
System.out.println(output);
return output;
}
private void writeOutput(File output, String[] results) throws Exception {
PrintWriter pw = new PrintWriter(new FileWriter(output));
for (int i = 0; i < results.length; i++) {
pw.println(results[i]);
}
pw.close();
}
private void init() {
}
private String executeCase(int caseID, String input) {
String[] split = input.split(" ");
int start = Integer.parseInt(split[0]);
int end = Integer.parseInt(split[1]);
int answer = 0;
char[] chars;
for (int n = start; n < end; n++) {
chars = getNumberChars(n);
if (chars == null) {
continue;
}
answer += recycle(n, chars, end);
}
return parseOutput(caseID, "" + answer);
}
/**
* Returns null if the number can't be recycled
*/
private char[] getNumberChars(int n) {
if (n < 10) {
return null;
}
char[] chars = Integer.toString(n).toCharArray();
int validChars = 0;
for (char c : chars) {
if (c != '0') {
validChars++;
}
}
if (validChars < 2) {
return null;
}
return chars;
}
private int recycle(int n, char[] chars, int end) {
char[] recycle = new char[chars.length];
Set<String> found = new HashSet<String>();
String str;
int answer;
int recycleTimes = 0;
for (int i = 1; i < chars.length; i++) {
System.arraycopy(chars, i, recycle, 0, chars.length - i);
System.arraycopy(chars, 0, recycle, chars.length - i, i);
str = new String(recycle);
answer = Integer.parseInt(str);
if (answer > n && answer <= end) {
if (found.add(str)) {
recycleTimes++;
}
}
}
return recycleTimes;
}
}
|
B10485 | B12210 | 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 hk.polyu.cslhu.codejam.solution.impl;
import hk.polyu.cslhu.codejam.solution.Solution;
import java.util.ArrayList;
import java.util.List;
public class StoreCredit extends Solution {
private int amountOfCredits, numOfItems;
private List<Integer> priceList;
@Override
public void setProblem(List<String> testCase) {
this.initial(testCase);
}
private void initial(List<String> testCase) {
// TODO Auto-generated method stub
this.amountOfCredits = Integer.valueOf(testCase.get(0));
this.numOfItems = Integer.valueOf(testCase.get(1));
this.setPriceList(testCase.get(2));
}
private void setPriceList(String string) {
// TODO Auto-generated method stub
String[] splitArray = string.split(" ");
if (splitArray.length != numOfItems)
logger.error("The price list does not include all items ("
+ splitArray.length
+ "/" + this.numOfItems + ")");
this.priceList = new ArrayList<Integer>();
for (String price : splitArray) {
this.priceList.add(Integer.valueOf(price));
}
}
@Override
public void solve() {
for (int itemIndex = 0; itemIndex < this.priceList.size() - 1; itemIndex++) {
for (int anotherItemIndex = itemIndex + 1; anotherItemIndex < this.priceList.size(); anotherItemIndex++) {
if (this.priceList.get(itemIndex) + this.priceList.get(anotherItemIndex) == this.amountOfCredits) {
this.result = (itemIndex + 1) + " " + (anotherItemIndex + 1);
break;
}
}
}
}
@Override
public String getResult() {
return this.result;
}
}
|
A12273 | A11301 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Dancing
* Jason Bradley Nel
* 16287398
*/
import java.io.*;
public class Dancing {
public static void main(String[] args) {
In input = new In("input.txt");
int T = Integer.parseInt(input.readLine());
for (int i = 0; i < T; i++) {
System.out.printf("Case #%d: ", i + 1);
int N = input.readInt();
int s = input.readInt();
int p = input.readInt();
int c = 0;//counter for >=p cases
//System.out.printf("N: %d, S: %d, P: %d, R: ", N, s, p);
for (int j = 0; j < N; j++) {
int score = input.readInt();
int q = score / 3;
int m = score % 3;
//System.out.printf("%2d (%d, %d) ", scores[j], q, m);
switch (m) {
case 0:
if (q >= p) {
c++;
} else if (((q + 1) == p) && (s > 0) && (q != 0)) {
c++;
s--;
}
break;
case 1:
if (q >= p) {
c++;
} else if ((q + 1) == p) {
c++;
}
break;
case 2:
if (q >= p) {
c++;
} else if ((q + 1) == p) {
c++;
} else if (((q + 2) == p) && (s > 0)) {
c++;
s--;
}
break;
}
}
//System.out.printf("Best result of %d or higher: ", p);
System.out.println(c);
}
}
}
| import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class B{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
double EPS=1e-9;
int caze, T;
int n, s, p;
int[] ts;
void run(){
T=sc.nextInt();
for(caze=1; caze<=T; caze++){
n=sc.nextInt();
s=sc.nextInt();
p=sc.nextInt();
ts=new int[n];
for(int i=0; i<n; i++){
ts[i]=sc.nextInt();
}
solve();
}
}
void solve(){
int count1=0, count2=0, count3=0;
for(int i=0; i<n; i++){
int t=ts[i];
int max1, max2;
if(t%3==0){
max1=t/3;
if(t>=3){
max2=t/3+1;
}else{
max2=t/3;
}
}else if(t%3==1){
max1=max2=t/3+1;
}else{
max1=t/3+1;
max2=t/3+2;
}
max2=min(max2, 10);
if(max1<p&&max2<p){
count1++;
}else if(max1<p&&max2>=p){
count2++;
}else{
count3++;
}
// debug(t, max1, max2, p);
}
int ans=count3+min(count2, s);
answer(ans+"");
}
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/B-small.in"));
System.setOut(new PrintStream(new FileOutputStream(
"dat/B-small.out")));
}catch(Exception e){}
new B().run();
System.out.flush();
System.out.close();
}
}
|
A11917 | A12916 | 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 lt.kasrud.gcj.common.io;
import java.io.*;
import java.util.List;
public class Writer {
private static String formatCase(int caseNr, String output){
return String.format("Case #%d: %s", caseNr, output);
}
public static void writeFile(String filename, List<String> data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
for (int i = 0; i < data.size(); i++) {
String output = formatCase(i+1, data.get(i));
writer.write(output + "\n");
}
writer.close();
}
}
|
B11696 | B10003 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package recycled;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.TreeSet;
/**
*
* @author Alfred
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
FileInputStream fstream = new FileInputStream("C-small-attempt0.in");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
FileWriter outFile = new FileWriter("out.txt");
PrintWriter out = new PrintWriter(outFile);
String line;
line = br.readLine();
int cases = Integer.parseInt(line);
for (int i=1; i<=cases;i++){
line = br.readLine();
String[] values = line.split(" ");
int A = Integer.parseInt(values[0]);
int B = Integer.parseInt(values[1]);
int total=0;
for (int n=A; n<=B;n++){
TreeSet<String> solutions = new TreeSet<String>();
for (int k=1;k<values[1].length();k++){
String m = circshift(n,k);
int mVal = Integer.parseInt(m);
if(mVal<=B && mVal!=n && mVal> n && !m.startsWith("0") && m.length()==Integer.toString(n).length() )
{
solutions.add(m);
}
}
total+=solutions.size();
}
out.println("Case #"+i+": "+total);
}
in.close();
out.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
private static String circshift(int n, int k) {
String nString=Integer.toString(n);
int len=nString.length();
String m = nString.substring(len-k)+nString.subSequence(0, len-k);
//System.out.println(n+" "+m);
return m;
}
}
| package qualification;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.Vector;
public class ProblemC {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int cases = scan.nextInt();
for ( int i = 1; i <= cases; i++ ) {
System.out.println("Case #" + i + ": " + solveCase());
}
}
public static int solveCase() {
int A = scan.nextInt();
int B = scan.nextInt();
Map<Integer, Long> map = new HashMap<Integer, Long>();
Integer[] digits;
for ( int i = A; i <= B; i++ ) {
digits = getDigits(i);
addToMap(digits, map);
}
int result = 0;
for ( Long l : map.values() ) {
result += (l * (l-1)) / 2;
}
return result;
}
public static void addToMap(Integer[] n, Map<Integer, Long> map) {
Vector<Integer> rots = getRotationSymmetricValues(n);
// Remember to handle leading 0! All must have same length
for ( Integer num : rots) {
if ( map.containsKey(num) ) {
map.put(num, map.get(num)+1);
return;
}
}
map.put(digitsToNum(n), 1L);
}
public static Vector<Integer> getRotationSymmetricValues(Integer[] n) {
Vector<Integer> result = new Vector<Integer>();
int origNum = digitsToNum(n);
Queue<Integer> v = new LinkedList<Integer>();
for ( int i = 0; i < n.length; i++ ) {
v.add(n[i]);
}
while (true) {
Integer first = v.poll();
v.add(first);
if ( v.peek() == 0 )
continue;
int num = 0;
for ( Integer i : v) {
num *= 10;
num += i;
}
if ( num == origNum )
break;
result.add(num);
}
return result;
}
public static int digitsToNum(Integer[] digits) {
int num = 0;
for ( int i = 0; i < digits.length; i++ ) {
num *= 10;
num += digits[i];
}
return num;
}
static Comparator<Integer> comp = new Comparator<Integer>() {
@Override
public int compare(Integer arg0, Integer arg1) {
if ( arg0 == 0 )
return 1;
else if ( arg1 == 0)
return -1;
else
return arg0.compareTo(arg1);
}
};
public static Integer[] getDigits(int n) {
int numDigits = (int)Math.log10(n) + 1;
Integer[] digits = new Integer[numDigits];
for ( int i = 0; i < numDigits; i++ ) {
digits[numDigits-1-i] = n % 10;
n /= 10;
}
return digits;
}
}
|
B13196 | B12897 | 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 exercise;
public class Solver {
private static int[][] MATCHES;
public static Integer[] solve(Integer[][] input) {
Integer[] result = new Integer[input.length];
for (int cnt = 0; cnt < input.length; ++cnt)
result[cnt] = solve(input[cnt]);
return result;
}
public static int solve(Integer[] input) {
if (input == null || input.length < 2)
return 0;
Integer min = input[0];
Integer max = input[1];
int result = 0;
MATCHES = new int[max][4];
for (int cnt = min; cnt < max; ++cnt) {
result += countMatches(cnt, min, max);
}
for (int i = 0; i < MATCHES.length; ++i)
for (int j = 0; j < MATCHES[i].length; ++j)
if (MATCHES[i][j] != 0)
++result;
else
break;
return result;
}
private static int countMatches(int value, int min, int max) {
String string = String.valueOf(value);
int result = 0;
for (int idx = string.length() - 1; idx > 0; --idx) {
String candidateString = string.substring(idx, string.length()) + string.substring(0, idx);
Integer candidate = Integer.parseInt(candidateString);
if (candidate.compareTo(value) > 0
&& candidate.compareTo(min) >= 0
&& candidate.compareTo(max) <= 0) {
addToMatches(value, candidate);
}
}
return result;
}
private static void addToMatches(int value, int match) {
boolean inserted = false;
for (int cnt = 0; cnt < MATCHES[value].length; ++cnt) {
if (MATCHES[value][cnt] == 0) {
MATCHES[value][cnt] = match;
inserted = true;
break;
} else if (MATCHES[value][cnt] == match)
return;
}
if (!inserted) {
int[] save = MATCHES[value];
MATCHES[value] = new int[save.length * 2];
int cnt;
for (cnt = 0; cnt < save.length; ++cnt) {
MATCHES[value][cnt] = save[cnt];
}
MATCHES[value][cnt] = match;
}
}
}
|
B20006 | B20731 | 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 fixjava;
/**
* Convenience class for declaring a method inside a method, so as to avoid code duplication without having to declare a new method
* in the class. This also keeps functions closer to where they are applied. It's butt-ugly but it's about the best you can do in
* Java.
*/
public interface Lambda2<P, Q, V> {
public V apply(P param1, Q param2);
}
|
B11318 | B11942 | 0 | import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
int casos=1, a, b, n, m, cont;
while(t!=0){
a=sc.nextInt();
b=sc.nextInt();
if(a>b){
int aux=a;
a=b;
b=aux;
}
System.out.printf("Case #%d: ",casos++);
if(a==b){
System.out.printf("%d\n",0);
}else{
cont=0;
for(n=a;n<b;n++){
for(m=n+1;m<=b;m++){
if(isRecycled(n,m)) cont++;
}
}
System.out.printf("%d\n",cont);
}
t--;
}
}
public static boolean isRecycled(int n1, int n2){
String s1, s2, aux;
s1 = String.valueOf( n1 );
s2 = String.valueOf( n2 );
boolean r = false;
for(int i=0;i<s1.length();i++){
aux="";
aux=s1.substring(i,s1.length())+s1.substring(0,i);
// System.out.println(aux);
if(aux.equals(s2)){
r=true;
break;
}
}
return r;
}
}
| import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
FileInputStream fstream = null;
try {
fstream = new FileInputStream("input.txt");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
ArrayList<String> plik = new ArrayList<String>();
try {
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
plik.add(strLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
plik.remove(0); // counter nie jest potrzebny
int count = 1;
FileWriter writer = null;
try {
writer = new FileWriter("output.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (String s : plik) {
StringBuilder outputString = new StringBuilder("Case #" + count++
+ ": ");
int recycledPairsCount = 0;
String[] splitted = s.split(" ");
Integer A = Integer.parseInt(splitted[0]);
Integer B = Integer.parseInt(splitted[1]);
int a = A;
int b = B;
for (int n = a; n < b; n++) {
for (int m = n + 1; m <= B; m++) {
if (Integer.toString(m).length() != Integer.toString(n)
.length()) {
continue;
}
if (isRecycledPair(n, m)) {
recycledPairsCount += 1;
}
}
}
outputString.append(recycledPairsCount);
System.out.println(outputString);
try {
writer.write(outputString.toString());
writer.write("\r\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static boolean isRecycledPair(int n, int m) {
String N = Integer.toString(n);
String M = Integer.toString(m);
int digitNumber = N.length();
if (digitNumber == 1) {
return false;
}
for (int i = 1; i <= digitNumber; i++) {
String temp = N.substring(i, digitNumber);
temp += N.substring(0, i);
if (temp.equals(M)) {
return true;
}
}
return false;
}
}
|
A10793 | A12635 | 0 | import java.io.*;
import java.math.*;
import java.util.*;
import java.text.*;
public class b {
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int T = sc.nextInt();
for (int casenumber = 1; casenumber <= T; ++casenumber) {
int n = sc.nextInt();
int s = sc.nextInt();
int p = sc.nextInt();
int[] ts = new int[n];
for (int i = 0; i < n; ++i)
ts[i] = sc.nextInt();
int thresh1 = (p == 1 ? 1 : (3 * p - 4));
int thresh2 = (3 * p - 2);
int count1 = 0, count2 = 0;
for (int i = 0; i < n; ++i) {
if (ts[i] >= thresh2) {
++count2;
continue;
}
if (ts[i] >= thresh1) {
++count1;
}
}
if (count1 > s) {
count1 = s;
}
System.out.format("Case #%d: %d%n", casenumber, count1 + count2);
}
}
}
| import java.util.*;
public class dancing_googlers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
int[] answers = new int[T];
for (int c = 0; c < T; c++) {
int N = scanner.nextInt();
int S = scanner.nextInt();
int p = scanner.nextInt();
answers[c] = 0;
for (int i = 0; i < N; i++) {
int t = scanner.nextInt();
if (t >= (p + (p - 1) + (p - 1))) {
answers[c]++;
}
else if ((t >= (p + (p - 1) + (p - 1)) - 2) && (S > 0) && (t > 1) && (t < 29)) {
answers[c]++;
S--;
}
}
}
for (int c = 0; c < T; c++) {
int j = c+1;
System.out.println("Case #"+j+": "+answers[c]);
}
}
}
|
B12762 | B12534 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;
/**
*
* @author imgps
*/
public class C {
public static void main(String args[]) throws Exception{
int A,B;
int ctr = 0;
int testCases;
Scanner sc = new Scanner(new FileInputStream("C-small-attempt0.in "));
testCases = sc.nextInt();
int input[][] = new int[testCases][2];
for(int i=0;i<testCases;i++)
{
// System.out.print("Enter input A B: ");
input[i][0] = sc.nextInt();
input[i][1] = sc.nextInt();
}
for(int k=0;k<testCases;k++){
ctr = 0;
A = input[k][0];
B = input[k][1];
for(int i = A;i<=B;i++){
int num = i;
int nMul = 1;
int mul = 1;
int tnum = num/10;
while(tnum > 0){
mul = mul *10;
tnum= tnum/10;
}
tnum = num;
int n = 0;
while(tnum > 0 && mul >= 10){
nMul = nMul * 10;
n = (num % nMul) * mul + (num / nMul);
mul = mul / 10;
tnum = tnum / 10;
for(int m=num;m<=B;m++){
if(n == m && m > num){
ctr++;
}
}
}
}
System.out.println("Case #"+(k+1)+": "+ctr);
}
}
}
| package com.google.codejam;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
public class RecycledNumbers {
public static void main(String argsp[]) throws NumberFormatException, IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("/Users/ashwinjain/Desktop/SmsLogger/InterviewStreet/src/com/google/codejam/in3.txt")));
int cases = Integer.parseInt(br.readLine());
for(int x=0;x<cases;x++){
String temp[] = br.readLine().split(" ");
long a = Long.parseLong(temp[0]);
long b = Long.parseLong(temp[1]);
long c=a;
long count=0;
while(c<=b){
String str= c+"";
HashMap<Long, Boolean> added = new HashMap<Long, Boolean>();
for(int i=1;i<str.length();i++){
long d=Long.parseLong(str.substring(i)+str.substring(0, i));
if(d!=c && d>=a && d<=b && !added.containsKey(d)){
added.put(d, true);
count++;
}
}
c++;
}
System.out.println("Case #"+(x+1)+": "+count/2);
}
}
}
|
B10858 | B10499 | 0 | package be.mokarea.gcj.common;
public abstract class TestCaseReader<T extends TestCase> {
public abstract T nextCase() throws Exception;
public abstract int getMaxCaseNumber();
}
| import java.util.Hashtable;
import java.util.Scanner;
class RecycleResult{
private int lowerBound, upperBound, numberOfDigits;
public RecycleResult(int a, int b, int d){
lowerBound = a;
upperBound = b;
numberOfDigits = d;
}
public int solve(){
int count = 0;
for (int i = lowerBound; i < upperBound; i++){
int p = i;
Hashtable<Integer, Integer> hash = new Hashtable<Integer, Integer>();
for (int j = 1; j < numberOfDigits; j++){
p = moveToFront(p);
if ((p <= upperBound) && (p > i) && (!(p == i)) && (!(hash.containsValue(p)))){
count++;
hash.put(count, p);
}
}
}
return count;
}
public int moveToFront(int z){
int lastDigit = z % 10;
int otherDigits = (z / 10);
for (int i = 0; i < numberOfDigits - 1; i++){
lastDigit = lastDigit * 10;
}
return otherDigits + lastDigit;
}
}
public class Recycle {
public static void main(String[] args) {
int numberOfCases;
Scanner myScanner = new Scanner(System.in);
int a, b;
numberOfCases = myScanner.nextInt();
RecycleResult myResult;
for (int i = 0; i < numberOfCases; i++){
a = myScanner.nextInt();
b = myScanner.nextInt();
int length = String.valueOf(a).length();
myResult = new RecycleResult(a, b, length);
int count = myResult.solve();
System.out.println("Case #" + (i+1) + ": " + count);
}
}
}
|
B10361 | B12861 | 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.codejam;
import java.util.HashMap;
public class RecycledNumberSolver implements GoogleSolver {
@Override
public String solve(String str) {
String [] numbers = str.split(" ");
int min = Integer.parseInt(numbers[0]);
int max = Integer.parseInt(numbers[1]);
int digits = numbers[0].length();
System.out.println("min:"+min + " max:"+ max);
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int count = 0;
for(int i=min; i<=max ; i++){
for(int move=1 ; move<digits ; move++){
String temp = i+"";
String test = temp.substring(temp.length()-move) + temp.substring(0, temp.length()-move);
int testNum = Integer.parseInt(test);
if(testNum>i && testNum>=min && testNum<=max){
//System.out.println("("+temp + " , " + testNum+ ")");
if(map.get(i)==null || map.get(i)!=testNum){
map.put(i, testNum);
count++;
}
}
}
map.clear();
}
return count+"";
}
}
|
B11327 | B10600 | 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]);
}
}
}
| import java.io.*;
import java.util.*;
class recycled
{
public static void main(String[] args) throws Exception
{
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
String inp;
int i,j;
int T=Integer.valueOf(r.readLine());
for(int a=0;a<T;a++)
{
/*consists of a single line containing the integers A and B. */
String[] tmp =r.readLine().split("\\s");
int A = Integer.valueOf(tmp[0]);
int B = Integer.valueOf(tmp[1]);
int y=0;
HashSet<String> stv = new HashSet<String>();
for(i=A;i<=B;i++) {
String s = ""+i;
for(j=1;j<s.length();j++) {
String sj = s.substring(j) + s.substring(0,j);
int k = Integer.valueOf(sj);
String str="("+s+","+sj+")";
if (k>i && k<=B && !stv.contains(str)) {
y++;
stv.add(str);
}
}
}
System.out.println("Case #"+(a+1)+": "+y);
}
}
}
|
A20934 | A20629 | 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.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
public class bsp2 {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
String inFile = "B-large.in";
String outFile = inFile + ".out";
LineNumberReader lin = new LineNumberReader(new InputStreamReader(new FileInputStream(inFile)));
PrintWriter out = new PrintWriter(new File(outFile));
int NCASE = Integer.parseInt(lin.readLine());
String line="";
int erg=0;
for(int CASE = 1; CASE <= NCASE; CASE++) {
String [] ch=lin.readLine().split(" ");
int googlers=Integer.parseInt(ch[0]);
int sTriplets=Integer.parseInt(ch[1]);
int bResult=Integer.parseInt(ch[2]);
//System.out.println("Case #"+CASE);
//System.out.println(googlers);
//System.out.println(sTriplets);
//System.out.println(bResult);
for(int SCORE=3;SCORE<ch.length;SCORE++){
//System.out.print(ch[SCORE]);
int base=Integer.parseInt(ch[SCORE])/3;
switch(Integer.parseInt(ch[SCORE])%3){
case 0:
if(base >=bResult) erg++;
else{
if(sTriplets>0 && base>0 && base+1 >=bResult){
erg++;
sTriplets--;
}
}
break;
case 1:
if(base>=bResult||base+1>=bResult) erg++;
else{
if(sTriplets>0 && base>0 && base+1 >=bResult){
erg++;
sTriplets--;
}
}
break;
case 2:
if(base+1>=bResult||base>=bResult) erg++;
else{
if(sTriplets>0 && base>0 && base+2 >=bResult){
erg++;
sTriplets--;
}
}
break;
}
}
out.println("Case #" + CASE + ": "+erg);
erg=0;
}
lin.close();
out.close();
}
}
|
B21227 | B20115 | 0 | import java.util.HashSet;
import java.util.Scanner;
public class C {
static HashSet p = new HashSet();
static int low;
static int high;
int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int no = sc.nextInt();
for (int i = 1; i <= no; i++) {
p.clear();
low = sc.nextInt();
high = sc.nextInt();
for (int l = low; l <= high; l++) {
recycle(l);
}
System.out.println("Case #" + i + ": " + p.size());
}
}
public static void recycle(int no) {
String s = Integer.toString(no);
for (int i = 0; i < s.length(); i++) {
String rec = s.substring(i) + s.substring(0, i);
int r = Integer.parseInt(rec);
if (r != no && r >= low && r <= high) {
int min = Math.min(r, no);
int max = Math.max(r, no);
String a = Integer.toString(min) + "" + Integer.toString(max);
p.add(a);
}
}
}
}
| import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
public class CodeJam
{
private static BufferedReader reader;
private static BufferedWriter writer;
public static void main(String args[]) throws Exception
{
prepareFiles("C-large");
int T = Integer.parseInt(reader.readLine());
for(int i = 0; i < T; i++)
{
String[] line = reader.readLine().split(" ");
int A = Integer.parseInt(line[0]);
int B = Integer.parseInt(line[1]);
int l = String.valueOf(A).length();
int recycled = 0;
for(int n = A; n <= B; n++)
{
HashSet<Integer> checkedCycles = new HashSet<>();
String recycledSequence = String.valueOf(n);
for(int j = 1; j < l; j++)
{
recycledSequence = recycle(recycledSequence);
int recycledInt = Integer.valueOf(recycledSequence);
if(checkedCycles.contains(recycledInt))
{
continue;
}
else
{
checkedCycles.add(recycledInt);
}
if(n < recycledInt && recycledInt <= B)
{
recycled ++;
}
}
}
print(getCase(i + 1));
print(recycled);
print("\n");
}
putAwayFiles();
}
private static String recycle(String sequence)
{
String newSequence = new String();
newSequence += sequence.charAt(sequence.length() - 1);
for(int i = 0; i < sequence.length() - 1; i++)
{
newSequence += sequence.charAt(i);
}
return newSequence;
}
private static void prepareFiles(String fileName) throws IOException
{
reader = new BufferedReader(new FileReader(new File(fileName + ".in")));
writer = new BufferedWriter(new FileWriter(new File(fileName + ".out")));
}
private static void putAwayFiles() throws IOException
{
reader.close();
writer.flush();
writer.close();
}
private static String getCase(int i)
{
return "Case #" + i + ": ";
}
private static void print(Object object) throws IOException
{
System.out.print(object.toString());
writer.write(object.toString());
}
}
|
A10699 | A10965 | 0 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Dancing {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// read input file
File file = new File("B-small-attempt4.in");
//File file = new File("input.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String ln = "";
int count = Integer.parseInt(br.readLine());
// write output file
File out = new File("outB.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(out));
int y = 0;
for (int i=0; i < count; i++){
ln = br.readLine();
y = getY(ln);
bw.write("Case #" + (i+1) + ": " + y);
bw.newLine();
}
bw.close();
}
private static int getY(String str) {
String[] data = str.split(" ");
int n = Integer.parseInt(data[0]);
int s = Integer.parseInt(data[1]);
int p = Integer.parseInt(data[2]);
int[] t = new int[n];
for (int i=0; i < n; i++){
t[i] = Integer.parseInt(data[i+3]);
}
int y = 0;
int base = 0;
for(int j=0; j < t.length; j++){
base = t[j] / 3;
if(base >= p) { y++; }
else if(base == p-1){
if(t[j] - (base+p) > base-1 && t[j] > 0){
y++;
} else if(s>0 && t[j] - (base+p) > base-2 && t[j] > 0){
s -= 1;
y++;
}
} else if(base == p-2){
if(s > 0 && t[j] - (base+p) > base-1 && t[j] > 0){
s -= 1;
y++;
}
}
}
return y;
}
}
| package org.tritree_tritree;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class ProblemBSmall {
static private Map<Integer, Integer> MAP_1 = new HashMap<Integer, Integer>();
static private Map<Integer, Integer> MAP_2 = new HashMap<Integer, Integer>();
static {
MAP_1.put(10, 28);
MAP_1.put(9, 25);
MAP_1.put(8, 22);
MAP_1.put(7, 19);
MAP_1.put(6, 16);
MAP_1.put(5, 13);
MAP_1.put(4, 10);
MAP_1.put(3, 7);
MAP_1.put(2, 4);
}
static {
MAP_2.put(10, 26);
MAP_2.put(9, 23);
MAP_2.put(8, 20);
MAP_2.put(7, 17);
MAP_2.put(6, 14);
MAP_2.put(5, 11);
MAP_2.put(4, 8);
MAP_2.put(3, 5);
MAP_2.put(2, 2);
}
public static void main(String[] args) throws IOException {
File source = new File("B-small-attempt0.in");
Scanner scan = new Scanner(source);
int t = scan.nextInt();
scan.nextLine();
List<String> resultList = new ArrayList<String>();
for (int i = 1; i < t + 1; i++) {
int n = scan.nextInt();
int s = scan.nextInt();
int p = scan.nextInt();
int[] pointArray = new int[n];
for (int j = 0; j < n; j++) {
pointArray[j] = scan.nextInt();
}
String result = "Case #" + i + ": " + resolve(s, p, pointArray);
resultList.add(result);
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_hhmmss");
File resultFile = new File("B-small-" + dateFormat.format(new Date()) + ".out");
FileOutputStream fileOutputStream = new FileOutputStream(resultFile);
for (String result: resultList) {
result = result + "\n";
fileOutputStream.write(result.getBytes());
}
fileOutputStream.flush();
fileOutputStream.close();
}
private static int resolve(int s, int p, int[] pointArray) {
int cnt = 0;
int remainScnt = s;
for (int i = 0; i < pointArray.length; i++) {
int target = pointArray[i];
if (p*3 -2 <= target) {
cnt++;
} else if (target == 0) {
continue;
} else if (0 < remainScnt) {
if (p*3 -4 <= target) {
cnt++;
remainScnt--;
}
}
}
return cnt;
}
}
|
A22191 | A21491 | 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 B {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(br.readLine());
int T = sc.nextInt();
int caseNumber = 1;
for(int i=0; i<T; i++){
sc = new Scanner(br.readLine());
int N = sc.nextInt();
int S = sc.nextInt();
int p = sc.nextInt();
int count = 0;
//int countS = 0;
//int countCanBeS = 0;
//ArrayList<Integer> ta = new ArrayList<Integer>();
//ArrayList<Integer> tb = new ArrayList<Integer>();
for(int j=0; j<N; j++){
int tr = sc.nextInt();
if(tr>0){
if(tr/3 >= p){
count++;
}else if((tr + 2)/3 >= p){
count++;
//countCanBeS++;
}else if(tr/3<p){
if(S>0){
if((tr+3)/3 >= p){
count++;
S--;
}else if((tr+4)/3 >= p){
//System.out.println("Hello" + count);
count++;
S--;
}
}
}
}else if(tr==0 && p==0){
count++;
}
}
System.out.println("Case #"+ caseNumber +": "+count);
caseNumber++;
}
}
} |
B20006 | B21343 | 0 | import java.io.*;
import java.math.BigInteger;
import java.util.*;
import org.jfree.data.function.PowerFunction2D;
public class r2a
{
Map numMap = new HashMap();
int output = 0;
/**
* @param args
*/
public static void main(String[] args)
{
r2a mk = new r2a();
try {
FileInputStream fstream = new FileInputStream("d:/cjinput.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str;
int i = 0;
while ((str = br.readLine()) != null) {
int begin=0,end = 0;
i++;
if (i == 1)
continue;
mk.numMap = new HashMap();
StringTokenizer strTok = new StringTokenizer(str, " ");
while (strTok.hasMoreTokens()) {
begin = Integer.parseInt(((String) strTok.nextToken()));
end = Integer.parseInt(((String) strTok.nextToken()));
}
mk.evaluate(i, begin, end);
}
in.close();
}
catch (Exception e) {
System.err.println(e);
}
}
private void evaluate(int rowNum, int begin, int end)
{
output=0;
for (int i = begin; i<= end; i++) {
if(numMap.containsKey(Integer.valueOf(i)))
continue;
List l = getPairElems(i);
if (l.size() > 0) {
Iterator itr = l.iterator();
int ctr = 0;
ArrayList tempList = new ArrayList();
while (itr.hasNext()) {
int next = ((Integer)itr.next()).intValue();
if (next <= end && next > i) {
numMap.put(Integer.valueOf(next), i);
tempList.add(next);
ctr++;
}
}
ctr = getCounter(ctr+1,2);
/* if (tempList.size() > 0 || ctr > 0)
System.out.println("DD: " + i + ": " + tempList +" ; ctr = " + ctr);*/
output = output + ctr;
}
}
String outputStr = "Case #" + (rowNum -1) + ": " + output;
System.out.println(outputStr);
}
private int getCounter(int n, int r) {
int ret = 1;
int nfactorial =1;
for (int i = 2; i<=n; i++) {
nfactorial = i*nfactorial;
}
int nrfact =1;
for (int i = 2; i<=n-r; i++) {
nrfact = i*nrfact;
}
return nfactorial/(2*nrfact);
}
private ArrayList getPairElems(int num) {
ArrayList retList = new ArrayList();
int temp = num;
if (num/10 == 0)
return retList;
String str = String.valueOf(num);
int arr[] = new int[str.length()];
int x = str.length();
while (temp/10 > 0) {
arr[x-1] = temp%10;
temp=temp/10;
x--;
}
arr[0]=temp;
int size = arr.length;
for (int pos = size -1; pos >0; pos--) {
if(arr[pos] == 0)
continue;
int pairNum = 0;
int multiplier =1;
for (int c=0; c < size-1; c++) {
multiplier = multiplier*10;
}
pairNum = pairNum + (arr[pos]*multiplier);
for(int ctr = pos+1, i=1; i < size; i++,ctr++) {
if (ctr == size)
ctr=0;
if (multiplier!=1)
multiplier=multiplier/10;
pairNum = pairNum + (arr[ctr]*multiplier);
}
if (pairNum != num)
retList.add(Integer.valueOf(pairNum));
}
return retList;
}
}
| import java.io.*;
import java.util.*;
public class C {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
enum InputType {
SAMPLE, SMALL, LARGE;
}
static final InputType currentInputType = InputType.LARGE;
static final int attemptNumber = 0; // for small inputs only
int pow10;
void solve() throws IOException {
int a = nextInt();
int b = nextInt();
pow10 = 1;
int cnt = Integer.toString(a).length();
for (int i = 0; i < cnt - 1; i++)
pow10 *= 10;
long ans = 0;
for (int i = a; i <= b; i++) {
for (int j = (i % 10) * pow10 + (i / 10); j != i; j = (j % 10) * pow10 + j / 10)
if (a <= j && j <= b && j > i)
ans++;
}
out.println(ans);
}
void inp() throws IOException {
switch (currentInputType) {
case SAMPLE:
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
break;
case SMALL:
String fileName = "C-small-attempt" + attemptNumber;
br = new BufferedReader(new FileReader(fileName + ".in"));
out = new PrintWriter(fileName + ".out");
break;
case LARGE:
fileName = "C-large";
br = new BufferedReader(new FileReader(fileName + ".in"));
out = new PrintWriter(fileName + ".out");
break;
}
int test = nextInt();
for (int i = 1; i <= test; i++) {
System.err.println("Running test " + i);
out.print("Case #" + i + ": ");
solve();
}
out.close();
}
public static void main(String[] args) throws IOException {
new C().inp();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (Exception e) {
eof = true;
return null;
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
B13196 | B10427 | 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.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<String> answer = read("/home/zehortigoza/Downloads/codejam/c/input.txt");
int tt = 0;
int amount = 1;
for (int i = 0; i < answer.size(); i++) {
String line = answer.get(i);
if (i == 0) {
tt = Integer.parseInt(line);
} else {
if (tt >= amount) {
HashMap<String, Boolean> count = new HashMap<String, Boolean>();
String[] splited = line.split(" ");
String a = splited[0];
String b = splited[1];
int aInt = Integer.parseInt(a);
int bInt = Integer.parseInt(b);
if (! (a.length() == 1 && b.length() == 1)) {
ArrayList<Integer> range = range(aInt, bInt);
for (int z = 0; z < range.size(); z++) {
String currentN = range.get(z)+"";
String currentM = range.get(z)+"";
int length = currentM.length();
for (int j = 0; j < length; j++) {
currentM = currentM.charAt(length-1) + currentM.substring(0, length - 1);
int currentNInt = Integer.parseInt(currentN);
int currentMInt = Integer.parseInt(currentM);
if (currentMInt <= bInt && currentMInt > currentNInt && currentMInt >= aInt) {
if(count.get(currentN+currentM) == null) {
count.put(currentN+currentM, true);
}
}
}
}
}
System.out.println("Case #" + amount + ": " + count.size());
amount++;
}
}
}
}
private static ArrayList<Integer> range(int start, int end) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (start > end) {
System.out.println("error to build range");
return null;
}
for (int i = start; i <= end; i++) {
list.add(i);
}
return list;
}
private static ArrayList<String> read(String url) {
ArrayList<String> lines = new ArrayList<String>();
Scanner scanner = null;
try {
scanner = new Scanner(new FileInputStream(url));
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
return lines;
}
}
|
A11201 | A12869 | 0 | package CodeJam.c2012.clasificacion;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* Problem
*
* You're watching a show where Googlers (employees of Google) dance, and then
* each dancer is given a triplet of scores by three judges. Each triplet of
* scores consists of three integer scores from 0 to 10 inclusive. The judges
* have very similar standards, so it's surprising if a triplet of scores
* contains two scores that are 2 apart. No triplet of scores contains scores
* that are more than 2 apart.
*
* For example: (8, 8, 8) and (7, 8, 7) are not surprising. (6, 7, 8) and (6, 8,
* 8) are surprising. (7, 6, 9) will never happen.
*
* The total points for a Googler is the sum of the three scores in that
* Googler's triplet of scores. The best result for a Googler is the maximum of
* the three scores in that Googler's triplet of scores. Given the total points
* for each Googler, as well as the number of surprising triplets of scores,
* what is the maximum number of Googlers that could have had a best result of
* at least p?
*
* For example, suppose there were 6 Googlers, and they had the following total
* points: 29, 20, 8, 18, 18, 21. You remember that there were 2 surprising
* triplets of scores, and you want to know how many Googlers could have gotten
* a best result of 8 or better.
*
* With those total points, and knowing that two of the triplets were
* surprising, the triplets of scores could have been:
*
* 10 9 10 6 6 8 (*) 2 3 3 6 6 6 6 6 6 6 7 8 (*)
*
* The cases marked with a (*) are the surprising cases. This gives us 3
* Googlers who got at least one score of 8 or better. There's no series of
* triplets of scores that would give us a higher number than 3, so the answer
* is 3.
*
* Input
*
* The first line of the input gives the number of test cases, T. T test cases
* follow. Each test case consists of a single line containing integers
* separated by single spaces. The first integer will be N, the number of
* Googlers, and the second integer will be S, the number of surprising triplets
* of scores. The third integer will be p, as described above. Next will be N
* integers ti: the total points of the Googlers.
*
* Output
*
* For each test case, output one line containing "Case #x: y", where x is the
* case number (starting from 1) and y is the maximum number of Googlers who
* could have had a best result of greater than or equal to p.
*
* Limits
*
* 1 ⤠T ⤠100. 0 ⤠S ⤠N. 0 ⤠p ⤠10. 0 ⤠ti ⤠30. At least S of the ti values
* will be between 2 and 28, inclusive.
*
* Small dataset
*
* 1 ⤠N ⤠3.
*
* Large dataset
*
* 1 ⤠N ⤠100.
*
* Sample
*
* Input Output 4 Case #1: 3 3 1 5 15 13 11 Case #2: 2 3 0 8 23 22 21 Case #3: 1
* 2 1 1 8 0 Case #4: 3 6 2 8 29 20 8 18 18 21
*
* @author Leandro Baena Torres
*/
public class B {
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader br = new BufferedReader(new FileReader("B.in"));
String linea;
int numCasos, N, S, p, t[], y, minSurprise, minNoSurprise;
linea = br.readLine();
numCasos = Integer.parseInt(linea);
for (int i = 0; i < numCasos; i++) {
linea = br.readLine();
String[] aux = linea.split(" ");
N = Integer.parseInt(aux[0]);
S = Integer.parseInt(aux[1]);
p = Integer.parseInt(aux[2]);
t = new int[N];
y = 0;
minSurprise = p + ((p - 2) >= 0 ? (p - 2) : 0) + ((p - 2) >= 0 ? (p - 2) : 0);
minNoSurprise = p + ((p - 1) >= 0 ? (p - 1) : 0) + ((p - 1) >= 0 ? (p - 1) : 0);
for (int j = 0; j < N; j++) {
t[j] = Integer.parseInt(aux[3 + j]);
if (t[j] >= minNoSurprise) {
y++;
} else {
if (t[j] >= minSurprise) {
if (S > 0) {
y++;
S--;
}
}
}
}
System.out.println("Case #" + (i + 1) + ": " + y);
}
}
}
|
import java.util.Scanner;
public class CodeJam12B {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
for (int zz = 1; zz <= T; zz++) {
int N = in.nextInt();
int S = in.nextInt();
int p = in.nextInt();
int[] t = new int[N];
int out = 0;
for (int i = 0; i < N; i++) {
t[i] = in.nextInt();
t[i] = t[i] - p;
if (t[i] >= 0) {
if (t[i] >= 2 * (p - 1)) {
out++;
} else if (t[i] >= 2 * (p - 2) && S > 0) {
S--;
out++;
}
}
}
System.out.format("Case #%d: %d\n", zz, out);
}
}
}
|
A22642 | A22764 | 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;
}
}
}
} | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package google_code_jam;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
*
* @author lenovo
*/
public class B {
public static void main(String[] args) throws IOException {
// TODO code application logic here
BufferedReader br = new BufferedReader(new FileReader("B-large.in"));
PrintWriter pw = new PrintWriter("B.out" );
StringTokenizer st=new StringTokenizer(br.readLine());
// System.out.println(st);
int x = Integer.parseInt(st.nextToken());
a1:for (int i = 0; i < x; i++) {
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());// number of players
int s = Integer.parseInt(st.nextToken());//number of surprising
int p = Integer.parseInt(st.nextToken());// best degree required
int count=0;//
for (int j = 0; j < n; j++) {
int temp=Integer.parseInt(st.nextToken());
int rem=temp%3;
int div=temp/3;
if(temp==0 && p!=0)continue;
else if(temp==0 && p==0){
count++;
continue;
}
if(rem==0){
if(div>=p){
count++;
continue;
}
else if(div+1>=p && s>0){
count++;
s--;
continue;
}
}// end of this condition
else{
if(rem==1){
if(div+1 >=p)count++;
}
else if(rem==2){
if(div+1 >= p)count++;
else if (div+2 >=p && s>0){
count++;
s--;
continue;
}
}
}
}// End of converting
pw.append("Case #"+(i+1)+": "+count+"\n");
}
pw.close();
}
}
|
A21557 | A21489 | 0 | import java.io.*;
import java.util.*;
public class DancingWithGooglers {
public static class Googlers {
public int T;
public int surp;
public boolean surprising;
public boolean pSurprising;
public boolean antiSurprising;
public boolean pAntiSurprising;
public Googlers(int T, int surp) {
this.T = T;
this.surp = surp;
}
public void set(int a, int b, int c) {
if (c >= 0 && (a + b + c) == T) {
int diff = (Math.max(a, Math.max(b, c)) - Math.min(a, Math.min(b, c)));
if (diff <= 2) {
if (diff == 2) {
if (a >= surp || b >= surp || c >= surp) {
pSurprising = true;
} else {
surprising = true;
}
} else {
if (a >= surp || b >= surp || c >= surp) {
pAntiSurprising = true;
} else {
antiSurprising = true;
}
}
}
}
}
}
public static void main(String... args) throws IOException {
// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader reader = new BufferedReader(new FileReader("B-large.in"));
// PrintWriter writer = new PrintWriter(System.out);
PrintWriter writer = new PrintWriter("B-large.out");
int len, cases = Integer.parseInt(reader.readLine());
List<Googlers> satisfied = new ArrayList<Googlers>();
List<Googlers> unsatisfied = new ArrayList<Googlers>();
String[] inputs;
int N, S, p;
for (int i = 1; i <= cases; i++) {
inputs = reader.readLine().split(" ");
p = Integer.parseInt(inputs[1]);
S = Integer.parseInt(inputs[2]);
satisfied.clear();
unsatisfied.clear();
for (int j = 3; j < inputs.length; j++) {
int t = Integer.parseInt(inputs[j]);
Googlers googlers = new Googlers(t, S);
for (int k = 0; k <= 10; k++) {
int till = k + 2 > 10 ? 10 : k + 2;
for (int l = k; l <= till; l++) {
googlers.set(k, l, (t - (k + l)));
}
}
if (googlers.pAntiSurprising) {
satisfied.add(googlers);
} else {
unsatisfied.add(googlers);
}
}
int pSurprising = 0;
if (p > 0) {
for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.pSurprising) {
pSurprising++;
iter.remove();
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.surprising) {
iter.remove();
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.pSurprising) {
iter.remove();
pSurprising++;
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.surprising) {
iter.remove();
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
writer.print("Case #" + i + ": 0");
}else {
writer.print("Case #" + i + ": " + (satisfied.size() + pSurprising));
}
writer.println();
}
writer.flush();
}
}
| package world2012.qualification;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class B {
public static boolean canPass(int[] t, int p) {
if (t[0] < 0 || t[1] < 0 || t[2] < 0)
return false;
return t[0] >= p || t[1] >= p || t[2] >= p;
}
public static int maxGooglers(int[] scores, int p, int s) {
B b = new B();
Triple[] ts = new Triple[scores.length];
for (int i = 0; i < scores.length; i++) {
ts[i] = b.new Triple(scores[i]);
}
int count = 0;
int surpr = 0;
for (Triple t : ts) {
if (canPass(t.triple, p))
count++;
else if (canPass(t.sTriple, p))
surpr++;
}
return count + Math.min(surpr, s);
}
static PrintWriter out;
public static void parseInput() throws Exception {
// String file = "world2012/qualification/B-large-attempt0.in";
String file = "world2012/qualification/B-large.in";
// String file = "input.in";
Scanner scanner = new Scanner(new File(file));
out = new PrintWriter(new FileWriter((file.replaceAll(".in", ""))));
int T = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < T; i++) {
String[] in = scanner.nextLine().split("\\s");
int N = Integer.parseInt(in[0]);
int S = Integer.parseInt(in[1]);
int P = Integer.parseInt(in[2]);
int[] scores = new int[N];
for (int j = 0; j < N; j++) {
scores[j] = Integer.parseInt(in[j + 3]);
}
int r = maxGooglers(scores, P, S);
out.println("Case #"+(i+1)+": "+r+"");
}
}
public static void main(String[] args) throws Exception {
parseInput();
out.close();
System.out.println("Done!");
}
class Triple {
int[] triple;
int[] sTriple;
int score;
public Triple(int score) {
this.score = score;
init();
}
private void init() {
if (score % 3 == 2) {
int l = score / 3;
int b = score / 3 + 1;
triple = new int[] {b, b, l};
sTriple = new int[] {b + 1, b - 1, l};
} else if (score % 3 == 1) {
int l = score / 3;
int b = score / 3 + 1;
triple = new int[] {b, l, l};
sTriple = new int[] {b, b, l - 1};
} else {
int l = score / 3;
triple = new int[] {l, l, l};
sTriple = new int[] {l + 1, l, l - 1};
}
}
}
}
|
B10858 | B10094 | 0 | package be.mokarea.gcj.common;
public abstract class TestCaseReader<T extends TestCase> {
public abstract T nextCase() throws Exception;
public abstract int getMaxCaseNumber();
}
| import java.io.*;
import java.util.*;
public class C implements Runnable{
public void run(){
try{
Scanner in = new Scanner(new File("C-small.in"));
PrintWriter out = new PrintWriter("C-small.out");
int a, b, t = in.nextInt(), ans, x, l;
String min, buf, max;
Set<String> set = new HashSet<String>();
for (int k = 1; k <= t; k++){
ans = 0;
a = in.nextInt();
b = in.nextInt();
max = Integer.toString(b);
for (int i = a; i < b; i++){
set.clear();
x = i;
min = buf = Integer.toString(x);
l = min.length();
for (int j = 0; j < l-1; j++){
buf = min.substring(l - j - 1) + min.substring(0, Math.max(0, l - j - 1));
if ((buf.length() == l) && (min.compareTo(buf) < 0) && (buf.compareTo(max) <= 0)) {
if (!set.contains(buf)){
set.add(buf);
ans++;
}
}
}
}
out.println("Case #" + k + ": " + ans);
}
out.close();
}
catch(Exception e){
}
}
public static void main(String[] args){
(new Thread(new C())).start();
}
} |
B21968 | B20136 | 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.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
public class GoogleNumbers {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int numberOfTestCases = Integer.parseInt(s);
StringBuffer output = new StringBuffer();
for (int i = 1; i <= numberOfTestCases; i++) {
String testCase = br.readLine().trim();
String[] inputparams = testCase.split(" ");
long A, B;
A = Long.parseLong(inputparams[0]);
B = Long.parseLong(inputparams[1]);
String outputString = solveTestCase(A, B);
if (i != 1) {
output.append("\n");
}
output.append("Case #" + i + ": ");
output.append(outputString);
}
System.out.println(output);
}
private static String solveTestCase(long A, long B) {
long pairCount = 0;
int d = String.valueOf(A).length();
for (long n = A; n <= B; n++) {
String currentNumber = String.valueOf(n);
HashMap<String, String> pairedNumbers = new HashMap<String, String>();
for (int i = 1; i < d; i++) {
int subIndex = d - i;
if (currentNumber.charAt(subIndex) == '0') {
continue;
}
String newNumber = currentNumber.substring(subIndex) + currentNumber.substring(0, subIndex);
if (pairedNumbers.containsKey(newNumber)) {
continue;
}
long m = Long.valueOf(newNumber);
if (m <= n || m > B) {
continue;
}
pairedNumbers.put(newNumber, "Y");
pairCount++;
}
}
return String.valueOf(pairCount);
}
}
|
B21752 | B20274 | 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.*;
import java.util.*;
class Recycle {
public static void main(String [] args) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(in.readLine());
for(int i = 0; i < T; i++){
int ans = 0;
StringTokenizer st = new StringTokenizer(in.readLine());
int A = Integer.parseInt(st.nextToken());
int B = Integer.parseInt(st.nextToken());
for(int j = A; j <= B; j++){
String s = "" + j;
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
for(int k = 0; k < s.length(); k++){
String rot = s.substring(k,s.length()) + s.substring(0,k);
hm.put(Integer.parseInt(rot),0);
}
for(int k : hm.keySet()){
if(j<k&&k<=B)
ans++;
}
}
System.out.println("Case #"+(i+1)+": " + ans);
}
}
} |
A21396 | A20695 | 0 | import java.util.*;
public class Test {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int T = in.nextInt();
for(int i = 1; i<=T; i++) {
int n = in.nextInt();
int s = in.nextInt();
int p = in.nextInt();
int result = 0;
for(int j = 0; j<n; j++){
int x = canAddUp(in.nextInt(), p);
if(x == 0) {
result++;
} else if (x==1 && s > 0) {
result++;
s--;
}
}
System.out.println("Case #"+i+": "+result);
}
}
public static int canAddUp(int sum, int limit) {
boolean flag = false;
for(int i = 0; i<=sum; i++) {
for(int j = 0; i+j <= sum; j++) {
int k = sum-(i+j);
int a = Math.abs(i-j);
int b = Math.abs(i-k);
int c = Math.abs(j-k);
if(a > 2 || b > 2 || c> 2){
continue;
}
if (i>=limit || j>=limit || k>=limit) {
if(a < 2 && b < 2 && c < 2) {
return 0;
}else{
flag = true;
}
}
}
}
return (flag) ? 1 : 2;
}
}
| package quiz.number05;
import java.io.*;
import java.util.Arrays;
/**
* @author Keesun Baik
*/
public class KeesunDancingTest {
public static void main(String[] args) throws IOException {
KeesunDancingTest dancing = new KeesunDancingTest();
BufferedReader in = new BufferedReader(new FileReader("/workspace/telepathy/test/quiz/number05/B-large.in"));
String s;
int lineNum = 0;
int problemNum = 0;
String answer = "";
while ((s = in.readLine()) != null) {
if (s.isEmpty()) {
return;
}
if (lineNum == 0) {
problemNum = Integer.parseInt(s);
} else {
answer += "Case #" + lineNum + ": " + dancing.figureP(s) + "\n";
}
lineNum++;
}
in.close();
System.out.println(answer);
BufferedWriter out = new BufferedWriter(new FileWriter("/workspace/telepathy/test/quiz/number05/B-large.out"));
out.write(answer);
out.close();
}
private int figureP(String s) {
String[] inputs = s.split(" ");
int people = Integer.parseInt(inputs[0]);
int surprise = Integer.parseInt(inputs[1]);
int minScore = Integer.parseInt(inputs[2]);
String[] scoreStrings = Arrays.copyOfRange(inputs, 3, inputs.length);
int[] scores = new int[scoreStrings.length];
for (int i = 0; i < scoreStrings.length; i++) {
scores[i] = Integer.parseInt(scoreStrings[i]);
}
int cases = 0;
for (int score : scores) {
int base = score / 3;
switch (score % 3) {
case 0: {
System.out.println("0");
if (base >= minScore) {
cases++;
} else if (surprise > 0 && base > 0 && base + 1 >= minScore) {
cases++;
surprise--;
}
break;
}
case 1: {
System.out.println("1");
if (base >= minScore || base + 1 >= minScore) {
cases++;
} else if (surprise > 0 && base + 1 >= minScore) {
cases++;
surprise--;
}
break;
}
case 2: {
System.out.println("2");
if (base + 1 >= minScore || base >= minScore) {
cases++;
} else if (surprise > 0 && base + 2 >= minScore) {
cases++;
surprise--;
}
break;
}
}
}
return cases;
}
}
|
A22992 | A22568 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package IO;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
*
* @author dannocz
*/
public class InputReader {
public static Input readFile(String filename){
try {
/* Sets up a file reader to read the file passed on the command
77 line one character at a time */
FileReader input = new FileReader(filename);
/* Filter FileReader through a Buffered read to read a line at a
time */
BufferedReader bufRead = new BufferedReader(input);
String line; // String that holds current file line
int count = 0; // Line number of count
ArrayList<String> cases= new ArrayList<String>();
// Read first line
line = bufRead.readLine();
int noTestCases=Integer.parseInt(line);
count++;
// Read through file one line at time. Print line # and line
while (count<=noTestCases){
//System.out.println("Reading. "+count+": "+line);
line = bufRead.readLine();
cases.add(line);
count++;
}
bufRead.close();
return new Input(noTestCases,cases);
}catch (ArrayIndexOutOfBoundsException e){
/* If no file was passed on the command line, this expception is
generated. A message indicating how to the class should be
called is displayed */
e.printStackTrace();
}catch (IOException e){
// If another exception is generated, print a stack trace
e.printStackTrace();
}
return null;
}// end main
}
| package googlecodejam2012.qualification.dancinggooglers;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class DancingGooglers {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// System.out.println(hasWithoutSurprise(6, 2));
// System.out.println(hasWithoutSurprise(5, 2));
// System.out.println(hasWithoutSurprise(4, 2));
// System.out.println(hasWithoutSurprise(7, 2));
// System.out.println(hasWithoutSurprise(8, 2));
// System.out.println(hasWithoutSurprise(3, 2));
// System.out.println(hasWithoutSurprise(1, 1));
// System.out.println(hasWithoutSurprise(0, 1));
// System.out.println();
// System.out.println(hasWithSurprise(6, 2));
// System.out.println(hasWithSurprise(5, 2));
// System.out.println(hasWithSurprise(4, 2));
// System.out.println(hasWithSurprise(7, 2));
// System.out.println(hasWithSurprise(8, 2));
// System.out.println(hasWithSurprise(3, 2));
// System.out.println("Should be false: " + hasWithSurprise(2, 3));
// System.out.println("Should be false: " + hasWithSurprise(3, 3));
// System.out.println("Should be false: " + hasWithSurprise(4, 3));
// System.out.println("Should be true: " + hasWithSurprise(5, 3));
// System.out.println("Should be true: " + hasWithSurprise(6, 3));
// System.out.println("Should be true: " + hasWithSurprise(7, 3));
// System.out.println("Should be false: " + hasWithSurprise(0, 1));
String lineSep = System.getProperty("line.separator");
BufferedReader br = new BufferedReader(
args.length > 0 ? new FileReader(args[0])
: new InputStreamReader(System.in));
try {
Writer out = new BufferedWriter(args.length > 1 ? new FileWriter(args[1]): new OutputStreamWriter(System.out));
try {
int numLines = Integer.parseInt(br.readLine().trim());
for (int i = 1; i <= numLines;++i) {
String line = br.readLine();
out.write("Case #" + i + ": "+count(line) + lineSep);
}
} finally {
out.close();
}
} finally {
br.close();
}
}
private static int count(String line) {
String[] parts = line.split(" ");
int n = Integer.parseInt(parts[0]);
int s = Integer.parseInt(parts[1]);
int p = Integer.parseInt(parts[2]);
int[] sumScores = new int[parts.length - 3];
for (int i = parts.length; i -->3;) {
sumScores[i - 3] = Integer.parseInt(parts[i]);
}
return count(n, s, p, sumScores);
}
private static int count(int n, int s, int p, int[] sumScores) {
int countWithoutSurprise = 0;
int countWithPossibleSurprise = 0;
for (int sumScore : sumScores) {
if(hasWithoutSurprise(sumScore, p)) {
countWithoutSurprise++;
} else if (hasWithSurprise(sumScore, p)) {
countWithPossibleSurprise++;
}
}
return countWithoutSurprise + Math.min(s, countWithPossibleSurprise);
}
private static boolean hasWithSurprise(int sumScore, int p) {
return sumScore >= p && (sumScore + 4) /3 >= p;
}
private static boolean hasWithoutSurprise(int sumScore, int p) {
return (sumScore + 2) / 3 >= p;
}
}
|
B10899 | B12786 | 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.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Parser {
File instance;
Scanner sc;
public Parser(String f){
instance = new File(f);
}
public List<List<List<String>>> parse(int nbLinePerCase) throws FileNotFoundException{
sc = new Scanner(instance);
int nbCase = sc.nextInt();
List<List<List<String>>> input = new ArrayList<List<List<String>>>(nbCase);
String line;
sc.nextLine();
for(int i = 0; i < nbCase; i++){
List<List<String>> ll = new ArrayList<List<String>>(nbLinePerCase);
for(int j = 0; j < nbLinePerCase; j++){
List<String> l = new ArrayList<String>();
line = sc.nextLine();
Scanner sc2 = new Scanner(line);
while(sc2.hasNext()){
l.add(sc2.next());
}
ll.add(l);
}
input.add(ll);
}
return input;
}
}
|
B20291 | B21398 | 0 | import java.io.*;
import java.util.*;
class B
{
public static void main(String[] args)
{
try
{
BufferedReader br = new BufferedReader(new FileReader("B.in"));
PrintWriter pw = new PrintWriter(new FileWriter("B.out"));
int X = Integer.parseInt(br.readLine());
for(int i=0; i<X; i++)
{
String[] S = br.readLine().split(" ");
int A = Integer.parseInt(S[0]);
int B = Integer.parseInt(S[1]);
int R = 0;
int x = 1;
int n = 0;
while(A/x > 0) {
n++;
x *= 10;
}
for(int j=A; j<B; j++) {
Set<Integer> seen = new HashSet<Integer>();
for(int k=1; k<n; k++) {
int p1 = j % (int)Math.pow(10, k);
int p2 = (int) Math.pow(10, n-k);
int p3 = j / (int)Math.pow(10, k);
int y = p1*p2 + p3;
if(j < y && !seen.contains(y) && y <= B) {
seen.add(y);
R++;
}
}
}
pw.printf("Case #%d: %d\n", i+1, R);
pw.flush();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
|
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class RecycledNumbers {
private Scanner in;
private PrintWriter out;
public long output;
public int A;
public int B;
/**
* main method
*/
public static void main(String args[]){
new RecycledNumbers("C-large.in");
}
/**
* constructor
*/
public RecycledNumbers(String filename){
initIO(filename);
int n = in.nextInt();
// long tmStart = System.currentTimeMillis();
for(int i=1;i<=n;i++){
A = in.nextInt();
B = in.nextInt();
output = 0;
output=solve();
out.println("Case #"+i+": "+output);
}
// System.out.println(System.currentTimeMillis() - tmStart);
closeIO();
}
public long solve(){
long op=0;
Set<Integer> s = new HashSet<Integer>();
for(int i=A;i<=B;i++){
String stringI = Integer.toString(i);
s.clear();
for(int ind=stringI.length()-1;ind>0;ind--){
if(stringI.substring(ind).charAt(0)!= '0'){
String stringTemp = stringI.substring(ind) + stringI.substring(0, ind);
if(Integer.parseInt(stringTemp) > i && Integer.parseInt(stringTemp)<=B){
// System.out.println(stringI + " "+Integer.parseInt(stringTemp));
s.add(Integer.parseInt(stringTemp));
// op++;
}
}
}
op+=s.size();
}
return op;
}
/**
* Set up devices to do I/O
*/
public void initIO(String filename){
try {
in = new Scanner(new FileReader(filename));
out = new PrintWriter(new FileWriter(filename+".out"));
}catch (IOException except) {
System.err.println("File is missing!");
}
}
/**
* Free memory used for I/O
*/
public void closeIO(){
in.close();
out.close();
}
}
|
B20856 | B21892 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Happy;
import java.io.*;
import java.math.*;
import java.lang.*;
import java.util.*;
import java.util.Arrays.*;
import java.io.BufferedReader;
//import java.io.IOException;
//import java.io.InputStreamReader;
//import java.io.PrintWriter;
//import java.util.StringTokenizer;
/**
*
* @author ipoqi
*/
public class Happy {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Happy().haha();
}
public void haha() {
BufferedReader in = null;
BufferedWriter out = null;
try{
in = new BufferedReader(new FileReader("C-large.in"));
out = new BufferedWriter(new FileWriter("LLL.out"));
int T = Integer.parseInt(in.readLine());
System.out.println("T="+T);
//LinkedList<Integer> mm = new LinkedList<Integer>();
//mm.add(new LinkedList<Integer>());
//int[][] mm;
//for(int ii=0;ii<mm.length;ii++){
// mm[0][ii] = 1;
//}
for(int i=0;i<T;i++){
String[] line = in.readLine().split(" ");
int A = Integer.parseInt(line[0]);
int B = Integer.parseInt(line[1]);
//System.out.print(" A = "+A+"\n");
//System.out.print(" B = "+B+"\n");
int ans = 0;
for(int j=A;j<B;j++){
int n=j;
if(n>=10){
String N = Integer.toString(n);
int nlen = N.length();
List<Integer> oks = new ArrayList<Integer>();
for(int k=0;k<nlen-1;k++){
String M = "";
for(int kk=1;kk<=nlen;kk++){
M = M + N.charAt((k+kk)%nlen);
}
int m = Integer.parseInt(M);
//System.out.print(" N = "+N+"\n");
//System.out.print(" M = "+M+"\n");
if(m>n && m<=B) {
boolean isNewOne = true;
for(int kkk=0;kkk<oks.size();kkk++){
//System.out.print(" KKK = "+oks.get(kkk)+"\n");
if(m==oks.get(kkk)){
isNewOne = false;
}
}
if(isNewOne){
//System.out.print(" N = "+N+"\n");
//System.out.print(" M = "+M+"\n");
oks.add(m);
ans++;
}
}
}
}
}
out.write("Case #"+(i+1)+": "+ans+"\n");
System.out.print("Case #"+(i+1)+": "+ans+"\n");
}
in.close();
out.close();
}catch(Exception e){
e.printStackTrace();
try{
in.close();
out.close();
}catch(Exception e1){
e1.printStackTrace();
}
}
System.out.print("YES!\n");
}
} | import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class CodeJamC
{
public static void main(String args[]) throws Exception
{
Scanner in = new Scanner(new File("in.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("out.txt"));
int cases = in.nextInt();
for(int casenum = 1;casenum <= cases;casenum++)
{
int a = in.nextInt();
int b = in.nextInt();
int count = 0;
HashMap<Integer,ArrayList<Integer>> map = new HashMap<Integer,ArrayList<Integer>>();
int len = ("" + a).length();
for(int n = a;n <= b;n++)
{
int t = n;
for(int i = 0;i<len-1;i++)
{
t = (t%10)*(int)(Math.pow(10,len-1)) + t/10;
if(t > n && t <= b)
{
if(map.containsKey(n))
{
if(!map.get(n).contains(t))
{
count++;
map.get(n).add(t);
}
}
else
{
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(t);
map.put(n,arr);
count++;
}
}
}
}
out.write("Case #" + casenum + ": " + count + "\n");
}
in.close();
out.close();
}
} |
A10996 | A10073 | 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.*;
/**
* @author Chris Dziemborowicz <chris@dziemborowicz.com>
* @version 2012.0414
*/
public class DancingWithTheGooglers
{
public static void main(String[] args)
throws Exception
{
// Get input files
File dir = new File("/Users/Chris/Documents/UniSVN/code-jam/dancing-with-the-googlers/data");
File[] inputFiles = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name)
{
return name.endsWith(".in");
}
});
// Learn score mappings
learn();
// Process each input file
for (File inputFile : inputFiles) {
System.out.printf("Processing \"%s\"...\n", inputFile.getName());
String outputPath = inputFile.getPath().replaceAll("\\.in$", ".out");
BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath));
Scanner scanner = new Scanner(inputFile);
System.out.printf("Number of test cases: %s\n", scanner.nextLine());
int count = 0;
while (scanner.hasNext()) {
String line = scanner.nextLine();
String output = String.format("Case #%d: %d\n", ++count, process(line));
System.out.print(output);
writer.write(output);
}
writer.close();
System.out.println("Done.\n");
}
// Compare to reference files (if any)
for (File inputFile : inputFiles) {
System.out.printf("Verifying \"%s\"...\n", inputFile.getName());
String referencePath = inputFile.getPath().replaceAll("\\.in$", ".ref");
String outputPath = inputFile.getPath().replaceAll("\\.in$", ".out");
File referenceFile = new File(referencePath);
if (referenceFile.exists()) {
InputStream referenceStream = new FileInputStream(referencePath);
InputStream outputStream = new FileInputStream(outputPath);
boolean matched = true;
int referenceRead, outputRead;
do {
byte[] referenceBuffer = new byte[4096];
byte[] outputBuffer = new byte[4096];
referenceRead = referenceStream.read(referenceBuffer);
outputRead = outputStream.read(outputBuffer);
matched = referenceRead == outputRead
&& Arrays.equals(referenceBuffer, outputBuffer);
} while (matched && referenceRead != -1);
if (matched) {
System.out.println("Verified.\n");
} else {
System.out.println("*** NOT VERIFIED ***\n");
}
} else {
System.out.println("No reference file found.\n");
}
}
}
private static int[] highestOrdinary = new int[31];
private static int[] highestSurprising = new int[31];
public static void learn()
{
Arrays.fill(highestOrdinary, -1);
Arrays.fill(highestSurprising, -1);
for (int i = 0; i <= 10; i++) {
for (int j = i; j <= i + 2 && j <= 10; j++) {
for (int k = j; k <= i + 2 && k <= 10; k++) {
int score = i + j + k;
if (k == i + 2) {
if (k > highestSurprising[score]) {
highestSurprising[score] = k;
}
} else {
if (k > highestOrdinary[score]) {
highestOrdinary[score] = k;
}
}
}
}
}
}
public static int process(String line)
{
// Parse input
Scanner scanner = new Scanner(line);
int num = scanner.nextInt();
int numSurprising = scanner.nextInt();
int p = scanner.nextInt();
int[] scores = new int[num];
for (int i = 0; i < num; i++) {
scores[i] = scanner.nextInt();
}
// Find surprising scores
int count = 0;
for (int score : scores) {
if (highestOrdinary[score] >= p) {
count++;
} else if (numSurprising > 0 && highestSurprising[score] >= p) {
numSurprising--;
count++;
}
}
return count;
}
} |
B10155 | B10886 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package codejam;
/**
*
* @author eblanco
*/
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import javax.swing.JFileChooser;
public class RecycledNumbers {
public static String DatosArchivo[] = new String[10000];
public static int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null) {
int intarray[] = new int[sarray.length];
for (int i = 0; i < sarray.length; i++) {
intarray[i] = Integer.parseInt(sarray[i]);
}
return intarray;
}
return null;
}
public static boolean CargarArchivo(String arch) throws FileNotFoundException, IOException {
FileInputStream arch1;
DataInputStream arch2;
String linea;
int i = 0;
if (arch == null) {
//frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));
int rc = fc.showDialog(null, "Select a File");
if (rc == JFileChooser.APPROVE_OPTION) {
arch = fc.getSelectedFile().getAbsolutePath();
} else {
System.out.println("No hay nombre de archivo..Yo!");
return false;
}
}
arch1 = new FileInputStream(arch);
arch2 = new DataInputStream(arch1);
do {
linea = arch2.readLine();
DatosArchivo[i++] = linea;
/* if (linea != null) {
System.out.println(linea);
}*/
} while (linea != null);
arch1.close();
return true;
}
public static boolean GuardaArchivo(String arch, String[] Datos) throws FileNotFoundException, IOException {
FileOutputStream out1;
DataOutputStream out2;
int i;
out1 = new FileOutputStream(arch);
out2 = new DataOutputStream(out1);
for (i = 0; i < Datos.length; i++) {
if (Datos[i] != null) {
out2.writeBytes(Datos[i] + "\n");
}
}
out2.close();
return true;
}
public static void echo(Object msg) {
System.out.println(msg);
}
public static void main(String[] args) throws IOException, Exception {
String[] res = new String[10000], num = new String[2];
int i, j, k, ilong;
int ele = 1;
ArrayList al = new ArrayList();
String FName = "C-small-attempt0", istr, irev, linea;
if (CargarArchivo("C:\\eblanco\\Desa\\CodeJam\\Code Jam\\test\\" + FName + ".in")) {
for (j = 1; j <= Integer.parseInt(DatosArchivo[0]); j++) {
linea = DatosArchivo[ele++];
num = linea.split(" ");
al.clear();
// echo("A: "+num[0]+" B: "+num[1]);
for (i = Integer.parseInt(num[0]); i <= Integer.parseInt(num[1]); i++) {
istr = Integer.toString(i);
ilong = istr.length();
for (k = 1; k < ilong; k++) {
if (ilong > k) {
irev = istr.substring(istr.length() - k, istr.length()) + istr.substring(0, istr.length() - k);
//echo("caso: " + j + ": isrt: " + istr + " irev: " + irev);
if ((Integer.parseInt(irev) > Integer.parseInt(num[0])) && (Integer.parseInt(irev) > Integer.parseInt(istr)) && (Integer.parseInt(irev) <= Integer.parseInt(num[1]))) {
al.add("(" + istr + "," + irev + ")");
}
}
}
}
HashSet hs = new HashSet();
hs.addAll(al);
al.clear();
al.addAll(hs);
res[j] = "Case #" + j + ": " + al.size();
echo(res[j]);
LeerArchivo.GuardaArchivo("C:\\eblanco\\Desa\\CodeJam\\Code Jam\\test\\" + FName + ".out", res);
}
}
}
}
| package de.at.codejam.util;
import java.io.IOException;
public interface InputFileParser<CASE> {
void initialize(TaskStatus taskStatus);
TaskStatus getTaskStatus();
boolean hasNextCase();
CASE getNextCase() throws IOException;
}
|
A12460 | A11587 | 0 | /**
*
*/
package pandit.codejam;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Scanner;
/**
* @author Manu Ram Pandit
*
*/
public class DancingWithGooglersUpload {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
FileInputStream fStream = new FileInputStream(
"input.txt");
Scanner scanner = new Scanner(new BufferedInputStream(fStream));
Writer out = new OutputStreamWriter(new FileOutputStream("output.txt"));
int T = scanner.nextInt();
int N,S,P,ti;
int counter = 0;
for (int count = 1; count <= T; count++) {
N=scanner.nextInt();
S = scanner.nextInt();
counter = 0;
P = scanner.nextInt();
for(int i=1;i<=N;i++){
ti=scanner.nextInt();
if(ti>=(3*P-2)){
counter++;
continue;
}
else if(S>0){
if(P>=2 && ((ti==(3*P-3)) ||(ti==(3*P-4)))) {
S--;
counter++;
continue;
}
}
}
// System.out.println("Case #" + count + ": " + counter);
out.write("Case #" + count + ": " + counter + "\n");
}
fStream.close();
out.close();
}
}
| package ru.sidorkevich.google.jam.qualification.b;
import java.util.List;
public class Task {
int n;
int s;
int p;
List<Integer> t;
public Task(int n, int s, int p, List<Integer> t) {
this.n = n;
this.s = s;
this.p = p;
this.t = t;
}
public int getN() {
return n;
}
public int getS() {
return s;
}
public int getP() {
return p;
}
public List<Integer> getT() {
return t;
}
@Override
public String toString() {
return "Task{" +
"n=" + n +
", s=" + s +
", p=" + p +
", t=" + t +
'}';
}
}
|
B11327 | B11395 | 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]);
}
}
}
| /*
Author: Gaurav Gupta
Date: 14 Apr 2012
*/
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Recycled {
/**
* TODO Put here a description of what this method does.
*
* @param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub.
FileWriter fw = new FileWriter("Output3.txt");
PrintWriter pw = new PrintWriter(fw);
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
int sum = 0;
int A, B;
for (int i = 0; i < T; i++) {
A = sc.nextInt();
B = sc.nextInt();
sum = 0;
for (int j = A; j <= B; j++) {
int n = j;
int m;
String ns = String.valueOf(n);
String ms;
int count = 0;
int found = 0;
int rep[] = new int[ns.length()];
for (int k = 0; k < ns.length(); k++) {
ms = ns.substring(k, ns.length()) + ns.substring(0, k);
m = Integer.parseInt(ms);
if (m > n && m >= A && m <= B) {
found = 0;
for (int l = 0; l < count; l++)
if (rep[l] == m) {
found = 1;
}
if (found == 0) {
rep[count] = m;
count++;
sum++;
// System.out.println(n + " " + m);
}
}
}
}
pw.println("Case #" + (i + 1) + ": " + sum);
System.out.println("Case #" + (i + 1) + ": " + sum);
}
pw.close();
}
}
|
B12115 | B10638 | 0 | package qual;
import java.util.Scanner;
public class RecycledNumbers {
public static void main(String[] args) {
new RecycledNumbers().run();
}
private void run() {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int t = 0; t < T; t++) {
int A = sc.nextInt();
int B = sc.nextInt();
int result = solve(A, B);
System.out.printf("Case #%d: %d\n", t + 1, result);
}
}
public int solve(int A, int B) {
int result = 0;
for (int i = A; i <= B; i++) {
int dig = (int) Math.log10(A/*same as B*/) + 1;
int aa = i;
for (int d = 0; d < dig - 1; d++) {
aa = (aa % 10) * (int)Math.pow(10, dig - 1) + (aa / 10);
if (i == aa) {
break;
}
if (i < aa && aa <= B) {
// System.out.printf("(%d, %d) ", i, aa);
result++;
}
}
}
return result;
}
}
| import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class C{
public static void main(String[] args) throws FileNotFoundException
{
Scanner sc = new Scanner(new File("C.txt"));
int testCase = Integer.parseInt(sc.nextLine());
for(int Case=1; Case<=testCase; Case++)
{
int total = 0;
int st = sc.nextInt();int en = sc.nextInt();
int len = (new Integer(st)).toString().length();
for(int i=en; i>=st;i--)
{
Set s = new HashSet();
for(int j=1; j<=len-1;j++)
{
String sam = (new Integer(i).toString());
//System.out.println(i+ "Actual String:" + sam);
StringBuffer temp=new StringBuffer();
//System.out.println("temp 1:"+temp.toString());
temp.append(sam.substring(j));
//System.out.println("temp 2:"+temp.toString());
temp.append(sam.substring(0, j));
//System.out.println("temp 3:"+temp.toString());
int num = Integer.parseInt(temp.toString());
if(num>=st && num<=en && num<i){s.add(num);}
}
total += s.size();
}
System.out.println("Case #"+Case+": "+total);
}
}
} |
B11318 | B11837 | 0 | import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
int casos=1, a, b, n, m, cont;
while(t!=0){
a=sc.nextInt();
b=sc.nextInt();
if(a>b){
int aux=a;
a=b;
b=aux;
}
System.out.printf("Case #%d: ",casos++);
if(a==b){
System.out.printf("%d\n",0);
}else{
cont=0;
for(n=a;n<b;n++){
for(m=n+1;m<=b;m++){
if(isRecycled(n,m)) cont++;
}
}
System.out.printf("%d\n",cont);
}
t--;
}
}
public static boolean isRecycled(int n1, int n2){
String s1, s2, aux;
s1 = String.valueOf( n1 );
s2 = String.valueOf( n2 );
boolean r = false;
for(int i=0;i<s1.length();i++){
aux="";
aux=s1.substring(i,s1.length())+s1.substring(0,i);
// System.out.println(aux);
if(aux.equals(s2)){
r=true;
break;
}
}
return r;
}
}
| import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
public class Numbers {
public static FileReader fr;
public static BufferedReader br;
public static FileWriter fw;
public static BufferedWriter bw;
public void read(String path) throws Exception
{
fr = new FileReader(path);
br=new BufferedReader(fr);
}
public void write(String path) throws Exception
{
}
public void execute(BufferedReader br,String path)throws Exception
{
String s;
fw =new FileWriter(path,false);
bw=new BufferedWriter(fw);
s=br.readLine();
int i1=1;
while((s=br.readLine())!=null)
{
int count =0;
String st[]=s.split("\\s");
int a=Integer.parseInt(st[0]);
int b=Integer.parseInt(st[1]);
for(int i=a;i<=b;i++)
{
int temp=i;
String abc=Integer.toString(temp);
int length=abc.length();
int index=length-1;
String tempString=abc;
while(index>0)
{
String first=tempString.substring(0, index);
String second=tempString.substring(index,length);
abc=second+first;
int newnumber=Integer.parseInt(abc);
if((newnumber<=b && newnumber>temp )&& !abc.startsWith("0") && (Integer.toString(temp).length())==abc.length())
count++;
index--;
}
}
bw.write("Case #"+ i1++ +": " +count +"\n");
}
bw.close();
fr.close();
}
public static void main(String[] args) throws Exception
{
Numbers t=new Numbers();
t.read("E:\\codejam\\Files\\A.in");
t.execute(br,"E:\\codejam\\Files\\A.out");
}
}
|
A20382 | A20695 | 0 | package dancinggooglers;
import java.io.File;
import java.util.Scanner;
public class DanceScoreCalculator {
public static void main(String[] args) {
if(args.length <= 0 || args[0] == null) {
System.out.println("You must enter a file to read");
System.out.println("Usage: blah <filename>");
System.exit(0);
}
File argFile = new File(args[0]);
try {
Scanner googleSpeakScanner = new Scanner(argFile);
String firstLine = googleSpeakScanner.nextLine();
Integer linesToScan = new Integer(firstLine);
for(int i = 1; i <= linesToScan; i++) {
String googleDancerLine = googleSpeakScanner.nextLine();
DanceScoreCase danceCase = new DanceScoreCase(googleDancerLine);
System.out.println(String.format("Case #%d: %d", i, danceCase.maxDancersThatCouldPass()));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| package quiz.number05;
import java.io.*;
import java.util.Arrays;
/**
* @author Keesun Baik
*/
public class KeesunDancingTest {
public static void main(String[] args) throws IOException {
KeesunDancingTest dancing = new KeesunDancingTest();
BufferedReader in = new BufferedReader(new FileReader("/workspace/telepathy/test/quiz/number05/B-large.in"));
String s;
int lineNum = 0;
int problemNum = 0;
String answer = "";
while ((s = in.readLine()) != null) {
if (s.isEmpty()) {
return;
}
if (lineNum == 0) {
problemNum = Integer.parseInt(s);
} else {
answer += "Case #" + lineNum + ": " + dancing.figureP(s) + "\n";
}
lineNum++;
}
in.close();
System.out.println(answer);
BufferedWriter out = new BufferedWriter(new FileWriter("/workspace/telepathy/test/quiz/number05/B-large.out"));
out.write(answer);
out.close();
}
private int figureP(String s) {
String[] inputs = s.split(" ");
int people = Integer.parseInt(inputs[0]);
int surprise = Integer.parseInt(inputs[1]);
int minScore = Integer.parseInt(inputs[2]);
String[] scoreStrings = Arrays.copyOfRange(inputs, 3, inputs.length);
int[] scores = new int[scoreStrings.length];
for (int i = 0; i < scoreStrings.length; i++) {
scores[i] = Integer.parseInt(scoreStrings[i]);
}
int cases = 0;
for (int score : scores) {
int base = score / 3;
switch (score % 3) {
case 0: {
System.out.println("0");
if (base >= minScore) {
cases++;
} else if (surprise > 0 && base > 0 && base + 1 >= minScore) {
cases++;
surprise--;
}
break;
}
case 1: {
System.out.println("1");
if (base >= minScore || base + 1 >= minScore) {
cases++;
} else if (surprise > 0 && base + 1 >= minScore) {
cases++;
surprise--;
}
break;
}
case 2: {
System.out.println("2");
if (base + 1 >= minScore || base >= minScore) {
cases++;
} else if (surprise > 0 && base + 2 >= minScore) {
cases++;
surprise--;
}
break;
}
}
}
return cases;
}
}
|
B10245 | B10262 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package recyclednumbers;
import java.util.HashSet;
/**
*
* @author vandit
*/
public class RecycleNumbers {
private HashSet<String> numbers = new HashSet<String>();
private HashSet<String> initialTempNumbers = new HashSet<String>();
private HashSet<String> finalTempNumbers = new HashSet<String>();
HashSet<Pair> numberPairs = new HashSet<Pair>();
private void findRecycledNumbers(int start, int end, int places) {
for (int i = start; i <= end; i++) {
String initialNumber = Integer.toString(i);
//if (!(numbers.contains(initialNumber) || finalTempNumbers.contains(initialNumber))) {
StringBuffer tempNumber = new StringBuffer(initialNumber);
int len = tempNumber.length();
int startIndexToMove = len - places;
String tempString = tempNumber.substring(startIndexToMove);
if ((places == 1 && tempString.equals("0")) || tempString.charAt(0) == '0') {
continue;
}
tempNumber.delete(startIndexToMove, len);
String finalTempNumber = tempString + tempNumber.toString();
if (! (finalTempNumber.equals(initialNumber) || Integer.parseInt(finalTempNumber) > end || Integer.parseInt(finalTempNumber) < Integer.parseInt(initialNumber))) {
numbers.add(initialNumber);
finalTempNumbers.add(finalTempNumber);
Pair pair = new Pair(finalTempNumber,initialNumber);
numberPairs.add(pair);
}
}
}
public HashSet<Pair> findAllRecycledNumbers(int start, int end) {
int length = Integer.toString(start).length();
for (int i = 1; i < length; i++) {
findRecycledNumbers(start, end, i);
}
return numberPairs;
}
}
| package core;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public abstract class Template {
/************* TO BE IMPLEMENTED ******************************************/
public abstract void feedData(ExtendedBufferedReader iR);
public abstract StringBuffer applyMethods();
/**************************************************************************/
public void readData(File iFile){
try {
FileReader aReader = new FileReader(iFile);
ExtendedBufferedReader aBufferedReader = new ExtendedBufferedReader(aReader);
feedData(aBufferedReader);
aBufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeResult(File iFile,StringBuffer iResult){
System.out.println(iResult.toString());
try {
FileWriter aWriter = new FileWriter(iFile);
aWriter.write(iResult.toString());
aWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void play(String[] args) {
if (args.length>1) {
File aFile = new File(args[0]);
readData(aFile);
StringBuffer result = applyMethods();
File aResultFile= new File(args[1]);
writeResult(aResultFile,result);
} else {
System.out.println("Your a bastard ! missing argument !");
}
}
}
|
B12941 | B10807 | 0 | package com.menzus.gcj._2012.qualification.c;
import com.menzus.gcj.common.InputBlockParser;
import com.menzus.gcj.common.OutputProducer;
import com.menzus.gcj.common.impl.AbstractProcessorFactory;
public class CProcessorFactory extends AbstractProcessorFactory<CInput, COutputEntry> {
public CProcessorFactory(String inputFileName) {
super(inputFileName);
}
@Override
protected InputBlockParser<CInput> createInputBlockParser() {
return new CInputBlockParser();
}
@Override
protected OutputProducer<CInput, COutputEntry> createOutputProducer() {
return new COutputProducer();
}
}
| package codejam;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class RecycledPairs {
private static String filename = "C-small-attempt0.in";
public static boolean isRecycledPair(int n, int m) {
String sn = Integer.toString(n);
String sm = Integer.toString(m);
int length = sn.length();
String shiftedString = "";
for (int i = 1; i <= length; i++) {
shiftedString = sn.substring(i, length) + sn.substring(0, i);
//System.out.println(shiftedString + " " + sn + " " + sm);
if (shiftedString.equals(sm)) return true;
}
return false;
}
public static int recycledPairs(int A, int B) {
int acc = 0;
for (int n = A, m; n < B; n++) {
m = n + 1;
for (; m <= B; m++) {
if (isRecycledPair(n, m)) acc++;
}
}
return acc;
}
public static void main(String[] args) {;
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
BufferedWriter out = new BufferedWriter(new FileWriter(filename + ".out"));
String currentString = in.readLine();
int testCases = Integer.parseInt(currentString);
for (int i = 1; i <= testCases; i++) {
String[] input = in.readLine().split(" ");
int A = Integer.parseInt(input[0]);
int B = Integer.parseInt(input[1]);
int result = recycledPairs(A, B);
out.write("Case #" + i + ": " + result + '\n');
}
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
B10858 | B12448 | 0 | package be.mokarea.gcj.common;
public abstract class TestCaseReader<T extends TestCase> {
public abstract T nextCase() throws Exception;
public abstract int getMaxCaseNumber();
}
| package qual;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class C {
public static int[] prepare(int m, int base, int k){
int[] res = new int[m];
for (int i = 0; i < m; i++){
int rest = k % 10;
k /= 10;
k += rest * base;
res[i] = k;
}
return res;
}
public static void main(String[] args) throws Exception{
String in_file = "q/c/s_in.txt";
String out_file = in_file.replace("_in.txt", "_out.txt");
BufferedReader in = new BufferedReader(new FileReader(in_file));
BufferedWriter out = new BufferedWriter(new FileWriter(out_file));
int n = Integer.parseInt(in.readLine());
for (int i = 1; i <= n; i++){
String[] s = in.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
int count = 0;
int base = 1;
int m = 0;
while (base * 10 <= a) {
base *= 10;
m++;
}
for (int k = a; k < b; k++){
int[] prob = prepare(m, base, k);
for (int p : prob){
if (p > k && p <= b) count++;
}
}
out.write("Case #" + i + ": " + count + "\n");
}
in.close();
out.close();
}
}
|
A12570 | A12911 | 0 | package util.graph;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;
public class DynDjikstra {
public static State FindShortest(Node start, Node target) {
PriorityQueue<Node> openSet = new PriorityQueue<>();
Set<Node> closedSet = new HashSet<>();
openSet.add(start);
while (!openSet.isEmpty()) {
Node current = openSet.poll();
for (Edge edge : current.edges) {
Node end = edge.target;
if (closedSet.contains(end)) {
continue;
}
State newState = edge.travel(current.last);
//if (end.equals(target)) {
//return newState;
//}
if (openSet.contains(end)) {
if (end.last.compareTo(newState)>0) {
end.last = newState;
}
} else {
openSet.add(end);
end.last = newState;
}
}
closedSet.add(current);
if (closedSet.contains(target)) {
return target.last;
}
}
return target.last;
}
}
| package com.menzus.gcj._2012.qualification.b;
import com.menzus.gcj.common.OutputEntry;
public class BOutputEntry implements OutputEntry {
private int maximumGooglersNumber;
public void setMaximumGooglersNumber(int maximumGooglersNumber) {
this.maximumGooglersNumber = maximumGooglersNumber;
}
@Override
public String formatOutput() {
return Integer.toString(maximumGooglersNumber);
}
}
|
A11277 | A13003 | 0 | package googlers;
import java.util.Scanner;
import java.util.PriorityQueue;
import java.util.Comparator;
public class Googlers {
public static void main(String[] args) {
int n,s,p,count=0,t;
Scanner sin=new Scanner(System.in);
t=Integer.parseInt(sin.nextLine());
int result[]=new int[t];
int j=0;
if(t>=1 && t<=100)
{
for (int k = 0; k < t; k++) {
count=0;
String ip = sin.nextLine();
String[]tokens=ip.split(" ");
n=Integer.parseInt(tokens[0]);
s=Integer.parseInt(tokens[1]);
p=Integer.parseInt(tokens[2]);
if( (s>=0 && s<=n) && (p>=0 && p<=10) )
{
int[] total=new int[n];
for (int i = 0; i < n; i++)
{
total[i] = Integer.parseInt(tokens[i+3]);
}
Comparator comparator=new PointComparator();
PriorityQueue pq=new PriorityQueue<Point>(1, comparator);
for (int i = 0; i < n; i++)
{
int x=total[i]/3;
int r=total[i]%3;
if(x>=p)
count++;
else if(x<(p-2))
continue;
else
{
//System.out.println("enter "+x+" "+(p-2));
if(p-x==1)
{
Point temp=new Point();
temp.q=x;
temp.r=r;
pq.add(temp);
}
else // p-x=2
{
if(r==0)
continue;
else
{
Point temp=new Point();
temp.q=x;
temp.r=r;
pq.add(temp);
}
}
}
//System.out.println("hi "+pq.size());
}
while(pq.size()!=0)
{
Point temp=(Point)pq.remove();
if(p-temp.q==1 && temp.q!=0)
{
if(temp.r>=1)
count++;
else
{
if(s!=0)
{
s--;
count++;
}
}
}
else if(p-temp.q==2)
{
if(s!=0 && (temp.q+temp.r)>=p)
{
s--;
count++;
}
}
}
//System.out.println(p);
result[j++]=count;
}
}
for (int i = 0; i < t; i++)
{
System.out.println("Case #"+(i+1)+": "+result[i]);
}
}
}
/*Point x=new Point();
x.q=8;
Point y=new Point();
y.q=6;
Point z=new Point();
z.q=7;
pq.add(x);
pq.add(y);
pq.add(z);
*/
}
class PointComparator implements Comparator<Point>
{
@Override
public int compare(Point x, Point y)
{
// Assume neither string is null. Real code should
// probably be more robust
if (x.q < y.q)
{
return 1;
}
if (x.q > y.q)
{
return -1;
}
return 0;
}
}
class Point
{
int q,r;
public int getQ() {
return q;
}
public void setQ(int q) {
this.q = q;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
}
| package codejam;
public class Dancer extends CodeJam{
public Dancer() {
super("B-small-attempt0");
}
public static void main(String[] args) {
new Dancer().run();
}
@Override
protected String solve() {
int n = scanner.nextInt();
int s = scanner.nextInt();
int p = scanner.nextInt();
if (p == 0){
scanner.nextLine();
return n + "";
}
if (p == 1){
s = 0;
}
int sum = 3*p - 2;
int sum2 = 3*p - 4;
int count = 0;
for (int i = 0 ; i < n ; i++){
int v = scanner.nextInt();
if (v >= sum){
count++;
} else if (v >= sum2 && s-- > 0){
count++;
}
}
return count + "";
}
}
|
B11318 | B12113 | 0 | import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
int casos=1, a, b, n, m, cont;
while(t!=0){
a=sc.nextInt();
b=sc.nextInt();
if(a>b){
int aux=a;
a=b;
b=aux;
}
System.out.printf("Case #%d: ",casos++);
if(a==b){
System.out.printf("%d\n",0);
}else{
cont=0;
for(n=a;n<b;n++){
for(m=n+1;m<=b;m++){
if(isRecycled(n,m)) cont++;
}
}
System.out.printf("%d\n",cont);
}
t--;
}
}
public static boolean isRecycled(int n1, int n2){
String s1, s2, aux;
s1 = String.valueOf( n1 );
s2 = String.valueOf( n2 );
boolean r = false;
for(int i=0;i<s1.length();i++){
aux="";
aux=s1.substring(i,s1.length())+s1.substring(0,i);
// System.out.println(aux);
if(aux.equals(s2)){
r=true;
break;
}
}
return r;
}
}
| package com.renoux.gael.codejam.fwk;
import java.io.File;
import com.renoux.gael.codejam.utils.FluxUtils;
import com.renoux.gael.codejam.utils.Input;
import com.renoux.gael.codejam.utils.Output;
import com.renoux.gael.codejam.utils.Timer;
public abstract class Solver {
public void run() {
Timer.start();
if (!disableSample())
runOnce(getSampleInput(), getSampleOutput());
System.out.println(Timer.check());
Timer.start();
if (!disableSmall())
runOnce(getSmallInput(), getSmallOutput());
System.out.println(Timer.check());
Timer.start();
if (!disableLarge())
runOnce(getLargeInput(), getLargeOutput());
System.out.println(Timer.check());
}
public void runOnce(String pathIn, String pathOut) {
Input in = null;
Output out = null;
try {
in = Input.open(getFile(pathIn));
out = Output.open(getFile(pathOut));
int countCases = Integer.parseInt(in.readLine());
for (int k = 1; k <= countCases; k++) {
out.write("Case #", k, ": ");
solveCase(in, out);
}
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
FluxUtils.closeCloseables(in, out);
}
}
private File getFile(String path) {
return new File(path);
}
protected abstract void solveCase(Input in, Output out);
private String getFullPath(boolean input, String type) {
if (input)
return "D:\\Downloads\\CodeJam\\" + getProblemName() + "\\"
+ getProblemName() + "_input_" + type + ".txt";
else
return "D:\\Downloads\\CodeJam\\" + getProblemName() + "\\"
+ getProblemName() + "_output_" + type + ".txt";
}
protected String getSampleInput() {
return getFullPath(true, "sample");
}
protected String getSmallInput() {
return getFullPath(true, "small");
}
protected String getLargeInput() {
return getFullPath(true, "large");
}
protected String getSampleOutput() {
return getFullPath(false, "sample");
}
protected String getSmallOutput() {
return getFullPath(false, "small");
}
protected String getLargeOutput() {
return getFullPath(false, "large");
}
protected boolean disableSample() {
return disable()[0];
}
protected boolean disableSmall() {
return disable()[1];
}
protected boolean disableLarge() {
return disable()[2];
}
protected boolean[] disable() {
return new boolean[] { false, false, false };
}
protected abstract String getProblemName();
}
|
B20566 | B20183 | 0 | import java.util.Scanner;
import java.io.*;
import java.lang.Math;
public class C{
public static int recycle(String str){
String[] numbers = str.split(" ");
int min = Integer.parseInt(numbers[0]);
int max = Integer.parseInt(numbers[1]);
int ret = 0;
for(int i = min; i < max; i++){
String num = i + "";
int len = num.length();
int k = i;
for(int j = 1; j < len; j++){
k = (k/10) + (int)java.lang.Math.pow(10.0,(double)(len-1))*(k%10);
if (k > i && k <= max)
ret++;
else if(k == i)
break;
}
}
return ret;
}
public static void main(String[] args){
Scanner sc = null;
String next;
int out;
try{
sc = new Scanner(new File("C-large.in"));
int cases = Integer.parseInt(sc.nextLine());
int current = 0;
FileWriter fs = new FileWriter("output.txt");
BufferedWriter buff = new BufferedWriter(fs);
while(current < cases){
next = sc.nextLine();
current++;
out = recycle(next);
buff.write("Case #" + current + ": " + out + "\n");
}
buff.close();
}
catch(Exception ex){}
}
} | import java.io.*;
import java.util.*;
import java.text.*;
public class Main implements Runnable{
/**
* @param args
*/
private StringTokenizer stReader;
private BufferedReader bufReader;
private PrintWriter out;
public static void main(String[] args) {
// TODO Auto-generated method stub
(new Main()).run();
}
@Override
public void run() {
// TODO Auto-generated method stub
bufReader = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
stReader = null;
Solves();
out.flush();
}
public String ReadLine() {
String result = null;
try {
result = bufReader.readLine();
} catch (IOException e) {
}
return result;
}
public String NextString(){
if (stReader == null || !stReader.hasMoreTokens()){
stReader = new StringTokenizer(ReadLine(),"\n\r ");
}
return stReader.nextToken();
}
public int NextInt(){
return Integer.parseInt(NextString());
}
public long NextLong(){
return Long.parseLong(NextString());
}
public double NextDouble(){
return Double.parseDouble(NextString());
}
void Solves(){
int n = NextInt();
for(int i =0; i < n; i++){
out.print("Case #" +(i + 1) + ": ");
Solve();
out.println();
}
out.flush();
}
void Solve(){
int A = NextInt();
int B = NextInt();
int result = 0;
TreeSet<Integer> treeSet = new TreeSet<Integer>();
for(int i = A; i <=B; i++){
if (i <= 10) continue;
StringBuilder parse = new StringBuilder(String.valueOf(i));
treeSet.clear();
for(int j =0;j < parse.length(); j++){
int val = Shift(parse);
if (val > i && val <= B && !treeSet.contains(val)) {
result++;
treeSet.add(val);
}
}
treeSet.clear();
}
out.print(result);
}
int Shift(StringBuilder parse){
char last = parse.charAt(parse.length()-1);
parse = parse.deleteCharAt(parse.length()-1);
parse = parse.insert(0, last);
return Integer.valueOf(parse.toString());
}
}
|
A21557 | A23051 | 0 | import java.io.*;
import java.util.*;
public class DancingWithGooglers {
public static class Googlers {
public int T;
public int surp;
public boolean surprising;
public boolean pSurprising;
public boolean antiSurprising;
public boolean pAntiSurprising;
public Googlers(int T, int surp) {
this.T = T;
this.surp = surp;
}
public void set(int a, int b, int c) {
if (c >= 0 && (a + b + c) == T) {
int diff = (Math.max(a, Math.max(b, c)) - Math.min(a, Math.min(b, c)));
if (diff <= 2) {
if (diff == 2) {
if (a >= surp || b >= surp || c >= surp) {
pSurprising = true;
} else {
surprising = true;
}
} else {
if (a >= surp || b >= surp || c >= surp) {
pAntiSurprising = true;
} else {
antiSurprising = true;
}
}
}
}
}
}
public static void main(String... args) throws IOException {
// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader reader = new BufferedReader(new FileReader("B-large.in"));
// PrintWriter writer = new PrintWriter(System.out);
PrintWriter writer = new PrintWriter("B-large.out");
int len, cases = Integer.parseInt(reader.readLine());
List<Googlers> satisfied = new ArrayList<Googlers>();
List<Googlers> unsatisfied = new ArrayList<Googlers>();
String[] inputs;
int N, S, p;
for (int i = 1; i <= cases; i++) {
inputs = reader.readLine().split(" ");
p = Integer.parseInt(inputs[1]);
S = Integer.parseInt(inputs[2]);
satisfied.clear();
unsatisfied.clear();
for (int j = 3; j < inputs.length; j++) {
int t = Integer.parseInt(inputs[j]);
Googlers googlers = new Googlers(t, S);
for (int k = 0; k <= 10; k++) {
int till = k + 2 > 10 ? 10 : k + 2;
for (int l = k; l <= till; l++) {
googlers.set(k, l, (t - (k + l)));
}
}
if (googlers.pAntiSurprising) {
satisfied.add(googlers);
} else {
unsatisfied.add(googlers);
}
}
int pSurprising = 0;
if (p > 0) {
for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.pSurprising) {
pSurprising++;
iter.remove();
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.surprising) {
iter.remove();
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.pSurprising) {
iter.remove();
pSurprising++;
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.surprising) {
iter.remove();
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
writer.print("Case #" + i + ": 0");
}else {
writer.print("Case #" + i + ": " + (satisfied.size() + pSurprising));
}
writer.println();
}
writer.flush();
}
}
| package dancing;
import java.io.BufferedReader;
import java.io.FileReader;
public class MaxScoreDetector {
/**
* @param args
*/
public static void main(String[] args) {
String fileName = null;
if(args.length == 1){
fileName = args[0];
}else{
System.err.println("Requires a command line argument: fileName");
System.exit(1);
};
new MaxScoreDetector(fileName);
}
public MaxScoreDetector(String fileName){
try{
BufferedReader in = new BufferedReader(new FileReader(fileName));
int cases = Integer.parseInt(in.readLine());
for(int i=0; i<cases; i++){
String[] line = in.readLine().split(" ");
int numScores = Integer.parseInt(line[0]);
int specials = Integer.parseInt(line[1]);
int min = Integer.parseInt(line[2]);
int[] scores = new int[numScores];
for(int j=0; j<scores.length; j++){
scores[j] = Integer.parseInt(line[j+3]);
}
System.out.println("Case #" + (i+1) + ": " + testScores(scores, min, specials));
}
}catch(Exception e){
e.printStackTrace();
}
}
public int testScores(int[] scores, int min, int specials){
int over = specials;
int count = 0;
for(int i=0; i<scores.length; i++){
if(scores[i] < min) continue;
double avg = scores[i]/3.;
if(avg >= min || Math.ceil(avg)>=min){
count++;
continue;
}
if(Math.round(avg) == (int)avg + 1 && Math.round(avg) + 1 >= min && over > 0){
count++;
over--;
continue;
}
if(avg == (int)avg && avg + 1 >= min && over > 0){
over--;
count++;
continue;
}
}
return count;
}
}
|
A20382 | A21672 | 0 | package dancinggooglers;
import java.io.File;
import java.util.Scanner;
public class DanceScoreCalculator {
public static void main(String[] args) {
if(args.length <= 0 || args[0] == null) {
System.out.println("You must enter a file to read");
System.out.println("Usage: blah <filename>");
System.exit(0);
}
File argFile = new File(args[0]);
try {
Scanner googleSpeakScanner = new Scanner(argFile);
String firstLine = googleSpeakScanner.nextLine();
Integer linesToScan = new Integer(firstLine);
for(int i = 1; i <= linesToScan; i++) {
String googleDancerLine = googleSpeakScanner.nextLine();
DanceScoreCase danceCase = new DanceScoreCase(googleDancerLine);
System.out.println(String.format("Case #%d: %d", i, danceCase.maxDancersThatCouldPass()));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| package com.google.codejam.p2;
import java.util.ArrayList;
public class TestCase {
public int N,S,p;
public ArrayList<Integer> scores;
public TestCase(int N, int S, int p, ArrayList<Integer> scores) {
this.N = N;
this.S = S;
this.p = p;
this.scores = scores;
}
}
|
B12941 | B10322 | 0 | package com.menzus.gcj._2012.qualification.c;
import com.menzus.gcj.common.InputBlockParser;
import com.menzus.gcj.common.OutputProducer;
import com.menzus.gcj.common.impl.AbstractProcessorFactory;
public class CProcessorFactory extends AbstractProcessorFactory<CInput, COutputEntry> {
public CProcessorFactory(String inputFileName) {
super(inputFileName);
}
@Override
protected InputBlockParser<CInput> createInputBlockParser() {
return new CInputBlockParser();
}
@Override
protected OutputProducer<CInput, COutputEntry> createOutputProducer() {
return new COutputProducer();
}
}
| package sebastianco;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashSet;
import java.util.Set;
public class RecycledNumbers {
public static void main(String[] args) throws Exception {
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(new File(args[0])));
writer = new BufferedWriter(new FileWriter(new File(args[1])));
final int nrOfTestCases = Integer.valueOf(reader.readLine());
String lineSepartor = "";
for (int i = 1; i <= nrOfTestCases; i++) {
writer.write(lineSepartor);
writer.write(String.format("Case #%d: %d",
i, new TestCase(reader.readLine()).computePairs()));
lineSepartor = "\n";
}
} finally {
if (writer != null) {
writer.flush();
writer.close();
}
reader.close();
}
}
public static class TestCase {
private int a;
private int b;
public TestCase(String caseLine) {
String[] tokens = caseLine.split(" ");
a = Integer.parseInt(tokens[0]);
b = Integer.parseInt(tokens[1]);
}
public int computePairs() {
Set<String> distinctPairs = new HashSet<String>();
final String strB = String.valueOf(b);
final int maxRotations = strB.length() - 1;
int recycledPairs = 0;
for (int i = a; i < b; i++) {
String strI = String.valueOf(i); // System.out.println("==" + strI);
StringBuilder number = new StringBuilder(strI);
for (int j = 1; j <= maxRotations; j++) {
rotate(number);
String strNumber = number.toString();
if (strI.compareTo(strNumber) < 0
&& strNumber.compareTo(strB) <= 0) {
if (distinctPairs.add(strI + strNumber)) {
recycledPairs++; // System.out.println(strNumber);
}
}
}
}
return recycledPairs;
}
private void rotate(StringBuilder number) {
char c = number.charAt(number.length() - 1);
for (int i = number.length() - 1; i > 0; i--) {
number.setCharAt(i, number.charAt(i-1));
}
number.setCharAt(0, c);
}
}
}
|
B10361 | B10927 | 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);
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package codejam.y12.round0;
import utils.Jam;
import utils.JamCase;
/**
*
* @author fabien
*/
public class DancingGooglers extends Jam {
public DancingGooglers(String filename) {
super(filename);
}
@Override
public JamCase getJamCase(int number) {
return new Line(this, number, lines[number]);
}
private class Line extends JamCase {
private String line;
private int s;
private int p;
private int[] scores;
public Line(Jam parent, int number, String line) {
super(parent, number);
this.line = line;
}
@Override
public void parse() {
String[] integers = line.split(" ");
scores = new int[Integer.parseInt(integers[0])];
s = Integer.parseInt(integers[1]);
p = Integer.parseInt(integers[2]);
int j = 0;
for (int i = 3; i < integers.length; i++) {
scores[j++] = Integer.parseInt(integers[i]);
}
}
@Override
public void solve() {
int r = 0;
if (p == 0) {
r = scores.length;
} else {
float average = 0;
float pnor = p - 1;
float psus = p - 1.4f;
for (int score : scores) {
if (score > 0) {
average = score / 3.0f;
if (average > pnor) {
r++;
} else if (s > 0 && average >= psus) {
r++;
s--;
}
}
}
}
result = Integer.toString(r);
}
}
}
|
A20382 | A22806 | 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();
}
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Madu
*/
import java.io.*;
public class Ex2 {
public static void main(String[] args) {
try{
FileInputStream fstream = new FileInputStream("C:/Users/Madu/Documents/NetBeansProjects/CodeJamR1Ex1/input/A-small-attempt0.in");
FileOutputStream fout = new FileOutputStream ("C:/Users/Madu/Documents/NetBeansProjects/CodeJamR1Ex1/output/out.txt");
PrintStream printStream = new PrintStream(fout);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String inputIlne;
br.readLine();
//printStream.println ("Output");
//Read File Line By Line
int lineNum = 1;
while ((inputIlne = br.readLine()) != null) {
// Print the content on the console
//##########
String[] marks = inputIlne.split(" ");
int peopleCount = Integer.parseInt(marks[0].toString());
int s = Integer.parseInt(marks[1].toString());
int p = Integer.parseInt(marks[2].toString());
int ans = 0;
for (int i = 3; i < marks.length; i++) {
System.out.println(marks[i]);
int total = Integer.parseInt(marks[i].toString());
int value = total/3;
int reminder = total%3;
if(total==0){
if(p==0){ans++;}
continue;}
if(reminder==0){
if(value>=p){ans++;}
else if(value+1>=p){
if(s>=1){ans++; s--;
}
}
}
else if(reminder==1){
if(value>=p){ans++;}
else if(value+1>=p){ans++;}
}
else if(reminder==2){
if(value>=p){ans++;}
else if(value+1>=p){ans++;}
else if(value+2>=p){
if(s>=1){ans++; s--;}
}
}
}
printStream.print ("Case #"+lineNum+": "+ans);lineNum++;
//###########
printStream.println("");
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.toString());
}
}
// public static void main(String[] args) {
//
// String test = "2 1 1 8 0";
// int peopleCount = Integer.parseInt(test.substring(0, 1));
// int s = Integer.parseInt(test.substring(2, 3));
// int p = Integer.parseInt(test.substring(4, 5));
//
// int ans = 0;
//
// //System.out.println(p);
//
// String[] marks = (test.substring(6)).split(" ");
//
//
//
// for (int i = 0; i < marks.length; i++) {
//
// System.out.println(marks[i]);
// int total = Integer.parseInt(marks[i].toString());
//
// int value = total/3;
// int reminder = total%3;
//
// if(total==0){continue;}
//
// if(reminder==0){
//
// if(value>=p){ans++;}
// else if(value+1>=p){
//
// if(s>=1){ans++; s--;
// }
//
// }
//
// }
//
// else if(reminder==1){
//
// if(value>=p){ans++;}
// else if(value+1>=p){ans++;}
//
// }
//
// else if(reminder==2){
//
// if(value>=p){ans++;}
// else if(value+1>=p){ans++;}
// else if(value+2>=p){
//
// if(s>=1){ans++; s--;}
// }
//
// }
//
// }
//
//
//
// System.out.println("Answer :"+ans);
//
// }
}
|
B12669 | B11199 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package year_2012.qualification;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author paul
* @date 14 Apr 2012
*/
public class QuestionC {
private static Set<Integer> getCycle(int x) {
String s = Integer.toString(x);
Set<Integer> set = new HashSet<Integer>();
set.add(x);
for (int c = 1; c < s.length(); c++) {
String t = s.substring(c).concat(s.substring(0, c));
set.add(Integer.parseInt(t));
}
return set;
}
private static Set<Integer> mask(Set<Integer> set, int a, int b) {
Set<Integer> result = new HashSet<Integer>();
for (int x : set) {
if (x >= a && x <= b) {
result.add(x);
}
}
return result;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
String question = "C";
// String name = "large";
String name = "small-attempt0";
// String name = "test";
String filename = String.format("%s-%s", question, name);
BufferedReader input = new BufferedReader(
new FileReader(String.format("/home/paul/Documents/code-jam/2012/qualification/%s.in",
filename)));
String firstLine = input.readLine();
PrintWriter pw = new PrintWriter(new File(
String.format("/home/paul/Documents/code-jam/2012/qualification/%s.out", filename)));
int T = Integer.parseInt(firstLine);
// Loop through test cases.
for (int i = 0; i < T; i++) {
// Read data.
String[] tokens = input.readLine().split(" ");
// int N = Integer.parseInt(input.readLine());
int A = Integer.parseInt(tokens[0]);
int B = Integer.parseInt(tokens[1]);
// System.out.format("%d, %d\n", A, B);
boolean[] used = new boolean[B+1];
int total = 0;
for (int n = A; n <= B; n++) {
if (!used[n]) {
Set<Integer> set = mask(getCycle(n), A, B);
int k = set.size();
total += (k * (k-1))/2;
for (int m : set) {
used[m] = true;
}
}
}
pw.format("Case #%d: %d\n", i + 1, total);
}
pw.close();
}
}
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RecycledNumbers {
public static void readInput(String pFileName, List<String> pInputCases) {
File tFile = new File(pFileName);
try {
BufferedReader tBufferedReader = new BufferedReader(
new InputStreamReader(new FileInputStream(tFile)), 4096);
String tLineRead = tBufferedReader.readLine().trim();
int tCaseSize = Integer.valueOf(tLineRead);
int tLineIndex = 0;
while(tLineIndex < tCaseSize) {
tLineRead = tBufferedReader.readLine().trim();
pInputCases.add(tLineRead);
tLineIndex++;
}
} catch(FileNotFoundException pException) {
pException.printStackTrace();
} catch(IOException pException) {
pException.printStackTrace();
}
}
public static void main(String[] pArgs) {
if(pArgs.length == 0) {
System.out.println("no input");
return;
}
List<String> tInputCases = new ArrayList<String>();
readInput(pArgs[0], tInputCases);
for(int tCaseIndex = 0; tCaseIndex < tInputCases.size(); tCaseIndex++) {
String[] tInputs = tInputCases.get(tCaseIndex).split("[ ]+");
int tLower = Integer.valueOf(tInputs[0]);
int tUpper = Integer.valueOf(tInputs[1]);
int tPairs = 0;
Map<String, Integer> tMapPairs = new HashMap<String, Integer>();
for(int tNumber = tLower; tNumber < tUpper; ++tNumber) {
int tLength = String.valueOf(tNumber).length();
int tHighUnit = 1;
for(int i = 0; i < tLength - 1; ++i) {
tHighUnit *= 10;
}
int tValue = tNumber;
int[] tValues = new int[tLength];
tValues[0] = tNumber;
for(int i = 1; i < tLength; ++i) {
int tHead = tValue / tHighUnit;
int tTail = tValue - tHead * tHighUnit;
int tNewValue = tTail * 10 + tHead;
tValues[i] = tNewValue;
tValue = tNewValue;
}
for(int i = 0; i < tLength - 1; ++i) {
for(int j = i + 1; j < tLength; ++j) {
int tOldValue = tValues[i];
int tNewValue = tValues[j];
String tKey = tOldValue + "-" + tNewValue;
if((tOldValue < tNewValue) && (tLower <= tOldValue)
&& (tNewValue <= tUpper) && (tOldValue != tNewValue)) {
if(!tMapPairs.containsKey(tKey)) {
++tPairs;
tMapPairs.put(tKey, 1);
}
}
}
}
}
System.out.println("Case #" + (tCaseIndex + 1) + ": " + tPairs);
}
}
}
|
A12113 | A12454 | 0 | import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class B {
static int[][] memo;
static int[] nums;
static int p;
public static void main(String[] args)throws IOException
{
Scanner br=new Scanner(new File("B-small-attempt0.in"));
PrintWriter out=new PrintWriter(new File("b.out"));
int cases=br.nextInt();
for(int c=1;c<=cases;c++)
{
int n=br.nextInt(),s=br.nextInt();
p=br.nextInt();
nums=new int[n];
for(int i=0;i<n;i++)
nums[i]=br.nextInt();
memo=new int[n][s+1];
for(int[] a:memo)
Arrays.fill(a,-1);
out.printf("Case #%d: %d\n",c,go(0,s));
}
out.close();
}
public static int go(int index,int s)
{
if(index>=nums.length)
return 0;
if(memo[index][s]!=-1)
return memo[index][s];
int best=0;
for(int i=0;i<=10;i++)
{
int max=i;
for(int j=0;j<=10;j++)
{
if(Math.abs(i-j)>2)
continue;
max=Math.max(i,j);
thisone:
for(int k=0;k<=10;k++)
{
int ret=0;
if(Math.abs(i-k)>2||Math.abs(j-k)>2)
continue;
max=Math.max(max,k);
int count=0;
if(Math.abs(i-k)==2)
count++;
if(Math.abs(i-j)==2)
count++;
if(Math.abs(j-k)==2)
count++;
if(i+j+k==nums[index])
{
boolean surp=(count>=1);
if(surp&&s>0)
{
if(max>=p)
ret++;
ret+=go(index+1,s-1);
}
else if(!surp)
{
if(max>=p)
ret++;
ret+=go(index+1,s);
}
best=Math.max(best,ret);
}
else if(i+j+k>nums[index])
break thisone;
}
}
}
return memo[index][s]=best;
}
}
| import java.util.Scanner;
/*
4
3 1 5 15 13 11
3 0 8 23 22 21
2 1 1 8 0
6 2 8 29 20 8 18 18 21
*/
public class Problem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int test = 1,
numberOfTests,
dancarinos,
erros,
notaCorte,
notaAtual,
resposta;
numberOfTests = scanner.nextInt();
for( int i = 0; i < numberOfTests; i++ ){
resposta = 0;
dancarinos = scanner.nextInt();
erros = scanner.nextInt();
notaCorte = scanner.nextInt();
int[] notas = new int[dancarinos];
for( int j = 0; j < dancarinos; j++){
notas[j] = scanner.nextInt();
}
int div, resto;
for( int j = 0; j < dancarinos; j++ ){
notaAtual = notas[j];
div = notaAtual / 3;
resto = notaAtual % 3;
switch( resto ){
case 0:
if( div >= notaCorte){
resposta++;
}else{
if( erros > 0 && div > 0 && div +1 >= notaCorte){
resposta++;
erros--;
}
}
break;
case 1:
if (div >= notaCorte || div + 1 >= notaCorte){
resposta++;
}else{
if (erros > 0 && div + 1 >= notaCorte){
resposta++;
erros--;
}
}
break;
case 2:
if (div + 1 >= notaCorte || div >= notaCorte){
resposta++;
}else{
if (erros > 0 && div + 2 >= notaCorte){
resposta++;
erros--;
}
}
break;
}
}
System.out.println("Case #"+test+": "+resposta);
test++;
}
}
}
|
B10245 | B12971 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package recyclednumbers;
import java.util.HashSet;
/**
*
* @author vandit
*/
public class RecycleNumbers {
private HashSet<String> numbers = new HashSet<String>();
private HashSet<String> initialTempNumbers = new HashSet<String>();
private HashSet<String> finalTempNumbers = new HashSet<String>();
HashSet<Pair> numberPairs = new HashSet<Pair>();
private void findRecycledNumbers(int start, int end, int places) {
for (int i = start; i <= end; i++) {
String initialNumber = Integer.toString(i);
//if (!(numbers.contains(initialNumber) || finalTempNumbers.contains(initialNumber))) {
StringBuffer tempNumber = new StringBuffer(initialNumber);
int len = tempNumber.length();
int startIndexToMove = len - places;
String tempString = tempNumber.substring(startIndexToMove);
if ((places == 1 && tempString.equals("0")) || tempString.charAt(0) == '0') {
continue;
}
tempNumber.delete(startIndexToMove, len);
String finalTempNumber = tempString + tempNumber.toString();
if (! (finalTempNumber.equals(initialNumber) || Integer.parseInt(finalTempNumber) > end || Integer.parseInt(finalTempNumber) < Integer.parseInt(initialNumber))) {
numbers.add(initialNumber);
finalTempNumbers.add(finalTempNumber);
Pair pair = new Pair(finalTempNumber,initialNumber);
numberPairs.add(pair);
}
}
}
public HashSet<Pair> findAllRecycledNumbers(int start, int end) {
int length = Integer.toString(start).length();
for (int i = 1; i < length; i++) {
findRecycledNumbers(start, end, i);
}
return numberPairs;
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package recyclednumber;
/**
*
* @author pos
*/
public class Numbers {
int A;
int B;
int n;
int m;
int Result;
public Numbers(int A, int B) {
this.A = A;
this.B = B;
this.n = A;
this.m = n + 1;
}
String sn;
String sm;
int nLength;
int mLength;
int nIndex;
int mIndex;
private boolean isValid(int n, int m) {
int[] numberN = new int[10];
int[] numberM = new int[10];
sn = n + "";
sm = m + "";
nLength = sn.length();
mLength = sm.length();
for (int i = 0; i < nLength; i++) {
nIndex = Integer.valueOf(sn.charAt(i)) - 48;
numberN[nIndex]++;
mIndex = Integer.valueOf(sm.charAt(i)) - 48;
numberM[mIndex]++;
}
for (int i = 0; i < 10; i++) {
if (numberN[i] != numberM[i]) {
return false;
}
}
//System.out.println(A + "<=" + n + "<" + m + "<=" + B);
return true;
}
public void Calculate() {
int n, m;
for (int i = this.A; i < this.B; i++) {
for (int j = i+1; j <= this.B; j++) {
n = i;
m = j;
if (isValid(n, m))
isRecycled(n, m);
}
}
}
private boolean isRecycled(int n, int m){
String sn=n+"";
nLength=sn.length();
for(int i=1;i<nLength;i++){
if (Integer.valueOf(sn.substring(i)+sn.substring(0, i))==m){
Result++;
return true;
}
}
return false;
}
}
|
A11277 | A12902 | 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 qual2012;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Kattio extends PrintWriter {
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int getInt() {
return Integer.parseInt(nextToken());
}
public double getDouble() {
return Double.parseDouble(nextToken());
}
public long getLong() {
return Long.parseLong(nextToken());
}
public String getWord() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
}
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
} |
B20424 | B21917 | 0 | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
// static int MAX = 10000;
static int MAX = 2000000;
static Object[] All = new Object[MAX+1];
static int size( int x ) {
if(x>999999) return 7;
if(x>99999) return 6;
if(x>9999) return 5;
if(x>999) return 4;
if(x>99) return 3;
if(x>9) return 2;
return 1;
}
static int[] rotate( int value ) {
List<Integer> result = new ArrayList<Integer>();
int[] V = new int[8];
int s = size(value);
int x = value;
for(int i=s-1;i>=0;i--) {
V[i] = x%10;
x /=10;
}
int rot;
for(int i=1; i<s; i++) {
if(V[i]!=0){
rot=0;
for(int j=0,ii=i;j<s; j++,ii=(ii+1)%s){
rot=rot*10+V[ii];
}
if(rot>value && !result.contains(rot))
result.add(rot);
}
}
if( result.isEmpty() )
return null;
int[] r = new int[result.size()];
for(int i=0; i<r.length; i++)
r[i]=result.get(i);
return r;
}
static void precalculate() {
for(int i=1; i<=MAX; i++){
All[i] = rotate(i);
}
}
static int solve( Scanner in ) {
int A, B, sol=0;
A = in.nextInt();
B = in.nextInt();
for( int i=A; i<=B; i++) {
// List<Integer> result = rotate(i);
if( All[i]!=null ) {
for(int value: (int[])All[i] ) {
if( value <= B )
sol++;
}
}
}
return sol;
}
public static void main ( String args[] ) {
int T;
Scanner in = new Scanner(System.in);
T = in.nextInt();
int cnt=0;
int sol;
precalculate();
for( cnt=1; cnt<=T; cnt++ ) {
sol = solve( in );
System.out.printf("Case #%d: %d\n", cnt, sol);
}
}
}
|
import java.util.Scanner;
public class RecycledNumber {
public int deal(int A, int B)
{
int ans = 0;
for (int i = A; i<= B ; i ++)
{
int left = i;
int k = 1;
int tk = 1;
UniqueList newInts = new UniqueList(10);
while (left >= 10)
{
left = left / 10;
tk = tk * 10;
}
left = i;
while (k * 10 <= left)
{
k = k * 10;
int x = (left % k) * (tk * 10 / k) + (left / k);
//System.out.println(i + ": " + x);
if (x > i && x <= B)
newInts.add(x);
}
ans += newInts.getSize();
}
return ans;
}
public void solve()
{
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();scan.nextLine();
for (int i = 1; i <= T; i ++)
{
int A = scan.nextInt();
int B = scan.nextInt();
System.out.println("Case #" + i + ": " + this.deal(A, B));
}
}
public static void main(String args[])
{
RecycledNumber r = new RecycledNumber();
r.solve();
}
}
|
A21396 | A20516 | 0 | import java.util.*;
public class Test {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int T = in.nextInt();
for(int i = 1; i<=T; i++) {
int n = in.nextInt();
int s = in.nextInt();
int p = in.nextInt();
int result = 0;
for(int j = 0; j<n; j++){
int x = canAddUp(in.nextInt(), p);
if(x == 0) {
result++;
} else if (x==1 && s > 0) {
result++;
s--;
}
}
System.out.println("Case #"+i+": "+result);
}
}
public static int canAddUp(int sum, int limit) {
boolean flag = false;
for(int i = 0; i<=sum; i++) {
for(int j = 0; i+j <= sum; j++) {
int k = sum-(i+j);
int a = Math.abs(i-j);
int b = Math.abs(i-k);
int c = Math.abs(j-k);
if(a > 2 || b > 2 || c> 2){
continue;
}
if (i>=limit || j>=limit || k>=limit) {
if(a < 2 && b < 2 && c < 2) {
return 0;
}else{
flag = true;
}
}
}
}
return (flag) ? 1 : 2;
}
}
| package com.googlerese.file;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class FileRead {
private static FileRead instance = new FileRead();
private FileRead() {
}
public static FileRead getInstance() {
return instance;
}
public Map<Integer, GooglersBean> read( final String fileName ) {
FileInputStream fstream = null;
DataInputStream in = null;
BufferedReader br = null;
Map<Integer, GooglersBean> input = null;
try {
// Open the file that is the first
// command line parameter
fstream = new FileInputStream( fileName );
// Get the object of DataInputStream
in = new DataInputStream( fstream );
br = new BufferedReader( new InputStreamReader( in ) );
String strLine;
//Read File Line By Line
int count = 0;
while ( ( strLine = br.readLine() ) != null ) {
// Print the content on the console
if ( count == 0 ) {
input = new HashMap<Integer, GooglersBean>( Integer.parseInt( strLine ) );
} else {
System.out.println( count + " : " + strLine );
GooglersBean bean = new GooglersBean();
String[] arr = strLine.split( "\\s+" );
bean.setNumGooglers( Integer.parseInt( arr[0] ) );
bean.setSurprising( Integer.parseInt( arr[1] ) );
bean.setResult( Integer.parseInt( arr[2] ) );
for ( int i = 3; i < arr.length; i++ ) {
bean.addScore( ( i - 3 ), Integer.parseInt( arr[i] ) );
}
input.put( count, bean );
}
count++;
}
} catch ( Exception e ) {//Catch exception if any
System.err.println( "Error: " + e.getMessage() );
} finally {
//Close the input stream
try {
if ( br != null ) {
br.close();
}
if ( in != null ) {
in.close();
}
if ( fstream != null ) {
fstream.close();
}
} catch ( IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return input;
}
}
|
B10155 | B13094 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package codejam;
/**
*
* @author eblanco
*/
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import javax.swing.JFileChooser;
public class RecycledNumbers {
public static String DatosArchivo[] = new String[10000];
public static int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null) {
int intarray[] = new int[sarray.length];
for (int i = 0; i < sarray.length; i++) {
intarray[i] = Integer.parseInt(sarray[i]);
}
return intarray;
}
return null;
}
public static boolean CargarArchivo(String arch) throws FileNotFoundException, IOException {
FileInputStream arch1;
DataInputStream arch2;
String linea;
int i = 0;
if (arch == null) {
//frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));
int rc = fc.showDialog(null, "Select a File");
if (rc == JFileChooser.APPROVE_OPTION) {
arch = fc.getSelectedFile().getAbsolutePath();
} else {
System.out.println("No hay nombre de archivo..Yo!");
return false;
}
}
arch1 = new FileInputStream(arch);
arch2 = new DataInputStream(arch1);
do {
linea = arch2.readLine();
DatosArchivo[i++] = linea;
/* if (linea != null) {
System.out.println(linea);
}*/
} while (linea != null);
arch1.close();
return true;
}
public static boolean GuardaArchivo(String arch, String[] Datos) throws FileNotFoundException, IOException {
FileOutputStream out1;
DataOutputStream out2;
int i;
out1 = new FileOutputStream(arch);
out2 = new DataOutputStream(out1);
for (i = 0; i < Datos.length; i++) {
if (Datos[i] != null) {
out2.writeBytes(Datos[i] + "\n");
}
}
out2.close();
return true;
}
public static void echo(Object msg) {
System.out.println(msg);
}
public static void main(String[] args) throws IOException, Exception {
String[] res = new String[10000], num = new String[2];
int i, j, k, ilong;
int ele = 1;
ArrayList al = new ArrayList();
String FName = "C-small-attempt0", istr, irev, linea;
if (CargarArchivo("C:\\eblanco\\Desa\\CodeJam\\Code Jam\\test\\" + FName + ".in")) {
for (j = 1; j <= Integer.parseInt(DatosArchivo[0]); j++) {
linea = DatosArchivo[ele++];
num = linea.split(" ");
al.clear();
// echo("A: "+num[0]+" B: "+num[1]);
for (i = Integer.parseInt(num[0]); i <= Integer.parseInt(num[1]); i++) {
istr = Integer.toString(i);
ilong = istr.length();
for (k = 1; k < ilong; k++) {
if (ilong > k) {
irev = istr.substring(istr.length() - k, istr.length()) + istr.substring(0, istr.length() - k);
//echo("caso: " + j + ": isrt: " + istr + " irev: " + irev);
if ((Integer.parseInt(irev) > Integer.parseInt(num[0])) && (Integer.parseInt(irev) > Integer.parseInt(istr)) && (Integer.parseInt(irev) <= Integer.parseInt(num[1]))) {
al.add("(" + istr + "," + irev + ")");
}
}
}
}
HashSet hs = new HashSet();
hs.addAll(al);
al.clear();
al.addAll(hs);
res[j] = "Case #" + j + ": " + al.size();
echo(res[j]);
LeerArchivo.GuardaArchivo("C:\\eblanco\\Desa\\CodeJam\\Code Jam\\test\\" + FName + ".out", res);
}
}
}
}
| package RecycledNumbers;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class RecycledNumbers {
public static void main(String[] args) {
try {
// lets get the data in
FileInputStream fstream = new FileInputStream("E:/workspace_java/CodeJam12/src/RecycledNumbers/input.in");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// open file for writing
FileWriter fwstream = new FileWriter("E:/workspace_java/CodeJam12/src/RecycledNumbers/output.out");
BufferedWriter out = new BufferedWriter(fwstream);
// declare variables
int i,j,k;
int numCases;
String[] strArr;
// get number of cases
strLine = br.readLine();
numCases = Integer.parseInt(strLine);
// declare specific vars
int low, high, n;
int cur, len;
int count;
String ts, ns, a, b;
ArrayList<String> found = new ArrayList<String>();
// loop through cases
for(i=0;i<numCases;i++){
// read case
strLine = br.readLine();
strArr = strLine.split(" ");
count = 0;
low = Integer.parseInt(strArr[0]);
high = Integer.parseInt(strArr[1]);
for(j = low; j <= high; j++){
cur = j;
ts = new Integer(cur).toString();
len = ts.length();
//System.out.print(ts + " => ");
for(k = len - 1; k >= 0; k--){
a = ts.substring(k);
b = ts.substring(0, k);
n = Integer.parseInt(a + b);
ns = new Integer(n).toString();
if(n >= low && n <= high && n > cur && !(in_array(ns+ts, found))){
count++;
//System.out.print(ns + " ");
}
}
//System.out.println();
}
/* final tests
if((one >= 0 && one <= 10) && (two >= 0 && two <= 10) && (three >= 0 && three <= 10)) { }
else { System.out.println("Out of bounds on number"); }
if(total != tempScore) { System.out.println("Score does not add up"); }
if(surprisesTaken > numSurprises) { System.out.println("Too many surprises"); }
*/
//System.out.println(one + " " + two + " " + three);
System.out.print("Case #"+(i+1)+": ");
out.write("Case #"+(i+1)+": ");
System.out.println(count);
out.write(Integer.toString(count));
out.newLine();
}
//System.out.print("Case #"+(i+1)+": ");
//out.write("Case #"+(i+1)+": ");
//System.out.println(seanP2sum);
//out.write(Integer.toString(seanP2sum));
//out.newLine();
out.close();
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
public static boolean in_array(String needle, ArrayList<String> haystack){
boolean found = false;
int i = 0;
int len = haystack.size();
for(i=0; i<len; i++){
if(needle.equals(haystack.get(i))){
found = true;
System.out.println("found match of "+needle + " matching " + haystack.get(i) + " at index " + i);
}
}
return found;
}
}
|
A12846 | A12200 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package codejam.common;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Lance Chen
*/
public class CodeHelper {
private static String FILE_ROOT = "D:/workspace/googlecodejam/meta";
public static List<List<String>> loadInputsExcludes(String fileName) {
List<List<String>> result = new ArrayList<List<String>>();
List<String> lines = FileUtil.readLines(FILE_ROOT + fileName);
int index = 0;
for (String line : lines) {
if (index == 0) {
index++;
continue;
}
if (index % 2 == 1) {
index++;
continue;
}
List<String> dataList = new ArrayList<String>();
String[] dataArray = line.split("\\s+");
for (String data : dataArray) {
if (data.trim().length() > 0) {
dataList.add(data);
}
}
result.add(dataList);
index++;
}
return result;
}
public static List<List<String>> loadInputs(String fileName) {
List<List<String>> result = new ArrayList<List<String>>();
List<String> lines = FileUtil.readLines(FILE_ROOT + fileName);
for (String line : lines) {
List<String> dataList = new ArrayList<String>();
String[] dataArray = line.split("\\s+");
for (String data : dataArray) {
if (data.trim().length() > 0) {
dataList.add(data);
}
}
result.add(dataList);
}
return result;
}
public static List<String> loadInputLines(String fileName) {
return FileUtil.readLines(FILE_ROOT + fileName);
}
public static void writeOutputs(String fileName, List<String> lines) {
FileUtil.writeLines(FILE_ROOT + fileName, lines);
}
}
| import java.io.*;
import java.util.Scanner;
public class functions {
int mod(int a){
int b = 0;
if(a > 0) b = a; else b = -a;
return b;
}
int solve(int[] a, int p, int s, int n){
int result = 0;
int i = 0;
int x = 0;
int onlyS = 0;
int onlyNotS = 0;
int both = 0;
int none = 0;
for ( i = 0;i < n; i++){
x = a[i]/3;
if(a[i]%3 ==0){
if(a[i] == 30){
onlyNotS++;
}
else if(p==x+1 && a[i]!=0){
onlyS++;
}
else if ( p<=x ){
both++;
}
else{
none++;
}
}
else if(a[i]%3 ==1){
if(a[i]==1 && p<=1){
onlyNotS++;
}
else if(p <= x+1){
both++;
}
else none++;
}
else{
if(a[i] == 29){
onlyNotS++;
}
else if(p == x+2){
onlyS++;
}
else if(p <= x+1){
both++;
}
else {
none++;
}
}
}
if(onlyS <= s){
result = both+onlyNotS+onlyS;
}
else{
result = s+both+onlyNotS;
}
return result;
}
}
|
A10568 | A12784 | 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);
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dancinggooglers;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
/**
*
* @author administrator
*/
public class DancingGooglers {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String input = "c:\\input.in";
String output = "c:\\output.txt";
System.out.println("Hello World");
DancingGooglers code1 = new DancingGooglers();
File in = new File(input);
File out = new File(output);
code1.processOutput(in, out, "UTF-8");
}
public void processOutput(File input, File output, String charSet) {
String temp = "";
try {
Scanner scanner = new Scanner(input, charSet);
PrintWriter out = new PrintWriter(output);
int count = 0;
int test_case = 0;
while (scanner.hasNext()) {
String test = scanner.nextLine();
int noOfGooglers;
int surprising_triplets;
int P;
int t[];
int surprises_left;
int result;
if (count == 0) {
test_case = Integer.parseInt(test);
count++;
} else {
String[] line_data = test.split("\\s");
noOfGooglers = Integer.parseInt(line_data[0]);
surprising_triplets = Integer.parseInt(line_data[1]);
P = Integer.parseInt(line_data[2]);
t = new int[noOfGooglers];
result = 0;
surprises_left = surprising_triplets;
for (int i = 0; i < noOfGooglers; i++) {
t[i] = Integer.parseInt(line_data[i + 3]);
}
for (int i = 0; i < noOfGooglers; i++) {
if (isTGreaterThanP(t[i], P)) {
result++;
} else {
if (surprises_left > 0 && isTGreaterPSurprises(t[i], P)) {
result++;
surprises_left--;
}
}
}
System.out.println("Case #" + count + ": " + result);
if (count == test_case) {
out.print("Case #" + count + ": " + result);
} else {
out.println("Case #" + count + ": " + result);
}
count++;
}
temp = temp + "\n" + test;
}
out.close();
scanner.close();
} catch (Exception e) {
System.out.println("File read/write error");
return;
}
}
private boolean isTGreaterThanP(int total, int P) {
int max = (total + 2) / 3;
if (max >= P) {
return true;
}
return false;
}
private boolean isTGreaterPSurprises(int total, int P) {
int max = (total + 4) / 3;
if (max >= 10) {
max = 10;
}
if (total == 1) {
max = 1;
} else if (total == 0) {
max = 0;
}
if (max >= P) {
return true;
}
return false;
}
}
|
A12113 | A10190 | 0 | import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class B {
static int[][] memo;
static int[] nums;
static int p;
public static void main(String[] args)throws IOException
{
Scanner br=new Scanner(new File("B-small-attempt0.in"));
PrintWriter out=new PrintWriter(new File("b.out"));
int cases=br.nextInt();
for(int c=1;c<=cases;c++)
{
int n=br.nextInt(),s=br.nextInt();
p=br.nextInt();
nums=new int[n];
for(int i=0;i<n;i++)
nums[i]=br.nextInt();
memo=new int[n][s+1];
for(int[] a:memo)
Arrays.fill(a,-1);
out.printf("Case #%d: %d\n",c,go(0,s));
}
out.close();
}
public static int go(int index,int s)
{
if(index>=nums.length)
return 0;
if(memo[index][s]!=-1)
return memo[index][s];
int best=0;
for(int i=0;i<=10;i++)
{
int max=i;
for(int j=0;j<=10;j++)
{
if(Math.abs(i-j)>2)
continue;
max=Math.max(i,j);
thisone:
for(int k=0;k<=10;k++)
{
int ret=0;
if(Math.abs(i-k)>2||Math.abs(j-k)>2)
continue;
max=Math.max(max,k);
int count=0;
if(Math.abs(i-k)==2)
count++;
if(Math.abs(i-j)==2)
count++;
if(Math.abs(j-k)==2)
count++;
if(i+j+k==nums[index])
{
boolean surp=(count>=1);
if(surp&&s>0)
{
if(max>=p)
ret++;
ret+=go(index+1,s-1);
}
else if(!surp)
{
if(max>=p)
ret++;
ret+=go(index+1,s);
}
best=Math.max(best,ret);
}
else if(i+j+k>nums[index])
break thisone;
}
}
}
return memo[index][s]=best;
}
}
| package codejam;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
/*
import lib.tuple.Pair;
import lib.tuple.Tuple;
import lib.util.StringUtil;
*/
public class CodeJam2012RQB {
static final String fileIn = "/Users/jhorwitz/Documents/workspace/test/src/codejam/data/RQ-B-in.txt"; //"data/in.txt";
static final String fileOut = "/Users/jhorwitz/Documents/workspace/test/src/codejam/data/RQ-B-out.txt"; //"data/out.txt";
public static void main(String[] args) throws Exception {
BufferedReader r = new BufferedReader(new FileReader(fileIn));
BufferedWriter w = new BufferedWriter(new FileWriter(fileOut));
String line = r.readLine();
int T = Integer.parseInt(line);
for (int caseNum = 1; caseNum <= T; caseNum++) {
line = r.readLine();
String str = "Case #" + caseNum + ": " + solve(line);
w.write(str + "\n");
System.out.println(str);
}
w.close();
r.close();
}
private static int solve(String line) {
String[] inputLineAsAnArray = line.split(" ");
int N = Integer.parseInt(inputLineAsAnArray[0]);
int S = Integer.parseInt(inputLineAsAnArray[1]);
int p = Integer.parseInt(inputLineAsAnArray[2]);
int[] t = new int[N];
int numGooglersWithMaxScoreGreaterThanP = 0;
for (int i=0; i<N; ++i) { // fill t array--separate for loop from below solely for debug purposes
t[i] = Integer.parseInt(inputLineAsAnArray[3+i]);
}
for (int iGoogler=0; iGoogler<N; ++iGoogler) {
int tBy3 = t[iGoogler]/3;
switch(t[iGoogler] % 3) {
case 0:
if(tBy3 >= p && 0<=tBy3 && tBy3<=10) { // no need for a surprising triplet for this Googler to get p or more
++numGooglersWithMaxScoreGreaterThanP;
} else if(tBy3+1 == p && 0<=tBy3-1 && tBy3+1<=10) { // a surprising triplet is needed for this Googler to get a p or more -- "use" one if there's one left
if(S>0) {
++numGooglersWithMaxScoreGreaterThanP;
--S;
}
}
// if neither of those cases, then not valid triplet (surprising or otherwise) could give this Googler a p or more
break;
case 1:
if(tBy3 + 1 >= p && 0<=tBy3 && tBy3+1<=10) { // no need for a surprising triplet for this Googler to get p or more
++numGooglersWithMaxScoreGreaterThanP;
} // for this case (1 mod 3), a surprising triplet will have the same max as a non-surprising one
// so otherwise, then not valid triplet (surprising or otherwise) could give this Googler a p or more
break;
case 2:
if(tBy3 + 1 >= p && 0<=tBy3 && tBy3+1<=10) { // no need for a surprising triplet for this Googler to get p or more
++numGooglersWithMaxScoreGreaterThanP;
} else if(tBy3 + 2 == p && 0<=tBy3 && tBy3+2<=10) { // a surprising triplet is needed for this Googler to get a p or more -- "use" one if there's one left
if(S>0) {
++numGooglersWithMaxScoreGreaterThanP;
--S;
}
}
// if neither of those cases, then not valid triplet (surprising or otherwise) could give this Googler a p or more
break;
// default left out since there better only be the three listed cases!
}
}
return numGooglersWithMaxScoreGreaterThanP;
}
} |
B12082 | B11904 | 0 | package jp.funnything.competition.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.apache.commons.io.IOUtils;
public class QuestionReader {
private final BufferedReader _reader;
public QuestionReader( final File input ) {
try {
_reader = new BufferedReader( new FileReader( input ) );
} catch ( final FileNotFoundException e ) {
throw new RuntimeException( e );
}
}
public void close() {
IOUtils.closeQuietly( _reader );
}
public String read() {
try {
return _reader.readLine();
} catch ( final IOException e ) {
throw new RuntimeException( e );
}
}
public BigDecimal[] readBigDecimals() {
return readBigDecimals( " " );
}
public BigDecimal[] readBigDecimals( final String separator ) {
final String[] tokens = readTokens( separator );
final BigDecimal[] values = new BigDecimal[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = new BigDecimal( tokens[ index ] );
}
return values;
}
public BigInteger[] readBigInts() {
return readBigInts( " " );
}
public BigInteger[] readBigInts( final String separator ) {
final String[] tokens = readTokens( separator );
final BigInteger[] values = new BigInteger[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = new BigInteger( tokens[ index ] );
}
return values;
}
public int readInt() {
final int[] values = readInts();
if ( values.length != 1 ) {
throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" );
}
return values[ 0 ];
}
public int[] readInts() {
return readInts( " " );
}
public int[] readInts( final String separator ) {
final String[] tokens = readTokens( separator );
final int[] values = new int[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = Integer.parseInt( tokens[ index ] );
}
return values;
}
public long readLong() {
final long[] values = readLongs();
if ( values.length != 1 ) {
throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" );
}
return values[ 0 ];
}
public long[] readLongs() {
return readLongs( " " );
}
public long[] readLongs( final String separator ) {
final String[] tokens = readTokens( separator );
final long[] values = new long[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = Long.parseLong( tokens[ index ] );
}
return values;
}
public String[] readTokens() {
return readTokens( " " );
}
public String[] readTokens( final String separator ) {
return read().split( separator );
}
}
| package googleJam;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
public class RecycledNumbers
{
public static void main(String[] args)
{
Scanner scan = null;
try
{
scan = new Scanner(new File(args[0]));
}
catch (FileNotFoundException e)
{
System.err.println("File not found!");
return;
}
if (!scan.hasNext())
{
System.err.println("Nothing in File!");
return;
}
int testCases = Integer.parseInt(scan.nextLine());
int lower;
int upper;
int move;
int d;
int total;
int zeroes;
int num = 1;
int first;
HashSet<Integer> set;
while(scan.hasNext())
{
System.out.print("Case #" + num + ": ");
total = 0;
lower = scan.nextInt();
upper = scan.nextInt();
for (int x = lower; x <= (upper); x++)
{
set = new HashSet<Integer>();
zeroes = 1;
move = x;
while (move > 9)
{
move = move/10;
zeroes = zeroes * 10;
}
int limit = zeroes;
for(int n = 10; n < (limit*10); n = n * 10)
{
move = x/n;
d = x % n;
d = d * zeroes;
d = d + move;
zeroes = zeroes / 10;
if (d < x && d >= lower && !set.contains(d) && d > 9)
{
total++;
//System.out.println(d + " , " + x);
set.add(d);
}
}
}
num++;
System.out.print(total);
if (scan.hasNext())
{
System.out.println();
}
}
}
}
|
B11327 | B12864 | 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]);
}
}
}
| import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
public class Recycle {
public static void main(String[] args)
{
File f = new File("C-small-attempt0.in");
try
{
Scanner scan = new Scanner(f);
int lines = Integer.parseInt(scan.nextLine());
FileWriter fstream = new FileWriter("output.txt");
BufferedWriter out = new BufferedWriter(fstream);
for(int i=0; i<lines; i++)
{
String line = scan.nextLine();
String[] bounds = line.split(" ");
int count = countPairs(Integer.parseInt(bounds[0]), Integer.parseInt(bounds[1]), bounds[0].length());
out.write("Case #"+(i+1)+": "+count);
out.newLine();
}
out.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
public static int countPairs(int l, int u, int n)
{
if(n==1)
return 0;
int count=0;
for(int i=l+1; i<=u; i++)
{
int cycle = (i%10)*((int)Math.pow(10,n-1)) + (i/10);
while(cycle != i)
{
if(cycle >= l && cycle < i)
count++;
cycle = (cycle%10)*((int)Math.pow(10,n-1)) + (cycle/10);
}
}
return count;
}
}
|
A20382 | A20516 | 0 | package dancinggooglers;
import java.io.File;
import java.util.Scanner;
public class DanceScoreCalculator {
public static void main(String[] args) {
if(args.length <= 0 || args[0] == null) {
System.out.println("You must enter a file to read");
System.out.println("Usage: blah <filename>");
System.exit(0);
}
File argFile = new File(args[0]);
try {
Scanner googleSpeakScanner = new Scanner(argFile);
String firstLine = googleSpeakScanner.nextLine();
Integer linesToScan = new Integer(firstLine);
for(int i = 1; i <= linesToScan; i++) {
String googleDancerLine = googleSpeakScanner.nextLine();
DanceScoreCase danceCase = new DanceScoreCase(googleDancerLine);
System.out.println(String.format("Case #%d: %d", i, danceCase.maxDancersThatCouldPass()));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| package com.googlerese.file;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class FileRead {
private static FileRead instance = new FileRead();
private FileRead() {
}
public static FileRead getInstance() {
return instance;
}
public Map<Integer, GooglersBean> read( final String fileName ) {
FileInputStream fstream = null;
DataInputStream in = null;
BufferedReader br = null;
Map<Integer, GooglersBean> input = null;
try {
// Open the file that is the first
// command line parameter
fstream = new FileInputStream( fileName );
// Get the object of DataInputStream
in = new DataInputStream( fstream );
br = new BufferedReader( new InputStreamReader( in ) );
String strLine;
//Read File Line By Line
int count = 0;
while ( ( strLine = br.readLine() ) != null ) {
// Print the content on the console
if ( count == 0 ) {
input = new HashMap<Integer, GooglersBean>( Integer.parseInt( strLine ) );
} else {
System.out.println( count + " : " + strLine );
GooglersBean bean = new GooglersBean();
String[] arr = strLine.split( "\\s+" );
bean.setNumGooglers( Integer.parseInt( arr[0] ) );
bean.setSurprising( Integer.parseInt( arr[1] ) );
bean.setResult( Integer.parseInt( arr[2] ) );
for ( int i = 3; i < arr.length; i++ ) {
bean.addScore( ( i - 3 ), Integer.parseInt( arr[i] ) );
}
input.put( count, bean );
}
count++;
}
} catch ( Exception e ) {//Catch exception if any
System.err.println( "Error: " + e.getMessage() );
} finally {
//Close the input stream
try {
if ( br != null ) {
br.close();
}
if ( in != null ) {
in.close();
}
if ( fstream != null ) {
fstream.close();
}
} catch ( IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return input;
}
}
|
B21968 | B22250 | 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.*;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.ArrayList;
public class ReadWriter
{
public ArrayList<String> readFile(String path){
File file = new File(path);
ArrayList<String> strings = new ArrayList<String>();
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(file));
String text = null;
while((text=reader.readLine())!=null){
strings.add(text);
}
return strings;
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(reader!=null){
reader.close();
}
}
catch(Exception e){
e.printStackTrace();
}
}
return null;
}
public void writeFile(ArrayList<String> list, String path){
BufferedWriter out=null;
try{
FileWriter fstream = new FileWriter(path);
out = new BufferedWriter(fstream);
for(String s : list){
out.write(s);
out.write("\r\n");
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(out!=null){
out.close();
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
|
B10361 | B12471 | 0 | package codejam;
import java.util.*;
import java.io.*;
public class RecycledNumbers {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("in.txt"));
PrintWriter out = new PrintWriter(new File("out.txt"));
int T = Integer.parseInt(in.readLine());
for (int t = 1; t <= T; ++t) {
String[] parts = in.readLine().split("[ ]+");
int A = Integer.parseInt(parts[0]);
int B = Integer.parseInt(parts[1]);
int cnt = 0;
for (int i = A; i < B; ++i) {
String str = String.valueOf(i);
int n = str.length();
String res = "";
Set<Integer> seen = new HashSet<Integer>();
for (int j = n - 1; j > 0; --j) {
res = str.substring(j) + str.substring(0, j);
int k = Integer.parseInt(res);
if (k > i && k <= B) {
//System.out.println("(" + i + ", " + k + ")");
if (!seen.contains(k)) {
++cnt;
seen.add(k);
}
}
}
}
out.println("Case #" + t + ": " + cnt);
}
in.close();
out.close();
System.exit(0);
}
}
| import java.io.*;
import java.util.*;
import java.util.regex.*;
public class jam03 {
/**
* @param args
*/
public static void main1(){
// scalar product problem
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int number_test;
Scanner sc = new Scanner(System.in);
number_test = sc.nextInt();
for(int j=1;j<=number_test;j++) {
int lowerLimit = sc.nextInt();
int upperLimit = sc.nextInt();
System.out.print("Case #" + j + ": ");
action(lowerLimit,upperLimit);
// System.out.println(sum);
}
}
private static void action(int lowerLimit, int upperLimit ) {
// TODO Auto-generated method stub
// Iterating over the elements in the set
int finalGuys = 0;
int maxZeroes = 0;
int oldNum=0;
// System.out.println("lower"+ lowerLimit);
// System.out.println("uper"+upperLimit);
for(int i=lowerLimit;i<upperLimit;i++)
{
for(int k=4;k>=1;k--)
{//3422
int temp = (int) (i/Math.pow(10, k));//34
if(maxZeroes ==0 && temp > 0)
{
maxZeroes = k;
//System.out.println("maxZeroes"+maxZeroes);
}
if(maxZeroes>0)
{
int temp1 = (int) (i - (temp*Math.pow(10, k)));//3422-3400
int newNum = (int) ((temp1*Math.pow(10, maxZeroes-k+1))+temp);//4223
if(newNum <= upperLimit && newNum > i && newNum != oldNum)
{
oldNum = newNum;
finalGuys++;
}
}
}
}
System.out.println(finalGuys);
}
}
|
B11421 | B12917 | 0 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Recycled {
public static void main(String[] args) throws Exception{
String inputFile = "C-small-attempt0.in";
BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output")));
long num_cases = Long.parseLong(input.readLine());
int current_case = 0;
while (current_case < num_cases){
current_case++;
String[] fields = input.readLine().split(" ");
int A = Integer.parseInt(fields[0]);
int B = Integer.parseInt(fields[1]);
int total = 0;
for (int n = A; n < B; n++){
for (int m = n+1; m <= B; m++){
if (isRecycled(n,m)) total++;
}
}
System.out.println("Case #" + current_case + ": " + total);
output.write("Case #" + current_case + ": " + total + "\n");
}
output.close();
}
private static boolean isRecycled(int n, int m) {
String sn = ""+n;
String sm = ""+m;
if (sn.length() != sm.length()) return false;
int totaln = 0, totalm = 0;
for (int i = 0; i < sn.length(); i++){
totaln += sn.charAt(i);
totalm += sm.charAt(i);
}
if (totaln != totalm) return false;
for (int i = 0; i < sn.length()-1; i++){
sm = sm.charAt(sm.length() - 1) + sm.substring(0, sm.length() - 1);
if (sm.equals(sn)) return true;
}
return false;
}
}
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
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 B4dT0bi
*/
public class RecycledNumbers
{
public static String [] input;
public static String wholeOutput="";
public static void readInput(String inputFile)
{
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader(inputFile));
String serializedSettings = "";
String line = null;
while ((line = br.readLine()) != null)
serializedSettings += line + "\n";
input=serializedSettings.split("\n");
br.close();
} catch (Exception ex)
{
ex.printStackTrace();
} finally
{
try
{
br.close();
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
public static void writeOutput(String inputFile)
{
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(inputFile+".out"));
out.write(wholeOutput);
out.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
readInput(args[0]);
wholeOutput="";
for(int i=1;i<input.length;i++)
{
String [] tmp=input[i].split(" ");
int A=Integer.parseInt(tmp[0]);
int B=Integer.parseInt(tmp[1]);
int anz=0;
for(int x=A;x<B-1;x++)
{
anz+=existingPairs(x, B);
}
wholeOutput+="Case #"+i+": "+anz+"\n";
}
writeOutput(args[0]);
}
private static int existingPairs(int x, int B)
{
String sX=""+x;
int anz=0;
HashSet<String>already=new HashSet<String>();
for(int i=1;i<sX.length();i++)
{
String tmp=sX.substring(sX.length()-i)+""+sX.substring(0,sX.length()-i);
if(tmp.charAt(0)=='0')continue;
int nr=Integer.parseInt(tmp);
if(nr<=B && nr>x)
{
if(!already.contains(tmp))
{
already.add(tmp);
anz++;
}
}
}
return anz;
}
}
|
B12115 | B12348 | 0 | package qual;
import java.util.Scanner;
public class RecycledNumbers {
public static void main(String[] args) {
new RecycledNumbers().run();
}
private void run() {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int t = 0; t < T; t++) {
int A = sc.nextInt();
int B = sc.nextInt();
int result = solve(A, B);
System.out.printf("Case #%d: %d\n", t + 1, result);
}
}
public int solve(int A, int B) {
int result = 0;
for (int i = A; i <= B; i++) {
int dig = (int) Math.log10(A/*same as B*/) + 1;
int aa = i;
for (int d = 0; d < dig - 1; d++) {
aa = (aa % 10) * (int)Math.pow(10, dig - 1) + (aa / 10);
if (i == aa) {
break;
}
if (i < aa && aa <= B) {
// System.out.printf("(%d, %d) ", i, aa);
result++;
}
}
}
return result;
}
}
| import java.util.*;
public class b {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String ss = sc.nextLine();
int casenum = Integer.parseInt(ss);
String answer = "";
for(int i = 1;i<=casenum;i++){
answer = answer.concat("Case #".concat(Integer.toString(i)).concat(": "));
ss = sc.nextLine();
String wer = recycledpair(ss);
answer = answer.concat(wer);
answer = answer.concat("\n");
}
System.out.print(answer);
}
public static String recycledpair(String a){
int n = Integer.parseInt(a.substring(0, a.indexOf(' ')));
int m = Integer.parseInt(a.substring(a.indexOf(' ')+1, a.length()));
int nlength = a.substring(0, a.indexOf(' ')).length();
int pairnum = 0;
String rcp ="";
for(int i=n; i<m; i++){
LinkedList<Integer> mylist = new LinkedList<Integer>();
String sn = Integer.toString(i);
//a.substring(0, a.indexOf(' '));
for(int j=1; j<sn.length(); j++){
String newnum = sn.substring(j,sn.length()).concat(sn.substring(0,j));
int newint = Integer.parseInt(newnum);
if(newint>i&&newint<=m){
if(!mylist.contains(newint)){
pairnum++;
mylist.add(newint);
}
else{
mylist.add(newint);
}
}
}
}
String snumreturn = Integer.toString(pairnum);
//System.out.print(snumreturn);
return snumreturn;
}
}
|
A20730 | A22237 | 0 | import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
for(int zz = 1; zz <= T;zz++){
int N = in.nextInt();
int S = in.nextInt();
int p = in.nextInt();
int x = 0;
for(int i = 0; i < N;i++){
int score = in.nextInt();
int best = score/3;
int mod = score%3;
int diff = p-best;
if(diff<1){
x++;
}else if(diff<2){
if(mod==0 && score !=0){
if(S!=0){
S--;x++;
}
}else if(score!=0){
x++;
}
}else if(diff<3){
if(mod==2){
if(S!=0){
S--;x++;
}
}
}
}
System.out.format("Case #%d: %d\n", zz, x);
}
}
}
| import java.io.*;
import java.util.*;
/**
* @author: Ignat Alexeyenko
* Date: 4/14/12
*/
public class DancingWithGooglersMain {
public static final int MAX_LENGTH = 1024;
public static void main(String[] args) {
DancingWithGooglersMain main = new DancingWithGooglersMain();
main.runConsoleApp(System.in, System.out);
}
public void runConsoleApp(InputStream inputStream, OutputStream outputStream) {
final String s = readLn(inputStream, MAX_LENGTH);
Integer cases = Integer.valueOf(s);
Writer writer = new OutputStreamWriter(outputStream);
for (int i= 0; i < cases; i++) {
String rawLine = readLn(inputStream, MAX_LENGTH);
try {
writer.write("Case #" + (i + 1) + ": " + runFunction(rawLine) + "\n");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
try {
writer.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private long runFunction(String rawLine) {
String[] edgesArr = rawLine.split(" ");
int numOfGooglers = Integer.valueOf(edgesArr[0]);
int surprises = Integer.valueOf(edgesArr[1]);
int minScoreP = Integer.valueOf(edgesArr[2]);
List<Integer> marksT = new ArrayList<Integer>(numOfGooglers);
for (int t = 0; t < numOfGooglers; t++) {
marksT.add(Integer.valueOf(edgesArr[t + 3]));
}
return caclulateAmountOfGooglersThatExceedScoreP(surprises, minScoreP, marksT);
}
private int caclulateAmountOfGooglersThatExceedScoreP(int surprises, int minScoreP, List<Integer> marksT) {
Map<Integer, Set<Mark>> sumToPermutations = new HashMap<Integer, Set<Mark>>(marksT.size());
for (Integer theSum : marksT) {
Set<Mark> allPossiblePermutations = getAllPossiblePermutations(theSum, minScoreP);
sumToPermutations.put(theSum, allPossiblePermutations);
}
int exceedsWithoutSurprises = 0;
int exceedsOnlyWithSurprises = 0;
for (Integer theSum : marksT) {
Set<Mark> marksPermutations = sumToPermutations.get(theSum);
boolean exceeded = false;
boolean needSurprise = true;
for (Mark marksPermutation : marksPermutations) {
if (marksPermutation.exceedsScore) {
exceeded = true;
if (!marksPermutation.surprise && needSurprise) {
needSurprise = false;
}
}
}
if (exceeded && needSurprise) {
exceedsOnlyWithSurprises++;
}
if (exceeded && !needSurprise) {
exceedsWithoutSurprises++;
}
}
return exceedsWithoutSurprises + Math.min(exceedsOnlyWithSurprises, surprises);
}
Set<Mark> getAllPossiblePermutations(int sum, int minScoreP) {
Set<Mark> markList = new LinkedHashSet<Mark>(5);
final int start = Math.max(sum / 3 - 2, 0);
final int stop = sum / 3 + 2;
for (int i = start; i <= stop; i++) {
for (int j = start; j <= stop; j++) {
for (int k = start; k <= stop; k++) {
final int divergence = Math.abs(max(i, j, k) - min(i, j, k));
if ((i + j + k == sum) && divergence <= 2) {
boolean exceedsScore = i >= minScoreP || j >= minScoreP || k >= minScoreP;
markList.add(new Mark(i, j, k, divergence == 2, exceedsScore));
}
}
}
}
return markList;
}
private static int min(int a, int b, int c) {
return Math.min(Math.min(a, b), c);
}
private static int max(int a, int b, int c) {
return Math.max(Math.max(a, b), c);
}
private String readLn(InputStream inputStream, int maxLength) { // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte line[] = new byte[maxLength];
int length = 0;
int input = -1;
try {
while (length < maxLength) {//Read untill maxlength
input = inputStream.read();
if ((input < 0) || (input == '\n')) break; //or untill end of line ninput
line[length++] += input;
}
if ((input < 0) && (length == 0)) return null; // eof
return new String(line, 0, length);
} catch (IOException e) {
return null;
}
}
static class Mark {
// array represents marks, always are sorted
private List<Integer> marks;
private boolean surprise;
private boolean exceedsScore;
Mark(int m0, int m1, int m2, boolean surprise, boolean exceedsScore) {
this.marks = new ArrayList<Integer>(3);
this.marks.add(m1);
this.marks.add(m0);
this.marks.add(m2);
this.surprise = surprise;
this.exceedsScore = exceedsScore;
// todo: possibly just put elements in the list in a right order
Collections.sort(this.marks);
Collections.reverse(this.marks);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Mark mark = (Mark) o;
if (exceedsScore != mark.exceedsScore) return false;
if (surprise != mark.surprise) return false;
if (marks != null ? !marks.equals(mark.marks) : mark.marks != null) return false;
return true;
}
@Override
public int hashCode() {
int result = marks != null ? marks.hashCode() : 0;
result = 31 * result + (surprise ? 1 : 0);
result = 31 * result + (exceedsScore ? 1 : 0);
return result;
}
@Override
public String toString() {
return "Mark{" +
"marks=" + marks +
", surprise=" + surprise +
", exceedsScore=" + exceedsScore +
'}';
}
}
}
|
A11201 | A11229 | 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 qualifyingRound;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class DancingWithGooglers {
public static void main (String [] args) throws FileNotFoundException
{
Scanner in = new Scanner (new File ("input.txt"));
int numLines = Integer.parseInt(in.nextLine());
int caseNum = 1;
for (int j = 0; j < numLines; j++)
{
System.out.print("Case #" + caseNum + ": ");
int n = in.nextInt();
int s = in.nextInt();
int p = in.nextInt();
int noSup = 0;
int sup = 0;
for (int i = 0; i < n; i++)
{
int total = in.nextInt();
int maxNoSup = maxNoSup(total);
int maxSup = maxSup(total);
// System.out.println(total + " " + maxNoSup + " " + maxSup);
if (maxNoSup >= p)
noSup++;
else if (maxSup >= p)
sup++;
}
int temp = s - sup;
if (temp <= 0)
System.out.println((noSup + s));
else
System.out.println((noSup + (sup)));
caseNum++;
}
}
private static int maxNoSup(int totalScore)
{
int i = totalScore % 3;
switch (i)
{
case 0: return totalScore/3;
case 1: return totalScore/3 + 1;
default: return totalScore/3 + 1;
}
}
private static int maxSup(int totalScore)
{
if (totalScore == 0)
return 0;
int i = totalScore % 3;
switch (i)
{
case 0: return totalScore/3 + 1;
case 1: return totalScore/3 + 1;
default: return totalScore/3 + 2;
}
}
}
|
B10361 | B13044 | 0 | package codejam;
import java.util.*;
import java.io.*;
public class RecycledNumbers {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("in.txt"));
PrintWriter out = new PrintWriter(new File("out.txt"));
int T = Integer.parseInt(in.readLine());
for (int t = 1; t <= T; ++t) {
String[] parts = in.readLine().split("[ ]+");
int A = Integer.parseInt(parts[0]);
int B = Integer.parseInt(parts[1]);
int cnt = 0;
for (int i = A; i < B; ++i) {
String str = String.valueOf(i);
int n = str.length();
String res = "";
Set<Integer> seen = new HashSet<Integer>();
for (int j = n - 1; j > 0; --j) {
res = str.substring(j) + str.substring(0, j);
int k = Integer.parseInt(res);
if (k > i && k <= B) {
//System.out.println("(" + i + ", " + k + ")");
if (!seen.contains(k)) {
++cnt;
seen.add(k);
}
}
}
}
out.println("Case #" + t + ": " + cnt);
}
in.close();
out.close();
System.exit(0);
}
}
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.StringTokenizer;
public class MainC {
private static boolean esValido(Integer n,Integer A,Integer B,boolean comp)
{
int i=0;
boolean valido=false;
if (!comp || (n>=A && n<B))
{
if (n>9)
{
while((i+1)<n.toString().length() && valido==false)
{
if (n.toString().charAt(i)!=n.toString().charAt(i+1))
{
valido=true;
}
i++;
}
}
}
return valido;
}
private static String rotar(String i)
{
return (i.charAt(i.length()-1)+i.substring(0, i.length()-1));
}
private static void combValidas(Integer i,Integer A,Integer B,HashSet<Par> conj)
{
String aux=rotar(i.toString());
Integer num=Integer.parseInt(aux);
if (esValido(num,A,B,true))
{
if (!i.equals(num))
{
conj.add(new Par(i,num));
}
//System.out.println("Se encuentra el par " + i + ", "+num + " ya que esValido "+num+" en el intervalo "+ A+ "-"+B);
}
for (int j=0;j<i.toString().length()-2;j++)
{
aux=rotar(aux);
num=Integer.parseInt(aux);
if (esValido(num,A,B,true))
{
//System.out.println("Se encuentra el par " + i + ", "+num + " ya que esValido "+num+" en el intervalo "+ A+ "-"+B);
if (!i.equals(num))
{
conj.add(new Par(i,num));
}
}
}
}
private static Integer calcularResultado(Integer A, Integer B)
{
//Para cada número hay tantas combinaciones como su longitud menos 1 (podemos rotarlo n-1 veces)
HashSet<Par> conj=new HashSet<Par>();
for (int i=A;i<B;i++)
{
if (esValido(i,A,B,false))
{
combValidas(i,A,B,conj);
}
}
//Imprimimos resultados
for (Par p:conj)
{
System.out.println(p + " en "+A+"-"+B);
}
return conj.size();
}
public static void main(String[] args) {
File archivo = null;
FileReader fr = null;
FileWriter wr = null;
PrintWriter pw = null;
BufferedReader br = null;
Integer A,B;
Integer num = 0;
String linea;
String aux;
StringTokenizer st;
try {
archivo = new File("C:/Users/Pc/Desktop/input.in");
fr = new FileReader(archivo);
br = new BufferedReader(fr);
wr = new FileWriter("C:/Users/Pc/Desktop/output.out");
pw = new PrintWriter(wr);
// Lectura del fichero
while ((linea = br.readLine()) != null) {
if (num != 0) {
aux = "Case #" + num.toString() + ": "; //Inicialización del case #N:
st=new StringTokenizer(linea," ");
A=Integer.parseInt(st.nextToken());
B=Integer.parseInt(st.nextToken());
aux+=calcularResultado(A,B).toString();
pw.println(aux);
}
num++;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != fr) {
fr.close();
wr.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
|
B21752 | B21951 | 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.InputStreamReader;
import java.util.HashSet;
public class RecycledNumbers {
private static final boolean DEBUG = false;
public static void main( final String[] args ) throws Exception {
final BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
final int t = Integer.parseInt( br.readLine() );
for ( int ii = 0; ii < t; ++ii ) {
final String parts[] = br.readLine().split( " " );
final int from = Integer.parseInt( parts[ 0 ] );
final int to = Integer.parseInt( parts[ 1 ] );
System.out.println( solve( ii + 1, from, to ) );
if ( DEBUG ) System.out.println( "=== === === === ===" );
}
}
private static String solve( final int idx, final int from, final int to ) {
final HashSet<Long> set = new HashSet<Long>();
for ( int i = from; i <= to; ++i ) {
add( set, i, from, to );
}
return String.format( "Case #%d: %d", idx, set.size() );
}
private static void add( final HashSet<Long> set, final long n, final int from, final int to ) {
final String ns = Long.toString( n );
for ( int i = 1; i < ns.length(); ++i ) {
final String f = ns.substring( 0, i );
final String t = ns.substring( i );
final long pair = getN( t, f );
final long min = Math.min( n, pair );
final long max = Math.max( n, pair );
if ( from <= pair && pair <= to && pair != n )
set.add( min * 3000000 + max );
}
}
private static long getN( final String s1, final String s2 ) {
long res = 0;
for ( int i = 0; i < s1.length(); ++i ) {
res += s1.charAt( i ) - '0';
res *= 10;
}
for ( int i = 0; i < s2.length(); ++i ) {
res += s2.charAt( i ) - '0';
res *= 10;
}
if ( DEBUG ) System.out.printf( "DEBUG: s1='%s', s2='%s', res=%d\n", s1, s2, res / 10 );
return res / 10;
}
@org.junit.Test
public void statement1() {
org.junit.Assert.assertEquals( String.format( "Case #%d: %d", 1, 0 ), solve( 1, 1, 9 ) );
}
@org.junit.Test
public void statement2() {
org.junit.Assert.assertEquals( String.format( "Case #%d: %d", 2, 3 ), solve( 2, 10, 40 ) );
}
@org.junit.Test
public void statement3() {
org.junit.Assert.assertEquals( String.format( "Case #%d: %d", 3, 156 ), solve( 3, 100, 500 ) );
}
@org.junit.Test
public void statement4() {
org.junit.Assert.assertEquals( String.format( "Case #%d: %d", 4, 287 ), solve( 4, 1111, 2222 ) );
}
@org.junit.Test(timeout = 10000)
public void my1() {
org.junit.Assert.assertEquals( String.format( "Case #%d: %d", 5, 299997 ), solve( 5, 1000000, 2000000 ) );
}
}
|
B21373 | B21042 | 0 | import java.io.*;
import java.util.*;
import java.awt.Point;
class Case{
int num0;
long num1,num2;
String result="";
public Case(File aFile) {
try{
StringBuilder contents = new StringBuilder();
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = input.readLine();
num0 = Integer.valueOf(line).intValue();
int i=1;
while (i<=num0 && ( line = input.readLine()) != null){
StringTokenizer st = new StringTokenizer(line," ");
num1=Long.valueOf(st.nextToken()).longValue();
num2=Long.valueOf(st.nextToken()).longValue();
oneCase(i,num1,num2);
i++;
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
public String getResult (){
return result;
}
public void oneCase (int c,long n1,long n2){
String re="";
//*** output
System.out.println("case="+c+": "+n1+":"+n2);
//***
int y=0;
for (long i=n1; i<=n2; i++){
y+=checkRecycle(n1,n2,i);
}
re=y+"";
result+="Case #"+c+": "+re+System.getProperty("line.separator");
}
public int checkRecycle (long n1, long n2, long num){
String numSt=Long.valueOf(num).toString();
if (numSt.length()<2) return 0;
int re=0;
Vector allNum=new Vector();
for (int i=1; i<numSt.length(); i++){
String newNumSt=numSt.substring(i)+numSt.substring(0,i);
if (!newNumSt.substring(0,1).equals("0")){
if (Long.valueOf(newNumSt).longValue()>num){
if (Long.valueOf(newNumSt).longValue()>n1 && Long.valueOf(newNumSt).longValue()<=n2){
boolean found=false;
for (int j=0;!found&&j<allNum.size();j++){
if (newNumSt.equals((String)(allNum.elementAt(j))))
found=true;
}
if (!found){
allNum.addElement(newNumSt);
re++;
}
}
}
}
}
//if (re>0)System.out.println("checkRecycle "+numSt+" re="+re+" allNum="+allNum);
return re;
}
}
public class ReadWriteTextFile {
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
static public void setContents(File aFile, String aContents)
throws FileNotFoundException, IOException {
if (aFile == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!aFile.exists()) {
throw new FileNotFoundException ("File does not exist: " + aFile);
}
if (!aFile.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) {
throw new IllegalArgumentException("File cannot be written: " + aFile);
}
Writer output = new BufferedWriter(new FileWriter(aFile));
try {
output.write( aContents );
}
finally {
output.close();
}
}
public static void main (String... aArguments) throws IOException {
File testFile = new File("source.txt");
File testFile2 = new File("result.txt");
Case allcases = new Case(testFile);
setContents(testFile2, allcases.getResult());
}
}
| package de.hg.codejam.tasks.io;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public abstract class Writer {
public static String generateOutputPath(String inputPath) {
return inputPath.substring(0, inputPath.lastIndexOf('.') + 1) + "out";
}
public static void print(String[] output) {
for (String s : output)
System.out.println(s);
}
public static void write(String[] output) {
for (int i = 0; i < output.length; i++)
System.out.println(getCase(i + 1, output[i]));
}
public static void write(String[] output, String path) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(path,
false))) {
for (int i = 0; i < output.length; i++) {
writer.append(getCase(i + 1, output[i]));
writer.newLine();
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getCase(int number, String caseString) {
return "Case #" + (number) + ": " + caseString;
}
}
|
B20424 | B20120 | 0 | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
// static int MAX = 10000;
static int MAX = 2000000;
static Object[] All = new Object[MAX+1];
static int size( int x ) {
if(x>999999) return 7;
if(x>99999) return 6;
if(x>9999) return 5;
if(x>999) return 4;
if(x>99) return 3;
if(x>9) return 2;
return 1;
}
static int[] rotate( int value ) {
List<Integer> result = new ArrayList<Integer>();
int[] V = new int[8];
int s = size(value);
int x = value;
for(int i=s-1;i>=0;i--) {
V[i] = x%10;
x /=10;
}
int rot;
for(int i=1; i<s; i++) {
if(V[i]!=0){
rot=0;
for(int j=0,ii=i;j<s; j++,ii=(ii+1)%s){
rot=rot*10+V[ii];
}
if(rot>value && !result.contains(rot))
result.add(rot);
}
}
if( result.isEmpty() )
return null;
int[] r = new int[result.size()];
for(int i=0; i<r.length; i++)
r[i]=result.get(i);
return r;
}
static void precalculate() {
for(int i=1; i<=MAX; i++){
All[i] = rotate(i);
}
}
static int solve( Scanner in ) {
int A, B, sol=0;
A = in.nextInt();
B = in.nextInt();
for( int i=A; i<=B; i++) {
// List<Integer> result = rotate(i);
if( All[i]!=null ) {
for(int value: (int[])All[i] ) {
if( value <= B )
sol++;
}
}
}
return sol;
}
public static void main ( String args[] ) {
int T;
Scanner in = new Scanner(System.in);
T = in.nextInt();
int cnt=0;
int sol;
precalculate();
for( cnt=1; cnt<=T; cnt++ ) {
sol = solve( in );
System.out.printf("Case #%d: %d\n", cnt, sol);
}
}
}
| package taskc;
import java.util.*;
public class TaskC {
public static void main(String[] args) {
new TaskC().main();
}
int numOfDigits(int x) {
int res = 0;
while (x > 0) {
res++;
x /= 10;
}
return res;
}
int getCycle(int n, int i) {
String s = Integer.toString(n);
int leftlen = s.length() - i;
String res = s.substring(leftlen) + s.substring(0, leftlen);
return Integer.parseInt(res);
}
Set<Integer> generateCycleNumbers(int x) {
Set<Integer> res = new HashSet<Integer>();
int n = numOfDigits(x);
for (int i = 1; i < n; i++) {
int z = getCycle(x, i);
if (numOfDigits(z) == numOfDigits(x)) {
res.add(z);
}
}
return res;
}
int f(int x, int y) {
int res = 0;
for (int i = x; i <= y; i++) {
Set<Integer> cycles = generateCycleNumbers(i);
for (int q: cycles) {
if (q >= x && q <= y && q != i) {
//System.out.println(i +" -> " + q);
res++;
}
}
}
return res/2;
}
void main() {
Scanner s = new Scanner(System.in);
int T = s.nextInt();
for (int i = 1; i <= T; i++) {
int a = s.nextInt(), b = s.nextInt();
int ans = f(a, b);
System.out.println("Case #" + i + ": " + ans);
}
}
}
|
B12085 | B12240 | 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.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
public class RecycledNumbers {
private static FileReader freader;
private static BufferedReader buffreader;
private static FileWriter fwriter;
private static BufferedWriter buffwriter;
public static void main(String[] args) throws IOException {
freader = new FileReader("C-small-attempt0.in");
buffreader = new BufferedReader(freader);
fwriter= new FileWriter("result.txt");
buffwriter = new BufferedWriter(fwriter);
String str = null;
int linenum = 0;
int i=1;
while((str=buffreader.readLine())!=null){
if(i==1)
linenum=Integer.parseInt(str);
else{
int start = Integer.parseInt(str.split(" ")[0]);
int end = Integer.parseInt(str.split(" ")[1]);
int num = calRecycleNum(start, end);
String finalStr = "Case #"+Integer.toString(i-1)+": "+Integer.toString(num)+"\n";
buffwriter.write(finalStr);
}
i++;
}
buffwriter.close();
fwriter.close();
buffreader.close();
freader.close();
}
public static int calRecycleNum(int start, int end){
int num = 0;
for(int i=start; i<=end; i++){
int len = Integer.toString(i).length();
int recycleVal = i;
HashSet<Integer> targetSet = new HashSet<Integer>();
for(int j=1; j<len; j++){
recycleVal = recycleOnce(recycleVal,len);
if(recycleVal<=i)
continue;
else if(recycleVal<=end && recycleVal>=start){
if(!targetSet.contains(recycleVal)){
num++;
//System.out.println(i+"\t"+recycleVal);
targetSet.add(recycleVal);
}
/*else{
System.out.println("Duplicate:"+recycleVal+"\t"+i);
}*/
}
}
}
//System.out.println(num);
return num;
}
public static int recycleOnce(int val, int length){
return (int) (val%Math.pow(10, length-1)*10+val/Math.pow(10, length-1));
}
}
|
A11277 | A10750 | 0 | package googlers;
import java.util.Scanner;
import java.util.PriorityQueue;
import java.util.Comparator;
public class Googlers {
public static void main(String[] args) {
int n,s,p,count=0,t;
Scanner sin=new Scanner(System.in);
t=Integer.parseInt(sin.nextLine());
int result[]=new int[t];
int j=0;
if(t>=1 && t<=100)
{
for (int k = 0; k < t; k++) {
count=0;
String ip = sin.nextLine();
String[]tokens=ip.split(" ");
n=Integer.parseInt(tokens[0]);
s=Integer.parseInt(tokens[1]);
p=Integer.parseInt(tokens[2]);
if( (s>=0 && s<=n) && (p>=0 && p<=10) )
{
int[] total=new int[n];
for (int i = 0; i < n; i++)
{
total[i] = Integer.parseInt(tokens[i+3]);
}
Comparator comparator=new PointComparator();
PriorityQueue pq=new PriorityQueue<Point>(1, comparator);
for (int i = 0; i < n; i++)
{
int x=total[i]/3;
int r=total[i]%3;
if(x>=p)
count++;
else if(x<(p-2))
continue;
else
{
//System.out.println("enter "+x+" "+(p-2));
if(p-x==1)
{
Point temp=new Point();
temp.q=x;
temp.r=r;
pq.add(temp);
}
else // p-x=2
{
if(r==0)
continue;
else
{
Point temp=new Point();
temp.q=x;
temp.r=r;
pq.add(temp);
}
}
}
//System.out.println("hi "+pq.size());
}
while(pq.size()!=0)
{
Point temp=(Point)pq.remove();
if(p-temp.q==1 && temp.q!=0)
{
if(temp.r>=1)
count++;
else
{
if(s!=0)
{
s--;
count++;
}
}
}
else if(p-temp.q==2)
{
if(s!=0 && (temp.q+temp.r)>=p)
{
s--;
count++;
}
}
}
//System.out.println(p);
result[j++]=count;
}
}
for (int i = 0; i < t; i++)
{
System.out.println("Case #"+(i+1)+": "+result[i]);
}
}
}
/*Point x=new Point();
x.q=8;
Point y=new Point();
y.q=6;
Point z=new Point();
z.q=7;
pq.add(x);
pq.add(y);
pq.add(z);
*/
}
class PointComparator implements Comparator<Point>
{
@Override
public int compare(Point x, Point y)
{
// Assume neither string is null. Real code should
// probably be more robust
if (x.q < y.q)
{
return 1;
}
if (x.q > y.q)
{
return -1;
}
return 0;
}
}
class Point
{
int q,r;
public int getQ() {
return q;
}
public void setQ(int q) {
this.q = q;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
}
| import java.util.Scanner;
/*
* Google Code Jam 2012
* Program by Tommy Ludwig
* Problem: Dancing With the Googlers
* Date: 2012-04-13
*/
public class dancing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T, N, S, p;
T = in.nextInt();
for (int i = 1; i <= T; i++) {
int y = 0;
N = in.nextInt();
S = in.nextInt();
p = in.nextInt();
int [] t = new int[N];
for (int j = 0; j < N; j++)
t[j] = in.nextInt();
//minimum number with surprise case
int minNumS = (3 * p) - 4;
if (minNumS < 2) minNumS = 2;
//minimum number without surprise case
int minNum = (3 * p) - 2;
//if (minNum < 0) minNum = 0;
for (int j = 0; j < N; j++) {
if (t[j] >= minNum)
y++;
else if (t[j] >= minNumS && S > 0) {
y++;
S--;
}
}
System.out.printf("Case #%d: %d\n", i, y);
}
}
}
|
B10485 | B12231 | 0 |
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class Recycle
{
public static void main(String[] args)
{
/* Set<Integer> perms = getPermutations(123456);
for(Integer i: perms)
System.out.println(i);*/
try
{
Scanner s = new Scanner(new File("recycle.in"));
BufferedWriter w = new BufferedWriter(new FileWriter(new File("recycle.out")));
int numCases = s.nextInt();
s.nextLine();
for(int n = 1;n <= numCases; n++)
{
int A = s.nextInt();
int B = s.nextInt();
int count = 0;
for(int k = A; k <= B; k++)
{
count += getNumPairs(k, B);
}
w.write("Case #" + n + ": " + count + "\n");
}
w.flush();
w.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static int getNumPairs(int n, int B)
{
Set<Integer> possibles = getPermutations(n);
int count = 0;
for(Integer i : possibles)
if(i > n && i <= B)
count++;
return count;
}
public static Set<Integer> getPermutations(int n)
{
Set<Integer> perms = new TreeSet<Integer>();
char[] digits = String.valueOf(n).toCharArray();
for(int firstPos = 1; firstPos < digits.length; firstPos++)
{
String toBuild = "";
for(int k = 0; k < digits.length; k++)
toBuild += digits[(firstPos + k) % digits.length];
perms.add(Integer.parseInt(toBuild));
}
return perms;
}
} | import java.io.*;
class Programa
{
public static long procesar(String linea)
{
String vals[]=linea.split(" ");
int digitos=vals[0].length();
long a,b;
a=Long.parseLong(vals[0]);
b=Long.parseLong(vals[1]);
long reciclados=0;
int indi,ind = (int)(b-a+1);
int parejas[][]=new int[ind][ind];
long t=b-a+1;
long cal;
long v,resto,pot;
String resu,resu2;
/* for (long =0;l<t;l++) {
r[(int)l]=0;
r[(int)l]=0;
}*/
for (long l=a;l<=b;l++)
{
ind=(int) (l-a);
for (int k=1;k<digitos;k++)
{
pot=(long) Math.pow(10,k);
resto=l%pot;
v=l/pot;
resu=""+resto+v;
cal=Long.parseLong(resu);
indi=(int) (l-a);
ind=(int) (cal-a);
if (cal>=a && cal<=b && cal!=l && parejas[indi][ind]==0 && parejas[ind][indi]==0 )
{
// System.out.println(""+l+" "+cal);
parejas[indi][ind]=1;
reciclados++;
}
}
}
return reciclados;
}
public static void main(String args[])
{
try{
FileInputStream fstream = new FileInputStream(args[0]);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
strLine = br.readLine();
int casos=Integer.parseInt(strLine);
int caso=1;
long respuesta=0;
while ((strLine = br.readLine()) != null) {
respuesta=procesar(strLine);
System.out.println("Case #"+caso+": "+respuesta);
caso++;
}
//Close the input stream
in.close();
}catch (IOException e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
} |
B10899 | B11905 | 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.util.*;
public class C
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int test = 1, cases = sc.nextInt();
int a, b, curr, count;
String aStr, bStr, num, shift;
while(test <= cases)
{
count = 0;
a = sc.nextInt();
b = sc.nextInt();
aStr = Integer.toString(a);
bStr = Integer.toString(b);
for(curr = a; curr <= b; curr++)
{
num = Integer.toString(curr);
shift = nextShift(num);
while(!num.equals(shift))
{
if(shift.charAt(0) != '0' && aStr.compareTo(shift) <= 0 && bStr.compareTo(shift) >= 0 && num.compareTo(shift) < 0)
count++;
shift = nextShift(shift);
}
}
System.out.println("Case #" + test + ": " + count);
test++;
}
}
public static String nextShift(String s)
{
if(s.length() <= 1)
return s;
else return s.substring(1, s.length()) + s.substring(0, 1);
}
} |
B10702 | B12419 | 0 | import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class Recycle {
private static HashMap<Integer, HashSet<Integer>> map = new HashMap<Integer, HashSet<Integer>>();
private static HashSet<Integer> toSkip = new HashSet<Integer>();
/**
* @param args
*/
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int T = reader.nextInt();
for (int tc = 1; tc <= T; tc++) {
int a = reader.nextInt();
int b = reader.nextInt();
long before = System.currentTimeMillis();
int res = doit(a, b);
System.out.printf("Case #%d: %d\n", tc, res);
long after = System.currentTimeMillis();
// System.out.println("time taken: " + (after - before));
}
}
private static int doit(int a, int b) {
int count = 0;
HashSet<Integer> skip = new HashSet<Integer>(toSkip);
for (int i = a; i <= b; i++) {
if (skip.contains(i))
continue;
HashSet<Integer> arr = generate(i);
// if(arr.size() > 1) {
// map.put(i, arr);
// }
// System.out.println(i + " --> " +
// Arrays.deepToString(arr.toArray()));
int temp = 0;
if (arr.size() > 1) {
for (int x : arr) {
if (x >= a && x <= b) {
temp++;
skip.add(x);
}
}
count += temp * (temp - 1) / 2;
}
// System.out.println("not skipping " + i + " gen: " + arr.size()+ " " + (temp * (temp - 1) / 2));
}
return count;
}
private static HashSet<Integer> generate(int num) {
if(map.containsKey(num)) {
HashSet<Integer> list = map.get(num);
return list;
}
HashSet<Integer> list = new HashSet<Integer>();
String s = "" + num;
list.add(num);
int len = s.length();
for (int i = 1; i < len; i++) {
String temp = s.substring(i) + s.substring(0, i);
// System.out.println("temp: " + temp);
if (temp.charAt(0) == '0')
continue;
int x = Integer.parseInt(temp);
if( x <= 2000000) {
list.add(x);
}
}
if(list.size() > 1) {
map.put(num, list);
} else {
toSkip.add(num);
}
return list;
}
}
| import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
/**
* Created by IntelliJ IDEA.
* User: elbek
* Date: 4/13/12
* Time: 7:31 PM
* To change this template use File | Settings | File Templates.
*/
public class Test {
public static void main(String[] args) {
int count = 0;
Set<String> found = new TreeSet<String>();
int t = 50;
Scanner scanner = new Scanner(System.in);
for (int q = 0; q <= t; q++) {
count = 0;
String str = scanner.nextLine();
String []arg = str.split(" ");
Integer a = Integer.parseInt(arg[0]);
Integer b = Integer.parseInt(arg[1]);
for (int i = a; i <= b; i++) {
String input = String.valueOf(i);
String changed;
int len = input.length();
for (int j = 1; j < len; j++) {
changed = input.substring(j, len) + input.substring(0, j);
if (Integer.valueOf(changed) <= Integer.valueOf(input)) continue;
if (Integer.valueOf(changed) <= b && Integer.valueOf(changed) >= a) {
found.add(input + " - " + changed);
// found.add(changed);
count++;
}
}
}
System.out.println("Case #"+(q+1)+": "+count);
}
}
}
|
A22191 | A21460 | 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.*;
public class Dancing{
public static void main(String args []){
try{
FileInputStream fstream = new FileInputStream("Blarge.in");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
FileWriter ostream = new FileWriter("danceOut.txt");
BufferedWriter out = new BufferedWriter(ostream);
String str = br.readLine();
int num = Integer.parseInt(str.replaceAll("\\s",""));
String [] cases = new String[num];
String temp;
int k = 0;
while((temp = br.readLine()) != null && k < num){
cases[k] = temp;
++k;
}
for(int i=1; i<= num; i++){
String scores = cases[i-1].trim();
int n = calcScores(scores);
out.write("Case #" + i + ": " + n);
out.write("\n");
out.flush();
}
out.close();
}
catch(Exception e){}
}
public static int calcScores(String input){
String [] nums = input.split(" ");
int N = Integer.parseInt(nums[0].replaceAll("\\s",""));
int s = Integer.parseInt(nums[1].replaceAll("\\s",""));
int p = Integer.parseInt(nums[2].replaceAll("\\s",""));
int scores[] = new int[N];
int max = 0;
int sLeft = s;
for (int i=0; i< N; i++)
scores[i] = Integer.parseInt(nums[3+i].replaceAll("\\s",""));
for(int i=0; i < N; i++){
int x = scores[i];
if(findMax(x) >= p)
++max;
else{
if(sLeft > 0 && findSurprise(x) >= p){
++max;
--sLeft;
}
}
}
return max;
}
// Three cases: mod 1, mod 2 or mod 0
public static int findMax(int x){
if(x % 3 == 0)
return x/3;
else
return (x/3) + 1;
}
public static int findSurprise(int x){
if(x % 3 == 2)
return (x/3) + 2;
else if(x != 0)
return (x/3) + 1;
else
return 0;
}
}
|
A22992 | A20361 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package IO;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
*
* @author dannocz
*/
public class InputReader {
public static Input readFile(String filename){
try {
/* Sets up a file reader to read the file passed on the command
77 line one character at a time */
FileReader input = new FileReader(filename);
/* Filter FileReader through a Buffered read to read a line at a
time */
BufferedReader bufRead = new BufferedReader(input);
String line; // String that holds current file line
int count = 0; // Line number of count
ArrayList<String> cases= new ArrayList<String>();
// Read first line
line = bufRead.readLine();
int noTestCases=Integer.parseInt(line);
count++;
// Read through file one line at time. Print line # and line
while (count<=noTestCases){
//System.out.println("Reading. "+count+": "+line);
line = bufRead.readLine();
cases.add(line);
count++;
}
bufRead.close();
return new Input(noTestCases,cases);
}catch (ArrayIndexOutOfBoundsException e){
/* If no file was passed on the command line, this expception is
generated. A message indicating how to the class should be
called is displayed */
e.printStackTrace();
}catch (IOException e){
// If another exception is generated, print a stack trace
e.printStackTrace();
}
return null;
}// end main
}
| package R0;
import java.io.*;
import java.util.*;
public class B {
private static void solve(int TC) {
int N = ni();
int S = ni();
int p = ni();
int g[] = new int[N];
for (int i = 0; i < g.length; i++)
g[i] = ni();
int ok = 3 * p - 2;
int pok = ok - 2;
if ( p == 1 )
pok = 1;
int ret = 0;
for (int i : g) {
if ( i >= ok ) {
ret++;
continue;
}
if ( S > 0 && i >= pok ) {
ret++;
S--;
}
}
out.println(String.format("Case #%d: %d", TC, ret));
}
private static final boolean STDIO = false;
private static final String TASK = "B";
private static final String ROUND = "R0";
private static final String DATA = "large";
private static Scanner sc;
private static PrintStream out;
public static void main(String[] args) throws FileNotFoundException, IOException {
Locale.setDefault(Locale.ENGLISH);
String DATA_IN = String.format("tst/%s/%s.%s.in", ROUND, TASK, DATA);
String DATA_OUT = String.format("tst/%s/%s.%s.out", ROUND, TASK, DATA);
String str = null;
if ( args.length > 0 )
str = args[0];
else if ( !STDIO )
str = DATA_IN;
sc = new Scanner((str != null) ? new FileInputStream(str) : System.in);
str = null;
if ( args.length > 1 )
str = args[1];
else if ( !STDIO )
str = DATA_OUT;
out = (str != null) ? new PrintStream(str) : System.out;
int TC = ni();
for (int i = 1; i <= TC; i++) {
solve(i);
}
}
private static int ni() {
return sc.nextInt();
}
}
|
B20424 | B21756 | 0 | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
// static int MAX = 10000;
static int MAX = 2000000;
static Object[] All = new Object[MAX+1];
static int size( int x ) {
if(x>999999) return 7;
if(x>99999) return 6;
if(x>9999) return 5;
if(x>999) return 4;
if(x>99) return 3;
if(x>9) return 2;
return 1;
}
static int[] rotate( int value ) {
List<Integer> result = new ArrayList<Integer>();
int[] V = new int[8];
int s = size(value);
int x = value;
for(int i=s-1;i>=0;i--) {
V[i] = x%10;
x /=10;
}
int rot;
for(int i=1; i<s; i++) {
if(V[i]!=0){
rot=0;
for(int j=0,ii=i;j<s; j++,ii=(ii+1)%s){
rot=rot*10+V[ii];
}
if(rot>value && !result.contains(rot))
result.add(rot);
}
}
if( result.isEmpty() )
return null;
int[] r = new int[result.size()];
for(int i=0; i<r.length; i++)
r[i]=result.get(i);
return r;
}
static void precalculate() {
for(int i=1; i<=MAX; i++){
All[i] = rotate(i);
}
}
static int solve( Scanner in ) {
int A, B, sol=0;
A = in.nextInt();
B = in.nextInt();
for( int i=A; i<=B; i++) {
// List<Integer> result = rotate(i);
if( All[i]!=null ) {
for(int value: (int[])All[i] ) {
if( value <= B )
sol++;
}
}
}
return sol;
}
public static void main ( String args[] ) {
int T;
Scanner in = new Scanner(System.in);
T = in.nextInt();
int cnt=0;
int sol;
precalculate();
for( cnt=1; cnt<=T; cnt++ ) {
sol = solve( in );
System.out.printf("Case #%d: %d\n", cnt, sol);
}
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package recyclednumbers;
/**
*
* @author WC
*/
public class RecycledNumbers {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
(new RecycledNumbers()).findRecycledNumbers("C-large.in", "C-large.out", "\n");
}
private void findRecycledNumbers(String filename, String outputFile, String separator) {
int numberOfTestCases = CodeJamFileManager.getIntFromFirstLineOfFile(filename, separator);
String[] testCases = CodeJamFileManager.getTextLinesOfFile(filename, separator);
String output = "";
for (int i = 1; i <= numberOfTestCases; i++) {
output += "Case #" + i + ": " + getNumberOfRecycledInts(testCases[i]) + (i != numberOfTestCases ? separator : "");
}
CodeJamFileManager.saveOutputFile(output, outputFile, separator);
}
private int getNumberOfRecycledInts(String testcase) {
int[] params = getIntArrayFromString(testcase.split(" "));
int lower = params[0];
int upper = params[1];
int currentM = lower + 1;
int numberOfRecycles = 0;
while (currentM <= upper) {
int count = timesRecycled(lower, currentM++);
numberOfRecycles += count;
}
return numberOfRecycles;
}
private int timesRecycled(int lower, int currentM) {
String currentMStr = String.valueOf(currentM);
char[] individualNumbers = currentMStr.toCharArray();
int timesRecycled = 0;
for (int i = 1; i < individualNumbers.length; i++) {
int flip = flip(individualNumbers, i);
if (flip >= lower && flip < currentM) {
timesRecycled++;
}
}
return timesRecycled;
}
private int flip(char[] individualNumbers, int positionsToFlip) {
char[] flip = new char[individualNumbers.length];
int startInt = individualNumbers.length - positionsToFlip;
int flipPos = 0;
while (startInt < individualNumbers.length) {
flip[flipPos++] = individualNumbers[startInt++];
}
int i = 0;
while (i < (individualNumbers.length - positionsToFlip)) {
flip[flipPos++] = individualNumbers[i++];
}
return Integer.parseInt(String.valueOf(flip));
}
private int[] getIntArrayFromString(String[] intStrArray) {
int[] intArray = new int[intStrArray.length];
int i = 0;
for (String intStr : intStrArray) {
intArray[i++] = Integer.parseInt(intStr);
}
return intArray;
}
}
|
A20490 | A20063 | 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.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class DancingGooglers {
private final String inputFile = "D:\\input.in";
private final String outputFile = "D:\\output.out";
private static class TestCase{
int n;
int s;
int p;
int result = 0;
List<Integer> ti = new ArrayList<Integer>();
public void calculateBest(){
result = 0;
int max = p * 3;
for (int i: ti){
if (p <= 0){
result++;
continue;
}
if (i > 0 && i >= (max - 4)){
if (i >= max || (max - i) <= 2){
result++;
}else if((max - i) <= 4 && s > 0){
result++; s--;
}
}
}
}
}
List<TestCase> input = new ArrayList<DancingGooglers.TestCase>();
public void parseInput(){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
int numTestCases = Integer.parseInt(br.readLine());
for (int i = 0; i < numTestCases; i++){
String [] lineTokens = br.readLine().split(" ");
TestCase tc = new TestCase();
tc.n = Integer.parseInt(lineTokens[0]);
tc.s = Integer.parseInt(lineTokens[1]);
tc.p = Integer.parseInt(lineTokens[2]);
for (int j = 3; j < lineTokens.length; j++){
tc.ti.add(Integer.parseInt(lineTokens[j]));
}
tc.calculateBest();
input.add(tc);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doOutput(){
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(outputFile));
for (int i = 0; i < input.size(); i++){
TestCase tc = input.get(i);
pw.println("Case #" + (i + 1) + ": " + tc.result);
}
pw.flush();
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String [] args){
DancingGooglers dg = new DancingGooglers();
dg.parseInput();
dg.doOutput();
}
}
|
A12846 | A12385 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package codejam.common;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Lance Chen
*/
public class CodeHelper {
private static String FILE_ROOT = "D:/workspace/googlecodejam/meta";
public static List<List<String>> loadInputsExcludes(String fileName) {
List<List<String>> result = new ArrayList<List<String>>();
List<String> lines = FileUtil.readLines(FILE_ROOT + fileName);
int index = 0;
for (String line : lines) {
if (index == 0) {
index++;
continue;
}
if (index % 2 == 1) {
index++;
continue;
}
List<String> dataList = new ArrayList<String>();
String[] dataArray = line.split("\\s+");
for (String data : dataArray) {
if (data.trim().length() > 0) {
dataList.add(data);
}
}
result.add(dataList);
index++;
}
return result;
}
public static List<List<String>> loadInputs(String fileName) {
List<List<String>> result = new ArrayList<List<String>>();
List<String> lines = FileUtil.readLines(FILE_ROOT + fileName);
for (String line : lines) {
List<String> dataList = new ArrayList<String>();
String[] dataArray = line.split("\\s+");
for (String data : dataArray) {
if (data.trim().length() > 0) {
dataList.add(data);
}
}
result.add(dataList);
}
return result;
}
public static List<String> loadInputLines(String fileName) {
return FileUtil.readLines(FILE_ROOT + fileName);
}
public static void writeOutputs(String fileName, List<String> lines) {
FileUtil.writeLines(FILE_ROOT + fileName, lines);
}
}
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Solution2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// System.out.println(Solution2.calculteBestNum("6 2 8 29 20 8 18 18 21"));
BufferedReader bReader = null;
FileWriter fWriter = null;
try {
bReader = new BufferedReader(new FileReader(new File("B-small-attempt0.in")));
fWriter = new FileWriter(new File("Output"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int num = 0;
try {
num = Integer.parseInt(bReader.readLine());
} catch (NumberFormatException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for(int i = 1; i < num + 1; i ++){
String ssString = "";
try {
ssString = bReader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(ssString == null){
break;
}
else if(ssString.trim() == ""){
continue;
}
try {
fWriter.write("Case #"+ i +": " + Solution2.calculteBestNum(ssString));
fWriter.write("\n");
fWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static int calculteBestNum(String scores){
String[] tmp = scores.split(" ");
int num = Integer.parseInt(tmp[0].trim());
int surprising = Integer.parseInt(tmp[1].trim());
int p = Integer.parseInt(tmp[2].trim());
int key = 0;
int finalnum = 0;
for(int i = 0; i < num; i ++){
int score = Integer.parseInt(tmp[i + 3].trim());
if(score > 3 * (p - 1)){
finalnum++;
}
else if(key < surprising){
if(score >= p && score>= 3*p -4){
finalnum++;
key++;
}
}
}
return finalnum;
}
}
|
A12544 | A10309 | 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 org.cb.projectb.dancingwiththegooglers;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Contest {
public static void main(String[] args) throws FileNotFoundException {
File input = new File(System.getProperty("user.dir") + "/" + "resources/projectB/B-small-attempt0.in");
Scanner sc = new Scanner(input);
List<DanceOff> contests = new ArrayList<DanceOff>();
if (sc.hasNext()) {
Integer.parseInt(sc.nextLine()); // number of cases - ignored
while (sc.hasNext()) {
String contestString = sc.nextLine();
StringTokenizer contestTokenizer = new StringTokenizer(contestString);
int contestants = Integer.parseInt(contestTokenizer.nextToken());
int surprisingTriplets = Integer.parseInt(contestTokenizer.nextToken());
int scoreWeCareAbout = Integer.parseInt(contestTokenizer.nextToken());
List<Integer> scores = new ArrayList<Integer>();
for(int i = 0; i < contestants; i ++) {
scores.add(Integer.parseInt(contestTokenizer.nextToken()));
}
contests.add(new DanceOff(contestants, surprisingTriplets, scoreWeCareAbout, scores));
}
}
for(int i = 1; i <= contests.size(); i ++) {
DanceOff danceoff = contests.get(i-1);
System.out.println("Case #" + i + ": " + danceoff.getNumberAllowedToBeImportant());
}
}
private static class DanceOff {
private final int contestants;
private final int surprisingTriplets;
private final int scoreWeCareAbout;
private final List<Integer> contestantScores;
private final int numberAllowedToBeImportant;
public DanceOff(int contestants, int surprisingTriplets, int scoreWeCareAbout, List<Integer> contestantScores) {
this.contestants = contestants;
this.surprisingTriplets = surprisingTriplets;
this.scoreWeCareAbout = scoreWeCareAbout;
this.contestantScores = contestantScores;
this.numberAllowedToBeImportant = fillInDetails();
}
private int fillInDetails() {
int importantScores = 0;
List<Integer[]> allProbableScores = new ArrayList<Integer[]>();
for(Integer score: contestantScores) {
// System.out.print(score + " - ");
int baseScore = score / 3;
int remaining = score % 3;
Integer[] scoresArray = new Integer[]{baseScore, baseScore, baseScore};
for(int i = 0; i < remaining; i++) {
scoresArray[i] = scoresArray[i] + 1;
}
// System.out.print("Probable tripplet: [");
// for(int i = 0; i < scoresArray.length; i++) {
// System.out.print(scoresArray[i] + " ");
// }
// System.out.println("]");
allProbableScores.add(scoresArray);
}
int freebeeImportantScores = 0;
int ableToBeImportantIfSurprising = 0;
for (Integer[] scoresList : allProbableScores) {
// count how many in scores array are already important
boolean isImportant = false;
boolean canBeSurprising = false;
for (Integer integer : scoresList) {
if(integer >= this.scoreWeCareAbout) {
isImportant = true;
break;
}
}
if(isImportant) {
freebeeImportantScores++;
} else {
// see how many i can make 'surprising' to then care about
if(scoresList[0] + 1 >= this.scoreWeCareAbout) {
if(scoresList[0] == scoresList[1] && scoresList[0] != 0) {
canBeSurprising = true;
}
}
if(canBeSurprising) {
ableToBeImportantIfSurprising++;
}
}
}
// take min of allowed surprising & how many could be surprised
int numToMakeSpecial = Math.min(ableToBeImportantIfSurprising, this.surprisingTriplets);
// add min to current important scores
importantScores = freebeeImportantScores + numToMakeSpecial;
// System.out.println("Freebee important: " + freebeeImportantScores);
// System.out.println("Can be Made Important with surprising Score: " + ableToBeImportantIfSurprising);
// System.out.println("Num Of Scores we are making surprising: " + numToMakeSpecial);
// System.out.println("Max Special Scores: " + importantScores);
// System.out.println();
return importantScores;
}
public int getNumberAllowedToBeImportant() {
return numberAllowedToBeImportant;
}
@Override
public String toString() {
return "DanceOff [contestants = " + contestants
+ ", surprisingTriplets = " + surprisingTriplets
+ ", scoreWeCareAbout = " + scoreWeCareAbout
+ ", contestantScores = " + contestantScores + "]";
}
}
}
|
A21557 | A21937 | 0 | import java.io.*;
import java.util.*;
public class DancingWithGooglers {
public static class Googlers {
public int T;
public int surp;
public boolean surprising;
public boolean pSurprising;
public boolean antiSurprising;
public boolean pAntiSurprising;
public Googlers(int T, int surp) {
this.T = T;
this.surp = surp;
}
public void set(int a, int b, int c) {
if (c >= 0 && (a + b + c) == T) {
int diff = (Math.max(a, Math.max(b, c)) - Math.min(a, Math.min(b, c)));
if (diff <= 2) {
if (diff == 2) {
if (a >= surp || b >= surp || c >= surp) {
pSurprising = true;
} else {
surprising = true;
}
} else {
if (a >= surp || b >= surp || c >= surp) {
pAntiSurprising = true;
} else {
antiSurprising = true;
}
}
}
}
}
}
public static void main(String... args) throws IOException {
// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader reader = new BufferedReader(new FileReader("B-large.in"));
// PrintWriter writer = new PrintWriter(System.out);
PrintWriter writer = new PrintWriter("B-large.out");
int len, cases = Integer.parseInt(reader.readLine());
List<Googlers> satisfied = new ArrayList<Googlers>();
List<Googlers> unsatisfied = new ArrayList<Googlers>();
String[] inputs;
int N, S, p;
for (int i = 1; i <= cases; i++) {
inputs = reader.readLine().split(" ");
p = Integer.parseInt(inputs[1]);
S = Integer.parseInt(inputs[2]);
satisfied.clear();
unsatisfied.clear();
for (int j = 3; j < inputs.length; j++) {
int t = Integer.parseInt(inputs[j]);
Googlers googlers = new Googlers(t, S);
for (int k = 0; k <= 10; k++) {
int till = k + 2 > 10 ? 10 : k + 2;
for (int l = k; l <= till; l++) {
googlers.set(k, l, (t - (k + l)));
}
}
if (googlers.pAntiSurprising) {
satisfied.add(googlers);
} else {
unsatisfied.add(googlers);
}
}
int pSurprising = 0;
if (p > 0) {
for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.pSurprising) {
pSurprising++;
iter.remove();
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.surprising) {
iter.remove();
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.pSurprising) {
iter.remove();
pSurprising++;
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.surprising) {
iter.remove();
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
writer.print("Case #" + i + ": 0");
}else {
writer.print("Case #" + i + ": " + (satisfied.size() + pSurprising));
}
writer.println();
}
writer.flush();
}
}
| package jp.funnything.competition.util;
public enum Direction {
UP , DOWN , LEFT , RIGHT;
public int dx() {
switch ( this ) {
case UP:
case DOWN:
return 0;
case LEFT:
return -1;
case RIGHT:
return 1;
default:
throw new RuntimeException( "assert" );
}
}
public int dy() {
switch ( this ) {
case UP:
return -1;
case DOWN:
return 1;
case LEFT:
case RIGHT:
return 0;
default:
throw new RuntimeException( "assert" );
}
}
public Direction reverese() {
switch ( this ) {
case UP:
return DOWN;
case DOWN:
return UP;
case LEFT:
return RIGHT;
case RIGHT:
return LEFT;
default:
throw new RuntimeException( "assert" );
}
}
public Direction turnLeft() {
switch ( this ) {
case UP:
return LEFT;
case DOWN:
return RIGHT;
case LEFT:
return DOWN;
case RIGHT:
return UP;
default:
throw new RuntimeException( "assert" );
}
}
public Direction turnRight() {
switch ( this ) {
case UP:
return RIGHT;
case DOWN:
return LEFT;
case LEFT:
return UP;
case RIGHT:
return DOWN;
default:
throw new RuntimeException( "assert" );
}
}
}
|
A20490 | A20837 | 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.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
public class tongue {
static HashMap<String, String> translationMap = new HashMap<String, String>();
private static void init() {
translationMap.put("a", "y");
translationMap.put("b", "h");
translationMap.put("c", "e");
translationMap.put("d", "s");
translationMap.put("e", "o");
translationMap.put("f", "c");
translationMap.put("g", "v");
translationMap.put("h", "x");
translationMap.put("i", "d");
translationMap.put("j", "u");
translationMap.put("k", "i");
translationMap.put("l", "g");
translationMap.put("m", "l");
translationMap.put("n", "b");
translationMap.put("o", "k");
translationMap.put("p", "r");
translationMap.put("q", "z");
translationMap.put("r", "t");
translationMap.put("s", "n");
translationMap.put("t", "w");
translationMap.put("u", "j");
translationMap.put("v", "p");
translationMap.put("w", "f");
translationMap.put("x", "m");
translationMap.put("y", "a");
translationMap.put("z", "q");
translationMap.put(" ", " ");
}
/**
* @param args
*/
public static void main(String[] args) {
init();
String inputFilePath = args[0];
try {
File inputFile = new File(inputFilePath);
FileInputStream fis = new FileInputStream(inputFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
// translate(br);
findScore(br);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void findScore(BufferedReader br) throws NumberFormatException, IOException {
String line = null;
Integer numberOfLines = Integer.valueOf(br.readLine());
if( !(1<=numberOfLines && numberOfLines<=100)){
throw new IllegalArgumentException("Not valid number of lines");
}
for(int i=1; i<=numberOfLines; i++){
line = br.readLine();
String[] values = line.split(" ");
int res = computeResult(values); // line.substring(5).trim());
System.out.println("Case #"+i+": " +res);
}
}
private static int computeResult(String[] values) {
int peopleCount = Integer.valueOf(values[0].trim());
int surprisingCount = Integer.valueOf(values[1].trim());
int minScore = Integer.valueOf(values[2].trim());
int foundCases =0;
for (int i=3; i<values.length; i++) {
String oneScore = values[i];
Integer sc = Integer.valueOf(oneScore.trim());
int base = sc/3;
int left = sc%3;
switch(left){
case 0:
if(base>=minScore){
foundCases++;
}
else if(surprisingCount>0 && base>0 && base+1>=minScore){
surprisingCount--;
foundCases++;
}
break;
case 1:
// normal case
if(base>=minScore || (base+1)>=minScore){
foundCases++;
}
// suprise use case
else if(surprisingCount>0 && (base+1)>=minScore){
foundCases++;
surprisingCount--;
}
break;
case 2:
// normal case
if(base>=minScore || (base+1)>=minScore){
foundCases++;
}
// surprise case
else if(surprisingCount>0 && (base+2)>=minScore){
foundCases++;
surprisingCount--;
}
break;
}
}
return foundCases;
}
private static void translate(BufferedReader br) throws IOException {
String line = null;
StringBuffer result = new StringBuffer();
Integer numberOfLines = Integer.valueOf(br.readLine());
if( !(1<=numberOfLines && numberOfLines<=30)){
throw new IllegalArgumentException("Not valid number of lines");
}
for(int i=1; i<=numberOfLines; i++){
line = br.readLine();
result.append(translateLine(line));
System.out.println("Case #"+i+": " +result);
result = new StringBuffer();
}
}
private static StringBuffer translateLine(String line) {
StringBuffer translatedLine = new StringBuffer();
for (int i=0; i < line.length(); i++) {
translatedLine.append(translateChar(line.charAt(i)));
}
return translatedLine;
}
private static String translateChar(char charAt) {
return translationMap.get(new Character(charAt).toString());
}
}
|
B12762 | B10560 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;
/**
*
* @author imgps
*/
public class C {
public static void main(String args[]) throws Exception{
int A,B;
int ctr = 0;
int testCases;
Scanner sc = new Scanner(new FileInputStream("C-small-attempt0.in "));
testCases = sc.nextInt();
int input[][] = new int[testCases][2];
for(int i=0;i<testCases;i++)
{
// System.out.print("Enter input A B: ");
input[i][0] = sc.nextInt();
input[i][1] = sc.nextInt();
}
for(int k=0;k<testCases;k++){
ctr = 0;
A = input[k][0];
B = input[k][1];
for(int i = A;i<=B;i++){
int num = i;
int nMul = 1;
int mul = 1;
int tnum = num/10;
while(tnum > 0){
mul = mul *10;
tnum= tnum/10;
}
tnum = num;
int n = 0;
while(tnum > 0 && mul >= 10){
nMul = nMul * 10;
n = (num % nMul) * mul + (num / nMul);
mul = mul / 10;
tnum = tnum / 10;
for(int m=num;m<=B;m++){
if(n == m && m > num){
ctr++;
}
}
}
}
System.out.println("Case #"+(k+1)+": "+ctr);
}
}
}
| package com.googlerese.file;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class FileRead {
private static FileRead instance = new FileRead();
private FileRead() {
}
public static FileRead getInstance() {
return instance;
}
public Map<Integer, String[]> read( final String fileName ) {
FileInputStream fstream = null;
DataInputStream in = null;
BufferedReader br = null;
Map<Integer, String[]> input = null;
try {
// Open the file that is the first
// command line parameter
fstream = new FileInputStream( fileName );
// Get the object of DataInputStream
in = new DataInputStream( fstream );
br = new BufferedReader( new InputStreamReader( in ) );
String strLine;
//Read File Line By Line
int count = 0;
while ( ( strLine = br.readLine() ) != null ) {
// Print the content on the console
if ( count == 0 ) {
input = new HashMap<Integer, String[]>( Integer.parseInt( strLine ) );
} else {
System.out.println( count + " : " + strLine );
String[] arr = strLine.split( "\\s+" );
input.put( count, arr );
}
count++;
}
} catch ( Exception e ) {//Catch exception if any
System.err.println( "Error: " + e.getMessage() );
} finally {
//Close the input stream
try {
if ( br != null ) {
br.close();
}
if ( in != null ) {
in.close();
}
if ( fstream != null ) {
fstream.close();
}
} catch ( IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return input;
}
}
|
A12460 | A12609 | 0 | /**
*
*/
package pandit.codejam;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Scanner;
/**
* @author Manu Ram Pandit
*
*/
public class DancingWithGooglersUpload {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
FileInputStream fStream = new FileInputStream(
"input.txt");
Scanner scanner = new Scanner(new BufferedInputStream(fStream));
Writer out = new OutputStreamWriter(new FileOutputStream("output.txt"));
int T = scanner.nextInt();
int N,S,P,ti;
int counter = 0;
for (int count = 1; count <= T; count++) {
N=scanner.nextInt();
S = scanner.nextInt();
counter = 0;
P = scanner.nextInt();
for(int i=1;i<=N;i++){
ti=scanner.nextInt();
if(ti>=(3*P-2)){
counter++;
continue;
}
else if(S>0){
if(P>=2 && ((ti==(3*P-3)) ||(ti==(3*P-4)))) {
S--;
counter++;
continue;
}
}
}
// System.out.println("Case #" + count + ": " + counter);
out.write("Case #" + count + ": " + counter + "\n");
}
fStream.close();
out.close();
}
}
| import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
class dance {
int single[][] = new int[4][3];
int doublex[][] = new int[54][3];
dance() {
single[0][0] = 0;
single[0][1] = 0;
single[0][2] = 0;
single[1][0] = 0;
single[1][1] = 0;
single[1][2] = 1;
single[2][0] = 10;
single[2][1] = 10;
single[2][2] = 9;
single[3][0] = 10;
single[3][1] = 10;
single[3][2] = 10;
}
int[][] gen_tuple(int num) {
int tup[][] = new int[2][3];
if (num % 3 == 0) {
tup[0][0] = num / 3;
tup[0][1] = num / 3;
tup[0][2] = num / 3;
tup[1][0] = num / 3 - 1;
tup[1][1] = num / 3;
tup[1][2] = num / 3 + 1;
} else if (num % 3 == 1) {
tup[0][0] = num / 3;
tup[0][1] = num / 3;
tup[0][2] = num / 3 + 1;
tup[1][0] = num / 3 + 1;
tup[1][1] = num / 3 + 1;
tup[1][2] = num / 3 - 1;
} else if (num % 3 == 2) {
tup[0][0] = num / 3;
tup[0][1] = num / 3 + 1;
tup[0][2] = num / 3 + 1;
tup[1][0] = num / 3;
tup[1][1] = num / 3;
tup[1][2] = num / 3 + 2;
}
return tup;
}
int maxx(int a, int b, int c) {
int temp = Math.max(a, b);
temp = Math.max(temp, c);
return temp;
}
public static void main(String[] args) throws IOException {
dance my = new dance();
for (int i = 2; i < 29; i++) {
int temp[][] = my.gen_tuple(i);
// System.out.println((i - 2) * 2);
my.doublex[(i - 2) * 2][0] = temp[0][0];
my.doublex[(i - 2) * 2][1] = temp[0][1];
my.doublex[(i - 2) * 2][2] = temp[0][2];
my.doublex[(i - 2) * 2 + 1][0] = temp[1][0];
my.doublex[(i - 2) * 2 + 1][1] = temp[1][1];
my.doublex[(i - 2) * 2 + 1][2] = temp[1][2];
// System.out.print(my.doublex[(i - 2) * 2][0] + " ");
// System.out.print(my.doublex[(i - 2) * 2][1] + ",");
// System.out.print(my.doublex[(i - 2) * 2][2] + ",");
// System.out.print(my.doublex[(i - 2) * 2 + 1][0] + ",");
// System.out.print(my.doublex[(i - 2) * 2 + 1][1] + ",");
// System.out.println(my.doublex[(i - 2) * 2 + 1][2] + ",");
}
String Path = "C:\\Users\\Dell\\Desktop\\B-small-attempt0.in";
Scanner read = new Scanner(new File(Path));
File file = new File("C:\\Users\\Dell\\Desktop\\out.txt");
PrintWriter Fout = new PrintWriter(new BufferedWriter(new FileWriter(
file)), true);
String line = read.nextLine();
int iter = 0;
while (read.hasNextLine()) {
iter = iter + 1;
line = read.nextLine();
String d = "[ ]+";
String[] SplitD = line.split(d);
for (int x = 0; x < SplitD.length; x++) {
// System.out.println(SplitD[x]);
}
int N = Integer.parseInt(SplitD[0]);
int S = Integer.parseInt(SplitD[1]);
int p = Integer.parseInt(SplitD[2]);
int count = 0;
int surp = 0;
for (int j = 0; j < N; j++) {
int val = Integer.parseInt(SplitD[j + 3]);
if (val < 2) {
if (my.maxx(my.single[val][0], my.single[val][1],
my.single[val][2]) >= p) {
count += 1;
}
} else if (val > 28) {
if (my.maxx(my.single[val - 27][0], my.single[val - 27][1],
my.single[val - 27][2]) >= p) {
count += 1;
}
} else {
if (my.maxx(my.doublex[(val - 2) * 2][0],
my.doublex[(val - 2) * 2][1],
my.doublex[(val - 2) * 2][2]) >= p) {
count += 1;
} else if (my.maxx(my.doublex[(val - 2) * 2 + 1][0],
my.doublex[(val - 2) * 2 + 1][1],
my.doublex[(val - 2) * 2 + 1][2]) >= p) {
surp += 1;
}
}
}
if (surp > S) {
count = count + S;
} else {
count = count + surp;
}
String output_str = "Case #" + iter + ": " + count;
Fout.println(output_str);
}
read.close();
}
} |
A10996 | A11026 | 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 fixjava;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import fixjava.ParallelWorkQueue.CallableFactory;
public class ArrayUtils {
// ------------------------------------------------------------------------------------------------
/** Convert a 2D float array into a 2D double array */
public static double[][] toDblArray(float[][] data) {
double[][] copy = new double[data.length][data[0].length];
for (int i = 0; i < data.length; i++)
for (int j = 0; j < data[0].length; j++)
copy[i][j] = data[i][j];
return copy;
}
/** Convert a 2D double array into a 2D float array */
public static float[][] toFltArray(double[][] data) {
float[][] copy = new float[data.length][data[0].length];
for (int i = 0; i < data.length; i++)
for (int j = 0; j < data[0].length; j++)
copy[i][j] = (float) data[i][j];
return copy;
}
/** Transpose an array */
public static double[][] transpose(double[][] data) {
double[][] copy = new double[data[0].length][data.length];
for (int i = 0; i < data.length; i++)
for (int j = 0; j < data[0].length; j++)
copy[j][i] = data[i][j];
return copy;
}
/** Transpose an array */
public static float[][] transpose(float[][] data) {
float[][] copy = new float[data[0].length][data.length];
for (int i = 0; i < data.length; i++)
for (int j = 0; j < data[0].length; j++)
copy[j][i] = data[i][j];
return copy;
}
// ------------------------------------------------------------------------------------------------
public static float[][] matMulPar(float[][] A, boolean transposeA, float[][] B, boolean transposeB, int numThreads) {
return toFltArray(matMulPar(toDblArray(A), transposeA, toDblArray(B), transposeB, numThreads));
}
public static double[][] matMulPar(double[][] A, boolean transposeA, double[][] B, boolean transposeB, int numThreads) {
final double[][] matA = transposeA ? transpose(A) : A;
// Keep B transposed so that matrix multiplication is more able to exploit cache coherence (matrix is stored row-wise)
final double[][] matBT = transposeB ? B : transpose(B);
final int p = matA.length, q = matA[0].length, q2 = matBT[0].length, r = matBT.length;
if (q != q2)
throw new IllegalArgumentException("Array size mismatch");
final double[][] result = new double[p][r];
//final DecimalFormat formatPercent1dp = new DecimalFormat("0.0%");
try {
for (Future<Void> res : new ParallelWorkQueue<Integer, Void>(numThreads, ParallelWorkQueue.makeIntRangeIterable(p),
new CallableFactory<Integer, Void>() {
//IntegerMutable counter = new IntegerMutable();
@Override
public Callable<Void> newInstance(final Integer ii) {
return new Callable<Void>() {
int i = ii.intValue();
double[][] resultLocal = result;
int rLocal = r, qLocal = q;
double[][] matALocal = matA, matBTLocal = matBT;
@Override
public Void call() {
/**
* <code>
* TODO: try blocked matrix multiplication to see if it's faster
*
* for (int ib = 0; ib < p; ib += blockSize)
* for (int jb = 0; jb < q; jb += blockSize)
* for (int kb = 0; kb < r; kb += blockSize)
* for (int i = ib, iMax = Math.min(p, ib + blockSize); i < iMax; i++)
* for (int j = jb, jMax = Math.min(q, jb + blockSize); j < jMax; j++)
* for (int k = kb, kMax = Math.min(p, kb + blockSize); k < kMax; k++)
* prod[i][j] += matALocal[i][k] * matBTLocal[j][k];
*
* N.B. the "+=" operation above needs to use TLS accumulators
*/
for (int j = 0; j < rLocal; j++) {
float tot = 0.0f;
for (int k = 0; k < qLocal; k++)
tot += matALocal[i][k] * matBTLocal[j][k];
resultLocal[i][j] = tot;
}
// int count = counter.increment();
// if (count % 10 == 0)
// System.out.println(formatPercent1dp.format((count / (float) (pLocal - 1))));
return null;
}
};
}
}))
// Barricade
res.get();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return result;
}
// ------------------------------------------------------------------------------------------------
/** Multiply A by constant b */
public static double[][] matMulByConst(double[][] A, double b) {
int p = A.length, q = A[0].length;
double[][] result = new double[p][q];
for (int i = 0; i < p; i++)
for (int j = 0; j < q; j++)
result[i][j] = b * A[i][j];
return result;
}
/** Multiply A by constant b */
public static float[][] matMulByConst(float[][] A, float b) {
int p = A.length, q = A[0].length;
float[][] result = new float[p][q];
for (int i = 0; i < p; i++)
for (int j = 0; j < q; j++)
result[i][j] = b * A[i][j];
return result;
}
/** Multiply A by B transpose */
public static float[][] matMulABT(float[][] A, float[][] BT) {
int p = A.length, q = A[0].length, q2 = BT[0].length, r = BT.length;
if (q != q2)
throw new IllegalArgumentException("Array size mismatch");
float[][] result = new float[p][r];
for (int i = 0; i < p; i++) {
for (int j = 0; j < r; j++) {
float tot = 0.0f;
for (int k = 0; k < q; k++)
// This is the main matrix multiplication routine, because both operands here
// are in row-major order, so we get speedups of 3-8x due to cache coherence
// on large matrices. (Use the parallel version for really large matrices...)
tot += A[i][k] * BT[j][k];
result[i][j] = tot;
}
}
return result;
}
/** Multiply A by B transpose */
public static double[][] matMulABT(double[][] A, double[][] BT) {
int p = A.length, q = A[0].length, q2 = BT[0].length, r = BT.length;
if (q != q2)
throw new IllegalArgumentException("Array size mismatch");
double[][] result = new double[p][r];
for (int i = 0; i < p; i++) {
for (int j = 0; j < r; j++) {
float tot = 0.0f;
for (int k = 0; k < q; k++)
// This is the main matrix multiplication routine, because both operands here
// are in row-major order, so we get speedups of 3-8x due to cache coherence
// on large matrices. (Use the parallel version for really large matrices...)
tot += A[i][k] * BT[j][k];
result[i][j] = tot;
}
}
return result;
}
/** Multiply A by B */
public static float[][] matMulAB(float[][] A, float[][] B) {
// Transpose B so it's row-major, and multiply by BTT==B
return matMulABT(A, transpose(B));
}
/** Multiply A by B */
public static double[][] matMulAB(double[][] A, double[][] B) {
// Transpose B so it's row-major, and multiply by BTT==B
return matMulABT(A, transpose(B));
}
/** Multiply A transpose by B */
public static float[][] matMulATB(float[][] A, float[][] B) {
// Transpose B so it's row-major, and multiply by BTT==B
return matMulABT(transpose(A), transpose(B));
}
/** Multiply A transpose by B */
public static double[][] matMulATB(double[][] A, double[][] B) {
// Transpose B so it's row-major, and multiply by BTT==B
return matMulABT(transpose(A), transpose(B));
}
/** Multiply A transpose by B transpose */
public static double[][] matMulATBT(double[][] A, double[][] B) {
return matMulABT(transpose(A), B);
}
/** Multiply A transpose by B transpose */
public static float[][] matMulATBT(float[][] A, float[][] B) {
return matMulABT(transpose(A), B);
}
// ------------------------------------------------------------------------------------------------
/** Select a random subset of rows in a matrix */
public static float[][] selectRandomRowSubset(int numRows, float[][] mat) {
int n = Math.min(numRows, mat.length);
float[][] rows = new float[mat.length][];
for (int i = 0; i < mat.length; i++)
rows[i] = mat[i];
Random rand = new Random();
for (int i = 0; i < n; i++) {
int j = rand.nextInt(mat.length);
float[] tmp = rows[i];
rows[i] = rows[j];
rows[j] = tmp;
}
return Arrays.copyOf(rows, n);
}
// ------------------------------------------------------------------------------------------------
/** Write a double[][] array to a file */
public static void writeToFile(String filename, String arrayName, double[][] array) {
try {
System.out.println("Writing to " + filename);
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filename)));
writeArray(writer, arrayName, array);
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
/** Write a double[][] array to a PrintWriter */
public static void writeArray(PrintWriter writer, String name, double[][] arr) {
writer.println(name + "\t" + arr.length + "\t" + arr[0].length);
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++)
writer.print((j == 0 ? "" : "\t") + arr[i][j]);
writer.println();
}
}
/** Write a double[] array to a PrintWriter */
public static void writeArray(PrintWriter writer, String name, double[] arr) {
writer.println(name + "\t1\t" + arr.length);
for (int i = 0; i < arr.length; i++)
writer.print((i == 0 ? "" : "\t") + arr[i]);
writer.println();
}
}
|
A20490 | A20594 | 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.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
public class GooglerDancerMain {
public static void main(String[] args) {
try {
Scanner s=new Scanner(new BufferedReader(new FileReader("B-large.in")));
ArrayList<GooglerDancer> list=new ArrayList<GooglerDancer>();
int i=0;
int totalCases=Integer.parseInt(s.nextLine());
while(s.hasNextLine()){
list.add(new GooglerDancer(++i,s.nextLine()));
}
for (GooglerDancer googlerDancer : list) {
googlerDancer.process();
}
} catch (FileNotFoundException e) {
System.out.println("file not found");
}
}
}
|
B13196 | B12052 | 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.util.HashSet;
public class ProblemC
{
public static void main(String[] args) throws Exception
{
String base = "C-small-attempt0";
BufferedReader reader = new BufferedReader(new FileReader(base+".in"));
BufferedWriter writer = new BufferedWriter(new FileWriter(base+".out"));
int place = 0;
reader.readLine();
while (reader.ready())
{
String line = reader.readLine();
String[] strs = line.split(" ");
int a = Integer.parseInt(strs[0]);
int b = Integer.parseInt(strs[1]);
int num = solve(a,b);
writer.write("Case #" + (++place) + ": " + num+'\n');
}
reader.close();
writer.close();
}
public static int solve(int a, int b)
{
int number = 0;
for (int i=a;i<=b;i++)
{
HashSet<Integer> set = new HashSet<Integer>();
String str = i+"";
for (int p=str.length()-1;p>=1;p--)
{
String test = str.substring(p) + str.substring(0,p);
int j = Integer.parseInt(test);
String test2 = j+"";
if (i < j && j <= b && str.length()==test2.length() && !set.contains(j))
{
set.add(j);
number++;
}
}
}
return number;
}
}
|
B21968 | B21499 | 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.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class Recycled {
public static void main(String[] args) throws Exception {
FileInputStream fstream = new FileInputStream("text.in");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int count = 0;
int totalLines;
// ArrayList<List> numbers = new ArrayList<List>();
while ((strLine = br.readLine()) != null) {
if (count == 0) {
totalLines = Integer.parseInt(strLine);
} else {
int recycled = 0;
String[] nums = strLine.split(" ");
int startNum = Integer.parseInt(nums[0]);
int endNum = Integer.parseInt(nums[1]);
for (int i = startNum; i <= endNum; i++) {
recycled += testInteger(i, endNum);
}
System.out.println("Case #" + count + ": " + recycled);
}
count++;
}
in.close();
}
private static int testInteger(int i, int endNum) {
String numStr = String.valueOf(i);
int currentCount = 0;
Set<String> matches = new HashSet<String>();
for (int j = 1; j < numStr.length(); j++) {
String newNumStr = swapNumber(numStr);
if ((Integer.parseInt(newNumStr) > i) && ((Integer.parseInt(newNumStr) <= endNum))) {
// System.out.println(i+" "+newNumStr);
currentCount++;
matches.add(newNumStr);
// } else {
// return 0;
}
numStr = newNumStr;
}
return matches.size();
}
private static String swapNumber(String numStr) {
String lastDigit = numStr.substring(numStr.length()-1);
String firstDigits = numStr.substring(0, numStr.length()-1);
return lastDigit.concat(firstDigits);
}
}
|
B10149 | B11848 | 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.*;
import java.util.*;
import java.math.*;
public class C implements Runnable {
private long solve(int A, int B) {
int pow = 1;
while (pow <= A/10) {
pow *= 10;
}
HashSet<Long> h = new HashSet<Long>();
for (int n = A; n <= B; ++n) {
int nn = n;
nn = (nn%pow)*10 + (nn/pow);
while (nn != n) {
if (A <= nn && nn <= B) {
if (nn < n) {
h.add(1L*nn*pow*10+n);
}
else {
h.add(1L*n*pow*10+nn);
}
}
nn = (nn%pow)*10 + (nn/pow);
}
}
return h.size();
}
public void run() {
int n = nextInt();
for (int i = 0; i < n; ++i) {
int A = nextInt();
int B = nextInt();
long ans = solve(A, B);
out.println("Case #"+(i+1)+": "+ans);
}
out.flush();
}
private static BufferedReader br = null;
private static StringTokenizer stk = null;
private static PrintWriter out = null;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new FileReader(new File("D:\\C.txt")));
out = new PrintWriter("D:\\CC.txt");
(new Thread(new C())).start();
}
public void loadLine() {
try {
stk = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
public String nextLine() {
try {
return (br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
public int nextInt() {
while (stk==null || !stk.hasMoreTokens()) loadLine();
return Integer.parseInt(stk.nextToken());
}
public long nextLong() {
while (stk==null || !stk.hasMoreTokens()) loadLine();
return Long.parseLong(stk.nextToken());
}
public double nextDouble() {
while (stk==null || !stk.hasMoreTokens()) loadLine();
return Double.parseDouble(stk.nextToken());
}
public String nextWord() {
while (stk==null || !stk.hasMoreTokens()) loadLine();
return (stk.nextToken());
}
}
|
B12074 | B12540 | 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.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
public class RecycledNumbers {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int testCaseNumber;
String input;
BufferedReader in = new BufferedReader(new FileReader("C-small-attempt0.in"));
input = in.readLine();
testCaseNumber = Integer.parseInt(input.trim());
int[] totalAccountArray = new int[testCaseNumber];
for(int i=0; i<testCaseNumber; i++){
input = in.readLine();
String[] inputArray = input.split(" ");
int A = Integer.parseInt(inputArray[0]);
int B = Integer.parseInt(inputArray[1]);
int count = 0;
HashSet<String> hashSet = new HashSet<String>();
for(int j=A;j<=B; j++){
String num = String.valueOf(j);
for(int k=1; k<num.length(); k++){
String firstHalf = num.substring(0, k);
String lastHalf = num.substring(k,num.length());
String flipped = lastHalf+firstHalf;
int flippedNum = Integer.parseInt(flipped);
if(j>=flippedNum)
continue;
if(flippedNum>=A && flippedNum<=B){
if(hashSet.contains(num+flippedNum)){
System.out.println("DUPLICATE!!: " +num+flippedNum);
continue;
}
System.out.println("counted: "+"original: "+num+" Flipped: "+flippedNum);
count++;
hashSet.add(num+flippedNum);
}
}
}
System.out.println(count);
totalAccountArray[i] = count;
}
in.close();
FileWriter fstream = new FileWriter("C-small-attempt0.out");
BufferedWriter out = new BufferedWriter(fstream);
for(int i=1; i<=testCaseNumber;i++){
String outLine = "Case #"+i+": "+totalAccountArray[i-1]+"\n";
out.write(outLine);
}
out.close();
System.out.println("File created successfully.");
}
}
|
A11502 | A12774 | 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;
import java.io.PrintWriter;
public class DancingGooglers {
public static void main(String[] args) throws IOException {
BufferedReader fInput = new BufferedReader(new FileReader("res/inputB.in"));
PrintWriter fOutput = new PrintWriter(new BufferedWriter(new FileWriter(
"res/outputB.out")));
new DancingGooglers().run(fInput, fOutput);
fOutput.close();
}
private void run(BufferedReader fInput, PrintWriter fOutput) throws IOException {
int T = Integer.parseInt(fInput.readLine());
for (int i=0; i<T; i++) {
int count = 0;
String[] inputS = fInput.readLine().split(" ");
int N = Integer.parseInt(inputS[0]);
int S = Integer.parseInt(inputS[1]);
int p = Integer.parseInt(inputS[2]);
for (int j=3; j<N+3; j++) {
int t = Integer.parseInt(inputS[j]);
int base = t/3;
int max = t%3==0? base : base+1;
if (max >= p) {
count++;
continue;
}
if (S == 0 || t<2 || t%3==1) continue;
max = t%3==0? base+1 : base+2;
if (max >= p) {
count++;
S--;
}
}
fOutput.println("Case #" + (i+1) + ": " + count);
}
}
} |