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 | A13017 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Dancing
* Jason Bradley Nel
* 16287398
*/
import java.io.*;
public class Dancing {
public static void main(String[] args) {
In input = new In("input.txt");
int T = Integer.parseInt(input.readLine());
for (int i = 0; i < T; i++) {
System.out.printf("Case #%d: ", i + 1);
int N = input.readInt();
int s = input.readInt();
int p = input.readInt();
int c = 0;//counter for >=p cases
//System.out.printf("N: %d, S: %d, P: %d, R: ", N, s, p);
for (int j = 0; j < N; j++) {
int score = input.readInt();
int q = score / 3;
int m = score % 3;
//System.out.printf("%2d (%d, %d) ", scores[j], q, m);
switch (m) {
case 0:
if (q >= p) {
c++;
} else if (((q + 1) == p) && (s > 0) && (q != 0)) {
c++;
s--;
}
break;
case 1:
if (q >= p) {
c++;
} else if ((q + 1) == p) {
c++;
}
break;
case 2:
if (q >= p) {
c++;
} else if ((q + 1) == p) {
c++;
} else if (((q + 2) == p) && (s > 0)) {
c++;
s--;
}
break;
}
}
//System.out.printf("Best result of %d or higher: ", p);
System.out.println(c);
}
}
}
| package codejam20120413;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class B {
void run()throws IOException{
BufferedReader bf = new BufferedReader(new FileReader("B.in"));
PrintWriter pw = new PrintWriter(new FileWriter("B.out"));
int cases = Integer.parseInt(bf.readLine());
for (int i=0; i<cases; i++) {
String[] s = bf.readLine().split(" ");
int N = Integer.parseInt(s[0]);
int S = Integer.parseInt(s[1]);
int p = Integer.parseInt(s[2]);
int count = 0;
for (int j=0; j<N; j++) {
int score = Integer.parseInt(s[j+3]);
if (score>p*3-3)
count++;
else
if ((p*3-3 > 0) && (score==p*3-3 || score==p*3-4) && S-->0)
count++;
}
pw.write("Case #"+ (i+1) + ": "+ count + "\n");
}
pw.close();
}
public static void main(String[] args)throws IOException {
new B().run();
}
}
|
A12273 | A11795 | 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.FileWriter;
import java.util.Scanner;
public class B {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new File("B-small-attempt5.in"));
FileWriter f = new FileWriter("B.out");
int N,S,p;
int googler;
int kol,ost;
int br;
int T=sc.nextInt();
for(int t=1;t<=T;t++){
br=0;
sc.nextLine();
N=sc.nextInt();
S=sc.nextInt();
p=sc.nextInt();
for(int i=0;i<N;i++){
googler=sc.nextInt();
kol=googler/3;
ost=googler%3;
if(kol>=p){
br++;
continue;
}
if(ost==0){
if(kol+1>=p&&S>0&&kol-1>=0){
S--;
br++;
}
continue;
}
if(ost==1){
if(kol+1>=p){
br++;
}
continue;
}
//ost==2
if(kol+1>=p){
br++;
continue;
}
if(kol+2>=p&&S>0){
S--;
br++;
}
}
f.write("Case #"+t+": "+br+"\n");
}
f.close();
}
}
|
A22378 | A20753 | 0 | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class CodeJam {
// public static final String INPUT_FILE_PATH = "D://CodeJamInput.txt";
public static final String INPUT_FILE_PATH = "D://B-large.in";
public static final String OUTPUT_FILE_PATH = "D://CodeJamOutput.txt";
public static List<String> readInput() {
List<String> list = new ArrayList<String>();
try {
BufferedReader input = new BufferedReader(new FileReader(
INPUT_FILE_PATH));
try {
String line = null;
while ((line = input.readLine()) != null) {
list.add(line);
}
} finally {
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return list;
}
public static void writeOutput(List<String> output) {
PrintWriter writer = null;
try {
writer = new PrintWriter(new FileWriter(OUTPUT_FILE_PATH));
for (String line : output) {
writer.println(line);
}
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
writer.close();
}
}
public static void main(String[] args) {
List<DanceFloor> danceFloors = DanceFloor.parseFromFile(CodeJam.readInput());
List<String> output = new ArrayList<String>();
for(int i = 0; i < danceFloors.size(); i++) {
System.out.println(danceFloors.get(i));
String line = "";
line += "Case #" + (i + 1) + ": " + danceFloors.get(i).calculate();
output.add(line);
}
CodeJam.writeOutput(output);
}
}
class DanceFloor {
private List<Integer> tripletsTotalCounts;
private int surpriseCount;
private int targetScore;
private int dancersCount;
public DanceFloor(List<Integer> tripletsTotalCounts, int surpriseCount,
int targetScore, int dancersCount) {
this.tripletsTotalCounts = tripletsTotalCounts;
this.surpriseCount = surpriseCount;
this.targetScore = targetScore;
this.dancersCount = dancersCount;
}
public int calculate() {
int result = 0;
if (targetScore == 0) return dancersCount;
for (int i = 0; i < tripletsTotalCounts.size(); i++) {
int total = tripletsTotalCounts.get(i);
if (total < (targetScore * 3 - 4)) {
tripletsTotalCounts.remove(i--);
} else if (total == 0) {
tripletsTotalCounts.remove(i--);
}
}
for (int i = 0; i < tripletsTotalCounts.size(); i++) {
int total = tripletsTotalCounts.get(i);
if ((surpriseCount > 0) && (total == targetScore * 3 - 4)) {
result++;
surpriseCount--;
tripletsTotalCounts.remove(i--);
} else if ((surpriseCount == 0) && (total == targetScore * 3 - 4)) {
tripletsTotalCounts.remove(i--);
}
}
for (int i = 0; i < tripletsTotalCounts.size(); i++) {
int total = tripletsTotalCounts.get(i);
if ((surpriseCount > 0) && (total == targetScore * 3 - 3)) {
result++;
surpriseCount--;
tripletsTotalCounts.remove(i--);
} else if ((surpriseCount == 0) && (total == targetScore * 3 - 3)) {
tripletsTotalCounts.remove(i--);
}
}
result += tripletsTotalCounts.size();
return result;
}
public static List<DanceFloor> parseFromFile(List<String> readInput) {
List<DanceFloor> result = new ArrayList<DanceFloor>();
int testCaseCount = Integer.parseInt(readInput.get(0));
for (int i = 0; i < testCaseCount; i++) {
String line[] = readInput.get(i + 1).split(" ");
List<Integer> totalCounts = new ArrayList<Integer>();
for (int j = 0; j < Integer.parseInt(line[0]); j++) {
totalCounts.add(Integer.parseInt(line[3 + j]));
}
result.add(new DanceFloor(totalCounts, Integer.parseInt(line[1]),
Integer.parseInt(line[2]), Integer.parseInt(line[0])));
}
return result;
}
@Override
public String toString() {
return "dancersCount = " + dancersCount + "; surpriseCount = " + surpriseCount
+ "; targetScore = " + targetScore + "; tripletsTotalCounts"
+ tripletsTotalCounts.toString();
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package actual;
import codejam.*;
import java.io.*;
import java.util.Scanner;
/**
*
* @author atm
*/
public class PB {
public static void main(String[] args) throws Exception {
int Cases;
int N, P, S;
String words[];
FileInputStream fstreamIN = new FileInputStream("F:\\codejam\\input\\B-small-attempt1.in");
FileOutputStream fstreamOUT = new FileOutputStream("F:\\codejam\\output\\B-small-attempt1.out");
Scanner in=new Scanner(fstreamIN);
PrintWriter out=new PrintWriter(fstreamOUT);
Cases=in.nextInt();
for(int i=0;i<Cases;i++) // Cases loop
{
N=in.nextInt();
S=in.nextInt();
P=in.nextInt();
int tempS=S;
int ans=0;
for(int j=0;j<N;j++){
int num=in.nextInt();
if(P==0){
if(num>=0){
ans++;
}
} else if(P==1){
if(num>0)
ans++;
}else if(num>=(3*P - 2))
ans++;
else if(num>=(3*P - 4) && tempS!=0)
{
ans++; tempS--;
}
}
out.printf("Case #%d: %d\n",i+1,ans);
}
out.close();
}
}
|
B10899 | B10378 | 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.PrintWriter;
import java.util.HashSet;
import java.util.Scanner;
/**
*
* @author pulasthi
*/
public class QC12 {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter("c.txt");
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
HashSet<String> hs = new HashSet<String>();
int min = sc.nextInt();
int max = sc.nextInt();
for (int j = min; j <= max; j++) {
String s = j+"";
for(int k =1; k<s.length();k++){
String compS = s.substring(k)+s.substring(0, k);
int compI = Integer.parseInt(compS);
if(compI>j && compI<=max){
hs.add(j+""+compI);
}
}
}
out.print("Case #"+(i+1)+": ");
out.println(hs.size());
System.out.println(hs.size());
}
out.flush();
out.close();
}
}
|
A21557 | A20450 | 0 | import java.io.*;
import java.util.*;
public class DancingWithGooglers {
public static class Googlers {
public int T;
public int surp;
public boolean surprising;
public boolean pSurprising;
public boolean antiSurprising;
public boolean pAntiSurprising;
public Googlers(int T, int surp) {
this.T = T;
this.surp = surp;
}
public void set(int a, int b, int c) {
if (c >= 0 && (a + b + c) == T) {
int diff = (Math.max(a, Math.max(b, c)) - Math.min(a, Math.min(b, c)));
if (diff <= 2) {
if (diff == 2) {
if (a >= surp || b >= surp || c >= surp) {
pSurprising = true;
} else {
surprising = true;
}
} else {
if (a >= surp || b >= surp || c >= surp) {
pAntiSurprising = true;
} else {
antiSurprising = true;
}
}
}
}
}
}
public static void main(String... args) throws IOException {
// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader reader = new BufferedReader(new FileReader("B-large.in"));
// PrintWriter writer = new PrintWriter(System.out);
PrintWriter writer = new PrintWriter("B-large.out");
int len, cases = Integer.parseInt(reader.readLine());
List<Googlers> satisfied = new ArrayList<Googlers>();
List<Googlers> unsatisfied = new ArrayList<Googlers>();
String[] inputs;
int N, S, p;
for (int i = 1; i <= cases; i++) {
inputs = reader.readLine().split(" ");
p = Integer.parseInt(inputs[1]);
S = Integer.parseInt(inputs[2]);
satisfied.clear();
unsatisfied.clear();
for (int j = 3; j < inputs.length; j++) {
int t = Integer.parseInt(inputs[j]);
Googlers googlers = new Googlers(t, S);
for (int k = 0; k <= 10; k++) {
int till = k + 2 > 10 ? 10 : k + 2;
for (int l = k; l <= till; l++) {
googlers.set(k, l, (t - (k + l)));
}
}
if (googlers.pAntiSurprising) {
satisfied.add(googlers);
} else {
unsatisfied.add(googlers);
}
}
int pSurprising = 0;
if (p > 0) {
for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.pSurprising) {
pSurprising++;
iter.remove();
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
for (Iterator<Googlers> iter = unsatisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.surprising) {
iter.remove();
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.pSurprising) {
iter.remove();
pSurprising++;
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
for (Iterator<Googlers> iter = satisfied.iterator(); iter.hasNext(); ) {
Googlers googlers = iter.next();
if (googlers.surprising) {
iter.remove();
p--;
if (p <= 0) break;
}
}
}
if(p > 0){
writer.print("Case #" + i + ": 0");
}else {
writer.print("Case #" + i + ": " + (satisfied.size() + pSurprising));
}
writer.println();
}
writer.flush();
}
}
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Dancing {
public static void main(String args[]) throws NumberFormatException, IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(in.readLine());
int t = 0;
String str = "";
String regex = " ";
String[] split;
String[] result = new String[T+1];
int N = 0;
int S = 0;
int p = 0;
for(int x = 1; x <= T; x++){
str = in.readLine();
split = str.split(regex);
N = Integer.parseInt(split[0]);
S = Integer.parseInt(split[1]);
p = Integer.parseInt(split[2]);
for(int y = 3; y < (3 + N); y++ ) {
if(bestScore(N, S, p, Integer.parseInt(split[y])) == 1) {
t++;
}
if(bestScore(N, S, p, Integer.parseInt(split[y])) == 2) {
S--;
t++;
}
}
result[x] = "Case #" + x + ": " + t;
t=0;
}
for(int u = 1; u <= T; u++){
System.out.println(result[u]);
}
}
public static int bestScore (int N, int S, int p, int t){
int work = 0;
int temp = t;
int score;
int special = 2;
if(S != 0){
for(score = 10; score > 0; score--){
if(t - score >= (score - special)*(2) && (t-score > 0)) {
temp = score;
score = -1;
}
}
if(temp >= p)
{
work = 2;
}
}
temp = t;
special = 1;
for(score = 10; score >= 0; score--){
if(t - score >= (score - special)*(2) && (t-score > 0)) {
temp = score;
score = -1;
}
}
if(temp >= p)
{
work = 1;
}
return work;
}
}
|
B12082 | B10668 | 0 | package jp.funnything.competition.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.apache.commons.io.IOUtils;
public class QuestionReader {
private final BufferedReader _reader;
public QuestionReader( final File input ) {
try {
_reader = new BufferedReader( new FileReader( input ) );
} catch ( final FileNotFoundException e ) {
throw new RuntimeException( e );
}
}
public void close() {
IOUtils.closeQuietly( _reader );
}
public String read() {
try {
return _reader.readLine();
} catch ( final IOException e ) {
throw new RuntimeException( e );
}
}
public BigDecimal[] readBigDecimals() {
return readBigDecimals( " " );
}
public BigDecimal[] readBigDecimals( final String separator ) {
final String[] tokens = readTokens( separator );
final BigDecimal[] values = new BigDecimal[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = new BigDecimal( tokens[ index ] );
}
return values;
}
public BigInteger[] readBigInts() {
return readBigInts( " " );
}
public BigInteger[] readBigInts( final String separator ) {
final String[] tokens = readTokens( separator );
final BigInteger[] values = new BigInteger[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = new BigInteger( tokens[ index ] );
}
return values;
}
public int readInt() {
final int[] values = readInts();
if ( values.length != 1 ) {
throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" );
}
return values[ 0 ];
}
public int[] readInts() {
return readInts( " " );
}
public int[] readInts( final String separator ) {
final String[] tokens = readTokens( separator );
final int[] values = new int[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = Integer.parseInt( tokens[ index ] );
}
return values;
}
public long readLong() {
final long[] values = readLongs();
if ( values.length != 1 ) {
throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" );
}
return values[ 0 ];
}
public long[] readLongs() {
return readLongs( " " );
}
public long[] readLongs( final String separator ) {
final String[] tokens = readTokens( separator );
final long[] values = new long[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = Long.parseLong( tokens[ index ] );
}
return values;
}
public String[] readTokens() {
return readTokens( " " );
}
public String[] readTokens( final String separator ) {
return read().split( separator );
}
}
| import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class RecycledNumbers {
public static void main(String args[]){
RecycledNumbers r= new RecycledNumbers();
r.convert(args[0]);
}
public void convert(String filename){
try{
File f= new File(filename);
Scanner scan= new Scanner(f);
String firstLine= scan.nextLine();
int num= Integer.parseInt(firstLine);
int[] answer= new int[num];
int[][] testnum= new int[num][2];
for(int i=0; i<num;i++){
int count= 0;
String line= scan.nextLine();
String[] array = line.split(" ");
int[] pair= new int[]{Integer.parseInt(array[0]), Integer.parseInt(array[1])};
testnum[i]= pair;
for (int k=pair[0];k<=pair[1];k++){
String strNum= ""+ k;
for(int l= strNum.length()-1;l>0;l=l-1){
String pos= strNum.substring(l,strNum.length())+strNum.substring(0,l);
int j= Integer.parseInt(pos);
if (j<=pair[1] && j>=pair[0] && j>k){
count=count+1;
}
}
}
answer[i]= count;
System.out.println("Case #"+(i+1)+": "+count);
}
}
catch(FileNotFoundException e){
}
}
} |
A22191 | A20311 | 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.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CodeJam {
private static final String FILE_NAME = "E:/download/B-large.in";
public static void main(String[] args) throws IOException {
File file = new File(FILE_NAME);
BufferedReader in = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
SolverModule solver = new TestTwoSolver();
builder = solver.process(in, builder);
System.out.println(builder);
file = new File(FILE_NAME.concat(".result"));
FileWriter fileWriter = new FileWriter(file);
fileWriter.append(builder);
fileWriter.flush();
fileWriter.close();
}
}
|
A10996 | A12849 | 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.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
public class Dance {
static int no_Test_Cases =0; //number of test cases
static String input_Array[]; //to read input file
static int output_Array[]; // to write the t output lines
public static void main(String[] args) {
readFile();
for (int i = 0; i< no_Test_Cases; i++ ){
googler_Dance(i);
}
writeFile();
}
public static void readFile(){
try{
FileInputStream fstream = new FileInputStream("C:/sarab/input.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
strLine = br.readLine();
no_Test_Cases = Integer.parseInt(strLine);
input_Array = new String[no_Test_Cases];
output_Array = new int[no_Test_Cases];
for (int i = 0; i< no_Test_Cases; i++){
strLine = br.readLine();
input_Array[i] = strLine;
}
//Close the input stream
in.close();
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void googler_Dance(int i){
String s1 = input_Array[i];
String s2[] = s1.split(" ");
int no_Googler = Integer.parseInt(s2[0]);
int no_Surprise = Integer.parseInt(s2[1]);
int best_Score = Integer.parseInt(s2[2]);
int counter = 0; // to count the no of googler getting more than best_Score
for (int i1 = 0; i1<no_Googler; i1++){
int score;
score = Integer.parseInt(s2[3+i1]);
int rem = score%3;
int x = score/3;
switch (rem) {
case 0:
if (x >= best_Score)
counter++;
else {
if (no_Surprise > 0){
if (x-1 >= 0 && x+1 <=10){
if (x >= best_Score -1){
counter++;
no_Surprise--;
}
}
}
}
break;
case 1:
if (x >= best_Score -1)
counter++;
break;
case 2:
if (x >= best_Score -1)
counter++;
else {
if (no_Surprise > 0){
if (x+2 <= 10){
if (x >= best_Score -2){
counter++;
no_Surprise--;
}
}
}
}
break;
}
}
output_Array[i]= counter;
}
public static void writeFile(){
String forOutput;
try{
FileWriter fstream = new FileWriter("C:/sarab/output.txt");
BufferedWriter out = new BufferedWriter(fstream);
for (int i=0; i<no_Test_Cases; i++){
forOutput="Case #"+(i+1)+": "+output_Array[i]+"";
out.write(forOutput);
out.newLine();
}
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
|
A20119 | A20507 | 0 | package code12.qualification;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class B {
public static String solve(int N, int S, int p, int[] t) {
// 3a -> (a, a, a), *(a - 1, a, a + 1)
// 3a + 1 -> (a, a, a + 1), *(a - 1, a + 1, a + 1)
// 3a + 2 -> (a, a + 1, a + 1), *(a, a, a + 2)
int numPNoS = 0;
int numPWithS = 0;
for (int i = 0; i < N; i++) {
int a = (int)Math.floor(t[i] / 3);
int r = t[i] % 3;
switch (r) {
case 0:
if (a >= p) {
numPNoS++;
} else if (a + 1 >= p && a - 1 >= 0) {
numPWithS++;
}
break;
case 1:
if (a >= p || a + 1 >= p) {
numPNoS++;
}
break;
case 2:
if (a >= p || a + 1 >= p) {
numPNoS++;
} else if (a + 2 >= p) {
numPWithS++;
}
break;
}
}
return "" + (numPNoS + Math.min(S, numPWithS));
}
public static void main(String[] args) throws Exception {
// file name
//String fileName = "Sample";
//String fileName = "B-small";
String fileName = "B-large";
// file variable
File inputFile = new File(fileName + ".in");
File outputFile = new File(fileName + ".out");
Scanner scanner = new Scanner(inputFile);
FileWriter writer = new FileWriter(outputFile);
// problem variable
int totalCase;
int N, S, p;
int[] t;
// get total case
totalCase = scanner.nextInt();
for (int caseIndex = 1; caseIndex <= totalCase; caseIndex++) {
// get input
N = scanner.nextInt();
S = scanner.nextInt();
p = scanner.nextInt();
t = new int[N];
for (int i = 0; i < N; i++) {
t[i] = scanner.nextInt();
}
String output = "Case #" + caseIndex + ": " + solve(N, S, p, t);
System.out.println(output);
writer.write(output + "\n");
}
scanner.close();
writer.close();
}
}
| import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class B {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
File in = new File("b.in");
File out = new File("b.out");
BufferedWriter bw = new BufferedWriter(new FileWriter(out));
Scanner sc = new Scanner(in);
int T = Integer.parseInt(sc.nextLine());
for(int i=0;i<T;i++){
int N = sc.nextInt();
int S = sc.nextInt();
int p = sc.nextInt();
int surp = 0;
int count = 0;
for(int j=0;j<N;j++){
int m = sc.nextInt();
if(m==0){
if(p==0){
count++;
}
}else if(m == 30){
if(p<=10){
count++;
}
}else if(m%3==0){
if(m/3 >= p){
count++;
}else if((m/3+1)>=p){
count++;
surp++;
}
}else if(m%3==1){
if((m/3 + 1)>=p){
count++;
}
}else{
if((m/3+1)>=p){
count++;
}else if((m/3+2)>=p){
count++;
surp++;
}
}
}
count = surp<=S ?count:count-(surp-S);
bw.write("Case #"+(i+1)+": "+count+"\n");
}
bw.close();
}
}
|
A11201 | A10583 | 0 | package CodeJam.c2012.clasificacion;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* Problem
*
* You're watching a show where Googlers (employees of Google) dance, and then
* each dancer is given a triplet of scores by three judges. Each triplet of
* scores consists of three integer scores from 0 to 10 inclusive. The judges
* have very similar standards, so it's surprising if a triplet of scores
* contains two scores that are 2 apart. No triplet of scores contains scores
* that are more than 2 apart.
*
* For example: (8, 8, 8) and (7, 8, 7) are not surprising. (6, 7, 8) and (6, 8,
* 8) are surprising. (7, 6, 9) will never happen.
*
* The total points for a Googler is the sum of the three scores in that
* Googler's triplet of scores. The best result for a Googler is the maximum of
* the three scores in that Googler's triplet of scores. Given the total points
* for each Googler, as well as the number of surprising triplets of scores,
* what is the maximum number of Googlers that could have had a best result of
* at least p?
*
* For example, suppose there were 6 Googlers, and they had the following total
* points: 29, 20, 8, 18, 18, 21. You remember that there were 2 surprising
* triplets of scores, and you want to know how many Googlers could have gotten
* a best result of 8 or better.
*
* With those total points, and knowing that two of the triplets were
* surprising, the triplets of scores could have been:
*
* 10 9 10 6 6 8 (*) 2 3 3 6 6 6 6 6 6 6 7 8 (*)
*
* The cases marked with a (*) are the surprising cases. This gives us 3
* Googlers who got at least one score of 8 or better. There's no series of
* triplets of scores that would give us a higher number than 3, so the answer
* is 3.
*
* Input
*
* The first line of the input gives the number of test cases, T. T test cases
* follow. Each test case consists of a single line containing integers
* separated by single spaces. The first integer will be N, the number of
* Googlers, and the second integer will be S, the number of surprising triplets
* of scores. The third integer will be p, as described above. Next will be N
* integers ti: the total points of the Googlers.
*
* Output
*
* For each test case, output one line containing "Case #x: y", where x is the
* case number (starting from 1) and y is the maximum number of Googlers who
* could have had a best result of greater than or equal to p.
*
* Limits
*
* 1 ⤠T ⤠100. 0 ⤠S ⤠N. 0 ⤠p ⤠10. 0 ⤠ti ⤠30. At least S of the ti values
* will be between 2 and 28, inclusive.
*
* Small dataset
*
* 1 ⤠N ⤠3.
*
* Large dataset
*
* 1 ⤠N ⤠100.
*
* Sample
*
* Input Output 4 Case #1: 3 3 1 5 15 13 11 Case #2: 2 3 0 8 23 22 21 Case #3: 1
* 2 1 1 8 0 Case #4: 3 6 2 8 29 20 8 18 18 21
*
* @author Leandro Baena Torres
*/
public class B {
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader br = new BufferedReader(new FileReader("B.in"));
String linea;
int numCasos, N, S, p, t[], y, minSurprise, minNoSurprise;
linea = br.readLine();
numCasos = Integer.parseInt(linea);
for (int i = 0; i < numCasos; i++) {
linea = br.readLine();
String[] aux = linea.split(" ");
N = Integer.parseInt(aux[0]);
S = Integer.parseInt(aux[1]);
p = Integer.parseInt(aux[2]);
t = new int[N];
y = 0;
minSurprise = p + ((p - 2) >= 0 ? (p - 2) : 0) + ((p - 2) >= 0 ? (p - 2) : 0);
minNoSurprise = p + ((p - 1) >= 0 ? (p - 1) : 0) + ((p - 1) >= 0 ? (p - 1) : 0);
for (int j = 0; j < N; j++) {
t[j] = Integer.parseInt(aux[3 + j]);
if (t[j] >= minNoSurprise) {
y++;
} else {
if (t[j] >= minSurprise) {
if (S > 0) {
y++;
S--;
}
}
}
}
System.out.println("Case #" + (i + 1) + ": " + y);
}
}
}
|
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
/**
*
* @author Gershom
*/
public class DancingWithGooglers {
public static void main(String[] args0) {
try {
File f = new File("example");
Scanner s = new Scanner(new FileReader(f));
int num = Integer.parseInt(s.nextLine());
for (int i = 0; i < num; i++) {
String line = s.nextLine();
int[] dat = new int[3];
intList(line, dat);
int numGooglers = dat[0];
int numSurprising = dat[1];
int p = dat[2];
int[] scoresTemp = new int[3 + numGooglers];
intList(line, scoresTemp);
int[] scores = new int[numGooglers];
for (int j = 0; j < scores.length; j++) {
scores[j] = scoresTemp[j + 3];
}
System.out.println("Case #" + (i + 1) + ": " +
calcNumBest(numSurprising, p, scores));
}
} catch (Exception e) {
e.printStackTrace();
}
}
static int calcNumBest(int sur, int p, int[] scores) {
int numSurprisingRequired = 0;
int num = 0;
for (int i = 0; i < scores.length; i++) {
switch (scoreBreakdown(scores[i], p)) {
case 1:
numSurprisingRequired++;
break;
case 2:
num++;
break;
}
}
return num + Math.min(sur, numSurprisingRequired);
}
/**
* 0 means target can't be met, 1 means it can be met if it's "surprising",
* 2 means it can be met without being surprising.
* @param best
* @return
*/
static int scoreBreakdown(int score, int target) {
//Remaining points assuming target was met
int rem = score - target;
if (rem < 0) {
return 0;
}
int otherScores = rem / 2;
int gap = target - otherScores;
if (gap > 2) {
return 0;
} else if (gap == 2) {
return 1;
}
return 2;
}
public static void intList(String s, int[] array) {
int index = 0;
String cur = "";
for (int i = 0; i < s.length() + 1; i++) {
if (i == s.length() || s.charAt(i) == ' ') {
array[index++] = Integer.parseInt(cur);
if (index == array.length) {
break;
}
cur = "";
} else {
cur += s.charAt(i);
}
}
}
}
|
B12082 | B10954 | 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 codejam.qualification;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import codejam.Task;
public class C extends Task {
private int t;
private String[][] testCases;
private String[] resultset;
public C(String[] args) {
super(args);
}
public static void main(String[] args) throws IOException {
Task taskC = new C(args);
taskC.execute();
}
protected void catchInputData() throws IOException {
t = Integer.parseInt(readLine());
testCases = new String[t][];
// iterates over cases
for (int c = 0; c < t; c++) {
testCases[c] = readLine().split(" ");
}
}
protected void processInputData() {
resultset = new String[t];
// iterates over cases
for (int c = 0; c < t; c++) {
String[] testCase = testCases[c];
int a = Integer.parseInt(testCase[0]);
int b = Integer.parseInt(testCase[1]);
int y = 0;
for (int n = a; n < b; n++) {
Set<Integer> mset = new HashSet<Integer>();
String sn = String.valueOf(n);
for (int i = 1; i < sn.length(); i++) {
if (sn.charAt(i) != '0') {
String sm = sn.substring(i) + sn.substring(0, i);
int m = Integer.parseInt(sm);
if (m > n && m <= b && !mset.contains(m)) {
y++;
mset.add(m);
}
}
}
}
resultset[c] = ""+y;
}
}
protected void generateOutputFile() throws IOException {
// iterates over cases
for (int c = 0; c < t; c++) {
writeLine("Case #" + (c + 1) + ": " + resultset[c]);
}
}
}
|
A12273 | A12521 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Dancing
* Jason Bradley Nel
* 16287398
*/
import java.io.*;
public class Dancing {
public static void main(String[] args) {
In input = new In("input.txt");
int T = Integer.parseInt(input.readLine());
for (int i = 0; i < T; i++) {
System.out.printf("Case #%d: ", i + 1);
int N = input.readInt();
int s = input.readInt();
int p = input.readInt();
int c = 0;//counter for >=p cases
//System.out.printf("N: %d, S: %d, P: %d, R: ", N, s, p);
for (int j = 0; j < N; j++) {
int score = input.readInt();
int q = score / 3;
int m = score % 3;
//System.out.printf("%2d (%d, %d) ", scores[j], q, m);
switch (m) {
case 0:
if (q >= p) {
c++;
} else if (((q + 1) == p) && (s > 0) && (q != 0)) {
c++;
s--;
}
break;
case 1:
if (q >= p) {
c++;
} else if ((q + 1) == p) {
c++;
}
break;
case 2:
if (q >= p) {
c++;
} else if ((q + 1) == p) {
c++;
} else if (((q + 2) == p) && (s > 0)) {
c++;
s--;
}
break;
}
}
//System.out.printf("Best result of %d or higher: ", p);
System.out.println(c);
}
}
}
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
public class DancingWiththeGooglers {
public static void main(String[] args) throws Exception {
PrintWriter out = new PrintWriter("output.out");
Scanner in = new Scanner(new File("B-small-attempt19.in"));
int testCases = in.nextInt();
for (int i = 1; i <= testCases; i++){
int N = in.nextInt(),counter=0;
int S = in.nextInt();
int P = in.nextInt();
for(int j = 0 ; j < N ;j++){
int googler= in.nextInt();
if(googler%3 == 0 && googler!=0){
if(googler/3 >= P){
counter++;
}
else if(googler/3 + 1 >= P && S!=0){
counter++;
S--;
}
}
else if (googler==0 && P==0){
counter++;
}
else if(googler%3==1){
if(googler/3 + 1 >= P){
counter++;
}
}
else if(googler%3==2){
if(googler/3 + 1 >= P){
counter++;
}
else if(googler/3 + 2 >= P && S!=0){
counter++;
S--;
}
}
}
out.printf("Case #%d: %d",i,counter);
out.printf("\n");
}
out.close();
in.close();
}
} |
A12113 | A10465 | 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.suraj.quals2012.googlerese;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import codejam.suraj.quals2012.CodeJamSkeleton;
public class Googlerese extends CodeJamSkeleton {
public static Map<Character, Character> map =
new HashMap<Character, Character>(52);
public static void initializeCharMap(){
map.put('e','o');
map.put('j','u');
map.put('p','r');
map.put('m','l');
map.put('y','a');
map.put('s','n');
map.put('l','g');
map.put('j','u');
map.put('y','a');
map.put('l','g');
map.put('c','e');
map.put('k','i');
map.put('d','s');
map.put('k','i');
map.put('x','m');
map.put('v','p');
map.put('e','o');
map.put('d','s');
map.put('d','s');
map.put('k','i');
map.put('n','b');
map.put('m','l');
map.put('c','e');
map.put('r','t');
map.put('e','o');
map.put('j','u');
map.put('s','n');
map.put('i','d');
map.put('c','e');
map.put('p','r');
map.put('d','s');
map.put('r','t');
map.put('y','a');
map.put('s','n');
map.put('i','d');
map.put('r','t');
map.put('b','h');
map.put('c','e');
map.put('p','r');
map.put('c','e');
map.put('y','a');
map.put('p','r');
map.put('c','e');
map.put('r','t');
map.put('t','w');
map.put('c','e');
map.put('s','n');
map.put('r','t');
map.put('a','y');
map.put('d','s');
map.put('k','i');
map.put('h','x');
map.put('w','f');
map.put('y','a');
map.put('f','c');
map.put('r','t');
map.put('e','o');
map.put('p','r');
map.put('k','i');
map.put('y','a');
map.put('m','l');
map.put('v','p');
map.put('e','o');
map.put('d','s');
map.put('d','s');
map.put('k','i');
map.put('n','b');
map.put('k','i');
map.put('m','l');
map.put('k','i');
map.put('r','t');
map.put('k','i');
map.put('c','e');
map.put('d','s');
map.put('d','s');
map.put('e','o');
map.put('k','i');
map.put('r','t');
map.put('k','i');
map.put('d','s');
map.put('e','o');
map.put('o','k');
map.put('y','a');
map.put('a','y');
map.put('k','i');
map.put('w','f');
map.put('a','y');
map.put('e','o');
map.put('j','u');
map.put('t','w');
map.put('y','a');
map.put('s','n');
map.put('r','t');
map.put('r','t');
map.put('e','o');
map.put('u','j');
map.put('j','u');
map.put('d','s');
map.put('r','t');
map.put('l','g');
map.put('k','i');
map.put('g','v');
map.put('c','e');
map.put('j','u');
map.put('v','p');
map.put('z','q');
map.put('q','z');
map.put(' ',' ');
}
@Override
protected void handleTestCase(int testCaseNumber) throws IOException {
String line = readLine();
StringBuffer text = new StringBuffer(line.length());
for(int i = 0; i < line.length(); ++i)
{
text.append(map.get(line.charAt(i)));
}
System.out.println(text);
addOutput(testCaseNumber, text.toString());
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
initializeCharMap();
CodeJamSkeleton testCase = new Googlerese();
testCase.handleAllTestCases(args[0], args[1]);
}
}
|
B21968 | B21429 | 0 | import java.util.*;
import java.io.*;
public class recycled_numbers {
public static void main(String[]a) throws Exception{
Scanner f = new Scanner(new File(a[0]));
int result=0;
int A,B;
String n,m;
HashSet<String> s=new HashSet<String>();
int T=f.nextInt(); //T total case count
for (int t=1; t<=T;t++){//for each case t
s.clear();
result=0; //reset
A=f.nextInt();B=f.nextInt(); //get values for next case
if (A==B)result=0;//remove case not meeting problem limits
else{
for(int i=A;i<=B;i++){//for each int in range
n=Integer.toString(i);
m=new String(n);
//System.out.println(n);
for (int j=1;j<n.length();j++){//move each digit to the front & test
m = m.substring(m.length()-1)+m.substring(0,m.length()-1);
if(m.matches("^0+[\\d]+")!=true &&
Integer.parseInt(m)<=B &&
Integer.parseInt(n)<Integer.parseInt(m)){
s.add(new String(n+","+m));
//result++;
//System.out.println(" matched: "+m);
}
}
}
result = s.size();
}
//display output
System.out.println("Case #" + t + ": " + result);
}
}
} | package jp.funnything.prototype;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import jp.funnything.competition.util.CompetitionIO;
import jp.funnything.competition.util.Packer;
import org.apache.commons.io.FileUtils;
import com.google.common.collect.Sets;
public class Runner {
public static void main( final String[] args ) throws Exception {
new Runner().run();
}
void pack() {
try {
final File dist = new File( "dist" );
if ( dist.exists() ) {
FileUtils.deleteQuietly( dist );
}
final File workspace = new File( dist , "workspace" );
FileUtils.copyDirectory( new File( "src/main/java" ) , workspace );
FileUtils.copyDirectory( new File( "../../../../CompetitionUtil/Lib/src/main/java" ) , workspace );
Packer.pack( workspace , new File( dist , "sources.zip" ) );
} catch ( final IOException e ) {
throw new RuntimeException( e );
}
}
void run() throws Exception {
final CompetitionIO io = new CompetitionIO();
final int t = io.readInt();
for ( int index = 0 ; index < t ; index++ ) {
final int[] values = io.readInts();
final int a = values[ 0 ];
final int b = values[ 1 ];
io.write( index + 1 , solve( a , b ) );
}
io.close();
pack();
}
int solve( final int a , final int b ) {
int count = 0;
final int nDigit = ( int ) Math.floor( Math.log10( a ) ) + 1;
final int next = ( int ) Math.pow( 10 , nDigit - 1 );
final Set< Integer > already = Sets.newTreeSet();
for ( int n = a ; n + 1 <= b ; n++ ) {
if ( already.contains( n ) ) {
continue;
}
int inRange = 1;
already.add( n );
for ( int base = 10 , m = next ; base < n ; base *= 10 , m /= 10 ) {
final int v = n / base + n % base * m;
if ( already.contains( v ) ) {
continue;
}
if ( v >= a && v <= b ) {
inRange++;
already.add( v );
}
}
count += inRange * ( inRange - 1 ) / 2;
}
return count;
}
}
|
A11917 | A11106 | 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 code.jam.y2012.quali;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class ProblemB {
private static String PATH = "F:\\dev\\projects\\code-jam-2012\\src\\code\\jam\\y2012\\quali";
File inputFile = new File(PATH, "B-small-attempt0.in");
File outputFile = new File(PATH, "B-small-attempt0.out");
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
public static void main(String[] args) throws Exception {
new ProblemB().solve();
}
void solve() throws Exception {
in = new BufferedReader(new FileReader(inputFile));
out = new PrintWriter(outputFile);
for (int testCase = 1, testCount = nextInt(); testCase <= testCount; testCase++) {
solve(testCase);
}
out.close();
}
void solve(int testCase) throws IOException {
final int googlers = nextInt();
final int surprises = nextInt();
final int atLeastRate = nextInt();
int googlersPass = 0;
int surprisesUsed = 0;
for (int i = 0; i < googlers; i++) {
final double minSafeAverage = (atLeastRate * 3 - 2) / 3d;
final double minSurpriseAverage = (atLeastRate * 3 - 4) / 3d;
final int googlerTotal = nextInt();
if (atLeastRate==0 && googlerTotal==0) {
googlersPass++;
continue;
}
if (googlerTotal==0) {
continue;
}
final double googlerAverage = googlerTotal / 3d;
if (googlerAverage>=minSafeAverage) {
//System.out.println("pass: " + googlerTotal + " " + googlerAverage);
googlersPass++;
continue;
}
if (googlerAverage>=minSurpriseAverage && surprises>surprisesUsed) {
//System.out.println("PASS: " + googlerTotal + " " + googlerAverage);
googlersPass++;
surprisesUsed++;
continue;
}
}
print("Case #" + testCase + ": " + googlersPass);
}
private void print(String text) {
out.println(text);
System.out.println(text);
}
/**
* helpers
*/
String nextToken() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextChar() throws IOException {
return in.read();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null) {
return true;
}
st = new StringTokenizer(s);
}
return false;
}
}
|
B21270 | B20420 | 0 | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class CopyOfCopyOfMain {
static int ndigits(int n) {
return (int) (Math.log10(n) + 1);
}
static int rot(int n, int dig) {
return (int) ((n % 10) * Math.pow(10, dig - 1)) + (int) (n / 10);
}
public static void main(String[] args) throws FileNotFoundException {
String file = "C-large";
Scanner in = new Scanner(new File(file + ".in"));
PrintWriter out = new PrintWriter(new File(file + ".out"));
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int A = in.nextInt();
int B = in.nextInt();
int c = 0;
int[] list = new int[ndigits(B)];
numbers: for (int i = A; i <= B; i++) {
int digs = ndigits(i);
int rot = i;
int pairs = 0;
Arrays.fill(list, -1);
list[0] = i;
digits: for (int j = 1; j <= digs + 1; j++) {
rot = rot(rot, digs);
if(rot < i)
continue;
if (A <= rot && rot <= B) {
for (int k = 0; k < j; k++) {
if (list[k] == rot) {
continue digits;
}
}
pairs++;
list[j] = rot;
}
}
//c += pairs * (pairs + 1) / 2;
c += pairs ;
// c+=digs;
}
out.println("Case #" + t + ": " + c);
}
in.close();
out.close();
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package codejam;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
/**
*
* @author cristian
*/
public class CodeJam {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
StringBuffer sb;
Boolean firstLine = true;
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("/tmp/problemB.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
int line = 1;
while ((strLine = br.readLine()) != null) {
if (firstLine) {
firstLine = false;
continue;
}
sb = new StringBuffer();
// Print the content on the console
int A = Integer.parseInt(strLine.split(" ")[0]);
int B = Integer.parseInt(strLine.split(" ")[1]);
int n = A;
int m;
int recycled = 0;
while (n < B) {
recycled += moveLast(n, B);
n++;
}
System.out.println("Case #" + line + ": " + recycled);
line++;
}
//Close the input stream
in.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
private static int moveLast(int n, int B) {
int recycled = 0;
int tmpN = n;
int m;
StringBuffer sb;
for (int i = 0; i < (n + "").length() - 1; i++) {
sb = new StringBuffer();
sb.append((tmpN + "").charAt((tmpN + "").length() - 1));
if ((tmpN + "").length() < (n + "").length()) {
sb.append("0");
}
sb.append((tmpN + "").substring(0, (tmpN + "").length() - 1));
m = Integer.parseInt(sb.toString());
//A ⤠n < m ⤠B
if ((n < m) && (m <= B)) {
recycled++;
}
tmpN = m;
}
return recycled;
}
}
|
A12113 | A10844 | 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 qualifying;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Google Code Jam, Problem B. Result finder
*
* @author Petar
*
*/
public class Dancers {
private static BufferedReader in;
private static BufferedWriter out;
/**
* Main, reads in scores, outputs max num of Googler's with result p
*
* @param args
*/
public static void main(String[] args) {
List<Integer> scores;
int numSurprise, numGooglers, p, maxGooglers;
String currLine = "";
try {
out = new BufferedWriter(new FileWriter(".out"));
in = new BufferedReader(new FileReader(".in"));
int testNum = Integer.parseInt(in.readLine());
for (int i = 0; i < testNum; i++) {
maxGooglers = 0;
currLine = in.readLine();
String[] testBound = currLine.split(" ");
numGooglers = Integer.parseInt(testBound[0]);
numSurprise = Integer.parseInt(testBound[1]);
p = Integer.parseInt(testBound[2]);
System.out
.println(String
.format("The bounds of the problem are %d googlers, %d surprising results and %d p value",
numGooglers, numSurprise, p));
// Read in the scores
scores = new ArrayList<Integer>(numGooglers);
for (int j = 0; j < numGooglers; j++) {
scores.add(Integer.parseInt(testBound[j + 3]));
}
// Determine the tallies
for (Integer score : scores) {
if (score < (3 * p - 4) || score < p) {
continue;
} else if (score >= (3 * p - 2)) {
maxGooglers++;
} else {
if (numSurprise > 0) {
maxGooglers++;
numSurprise--;
}
}
}
Collections.sort(scores);
out.write(String.format("Case #%d: %d", i + 1, maxGooglers));
out.newLine();
}
in.close();
out.flush();
out.close();
} catch (FileNotFoundException e) {
System.err.println("Input file was not found");
} catch (IOException e) {
System.err.println("Problem reading from input file");
e.printStackTrace();
}
}
}
|
B12115 | B11025 | 0 | package qual;
import java.util.Scanner;
public class RecycledNumbers {
public static void main(String[] args) {
new RecycledNumbers().run();
}
private void run() {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int t = 0; t < T; t++) {
int A = sc.nextInt();
int B = sc.nextInt();
int result = solve(A, B);
System.out.printf("Case #%d: %d\n", t + 1, result);
}
}
public int solve(int A, int B) {
int result = 0;
for (int i = A; i <= B; i++) {
int dig = (int) Math.log10(A/*same as B*/) + 1;
int aa = i;
for (int d = 0; d < dig - 1; d++) {
aa = (aa % 10) * (int)Math.pow(10, dig - 1) + (aa / 10);
if (i == aa) {
break;
}
if (i < aa && aa <= B) {
// System.out.printf("(%d, %d) ", i, aa);
result++;
}
}
}
return result;
}
}
| package org.moriraaca.codejam;
public enum DebugOutputLevel {
SOLUTION, IMPORTANT, ALL;
}
|
A11917 | A11585 | 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 quiz2012.quiz2;
import java.util.ArrayList;
import java.util.List;
import domain.QuizSolver;
import domain.QuizTestCaseInput;
import domain.QuizTestCaseOutput;
public class Quiz2Solver implements QuizSolver {
private static final int NUMBER_OF_JUDGES = 3;
@Override
public QuizTestCaseOutput solve(QuizTestCaseInput testCaseInput) {
Quiz2TestCaseInput input = (Quiz2TestCaseInput) testCaseInput;
System.out.println(input);
int numberOfGooglers = input.getNumberOfGooglers();
int numberOfSurprising = input.getNumberOfSurprising();
int minBestResult = input.getMinBestResult();
int[] totalPoints = input.getTotalPoints();
List<Googler> surprisePossibleGooglers = new ArrayList<Googler>();
int numberOfGooglersHavingMinBestResultWithoutSurprising = 0;
for (int i = 0; i < numberOfGooglers; i++) {
int q = totalPoints[i] / NUMBER_OF_JUDGES;
int r = totalPoints[i] % NUMBER_OF_JUDGES;
Googler googler = new Googler(q, r);
if (googler.getBestResult() >= minBestResult) {
numberOfGooglersHavingMinBestResultWithoutSurprising++;
} else {
if (totalPoints[i] >= 2 && totalPoints[i] <= 28) {
googler.setSurprising(true);
surprisePossibleGooglers.add(googler);
}
}
}
int numberOfPossibleGooglersHavingMinBestResultWithSurprise = 0;
for (Googler googler : surprisePossibleGooglers) {
if (googler.getBestResult() >= minBestResult) {
numberOfPossibleGooglersHavingMinBestResultWithSurprise++;
}
}
int numberOfGooglersHavingMinBestResultWithSurprise = Math.min(
numberOfSurprising,
numberOfPossibleGooglersHavingMinBestResultWithSurprise);
int numberOfGooglersHavingMinBestResult = numberOfGooglersHavingMinBestResultWithoutSurprising
+ numberOfGooglersHavingMinBestResultWithSurprise;
System.out.println(numberOfSurprising + ", "
+ numberOfPossibleGooglersHavingMinBestResultWithSurprise
+ ", " + numberOfGooglersHavingMinBestResultWithSurprise + ", "
+ numberOfGooglersHavingMinBestResultWithoutSurprising + ", "
+ numberOfGooglersHavingMinBestResult);
return new Quiz2TestCaseOutput(numberOfGooglersHavingMinBestResult);
}
}
class Googler {
private final int q;
private final int r;
private boolean surprising;
public Googler(int q, int r) {
this.q = q;
this.r = r;
}
public void setSurprising(boolean surprising) {
this.surprising = surprising;
}
public Integer getBestResult() {
switch (r) {
case 0:
return q + (surprising ? 1 : 0);
case 1:
return q + 1;
case 2:
return q + 1 + (surprising ? 1 : 0);
}
throw new IllegalStateException("r must be 0, 1, or 2: " + r);
}
@Override
public String toString() {
return "Googler [q=" + q + ", r=" + r + ", surprising=" + surprising
+ "]";
}
} |
A12113 | A10399 | 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 dancinggooglers;
import java.util.ArrayList;
public class DanceScoreCase {
private int dancers;
private int surpriseScores;
private int scoreThreshold;
private ArrayList<Integer> scores;
public DanceScoreCase(String scoreLine) {
String[] integers = scoreLine.split(" ");
if(integers.length < 4) {
throw new IllegalArgumentException("Not enough strings");
}
dancers = new Integer(integers[0]);
surpriseScores = new Integer(integers[1]);
scoreThreshold = new Integer(integers[2]);
scores = new ArrayList<Integer>();
for(int i = 3; i < integers.length; i++) {
scores.add(Integer.valueOf(integers[i]));
}
}
public Integer maxDancersThatCouldPass() {
int passesUnsurprising = 0;
int passesSurprising = 0;
ArrayList<Integer> couldNotPassUnsuprising = new ArrayList<Integer>();
for(Integer score : scores) {
if(canPassThresholdUnsurprising(score, scoreThreshold)) {
passesUnsurprising++;
} else if(canPassThresholdSurprising(score, scoreThreshold)) {
passesSurprising++;
}
}
return passesUnsurprising + Math.min(passesSurprising, surpriseScores);
}
public static boolean canPassThresholdUnsurprising(int score, int threshold) {
int minScore = Math.max(0, threshold-1);
return (score >= threshold + 2*minScore);
}
public static boolean canPassThresholdSurprising(int score, int threshold) {
int minScore = Math.max(0, threshold-2);
return (score >= threshold + 2*minScore);
}
public int getDancers() {
return dancers;
}
public int getSurpriseScores() {
return surpriseScores;
}
public int getScoreThreshold() {
return scoreThreshold;
}
public ArrayList<Integer> getScores() {
return scores;
}
}
|
A12460 | A11250 | 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();
}
}
| /**
* Copyright 2012 Christopher Schmitz. All Rights Reserved.
*/
package com.isotopeent.codejam.lib;
public interface InputConverter<T> {
boolean readLine(String data);
T generateObject();
}
|
A22642 | A20124 | 0 | import java.util.*;
import java.io.*;
public class DancingWithTheGooglers
{
public DancingWithTheGooglers()
{
Scanner inFile = null;
try
{
inFile = new Scanner(new File("inputB.txt"));
}
catch(Exception e)
{
System.out.println("Problem opening input file. Exiting...");
System.exit(0);
}
int t = inFile.nextInt();
int [] results = new int [t];
DancingWithTheGooglersMax [] rnc = new DancingWithTheGooglersMax[t];
int i, j;
int [] scores;
int s, p;
for(i = 0; i < t; i++)
{
scores = new int [inFile.nextInt()];
s = inFile.nextInt();
p = inFile.nextInt();
for(j = 0; j < scores.length; j++)
scores[j] = inFile.nextInt();
rnc[i] = new DancingWithTheGooglersMax(i, scores, s, p, results);
rnc[i].start();
}
inFile.close();
boolean done = false;
while(!done)
{
done = true;
for(i = 0; i < t; i++)
if(rnc[i].isAlive())
{
done = false;
break;
}
}
PrintWriter outFile = null;
try
{
outFile = new PrintWriter(new File("outputB.txt"));
}
catch(Exception e)
{
System.out.println("Problem opening output file. Exiting...");
System.exit(0);
}
for(i = 0; i < results.length; i++)
outFile.printf("Case #%d: %d\n", i+1, results[i]);
outFile.close();
}
public static void main(String [] args)
{
new DancingWithTheGooglers();
}
private class DancingWithTheGooglersMax extends Thread
{
int id;
int s, p;
int [] results, scores;
public DancingWithTheGooglersMax(int i, int [] aScores, int aS, int aP,int [] res)
{
id = i;
s = aS;
p = aP;
results = res;
scores = aScores;
}
public void run()
{
int a = 0, b = 0;
if(p == 0)
results[id] = scores.length;
else if(p == 1)
{
int y;
y = 3*p - 3;
for(int i = 0; i < scores.length; i++)
if(scores[i] > y)
a++;
else if(scores[i] > 0)
b++;
b = Math.min(b, s);
results[id] = a+b;
}
else
{
int y, z;
y = 3*p - 3;
z = 3*p - 5;
for(int i = 0; i < scores.length; i++)
if(scores[i] > y)
a++;
else if(scores[i] > z)
b++;
b = Math.min(b, s);
results[id] = a+b;
}
}
}
} | import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileWriter;
class Start{
BufferedInputStream bis=new BufferedInputStream(System.in);
PrintWriter out=new PrintWriter(System.out, true);
int i,j,k,l,m,n,o,p,q,r,s,t,w,x,y,z,ry,rz,rs;
long a,b,c;
double d,e,f,g,h;
char u,v;
String st;
int[] in,arr,res;
final double pi=3.14159265;
final double l2=0.69314718;
char chr()throws IOException{
while((ry=bis.read())==10 || ry==13 || ry==32){}
return (char)ry;
}
int num()throws IOException{
rz=0;rs=0;
ry=bis.read(); if(ry=='-') rs=-1; else rz+=(ry-'0');
while((ry=bis.read())>='0' && ry<='9') rz=rz*10+(ry-'0');
if(rs==-1) rz=-rz;
if(ry==13) bis.read();
return rz;
}
String str()throws IOException{
StringBuilder sb=new StringBuilder();
while((ry=bis.read())!=10 & ry!=13 && ry!=32) sb.append((char)ry);
if(ry==13) bis.read();
return sb.toString();
}
String line()throws IOException{
StringBuilder sb=new StringBuilder();
while((ry=bis.read())!=10 && ry!=13) sb.append((char)ry);
if(ry==13)bis.read();
return sb.toString();
}
int log2(double par){return (int)(Math.log(par)/l2);}
long perm(int p1,int p2){
long ret=1; int it;
it=p1; while(it>p2) ret*=it--;
return ret;
}
long comb(int p1,int p2){
long ret=1; int it;
if(p2<p1-p2) k=p1-p2;
it=p1; while(it>p2) ret*=it--;
it=p1-p2; while(it>1) ret/=it--;
return ret;
}
public void go()throws IOException{
out =new PrintWriter(new FileWriter("out.txt"),true);
t=num();
j=t;
while(--t>=0){
n=num();
s=num();
p=num();
x=0;
for(i=0;i<n;i++)
{
y=num();
z=y/3;
if((z>=p) ||
((z+1 + z*2 == y) && z+1>=p) ||
(((z+1)*2 + z == y) && z+1>=p)) x++;
else if(s>0 &&
((z-1>0 && (z*3 == y) && z+1>=p)||
(z-2>0 && (z*3+2 == y) && z+2>=p)||
(z-2>0 && (z*3-2 == y) && z>=p))||
(z+2<10 && (z*3+4 == y) && z+2>=p)||
(z-2>0 && (z*3-4 == y) && z>=p))
{ x++; s--;}
}
out.println("Case #"+(j-t)+": "+x);
}
while(bis.available()>0)bis.read();
out.close();
}
public static void main(String args[])throws IOException{new Start().go();}
}
|
A21010 | A21883 | 0 | package codejam;
import fixjava.Pair;
public class Utils {
public static long minLong(long firstVal, long... otherVals) {
long minVal = firstVal;
for (int i = 0; i < otherVals.length; i++)
minVal = Math.min(firstVal, otherVals[i]);
return minVal;
}
public static int minInt(int firstVal, int... otherVals) {
int minVal = firstVal;
for (int i = 0; i < otherVals.length; i++)
minVal = Math.min(firstVal, otherVals[i]);
return minVal;
}
public static float minFloat(float firstVal, float... otherVals) {
float minVal = firstVal;
for (int i = 0; i < otherVals.length; i++)
minVal = Math.min(firstVal, otherVals[i]);
return minVal;
}
/**
* ArgMin returned as a Pair<Integer, Integer>(index, value). Array must
* have at least one value.
*/
public static Pair<Integer, Integer> argMin(int[] arr) {
int min = arr[0];
int argMin = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
argMin = i;
}
}
return new Pair<Integer, Integer>(argMin, min);
}
/**
* ArgMax returned as a Pair<Integer, Integer>(index, value). Array must
* have at least one value.
*/
public static Pair<Integer, Integer> argMax(int[] arr) {
int max = arr[0];
int argMax = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
argMax = i;
}
}
return new Pair<Integer, Integer>(argMax, max);
}
}
| import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("B-large.in"));
PrintWriter out = new PrintWriter(new FileWriter("DancingWithTheGooglers-Large.out"));
DancingWithTheGooglers solver = new DancingWithTheGooglers();
int testCases = in.nextInt();
for (int i = 1; i <= testCases; ++i) {
solver.solve(i, in, out);
}
in.close();
out.close();
}
}
class DancingWithTheGooglers {
int MAX_SCORE = 31;
int[] bestScoreSurprising = new int[MAX_SCORE];
int[] bestScoreNotSurprising = new int[MAX_SCORE];
public DancingWithTheGooglers() {
Arrays.fill(bestScoreSurprising, -1);
Arrays.fill(bestScoreNotSurprising, -1);
for (int i = 0; i <= 10; ++i) {
for (int j = 0; j <= 10; ++j) {
for (int k = 0; k <= 10; ++k) {
if (Math.abs(i - j) > 2 || Math.abs(j - k) > 2 || Math.abs(k - i) > 2) continue;
if (Math.abs(i - j) == 2 || Math.abs(j - k) == 2 || Math.abs(k - i) == 2) {
int sum = i + j + k;
int score = Math.max(i, Math.max(j, k));
bestScoreSurprising[sum] = Math.max(bestScoreSurprising[sum], score);
}
else {
int sum = i + j + k;
int score = Math.max(i, Math.max(j, k));
bestScoreNotSurprising[sum] = Math.max(bestScoreNotSurprising[sum], score);
}
}
}
}
}
public void solve(int testNumber, Scanner in, PrintWriter out) {
int N = in.nextInt();
int S = in.nextInt();
int P = in.nextInt();
int[] t = new int[N];
for (int i = 0; i < N; ++i)
t[i] = in.nextInt();
int res = 0;
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, z = 0;
for (int score : t) {
if (bestScoreSurprising[score] == -1) {
if (bestScoreNotSurprising[score] >= P) {
++a;
}
else {
++c;
}
}
else if (bestScoreNotSurprising[score] == -1) {
if (bestScoreSurprising[score] >= P) {
++b;
}
else {
++d;
}
}
if (bestScoreSurprising[score] >= P) {
if (bestScoreNotSurprising[score] >= P) {
++h;
}
else {
++f;
}
}
else if (0 <= bestScoreSurprising[score] && bestScoreSurprising[score] < P) {
if (bestScoreNotSurprising[score] >= P) {
++g;
}
else {
++e;
}
}
}
z = Math.min(S, b + d);
S -= z;
res += a + b;
z = Math.min(S, f);
S -= z;
res += z;
z = Math.min(S, e + h);
S -= z;
res += g + h - S;
out.println("Case #" + testNumber + ": " + res);
}
}
|
A20261 | A20556 | 0 | package com.gcj.parser;
public class MaxPoints {
public static int normal(int value){
int toReturn = 0;
switch (value) {
case 0 : toReturn = 0 ; break;
case 1 : toReturn = 1 ; break;
case 2 : toReturn = 1 ; break;
case 3 : toReturn = 1 ; break;
case 4 : toReturn = 2 ; break;
case 5 : toReturn = 2 ; break;
case 6 : toReturn = 2 ; break;
case 7 : toReturn = 3 ; break;
case 8 : toReturn = 3 ; break;
case 9 : toReturn = 3 ; break;
case 10 : toReturn = 4 ; break;
case 11 : toReturn = 4 ; break;
case 12 : toReturn = 4 ; break;
case 13 : toReturn = 5 ; break;
case 14 : toReturn = 5 ; break;
case 15 : toReturn = 5 ; break;
case 16 : toReturn = 6 ; break;
case 17 : toReturn = 6 ; break;
case 18 : toReturn = 6 ; break;
case 19 : toReturn = 7 ; break;
case 20 : toReturn = 7 ; break;
case 21 : toReturn = 7 ; break;
case 22 : toReturn = 8 ; break;
case 23 : toReturn = 8 ; break;
case 24 : toReturn = 8 ; break;
case 25 : toReturn = 9 ; break;
case 26 : toReturn = 9 ; break;
case 27 : toReturn = 9 ; break;
case 28 : toReturn = 10 ; break;
case 29 : toReturn = 10 ; break;
case 30 : toReturn = 10 ; break;
}
return toReturn;
}
public static int surprising(int value){
int toReturn = 0;
switch (value) {
case 0 : toReturn = 0 ; break;
case 1 : toReturn = 1 ; break;
case 2 : toReturn = 2 ; break;
case 3 : toReturn = 2 ; break;
case 4 : toReturn = 2 ; break;
case 5 : toReturn = 3 ; break;
case 6 : toReturn = 3 ; break;
case 7 : toReturn = 3 ; break;
case 8 : toReturn = 4 ; break;
case 9 : toReturn = 4 ; break;
case 10 : toReturn = 4 ; break;
case 11 : toReturn = 5 ; break;
case 12 : toReturn = 5 ; break;
case 13 : toReturn = 5 ; break;
case 14 : toReturn = 6 ; break;
case 15 : toReturn = 6 ; break;
case 16 : toReturn = 6 ; break;
case 17 : toReturn = 7 ; break;
case 18 : toReturn = 7 ; break;
case 19 : toReturn = 7 ; break;
case 20 : toReturn = 8 ; break;
case 21 : toReturn = 8 ; break;
case 22 : toReturn = 8 ; break;
case 23 : toReturn = 9 ; break;
case 24 : toReturn = 9 ; break;
case 25 : toReturn = 9 ; break;
case 26 : toReturn = 10 ; break;
case 27 : toReturn = 10 ; break;
case 28 : toReturn = 10 ; break;
case 29 : toReturn = 10 ; break;
case 30 : toReturn = 10 ; break;
}
return toReturn;
}
}
| package codejam2012.qualification.b;
public final class Triplet {
public final int a;
public final int b;
public final int c;
public final int total;
public final boolean surprising;
private Triplet(int a, int b, int c, int total) {
this.a = a;
this.b = b;
this.c = c;
this.total = total;
surprising = Math.abs(a - b) > 1 || Math.abs(a - c) > 1 || Math.abs(b - c) > 1;
}
public static Triplet of(int a, int b, int c, int total) {
return new Triplet(a, b, c, total);
}
public boolean hasAtLeast(int p) {
return a >= p || b >= p || c >= p;
}
@Override
public String toString() {
return String.format("(%d,%d,%d)%s = %d", a, b, c, surprising ? "*" : "", total);
}
}
|
A22992 | A22647 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package IO;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
*
* @author dannocz
*/
public class InputReader {
public static Input readFile(String filename){
try {
/* Sets up a file reader to read the file passed on the command
77 line one character at a time */
FileReader input = new FileReader(filename);
/* Filter FileReader through a Buffered read to read a line at a
time */
BufferedReader bufRead = new BufferedReader(input);
String line; // String that holds current file line
int count = 0; // Line number of count
ArrayList<String> cases= new ArrayList<String>();
// Read first line
line = bufRead.readLine();
int noTestCases=Integer.parseInt(line);
count++;
// Read through file one line at time. Print line # and line
while (count<=noTestCases){
//System.out.println("Reading. "+count+": "+line);
line = bufRead.readLine();
cases.add(line);
count++;
}
bufRead.close();
return new Input(noTestCases,cases);
}catch (ArrayIndexOutOfBoundsException e){
/* If no file was passed on the command line, this expception is
generated. A message indicating how to the class should be
called is displayed */
e.printStackTrace();
}catch (IOException e){
// If another exception is generated, print a stack trace
e.printStackTrace();
}
return null;
}// end main
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dancingwiththegooglers;
/**
*
* @author James
*/
public class ScoreAnalyzer {
private int targetBestResultScore;
private int surprisingScores;
private int[] totalScores;
public ScoreAnalyzer(int[] data) {
surprisingScores = data[1];
targetBestResultScore = data[2];
totalScores = new int[data[0]];
for (int i = 0; i < data[0]; i++) {
totalScores[i] = data[i+3];
}
}
public int getMaxNumOfHighScoringDancers() {
int result = 0;
int avgTotal = targetBestResultScore * 3;
if (avgTotal == 0) {
return totalScores.length; // all competitors got at least 0.
}
for (int i = 0; i < totalScores.length; i++) {
if (totalScores[i] != 0) {
if (totalScores[i] >= (avgTotal-2)) {
// score set is at least
// target-1 target-1 target
result++;
} else if ((totalScores[i] >= (avgTotal-4)) && (surprisingScores > 0)) {
// score is at least
// target-2 target-2 target
// and this result may be a surprising score
result++;
surprisingScores--; // remove a surprising score
} // else it cannot possibly have a sufficiently high max score
}
}
return result;
}
}
|
B10858 | B10548 | 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.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Scanner;
public class Recycled {
public static Integer reorder(int n) {
int newn = n, digits = 0, greatest = 0, scale = 1;
while (newn > 0) {
newn /= 10;
digits++;
scale *= 10;
}
scale /= 10;
int temp = 0;
for (int i = 0; i < digits; i++) {
temp = n;
temp /= 10;
temp += scale * (n-(10*temp));
n = temp;
greatest = Math.max(n,greatest);
}
return greatest;
}
public static void main(String[] args) {
String fileName;
String line;
fileName = "C-small-attempt0.in";
Scanner fromFile = null;
try {
fromFile = new Scanner(new File(fileName));
} catch (Exception e) {}
int iterations = Integer.parseInt(fromFile.nextLine());
int count, lower, upper;
int[] answers = new int[iterations];
HashMap<Integer,Integer> map = null;
Integer ordered = null;
for (int i = 0; i < iterations; i++) {
line = fromFile.nextLine();
String[] arguments = line.split(" ");
lower = Integer.parseInt(arguments[0]);
upper = Integer.parseInt(arguments[1]);
count = 0;
map = new HashMap<Integer,Integer>();
for (int j = lower; j <= upper; j++) {
ordered = reorder(j);
if (map.containsKey(ordered)) {
int number = map.get(ordered);
count += number;
map.put(ordered, number+1);
} else {
map.put(ordered, 1);
}
}
answers[i] = count;
}
try {
fromFile.close();
} catch (Exception e){}
PrintWriter toFile = null;
try {
File f = new File("output.txt");
if (!f.exists())
f.createNewFile();
toFile = new PrintWriter(f);
for (int i = 0; i < iterations; i++) {
if (i == iterations - 1) {
toFile.print("Case #" + (i + 1) + ": " + answers[i]);
} else {
toFile.println("Case #" + (i + 1) + ": " + answers[i]);
}
}
toFile.close();
} catch (Exception e) {}
}
}
|
B11421 | B12665 | 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;
}
}
|
/**
*
*
* @Author :Yasith Maduranga(Merlin)
* @version :1.0
* @Date :2012/4/14
* @Copyright GSharp Lab, All Rights Reserved....
*/
import java.io.*;
import java.util.*;
class recyclednumbers {
public static void main(String args[]){
try{
BufferedReader br = new BufferedReader(new FileReader("C-small-attempt0.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("C-small-attempt0.out")));
int noOfCases = Integer.parseInt(br.readLine());
for(int i=0;i<noOfCases;i++){
String tmp[]=br.readLine().split(" ");
long a=Long.parseLong(tmp[0]);
long b=Long.parseLong(tmp[1]);
long pairOfNo=0;
ArrayList<Long> myArray=new ArrayList<Long>();
myArray.add(a);
for(long j=a;j<b+1;j++){
long charLength=String.valueOf(j).length();
if(charLength<=1){
break;
}
for(long k=0;k<charLength-1;k++){
String tmp1=String.valueOf(j).substring(0,(int)k+1);
String tmp2=String.valueOf(j).substring((int)k+1);
String newNo=tmp2+tmp1;
if(Long.parseLong(newNo)<=b){
if(!(Long.parseLong(newNo)==j)){
if(!(Long.parseLong(newNo)<=j)){
boolean isRepeated=true;
for(long l=0;l<myArray.size();l++){
if(myArray.get((int)l)==Long.parseLong(newNo)){
isRepeated=true;
}else{
isRepeated=false;
}
}
if(!isRepeated){
pairOfNo++;
myArray.add(Long.parseLong(newNo));
}
}
}
}
}
}
out.println("Case #"+(i+1)+": "+pairOfNo);
}
out.close();
}catch(Exception e){
e.printStackTrace();
}
System.exit(0);
}
}
|
B10702 | B10977 | 0 | import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class Recycle {
private static HashMap<Integer, HashSet<Integer>> map = new HashMap<Integer, HashSet<Integer>>();
private static HashSet<Integer> toSkip = new HashSet<Integer>();
/**
* @param args
*/
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int T = reader.nextInt();
for (int tc = 1; tc <= T; tc++) {
int a = reader.nextInt();
int b = reader.nextInt();
long before = System.currentTimeMillis();
int res = doit(a, b);
System.out.printf("Case #%d: %d\n", tc, res);
long after = System.currentTimeMillis();
// System.out.println("time taken: " + (after - before));
}
}
private static int doit(int a, int b) {
int count = 0;
HashSet<Integer> skip = new HashSet<Integer>(toSkip);
for (int i = a; i <= b; i++) {
if (skip.contains(i))
continue;
HashSet<Integer> arr = generate(i);
// if(arr.size() > 1) {
// map.put(i, arr);
// }
// System.out.println(i + " --> " +
// Arrays.deepToString(arr.toArray()));
int temp = 0;
if (arr.size() > 1) {
for (int x : arr) {
if (x >= a && x <= b) {
temp++;
skip.add(x);
}
}
count += temp * (temp - 1) / 2;
}
// System.out.println("not skipping " + i + " gen: " + arr.size()+ " " + (temp * (temp - 1) / 2));
}
return count;
}
private static HashSet<Integer> generate(int num) {
if(map.containsKey(num)) {
HashSet<Integer> list = map.get(num);
return list;
}
HashSet<Integer> list = new HashSet<Integer>();
String s = "" + num;
list.add(num);
int len = s.length();
for (int i = 1; i < len; i++) {
String temp = s.substring(i) + s.substring(0, i);
// System.out.println("temp: " + temp);
if (temp.charAt(0) == '0')
continue;
int x = Integer.parseInt(temp);
if( x <= 2000000) {
list.add(x);
}
}
if(list.size() > 1) {
map.put(num, list);
} else {
toSkip.add(num);
}
return list;
}
}
| import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Recycled {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException,
IOException {
// TODO Auto-generated method stub
int num_of_lines;
BufferedReader in = new BufferedReader(new FileReader(args[0]));
num_of_lines = Integer.parseInt(in.readLine());
String[] inputStrings = new String[num_of_lines];
String[] outputStrings = new String[num_of_lines];
for (int i = 0; i < num_of_lines; i++) {
inputStrings[i] = in.readLine();
String[] twoNum = inputStrings[i].split(" ");
int A = Integer.parseInt(twoNum[0]);
int B = Integer.parseInt(twoNum[1]);
int total = 0;
for (int n = A; n <= B; n++) {
for (int m = n + 1; m <= B; m++) {
String n_String = Integer.toString(n);
String m_String = Integer.toString(m);
for (int j = 0; j < m_String.length(); j++) {
if (String.format("%s%s", m_String.substring(j),
m_String.substring(0, j)).equals(n_String)) {
// System.out.println(String.format("%s%s", m_String.substring(0, j), m_String.substring(j)));
total++;
}
}
}
}
if(A > 1000)
total--;
System.out.println(String.format("Case #%d: %d", i + 1, total));
}
}
}
|
B20006 | B20378 | 0 | import java.io.*;
import java.math.BigInteger;
import java.util.*;
import org.jfree.data.function.PowerFunction2D;
public class r2a
{
Map numMap = new HashMap();
int output = 0;
/**
* @param args
*/
public static void main(String[] args)
{
r2a mk = new r2a();
try {
FileInputStream fstream = new FileInputStream("d:/cjinput.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str;
int i = 0;
while ((str = br.readLine()) != null) {
int begin=0,end = 0;
i++;
if (i == 1)
continue;
mk.numMap = new HashMap();
StringTokenizer strTok = new StringTokenizer(str, " ");
while (strTok.hasMoreTokens()) {
begin = Integer.parseInt(((String) strTok.nextToken()));
end = Integer.parseInt(((String) strTok.nextToken()));
}
mk.evaluate(i, begin, end);
}
in.close();
}
catch (Exception e) {
System.err.println(e);
}
}
private void evaluate(int rowNum, int begin, int end)
{
output=0;
for (int i = begin; i<= end; i++) {
if(numMap.containsKey(Integer.valueOf(i)))
continue;
List l = getPairElems(i);
if (l.size() > 0) {
Iterator itr = l.iterator();
int ctr = 0;
ArrayList tempList = new ArrayList();
while (itr.hasNext()) {
int next = ((Integer)itr.next()).intValue();
if (next <= end && next > i) {
numMap.put(Integer.valueOf(next), i);
tempList.add(next);
ctr++;
}
}
ctr = getCounter(ctr+1,2);
/* if (tempList.size() > 0 || ctr > 0)
System.out.println("DD: " + i + ": " + tempList +" ; ctr = " + ctr);*/
output = output + ctr;
}
}
String outputStr = "Case #" + (rowNum -1) + ": " + output;
System.out.println(outputStr);
}
private int getCounter(int n, int r) {
int ret = 1;
int nfactorial =1;
for (int i = 2; i<=n; i++) {
nfactorial = i*nfactorial;
}
int nrfact =1;
for (int i = 2; i<=n-r; i++) {
nrfact = i*nrfact;
}
return nfactorial/(2*nrfact);
}
private ArrayList getPairElems(int num) {
ArrayList retList = new ArrayList();
int temp = num;
if (num/10 == 0)
return retList;
String str = String.valueOf(num);
int arr[] = new int[str.length()];
int x = str.length();
while (temp/10 > 0) {
arr[x-1] = temp%10;
temp=temp/10;
x--;
}
arr[0]=temp;
int size = arr.length;
for (int pos = size -1; pos >0; pos--) {
if(arr[pos] == 0)
continue;
int pairNum = 0;
int multiplier =1;
for (int c=0; c < size-1; c++) {
multiplier = multiplier*10;
}
pairNum = pairNum + (arr[pos]*multiplier);
for(int ctr = pos+1, i=1; i < size; i++,ctr++) {
if (ctr == size)
ctr=0;
if (multiplier!=1)
multiplier=multiplier/10;
pairNum = pairNum + (arr[ctr]*multiplier);
}
if (pairNum != num)
retList.add(Integer.valueOf(pairNum));
}
return retList;
}
}
| import java.util.*;
public class C
{
public static int front;
public static int rotate(int in)
{
return (in / 10) + front*(in % 10);
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int T = in.nextInt();
for(int c = 1; c <= T; c++){
int ans = 0;
int A = in.nextInt();
int B = in.nextInt();
int ndig = ("" + A).length();
front = 1;
for(int i = 1; i < ndig; i++)
front *= 10;
for(int num = A; num <= B; num++){
int count = 1;
int rot = rotate(num);
boolean smallest=true;
while(smallest && rot!= num){
if(A <= rot && rot <= B)
if(rot < num)
smallest = false;
else
count++;
rot = rotate(rot);
}
if(smallest)
ans += count*(count - 1)/2;
}
System.out.println("Case #" + c + ": " + ans);
}
}
} |
A10568 | A12467 | 0 | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class DancingWithTheGooglers {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader (new FileReader("B-small.in"));
PrintWriter out = new PrintWriter(new FileWriter("B-small.out"));
int t = Integer.parseInt(f.readLine());
for (int i = 0; i < t; i++){
int c = 0;
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int[] ti = new int[n];
int s = Integer.parseInt(st.nextToken());
int p = Integer.parseInt(st.nextToken());
for (int j = 0; j < n; j ++){
ti[j] = Integer.parseInt(st.nextToken());
if (ti[j] % 3 == 0){
if (ti[j] / 3 >= p)
c++;
else if (ti[j] / 3 == (p-1) && s > 0 && ti[j] >= 2){
s--;
c++;
}
}
else if (ti[j] % 3 == 1){
if ((ti[j] / 3) + 1 >= p)
c++;
}
else{
if (ti[j] / 3 >= p-1)
c++;
else if (ti[j] / 3 == (p-2) && s > 0){
s--;
c++;
}
}
}
out.println("Case #" + (i+1) + ": " + c);
}
out.close();
System.exit(0);
}
}
| package R0;
import java.util.HashMap;
import java.util.Scanner;
/**
*
* @author Rohit
*/
public class QB {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int Tcases = s.nextInt();
s.nextLine();
for (int i = 0; i < Tcases; i++) {
int Ngooglers = s.nextInt();
int Ssurprising = s.nextInt();
int Paim = s.nextInt();
int score[] = new int[Ngooglers];
for (int j = 0; j < Ngooglers; j++) {
score[j] = s.nextInt();
}
/*
* if score is <2, surprisingNotPossible,
* if score is >=2 and <3*Paim - 4 surprisingPossible but bestNotPossible
* if score is >=3*Paim-4 and <3*Paim-2 bestPossible only using surprising
* if score is >=3*Paim-2 and <29 bestPossible and surprisingPossible
* if score is >=29 bestPossible and surprisingNotPossible
*/
int maxBest = 0;
if (Paim == 0) {
maxBest = Ngooglers;
}
if (Paim == 1) {
for (int j = 0; j < Ngooglers; j++) {
if (score[j] >= 1) {
maxBest++;
}
}
}
if (Paim > 1) {
for (int j = 0; j < Ngooglers; j++) {
if (score[j] >= 3 * Paim - 4) {
if (score[j] < 3 * Paim - 2) {
if (Ssurprising > 0) {
maxBest++;
Ssurprising--;
}
} else {
maxBest++;
}
}
}
}
//printing the output
System.out.println("Case #" + (i + 1) + ": " + maxBest);
}
}
}
|
B22190 | B21368 | 0 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
public class Recycled {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for (int i = 0; i < t; i++) {
String[] str = br.readLine().split(" ");
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[1]);
System.out.println("Case #" + (i + 1) + ": " + find(a, b));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static int find(int a, int b) {
HashSet<Long> used = new HashSet<Long>();
int digits = String.valueOf(a).length();
if (digits == 1) return 0;
for (int i = a; i <= b; i++) {
int s = 10;
int m = (int) Math.pow(10, digits-1);
for (int j = 0; j < digits-1; j++) {
int r = i % s;
if (r < s/10) continue;
int q = i / s;
int rn = r * m + q;
s *= 10; m /= 10;
if (i != rn && rn >= a && rn <= b) {
long pp;
if (rn < i) pp = (long)rn << 30 | i;
else pp = (long)i << 30 | rn;
if (!used.contains(pp)) {
used.add(pp);
}
}
}
}
return used.size();
}
}
| /**
* @author Saifuddin Merchant
*
*/
package com.sam.googlecodejam.helper;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class InputReader {
BufferedReader iFileBuffer;
long iCurrentLineNumber;
public InputReader(String pFileName) {
try {
iFileBuffer = new BufferedReader(new FileReader(pFileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
iCurrentLineNumber = 0;
}
public String readNextLine() {
try {
return iFileBuffer.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void close()
{
try {
iFileBuffer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
B12074 | B11567 | 0 | package jp.funnything.competition.util;
import java.math.BigInteger;
/**
* Utility for BigInteger
*/
public class BI {
public static BigInteger ZERO = BigInteger.ZERO;
public static BigInteger ONE = BigInteger.ONE;
public static BigInteger add( final BigInteger x , final BigInteger y ) {
return x.add( y );
}
public static BigInteger add( final BigInteger x , final long y ) {
return add( x , v( y ) );
}
public static BigInteger add( final long x , final BigInteger y ) {
return add( v( x ) , y );
}
public static int cmp( final BigInteger x , final BigInteger y ) {
return x.compareTo( y );
}
public static int cmp( final BigInteger x , final long y ) {
return cmp( x , v( y ) );
}
public static int cmp( final long x , final BigInteger y ) {
return cmp( v( x ) , y );
}
public static BigInteger div( final BigInteger x , final BigInteger y ) {
return x.divide( y );
}
public static BigInteger div( final BigInteger x , final long y ) {
return div( x , v( y ) );
}
public static BigInteger div( final long x , final BigInteger y ) {
return div( v( x ) , y );
}
public static BigInteger mod( final BigInteger x , final BigInteger y ) {
return x.mod( y );
}
public static BigInteger mod( final BigInteger x , final long y ) {
return mod( x , v( y ) );
}
public static BigInteger mod( final long x , final BigInteger y ) {
return mod( v( x ) , y );
}
public static BigInteger mul( final BigInteger x , final BigInteger y ) {
return x.multiply( y );
}
public static BigInteger mul( final BigInteger x , final long y ) {
return mul( x , v( y ) );
}
public static BigInteger mul( final long x , final BigInteger y ) {
return mul( v( x ) , y );
}
public static BigInteger sub( final BigInteger x , final BigInteger y ) {
return x.subtract( y );
}
public static BigInteger sub( final BigInteger x , final long y ) {
return sub( x , v( y ) );
}
public static BigInteger sub( final long x , final BigInteger y ) {
return sub( v( x ) , y );
}
public static BigInteger v( final long value ) {
return BigInteger.valueOf( value );
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package recyclednumbers;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.StringTokenizer;
/**
*
* @author arjun
*/
public class RecycledNumbers {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
parseAndTranslate();
}
private static void parseAndTranslate() {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C-small-attempt2.in");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = br.readLine();
if (null != strLine) {
int count = new Integer(strLine);
//Read File Line By Line
int lineNo = 0;
while ((strLine = br.readLine()) != null) {
lineNo++;
doOp(strLine, lineNo);
}
//Close the input stream
}
in.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
private static void doOp(String strLine, int lineNo) {
StringTokenizer st = new StringTokenizer(strLine);
System.out.print("Case #" + lineNo + ": ");
String no = st.nextElement().toString();
Integer numberA = new Integer(no);
no = st.nextElement().toString();
Integer numberB = new Integer(no);
Integer count = 0;
for (Integer i = numberA; i < numberB - 1; i++) {
for (Integer j = i + 1; j <= numberB; j++) {
boolean isRecycled = isNumberRecycleable(i, j);
if (isRecycled) {
count++;
//System.out.println("A: "+ i + " B:" + j);
}
}
}
System.out.println(count);
}
private static boolean isNumberRecycleable(Integer noA, Integer noB) {
String tmp = noA.toString();
char[] no1 = tmp.toCharArray();
String tmp2 = noB.toString();
char[] no2 = tmp2.toCharArray();
//System.out.println("\n\nNo 1: " + tmp + " No 2: " + tmp2);
if (no1.length != no2.length) {
return false;
} else {
for (int i = 1; i < no1.length; i++) {
//System.out.println("Diff: " + i);
boolean isRecy = isRecycleable(no1, no2, i);
if(isRecy){
return isRecy;
}
}
}
return false;
}
private static boolean isRecycleable(char[] no1, char[] no2, int add) {
for (int j = 0; j < no2.length; j++) {
int k = (j + add) % no2.length;
//System.out.println("Cmp: no1[" + j +"] = " + no1[j] + " & no2["+ k + "] = " + no2[k]);
if(no1[j] != no2[k]){
return false;
}
}
return true;
}
}
|
A22771 | A21844 | 0 | package com.menzus.gcj._2012.qualification.b;
import com.menzus.gcj.common.InputBlockParser;
import com.menzus.gcj.common.OutputProducer;
import com.menzus.gcj.common.impl.AbstractProcessorFactory;
public class BProcessorFactory extends AbstractProcessorFactory<BInput, BOutputEntry> {
public BProcessorFactory(String inputFileName) {
super(inputFileName);
}
@Override
protected InputBlockParser<BInput> createInputBlockParser() {
return new BInputBlockParser();
}
@Override
protected OutputProducer<BInput, BOutputEntry> createOutputProducer() {
return new BOutputProducer();
}
}
| import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class B_Small {
static int[] resu;
/**
* @param args
*/
public static void main(String[] args) {
File input=new File("D:\\Users\\xiaoguo\\Downloads\\B-small-attempt0.in");
File output=new File("D:\\Users\\xiaoguo\\Desktop\\output.txt");
readCaseFromInput(input);
writeToOutput(output);
System.out.println("Programe exist!");
}
static void readCaseFromInput(File input )
{
try {
FileReader reader=new FileReader(input);
BufferedReader buf=new BufferedReader(reader);
int numberCase=Integer.parseInt(buf.readLine());
resu=new int[numberCase];
String contentLine=null;
int numerLine=0;
while((contentLine=buf.readLine())!=null)
{
String[] tab=contentLine.split("\\s");
int s=Integer.parseInt(tab[1]);
int p=Integer.parseInt(tab[2]);
int n=0;
int needS=0;
for(int i=3;i<tab.length;i++)
{
int totalP=Integer.parseInt(tab[i]);
if(totalP>=Math.max((3*p-4),p))
{
if(totalP>=(3*p-2))
{
n++;
}
else
{
needS++;
}
}
}
n+=Math.min(needS, s);
resu[numerLine]=n;
numerLine++;
}
buf.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
static void writeToOutput(File output)
{
try {
FileWriter out=new FileWriter(output);
BufferedWriter buf=new BufferedWriter(out);
String headLine="Case #";
for(int i=0;i<resu.length;i++)
{
int number=i+1;
String line=headLine+number+": ";
line+=resu[i];
buf.write(line);
buf.newLine();
}
buf.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
B20734 | B21234 | 0 | package fixjava;
public class StringUtils {
/** Repeat the given string the requested number of times. */
public static String repeat(String str, int numTimes) {
StringBuilder buf = new StringBuilder(Math.max(0, str.length() * numTimes));
for (int i = 0; i < numTimes; i++)
buf.append(str);
return buf.toString();
}
/**
* Pad the left hand side of a field with the given character. Always adds at least one pad character. If the length of str is
* greater than numPlaces-1, then the output string will be longer than numPlaces.
*/
public static String padLeft(String str, char padChar, int numPlaces) {
int bufSize = Math.max(numPlaces, str.length() + 1);
StringBuilder buf = new StringBuilder(Math.max(numPlaces, str.length() + 1));
buf.append(padChar);
for (int i = 1, mi = bufSize - str.length(); i < mi; i++)
buf.append(padChar);
buf.append(str);
return buf.toString();
}
/**
* Pad the right hand side of a field with the given character. Always adds at least one pad character. If the length of str is
* greater than numPlaces-1, then the output string will be longer than numPlaces.
*/
public static String padRight(String str, char padChar, int numPlaces) {
int bufSize = Math.max(numPlaces, str.length() + 1);
StringBuilder buf = new StringBuilder(Math.max(numPlaces, str.length() + 1));
buf.append(str);
buf.append(padChar);
while (buf.length() < bufSize)
buf.append(padChar);
return buf.toString();
}
/** Intern all strings in an array, skipping null elements. */
public static String[] intern(String[] arr) {
for (int i = 0; i < arr.length; i++)
arr[i] = arr[i].intern();
return arr;
}
/** Intern a string, ignoring null */
public static String intern(String str) {
return str == null ? null : str.intern();
}
}
| import java.util.ArrayList;
import java.util.List;
public class RecycledNumbers {
/**
* @param args
*/
public static void main(String[] args) {
List<String> inputList = FileIO.readFile("C-large.in");
List<String> outputList = new ArrayList<String>();
int caseNo = 1 ;
int testCaseCount = Integer.parseInt(inputList.get(0));
while (caseNo <= testCaseCount) {
Number n = new Number(inputList.get(caseNo));
outputList.add("Case #" +caseNo +": " +n.getRecycledPairCount());
caseNo++;
}
FileIO.writeFile("C-large.out", outputList);
}
}
|
A20490 | A22945 | 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 y2012.quals;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class B {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("B.in"));
PrintWriter out = new PrintWriter(new File("B.out"));
int nTestCase = in.nextInt();
for (int testCase = 0; testCase < nTestCase; testCase++) {
int n = in.nextInt();
int s = in.nextInt();
int p = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
int res = 0;
int rl = p + p - 1 + p - 1, sl = p + p - 2 + p - 2;
if (p == 0) {
rl = 0;
sl = 0;
} else if (p == 1)
sl = 1;
for (int i = 0; i < n; i++)
if (a[i] >= rl)
res++;
else if (a[i] >= sl && s > 0) {
res++;
s--;
}
out.println("Case #" + (testCase + 1) + ": " + res);
}
in.close();
out.close();
}
}
|
A22360 | A21752 | 0 | import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class Dancing_With_the_Googlers {
/**
* The first line of the input gives the number of test cases, T.
* T test cases follow.
* Each test case consists of a single line containing integers separated by single spaces.
* The first integer will be N, the number of Googlers, and the second integer will be S, the number of surprising triplets of scores.
* The third integer will be p, as described above. Next will be N integers ti: the total points of the Googlers.
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// Reading the input file
Scanner in = new Scanner(new File("B-large.in"));
// writting the input file
FileOutputStream fos = new FileOutputStream("B-large.out");
PrintStream out = new PrintStream(fos);
//Close the output stream
int testCase=Integer.parseInt(in.nextLine());
for(int i=0;i<testCase;i++) {
out.print("Case #" + (i + 1) + ":\t");
int NoOfGooglers= in.nextInt();
int NoOfSurprisingResults = in.nextInt();
int atLeastP=in.nextInt();
ArrayList<Integer> scores= new ArrayList<Integer>();
int BestResults=0;
int Surprising=0;
for(int j=0;j<NoOfGooglers;j++)
{
scores.add(in.nextInt());
//System.out.print(scores.get(j));
int modulus=scores.get(j)%3;
int temp = scores.get(j);
switch (modulus) {
case 0:
if (((temp / 3) >= atLeastP)) {
BestResults++;
} else {
if (((((temp / 3) + 1) >= atLeastP) && ((temp / 3) >= 1))
&& (Surprising < NoOfSurprisingResults)) {
BestResults++;
Surprising++;
}
System.out.println("Case 0"+"itr:"+i+" surprising:"+temp);
}
break;
case 1:
if ((temp / 3) + 1 >= atLeastP) {
BestResults++;
continue;
}
break;
case 2:
if ((temp / 3) + 1 >= atLeastP) {
BestResults++;
} else {
if (((temp / 3) + 2 >= atLeastP)
&& (Surprising < NoOfSurprisingResults)) {
BestResults++;
Surprising++;
}
System.out.println("Case 2"+"itr:"+i+" surprising:"+temp);
}
break;
default:
System.out.println("Error");
}
}// Internal for
out.println(BestResults);
// System.out.println(BestResults);
System.out.println(Surprising);
BestResults = 0;
}// for
in.close();
out.close();
fos.close();
}
}
| import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class main {
main() throws FileNotFoundException {
Scanner sc = new Scanner(new File("B-large.in"));
PrintWriter out = new PrintWriter("result.txt");
int tests = sc.nextInt();
for (int t = 1; t <= tests; t++) {
int n = sc.nextInt();
int s = sc.nextInt();
int p = sc.nextInt();
Map<Integer, ArrayList<D>> map = new TreeMap<>();
ArrayList<Integer> scores = new ArrayList<>();
for (int m = 0; m < n; m++) {
int g = sc.nextInt();
scores.add(g);
map.put(g, dec(g));
}
int ww = 0;
int w = 0;
int cw = 0;
for (int i = 0; i < n; i++) {
if (isDecomposeThere(map.get(scores.get(i)), p, true) && isDecomposeThere(map.get(scores.get(i)), p, false)) {
ww++;
} else if (isDecomposeThere(map.get(scores.get(i)), p, true)) {
w++;
} else if (isDecomposeThere(map.get(scores.get(i)), p, false)) {
cw++;
}
}
out.printf("Case #%d: %d\n", t, (w >= s) ? (s + cw + ww) : (w + ww + cw));
}
out.flush();
}
public static void main(String[] args) throws FileNotFoundException {
main m = new main();
}
public boolean isDecomposeThere(ArrayList<D> ds, int p, boolean surprise) {
for (D dec : ds) {
if (dec.a >= p && dec.surprise == surprise) return true;
}
return false;
}
public ArrayList<D> dec(int n) {
ArrayList<D> list = new ArrayList<>();
for (int i = 0; i <= 10; i++) {
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= j; k++) {
if (i - j <= 2 && j - k <= 2 && i - k <= 2 && i + j + k == n) {
boolean surprise = (i - j == 2 || j - k == 2 || i - k == 2);
list.add(new D(i, j, k, surprise));
}
}
}
}
return list;
}
class D {
int a, b, c;
boolean surprise;
public D(int a, int b, int c, boolean surprise) {
this.a = a;
this.b = b;
this.c = c;
this.surprise = surprise;
}
@Override
public String toString() {
return "" + a + " " + b + " " + c + " " + surprise;
}
}
} |
A12460 | A11555 | 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.*;
public class GoogJam2
{
public static void main(String args[])
{
try{
BufferedReader br=new BufferedReader(new FileReader(args[0]));
int T=Integer.parseInt(br.readLine());
BufferedWriter bw=new BufferedWriter(new FileWriter("output.txt",true));
for(int i1=0;i1<T;i1++)
{
String st=br.readLine();
String sam[]=st.split(" ");
int N=Integer.parseInt(sam[0]);
int s=Integer.parseInt(sam[1]);
int p=Integer.parseInt(sam[2]);
int a[]=new int[N];
for(int k=0;k<N;k++)
{a[k]=Integer.parseInt(sam[k+3]);
}
int b[][]=new int[N][2];
int count=0;
for(int i=0;i<N;i++)
{
b[i][0]=a[i]/3;
b[i][1]=a[i]%3;
//System.out.println(b[i][0]+" "+b[i][1]+"\n");
}
for(int i=0;i<N;i++)
{
if((b[i][0]>=p)||((b[i][0]==p-1)&&(b[i][1]==1))||((b[i][0]==p-1)&&(b[i][1]==2)))
{//System.out.println("c1");
count++;
}
else if(s>0)
{
if((b[i][0]==p-1)&&(b[i][1]==0))
{if(a[i]>=1)
{//System.out.println(b[i][0]+" c2");
count++;
s--;
}
}
else if((b[i][0]==p-2)&&(b[i][1]==2))
{//System.out.println(b[i][0]+" "+b[i][1]+"\n");
if(a[i]>=2)
{//System.out.println(b[i][0]+" c2");
count++;
s--;
}
}
}
}
bw.write("Case #"+(i1+1)+": "+count+"\n");
//System.out.println(count);
}
bw.close();
br.close();
}
catch(Exception e)
{}
}
} |
B21790 | B21433 | 0 | import java.io.*;
import java.util.*;
public class C {
void solve() throws IOException {
in("C-large.in"); out("C-large.out");
long tm = System.currentTimeMillis();
boolean[] mask = new boolean[2000000];
int[] r = new int[10];
int t = readInt();
for (int cs = 1; cs <= t; ++cs) {
int a = readInt();
int b = readInt();
int ans = 0;
for (int m = a + 1; m <= b; ++m) {
char[] d = String.valueOf(m).toCharArray();
int c = 0;
for (int i = 1; i < d.length; ++i) {
if (d[i] != '0' && d[i] <= d[0]) {
int n = 0;
for (int j = 0; j < d.length; ++j) {
int jj = i + j;
if (jj >= d.length) jj -= d.length;
n = n * 10 + (d[jj] - '0');
}
if (n >= a && n < m && !mask[n]) {
++ans;
mask[n] = true;
r[c++] = n;
}
}
}
for (int i = 0; i < c; ++i) {
mask[r[i]] = false;
}
}
println("Case #" + cs + ": " + ans);
//System.out.println(cs);
}
System.out.println("time: " + (System.currentTimeMillis() - tm));
exit();
}
void in(String name) throws IOException {
if (name.equals("__std")) {
in = new BufferedReader(new InputStreamReader(System.in));
} else {
in = new BufferedReader(new FileReader(name));
}
}
void out(String name) throws IOException {
if (name.equals("__std")) {
out = new PrintWriter(System.out);
} else {
out = new PrintWriter(name);
}
}
void exit() {
out.close();
System.exit(0);
}
int readInt() throws IOException {
return Integer.parseInt(readToken());
}
long readLong() throws IOException {
return Long.parseLong(readToken());
}
double readDouble() throws IOException {
return Double.parseDouble(readToken());
}
String readLine() throws IOException {
st = null;
return in.readLine();
}
String readToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
boolean eof() throws IOException {
return !in.ready();
}
void print(String format, Object ... args) {
out.println(new Formatter(Locale.US).format(format, args));
}
void println(String format, Object ... args) {
out.println(new Formatter(Locale.US).format(format, args));
}
void print(Object value) {
out.print(value);
}
void println(Object value) {
out.println(value);
}
void println() {
out.println();
}
StringTokenizer st;
BufferedReader in;
PrintWriter out;
public static void main(String[] args) throws IOException {
new C().solve();
}
}
| package 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 );
}
}
|
B20006 | B21831 | 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 qualification;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Scanner;
public class C {
public static void main(String[] Args) throws IOException {
Scanner sc = new Scanner(new FileReader("C-small.in"));
PrintWriter pw = new PrintWriter(new FileWriter("output.txt"));
int caseCnt = sc.nextInt();
// int caseCnt=1;
for (int caseNum=1; caseNum <= caseCnt; caseNum++) {
System.out.println(caseNum);
int A=sc.nextInt();
int B=sc.nextInt();
// int A = 1234567;
// int B =1234567;
HashMap<Integer, LinkedList<Integer>> visited = new HashMap<Integer, LinkedList<Integer>>();
long total=0;
for(int i=A;i<=B;i++){
if(!visited.containsKey(i))
visited.put(i, new LinkedList<Integer>());
String stringI=String.valueOf(i);
for(int j=1;j<stringI.length();j++) {
String test = stringI.substring(j)+stringI.substring(0, j);
int testInt = Integer.parseInt(test);
if(testInt>=A && testInt<=B && testInt!=i){
if(!visited.containsKey(testInt))
visited.put(testInt, new LinkedList<Integer>());
if(!visited.get(testInt).contains(i)) {
total++;
visited.get(testInt).add(i);
visited.get(i).add(testInt);
}
}
}
}
System.out.println(total);
pw.println("Case #" + caseNum + ": " + total);
}
pw.flush();
pw.close();
sc.close();
}
}
|
B10361 | B11417 | 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);
}
}
| /**
* Written By Kylin
* Last modified: 2012-4-15
* State: Pending
*/
package me.kylin.gcj.c2012Q;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class RecycledNumbers {
String file;
Scanner sc;
PrintWriter pr;
int caseNO;
boolean showDebug;
void out(Object str) {
str = "Case #" + caseNO + ": " + str;
System.out.println(str);
if (pr != null)
pr.println(str);
}
void outNoPre(Object str) {
System.out.println(str);
if (pr != null)
pr.println(str);
}
void debug(Object str) {
if (showDebug)
System.out.printf("DEBUG - Case #%d: %s\n", caseNO, str);
}
void work() {
if (file != null) {
try {
sc = new Scanner(new FileInputStream(new File(file + ".in")));
pr = new PrintWriter(new File(file + ".out"));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
} else {
sc = new Scanner(System.in);
}
int tc = sc.nextInt();
sc.nextLine();
for (caseNO = 1; caseNO <= tc; caseNO++) {
solveACase();
if (pr != null)
pr.flush();
}
if (pr != null)
pr.close();
}
static String generateFilename(String x, int scale, int t) {
String fn = x.toUpperCase();
if (scale == 0)
return "sample";
if (scale == 1)
fn += "-small";
if (scale == 2)
fn += "-large";
if (t < 0)
return fn + "-practice";
if (t > 0) {
if (scale == 1)
fn += "-attempt" + (t - 1);
return fn;
}
return fn;
}
public static void main(String[] args) {
RecycledNumbers cls = new RecycledNumbers();
String base = "data/2012Q/";
cls.file = base + generateFilename("C", 1, 1);
cls.showDebug = true;
cls.work();
}
final static int[] P10 = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};
int leftShift(byte[] nArr) {
byte t = nArr[0];
for (int i = 1; i < nArr.length; i++) {
nArr[i - 1] = nArr[i];
}
nArr[nArr.length - 1] = t;
int m = 0;
for (int i = 0; i < nArr.length; i++) {
m = m * 10 + nArr[i];
}
return m;
}
void solveACase() {
int min = sc.nextInt();
int max = sc.nextInt();
int num = 0;
for (int n = min; n < max; n++) {
int k = 0;
while (n >= P10[k]) k++;
byte[] nArr = new byte[k];
int t = n;
while (t > 0) {
nArr[--k] = (byte)(t % 10);
t /= 10;
}
int m = leftShift(nArr);
while (m != n) {
if (m > n && m >= min && m <= max) num++;
m = leftShift(nArr);
}
}
out(num);
}
} |
B22190 | B21009 | 0 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
public class Recycled {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for (int i = 0; i < t; i++) {
String[] str = br.readLine().split(" ");
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[1]);
System.out.println("Case #" + (i + 1) + ": " + find(a, b));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static int find(int a, int b) {
HashSet<Long> used = new HashSet<Long>();
int digits = String.valueOf(a).length();
if (digits == 1) return 0;
for (int i = a; i <= b; i++) {
int s = 10;
int m = (int) Math.pow(10, digits-1);
for (int j = 0; j < digits-1; j++) {
int r = i % s;
if (r < s/10) continue;
int q = i / s;
int rn = r * m + q;
s *= 10; m /= 10;
if (i != rn && rn >= a && rn <= b) {
long pp;
if (rn < i) pp = (long)rn << 30 | i;
else pp = (long)i << 30 | rn;
if (!used.contains(pp)) {
used.add(pp);
}
}
}
}
return used.size();
}
}
| import java.io.FileInputStream;
import java.util.HashSet;
public class Jam3
{
public static String recycled(int start, int end){
int cnt = 0;
HashSet<String> seenit = new HashSet<String>();
for(int i=start; i <= end; i++){
String x = ""+i;
cnt += permutationsInRange(i, start , end, seenit);
}
return ""+cnt;
}
public static String rev(String in){
//p("in: " + in);
StringBuffer sb = new StringBuffer();
for(int i=in.length()-1; i>=0; i--){
sb.append(in.charAt(i));
}
String out = sb.toString();
//p("o: " + out);
return out;
}
public static String solveLine(String in){
String[] s = in.split(" ");
int start = Integer.parseInt(s[0]);
int end = Integer.parseInt(s[1]);
//System.out.println(totals);
return recycled(start, end);
}
public static void solveStrings(String[] input)
{
for(int i=1; i<input.length; i++){
String out = "Case #" + i + ": " + solveLine(input[i]);
System.out.println(out);
}
}
public static int permutationsInRange(int in, int min, int max, HashSet<String> seenit)
{
int count = 0;
p("in: " + in + " min_s " + min + " " + max);
String in_s = ""+in;
StringBuffer sb = new StringBuffer(in_s);
String rev = rev(sb.toString());
for(int i=0; i <in_s.length()-1; i++){
char first = sb.charAt(0);
sb.replace(0, 1, "").append(first);
int test = Integer.parseInt(sb.toString());
p("p: " + sb.toString());
if(sb.toString().startsWith("0")){
continue;
}
int low = Math.min(in, test);
int hi = Math.max(in, test);
if(seenit.contains(low+"_"+hi)){
continue;
}
if(test==in)
continue;
if(test>=min && test<=max){
p("match: " + test + " in: " + in);
seenit.add(low + "_" + hi);
count++;
}
}
return count;
}
public static String[] getLines(String fileName)
{
String[] lines = null;
try {
FileInputStream fis = new FileInputStream(fileName);
int nxtchar = 0;
StringBuffer sb = new StringBuffer();
while((nxtchar=fis.read())!=-1){
sb.append((char)nxtchar);
}
lines = sb.toString().split("\r\n|\n");
} catch (Exception e) {
e.printStackTrace();
}
return lines;
}
public static void main(String[] args)
{
solveStrings(getLines(args[0]));
}
public static void p(Object a){
//System.out.println(""+a);
}
public static void p2(Object a){
System.out.println(""+a);
}
}
|
A10568 | A12540 | 0 | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class DancingWithTheGooglers {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader (new FileReader("B-small.in"));
PrintWriter out = new PrintWriter(new FileWriter("B-small.out"));
int t = Integer.parseInt(f.readLine());
for (int i = 0; i < t; i++){
int c = 0;
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int[] ti = new int[n];
int s = Integer.parseInt(st.nextToken());
int p = Integer.parseInt(st.nextToken());
for (int j = 0; j < n; j ++){
ti[j] = Integer.parseInt(st.nextToken());
if (ti[j] % 3 == 0){
if (ti[j] / 3 >= p)
c++;
else if (ti[j] / 3 == (p-1) && s > 0 && ti[j] >= 2){
s--;
c++;
}
}
else if (ti[j] % 3 == 1){
if ((ti[j] / 3) + 1 >= p)
c++;
}
else{
if (ti[j] / 3 >= p-1)
c++;
else if (ti[j] / 3 == (p-2) && s > 0){
s--;
c++;
}
}
}
out.println("Case #" + (i+1) + ": " + c);
}
out.close();
System.exit(0);
}
}
| import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class DancingWithTheGooglers {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new FileReader("B-small-attempt0.in"));
PrintWriter pw = new PrintWriter(new FileWriter("outputB0.txt"));
int caseCount = sc.nextInt();
sc.nextLine();
for (int caseNum = 0; caseNum < caseCount; caseNum++) {
//System.out.println(caseNum);
int dancerCount = sc.nextInt();
int surprisingCount = sc.nextInt();
int p = sc.nextInt();
int pCount = 0;
int sCount = 0;
for (int dancerNum = 0; dancerNum < dancerCount; dancerNum++) {
int score = sc.nextInt();
int d = checkScore(score, p);
if (d == 1)
pCount++;
else if (d == 2)
sCount++;
}
//System.out.println(pCount + " " + sCount + " " + surprisingCount);
int count = pCount;
if (sCount < surprisingCount) {
count += sCount;
}
else {
count += surprisingCount;
}
pw.write("Case #" + (caseNum + 1) + ": ");
pw.write(count + "\n");
}
pw.flush();
pw.close();
sc.close();
}
private static int checkScore(int score, int p) {
boolean sScore = false;
for (int a = 0; a <= 10; a++) {
for (int b = 0; b <= 10; b++) {
for (int c = 0; c <= 10; c++) {
if (a + b + c == score &&
(a >= p || b >= p || c >= p)) {
int ab = Math.abs(a-b);
int ac = Math.abs(a-c);
int bc = Math.abs(b-c);
if (ab < 2 && ac < 2 && bc < 2) {
//System.out.println("P " + a + " " + b + " " + c);
return 1;
}
else if (ab < 3 && ac < 3 && bc < 3) {
//System.out.println("S " + a + " " + b + " " + c);
sScore = true;
}
}
}
}
}
if(sScore == true) {
return 2;
}
return 0;
}
}
|
A20934 | A21445 | 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.*;
import java.util.Scanner;
public class Dancers {
public static void main(String[] args) throws FileNotFoundException, IOException {
Scanner sc = new Scanner(new File("D:/testing/B-large.in"));
BufferedWriter bf = new BufferedWriter(new FileWriter("D:/testing/b.txt", false));
int T = sc.nextInt();
for (int i = 1; i <= T; i++) {
int N, S, p;
int hscr = 0, mscr = 0;
N = sc.nextInt();
S = sc.nextInt();
p = sc.nextInt();
for (int j = 0; j < N; j++) {
int scr = sc.nextInt();
if (scr > 3 * (p - 1)) {
hscr++;
} else if (p>1 && scr > 3 * (p - 2) + 1) {
mscr++;
}
}
int max=hscr+ Math.min(S, mscr);
System.out.println("Case #" + i+": "+max);
bf.write("Case #" + i+": "+max+ "\n");
}
bf.close();
}
}
|
A11502 | A11356 | 0 | package template;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
public class TestCase {
private boolean isSolved;
private Object solution;
private Map<String, Integer> intProperties;
private Map<String, ArrayList<Integer>> intArrayProperties;
private Map<String, ArrayList<ArrayList<Integer>>> intArray2DProperties;
private Map<String, Double> doubleProperties;
private Map<String, ArrayList<Double>> doubleArrayProperties;
private Map<String, ArrayList<ArrayList<Double>>> doubleArray2DProperties;
private Map<String, String> stringProperties;
private Map<String, ArrayList<String>> stringArrayProperties;
private Map<String, ArrayList<ArrayList<String>>> stringArray2DProperties;
private Map<String, Boolean> booleanProperties;
private Map<String, ArrayList<Boolean>> booleanArrayProperties;
private Map<String, ArrayList<ArrayList<Boolean>>> booleanArray2DProperties;
private Map<String, Long> longProperties;
private Map<String, ArrayList<Long>> longArrayProperties;
private Map<String, ArrayList<ArrayList<Long>>> longArray2DProperties;
private int ref;
private double time;
public TestCase() {
initialise();
}
private void initialise() {
isSolved = false;
intProperties = new HashMap<>();
intArrayProperties = new HashMap<>();
intArray2DProperties = new HashMap<>();
doubleProperties = new HashMap<>();
doubleArrayProperties = new HashMap<>();
doubleArray2DProperties = new HashMap<>();
stringProperties = new HashMap<>();
stringArrayProperties = new HashMap<>();
stringArray2DProperties = new HashMap<>();
booleanProperties = new HashMap<>();
booleanArrayProperties = new HashMap<>();
booleanArray2DProperties = new HashMap<>();
longProperties = new HashMap<>();
longArrayProperties = new HashMap<>();
longArray2DProperties = new HashMap<>();
ref = 0;
}
public void setSolution(Object o) {
solution = o;
isSolved = true;
}
public Object getSolution() {
if (!isSolved) {
Utils.die("getSolution on unsolved testcase");
}
return solution;
}
public void setRef(int i) {
ref = i;
}
public int getRef() {
return ref;
}
public void setTime(double d) {
time = d;
}
public double getTime() {
return time;
}
public void setInteger(String s, Integer i) {
intProperties.put(s, i);
}
public Integer getInteger(String s) {
return intProperties.get(s);
}
public void setIntegerList(String s, ArrayList<Integer> l) {
intArrayProperties.put(s, l);
}
public void setIntegerMatrix(String s, ArrayList<ArrayList<Integer>> l) {
intArray2DProperties.put(s, l);
}
public ArrayList<Integer> getIntegerList(String s) {
return intArrayProperties.get(s);
}
public Integer getIntegerListItem(String s, int i) {
return intArrayProperties.get(s).get(i);
}
public ArrayList<ArrayList<Integer>> getIntegerMatrix(String s) {
return intArray2DProperties.get(s);
}
public ArrayList<Integer> getIntegerMatrixRow(String s, int row) {
return intArray2DProperties.get(s).get(row);
}
public Integer getIntegerMatrixItem(String s, int row, int column) {
return intArray2DProperties.get(s).get(row).get(column);
}
public ArrayList<Integer> getIntegerMatrixColumn(String s, int column) {
ArrayList<Integer> out = new ArrayList();
for(ArrayList<Integer> row : intArray2DProperties.get(s)) {
out.add(row.get(column));
}
return out;
}
public void setDouble(String s, Double i) {
doubleProperties.put(s, i);
}
public Double getDouble(String s) {
return doubleProperties.get(s);
}
public void setDoubleList(String s, ArrayList<Double> l) {
doubleArrayProperties.put(s, l);
}
public void setDoubleMatrix(String s, ArrayList<ArrayList<Double>> l) {
doubleArray2DProperties.put(s, l);
}
public ArrayList<Double> getDoubleList(String s) {
return doubleArrayProperties.get(s);
}
public Double getDoubleListItem(String s, int i) {
return doubleArrayProperties.get(s).get(i);
}
public ArrayList<ArrayList<Double>> getDoubleMatrix(String s) {
return doubleArray2DProperties.get(s);
}
public ArrayList<Double> getDoubleMatrixRow(String s, int row) {
return doubleArray2DProperties.get(s).get(row);
}
public Double getDoubleMatrixItem(String s, int row, int column) {
return doubleArray2DProperties.get(s).get(row).get(column);
}
public ArrayList<Double> getDoubleMatrixColumn(String s, int column) {
ArrayList<Double> out = new ArrayList();
for(ArrayList<Double> row : doubleArray2DProperties.get(s)) {
out.add(row.get(column));
}
return out;
}
public void setString(String s, String t) {
stringProperties.put(s, t);
}
public String getString(String s) {
return stringProperties.get(s);
}
public void setStringList(String s, ArrayList<String> l) {
stringArrayProperties.put(s, l);
}
public void setStringMatrix(String s, ArrayList<ArrayList<String>> l) {
stringArray2DProperties.put(s, l);
}
public ArrayList<String> getStringList(String s) {
return stringArrayProperties.get(s);
}
public String getStringListItem(String s, int i) {
return stringArrayProperties.get(s).get(i);
}
public ArrayList<ArrayList<String>> getStringMatrix(String s) {
return stringArray2DProperties.get(s);
}
public ArrayList<String> getStringMatrixRow(String s, int row) {
return stringArray2DProperties.get(s).get(row);
}
public String getStringMatrixItem(String s, int row, int column) {
return stringArray2DProperties.get(s).get(row).get(column);
}
public ArrayList<String> getStringMatrixColumn(String s, int column) {
ArrayList<String> out = new ArrayList();
for(ArrayList<String> row : stringArray2DProperties.get(s)) {
out.add(row.get(column));
}
return out;
}
public void setBoolean(String s, Boolean b) {
booleanProperties.put(s, b);
}
public Boolean getBoolean(String s) {
return booleanProperties.get(s);
}
public void setBooleanList(String s, ArrayList<Boolean> l) {
booleanArrayProperties.put(s, l);
}
public void setBooleanMatrix(String s, ArrayList<ArrayList<Boolean>> l) {
booleanArray2DProperties.put(s, l);
}
public ArrayList<Boolean> getBooleanList(String s) {
return booleanArrayProperties.get(s);
}
public Boolean getBooleanListItem(String s, int i) {
return booleanArrayProperties.get(s).get(i);
}
public ArrayList<ArrayList<Boolean>> getBooleanMatrix(String s) {
return booleanArray2DProperties.get(s);
}
public ArrayList<Boolean> getBooleanMatrixRow(String s, int row) {
return booleanArray2DProperties.get(s).get(row);
}
public Boolean getBooleanMatrixItem(String s, int row, int column) {
return booleanArray2DProperties.get(s).get(row).get(column);
}
public ArrayList<Boolean> getBooleanMatrixColumn(String s, int column) {
ArrayList<Boolean> out = new ArrayList();
for(ArrayList<Boolean> row : booleanArray2DProperties.get(s)) {
out.add(row.get(column));
}
return out;
}
public void setLong(String s, Long b) {
longProperties.put(s, b);
}
public Long getLong(String s) {
return longProperties.get(s);
}
public void setLongList(String s, ArrayList<Long> l) {
longArrayProperties.put(s, l);
}
public void setLongMatrix(String s, ArrayList<ArrayList<Long>> l) {
longArray2DProperties.put(s, l);
}
public ArrayList<Long> getLongList(String s) {
return longArrayProperties.get(s);
}
public Long getLongListItem(String s, int i) {
return longArrayProperties.get(s).get(i);
}
public ArrayList<ArrayList<Long>> getLongMatrix(String s) {
return longArray2DProperties.get(s);
}
public ArrayList<Long> getLongMatrixRow(String s, int row) {
return longArray2DProperties.get(s).get(row);
}
public Long getLongMatrixItem(String s, int row, int column) {
return longArray2DProperties.get(s).get(row).get(column);
}
public ArrayList<Long> getLongMatrixColumn(String s, int column) {
ArrayList<Long> out = new ArrayList();
for(ArrayList<Long> row : longArray2DProperties.get(s)) {
out.add(row.get(column));
}
return out;
}
}
| //package com.GoogleCodeJam.y2012.Qualification.DancingWithTheGooglers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class DancingWithTheGooglers {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader(new File("B-small-attempt0.in")));
int numCases = Integer.parseInt(in.readLine());
for (int caseNum = 1; caseNum <= numCases; caseNum++) {
String[] caseInput = in.readLine().split(" ");
int numFound = getNumOverBar(caseInput);
System.out.println("Case #"+ caseNum + ": " + numFound);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static int getNumOverBar(String[] caseInput) {
int numGooglers = Integer.parseInt(caseInput[0]);
int surprisingRemaining = Integer.parseInt(caseInput[1]);
int minThreshhold = Integer.parseInt(caseInput[2]);
int numFound = 0;
for (int scoreId = 3; scoreId < (numGooglers + 3); scoreId ++) {
int givenScore = Integer.parseInt(caseInput[scoreId]);
int checkedScore = givenScore %3 == 0 ? givenScore : (givenScore + 3 - givenScore %3);
if (checkedScore/3 >= minThreshhold) {
numFound ++;
} else if (givenScore == 0) {
if (minThreshhold == 0) {
numFound++;
}
} else if (surprisingRemaining > 0) {
if (givenScore % 3 == 2) {
if ((givenScore + 4)/3 >= minThreshhold) {
numFound ++;
surprisingRemaining --;
}
} else if (givenScore % 3 == 0) {
if ((givenScore+3) / 3 >= minThreshhold) {
numFound ++;
surprisingRemaining --;
}
}
}
}
return numFound;
}
}
|
B20291 | B22183 | 0 | import java.io.*;
import java.util.*;
class B
{
public static void main(String[] args)
{
try
{
BufferedReader br = new BufferedReader(new FileReader("B.in"));
PrintWriter pw = new PrintWriter(new FileWriter("B.out"));
int X = Integer.parseInt(br.readLine());
for(int i=0; i<X; i++)
{
String[] S = br.readLine().split(" ");
int A = Integer.parseInt(S[0]);
int B = Integer.parseInt(S[1]);
int R = 0;
int x = 1;
int n = 0;
while(A/x > 0) {
n++;
x *= 10;
}
for(int j=A; j<B; j++) {
Set<Integer> seen = new HashSet<Integer>();
for(int k=1; k<n; k++) {
int p1 = j % (int)Math.pow(10, k);
int p2 = (int) Math.pow(10, n-k);
int p3 = j / (int)Math.pow(10, k);
int y = p1*p2 + p3;
if(j < y && !seen.contains(y) && y <= B) {
seen.add(y);
R++;
}
}
}
pw.printf("Case #%d: %d\n", i+1, R);
pw.flush();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
| package googleCodeJam;
import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Set;
import java.util.TreeSet;
public class RecycledNumbers {
public static void main(String[] args) throws Exception {
if (args.length == 1) {
// opening the input
BufferedReader in = new BufferedReader(new FileReader(args[0]));
// reading the number of test cases
String line = null;
int numberOfTestCases = ((line = in.readLine()) != null) ? Integer.parseInt(line) : 0;
for (int t = 0; t < numberOfTestCases; t ++) {
line = in.readLine();
out.print("Case #" + (t+1) + ": ");
// parse input
String[] numbers = line.split(" ");
int n = Integer.parseInt(numbers[0]);
int m = Integer.parseInt(numbers[1]);
int counter = 0;
StringBuffer is = new StringBuffer(128);
String isCurrent = null;
for (int i = n; i <= m; i ++) {
is.append(i);
int size = is.length();
is.append(i);
//
Set<Integer> qs = new TreeSet<Integer>();
for (int j = 0; j < size; j ++) {
isCurrent = is.substring(j, j+size);
int q = Integer.parseInt(isCurrent);
if (i < q && q <= m /*&& !isCurrent.startsWith("0")*/) {
//counter ++;
//out.println(i + "\t" + q + "\t" + (size - j));
qs.add(q);
}
}
//
counter += qs.size();
is.setLength(0);
}
out.println(counter);
}
// closing the input
in.close();
} else {
// show the usage
System.err.println("Using: java googleCodeJam.RecycledNumbers input");
}
}
}
|
B21207 | B20527 | 0 | /*
* Problem C. Recycled Numbers
*
* Do you ever become frustrated with television because you keep seeing the
* same things, recycled over and over again? Well I personally don't care about
* television, but I do sometimes feel that way about numbers.
*
* Let's say a pair of distinct positive integers (n, m) is recycled if you can
* obtain m by moving some digits from the back of n to the front without
* changing their order. For example, (12345, 34512) is a recycled pair since
* you can obtain 34512 by moving 345 from the end of 12345 to the front. Note
* that n and m must have the same number of digits in order to be a recycled
* pair. Neither n nor m can have leading zeros.
*
* Given integers A and B with the same number of digits and no leading zeros,
* how many distinct recycled pairs (n, m) are there with A ⤠n < m ⤠B?
*
* Input
*
* The first line of the input gives the number of test cases, T. T test cases
* follow. Each test case consists of a single line containing the integers A
* and B.
*
* Output
*
* For each test case, output one line containing "Case #x: y", where x is the
* case number (starting from 1), and y is the number of recycled pairs (n, m)
* with A ⤠n < m ⤠B.
*
* Limits
*
* 1 ⤠T ⤠50.
*
* A and B have the same number of digits.
Small dataset
1 ⤠A ⤠B ⤠1000.
Large dataset
1 ⤠A ⤠B ⤠2000000.
Sample
Input
Output
4
1 9
10 40
100 500
1111 2222
Case #1: 0
Case #2: 3
Case #3: 156
Case #4: 287
*/
package google.codejam.y2012.qualifications;
import google.codejam.commons.Utils;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* @author Marco Lackovic <[email protected]>
* @version 1.0, Apr 14, 2012
*/
public class RecycledNumbers {
private static final String INPUT_FILE_NAME = "C-large.in";
private static final String OUTPUT_FILE_NAME = "C-large.out";
public static void main(String[] args) throws IOException {
String[] input = Utils.readFromFile(INPUT_FILE_NAME);
String[] output = new String[input.length];
int x = 0;
for (String line : input) {
StringTokenizer st = new StringTokenizer(line);
int a = Integer.valueOf(st.nextToken());
int b = Integer.valueOf(st.nextToken());
System.out.println("Computing case #" + (x + 1));
output[x++] = "Case #" + x + ": " + recycledNumbers(a, b);
}
Utils.writeToFile(output, OUTPUT_FILE_NAME);
}
private static int recycledNumbers(int a, int b) {
int count = 0;
for (int n = a; n < b; n++) {
count += getNumGreaterRotations(n, b);
}
return count;
}
private static int getNumGreaterRotations(int n, int b) {
int count = 0;
char[] chars = Integer.toString(n).toCharArray();
for (int i = 0; i < chars.length; i++) {
chars = rotateRight(chars);
if (chars[0] != '0') {
int m = Integer.valueOf(new String(chars));
if (n == m) {
break;
} else if (n < m && m <= b) {
count++;
}
}
}
return count;
}
private static char[] rotateRight(char[] chars) {
char last = chars[chars.length - 1];
for (int i = chars.length - 2; i >= 0; i--) {
chars[i + 1] = chars[i];
}
chars[0] = last;
return chars;
}
}
| package com.codejam.twelve;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
public class ProbC {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader(
"D:\\Dev\\Workspaces\\Android\\codejam\\io\\qualification\\C-large.in");
FileWriter fw = new FileWriter(
"D:\\Dev\\Workspaces\\Android\\codejam\\io\\qualification\\C-large.out");
BufferedReader br = new BufferedReader(fr);
BufferedWriter bw = new BufferedWriter(fw);
int t = Integer.parseInt(br.readLine());
for (int l = 1; l <= t; l++) {
String s = br.readLine();
bw.append("Case #" + l + ": ");
String ss[] = s.split(" ");
int A = Integer.parseInt(ss[0]);
int B = Integer.parseInt(ss[1]);
int ans = 0;
HashSet<String> hs = new HashSet<String>();
for (int i = A; i < B; i++) {
String n = "" + i;
int len = n.length();
for (int j = 0; j < len - 1; j++) {
n = n.charAt(n.length() - 1)
+ n.substring(0, n.length() - 1);
int nn = Integer.parseInt(n);
if (nn > i && nn <= B) {
/*System.out.println(i + "," + nn);
if (hs.contains(i + "," + nn)) {
System.out.println("**********");
} else*/
if (!hs.contains(i + "," + nn)){
hs.add(i + "," + nn);
ans++;
}
}
}
}
bw.append("" + ans);
bw.newLine();
}
bw.flush();
bw.close();
br.close();
}
}
|
A11135 | A11843 | 0 | /**
* Created by IntelliJ IDEA.
* User: Administrator
* Date: 3/3/12
* Time: 11:00 AM
* To change this template use File | Settings | File Templates.
*/
import SRMLib.MathLibrary;
import SRMLib.TestSRMLib;
import com.sun.org.apache.bcel.internal.generic.F2D;
import java.io.*;
import java.util.*;
import java.util.zip.Inflater;
public class SRM {
public static void main(String[] args) throws IOException {
//TestSRMLib.run();
codeJam1.main();
return;
}
}
class codeJam1 {
public static void main() throws IOException {
String inputPath = "E:\\input.txt";
String outputPath = "E:\\output.txt";
BufferedReader input = new BufferedReader(new FileReader(inputPath));
BufferedWriter output = new BufferedWriter(new FileWriter(outputPath));
String line;
line = input.readLine();
int T = Integer.parseInt(line);
for (int i = 1; i <= T; ++i) {
line = input.readLine();
String[] words = line.split(" ");
int N = Integer.parseInt(words[0]);
int S = Integer.parseInt(words[1]);
int p = Integer.parseInt(words[2]);
int n = 0;
int res = 0;
for (int j = 3; j < words.length; ++j) {
if (p == 0) {
res++;
continue;
}
int t = Integer.parseInt(words[j]);
if (p == 1) {
if (t > 0)
res++;
continue;
}
if (t >= 3 * p - 2)
res++;
else if (t >= 3 * p - 4)
n++;
}
res += Math.min(n, S);
output.write("Case #" + i + ": " + res);
output.newLine();
}
input.close();
output.close();
}
}
| import java.util.*;
public class Dancing {
public static boolean wasS(int score){
switch(score) {
case 0:
return false;
case 1:
return false;
case 30:
return false;
case 29:
return false;
}
int resi = score%3;
if(resi == 1){
return false;
}
return true;
}
public static int maxp(int score, boolean surpr){
switch(score) {
case 0:
return 0;
case 1:
return 1;
case 30:
return 10;
case 29:
return 10;
}
int mid = score/3;
int resi = score%3;
switch (resi) {
case 0:
if(surpr)
return mid+1;
else
return mid;
case 1:
return mid+1;
case 2:
if(surpr)
return mid+2;
else
return mid+1;
}
return mid;
}
public static int solve( int n, int sur, int p, int[] sc){
int abovep = 0;
for(int i = 0; i<sc.length; i++){
int maxpos = maxp(sc[i], false);
if(maxpos >= p ){
abovep++;
}else {
if(sur > 0){
maxpos = maxp(sc[i], true);
//wasSurpr = wasS(sc[i]);
if(maxpos >= p){
abovep++;
sur--;
}
}
}
// System.out.println(sc[i]+" max "+maxpos);
// System.out.println(" abovep "+abovep+" sur "+sur);
}
return abovep;
}
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int T = s.nextInt();
for(int i = 1; i<=T; i++){
int n = s.nextInt();
int sur = s.nextInt();
int p = s.nextInt();
int sc[] = new int[n];
for(int j = 0; j<n; j++){
sc[j] = s.nextInt();
}
int y = solve(n, sur, p, sc);
System.out.println("Case #"+i+": "+y);
}
}
} |
A22771 | A22384 | 0 | package com.menzus.gcj._2012.qualification.b;
import com.menzus.gcj.common.InputBlockParser;
import com.menzus.gcj.common.OutputProducer;
import com.menzus.gcj.common.impl.AbstractProcessorFactory;
public class BProcessorFactory extends AbstractProcessorFactory<BInput, BOutputEntry> {
public BProcessorFactory(String inputFileName) {
super(inputFileName);
}
@Override
protected InputBlockParser<BInput> createInputBlockParser() {
return new BInputBlockParser();
}
@Override
protected OutputProducer<BInput, BOutputEntry> createOutputProducer() {
return new BOutputProducer();
}
}
|
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author xeyyam
*/
public class DancingWiththeGooglers {
boolean[][] ansNoS = new boolean[31][11];
boolean[][] ansS = new boolean[31][11];
public static void main(String args[]) throws Exception {
new DancingWiththeGooglers().solve();
}
public void solve() throws Exception {
generate();
Scanner sc = new Scanner(new File("B-large.in"));
PrintWriter pw = new PrintWriter("B-large.out");
int t, n, s, p;
t = sc.nextInt();
for (int i = 1; i <= t; i++) {
n = sc.nextInt();
s = sc.nextInt();
p = sc.nextInt();
int ans = 0;
int temp = 0;
for(int j = 1 ; j<=n ; j++ ){
temp = sc.nextInt();
if( check(temp , p , false) ) ans++;
else if( s>0 && check(temp , p , true ) ){ ans++ ; s--;}
}
pw.println("Case #"+i+": "+ans);
}
pw.flush();
pw.close();
}
public boolean check(int sum , int p , boolean surprise){
if( !surprise )
for(int i = p ; i<=10 ; i++){
if( ansNoS[sum][i] )
return true;
}
else{
for(int i = p ; i<=10 ; i++){
if( ansS[sum][i] )
return true;
}
}
return false;
}
public void generate() {
for (int i = 0; i <= 10; i++) {
for (int j = 0; j <= 10; j++) {
for (int k = 0; k <= 10; k++) {
if (Math.abs(j - i) <= 1 && Math.abs(k - j) <= 1 && Math.abs(i - k) <= 1) {
ansNoS[i + j + k][i] = true;
ansNoS[i + j + k][j] = true;
ansNoS[i + j + k][k] = true;
} else if (Math.abs(j - i) <= 2 && Math.abs(k - j) <= 2 && Math.abs(i - k) <= 2) {
ansS[i + j + k][i] = true;
ansS[i + j + k][j] = true;
ansS[i + j + k][k] = true;
}
}
}
}
}
}
|
B20291 | B22097 | 0 | import java.io.*;
import java.util.*;
class B
{
public static void main(String[] args)
{
try
{
BufferedReader br = new BufferedReader(new FileReader("B.in"));
PrintWriter pw = new PrintWriter(new FileWriter("B.out"));
int X = Integer.parseInt(br.readLine());
for(int i=0; i<X; i++)
{
String[] S = br.readLine().split(" ");
int A = Integer.parseInt(S[0]);
int B = Integer.parseInt(S[1]);
int R = 0;
int x = 1;
int n = 0;
while(A/x > 0) {
n++;
x *= 10;
}
for(int j=A; j<B; j++) {
Set<Integer> seen = new HashSet<Integer>();
for(int k=1; k<n; k++) {
int p1 = j % (int)Math.pow(10, k);
int p2 = (int) Math.pow(10, n-k);
int p3 = j / (int)Math.pow(10, k);
int y = p1*p2 + p3;
if(j < y && !seen.contains(y) && y <= B) {
seen.add(y);
R++;
}
}
}
pw.printf("Case #%d: %d\n", i+1, R);
pw.flush();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
| package qualification.common;
import java.io.*;
/**
* Created by IntelliJ IDEA.
* User: ofer
* Date: 14/04/12
* Time: 17:21
* To change this template use File | Settings | File Templates.
*/
public class InputReader {
public static String[] getInputLines(String filename){
String[] input = null;
File file = new File(filename);
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
int size = Integer.parseInt(line);
input = new String[size + 1];
input[0] = line;
for (int i=0 ; i <size ; i++){
line = br.readLine();
input[i+1] = line;
}
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return input;
}
}
|
B10858 | B12298 | 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.*;
import java.io.*;
import java.text.*;
import java.math.*;
public class RecycledNumbers {
public static BufferedReader BR;
public static String readLine() {
try {
return BR.readLine();
} catch(Exception E) {
System.err.println(E.toString());
return null;
}
}
// ****** MAIN ******
public static void main(String [] args) throws Exception {
BR = new BufferedReader(new InputStreamReader(System.in));
int testcases = Integer.parseInt(readLine());
for (int t = 1; t <= testcases; t++) {
RecycledNumbers instance = new RecycledNumbers();
instance.solve(t);
}
}
// ****** GLOBAL VARIABLES ******
public RecycledNumbers() {
}
public boolean solve(int caseNumber) {
StringTokenizer st = new StringTokenizer(readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int n = Integer.toString(a).length();
long result = 0;
for (int i = a; i <= b; ++i) {
String s = Integer.toString(i);
Set<Integer> seen = new HashSet<Integer>();
for (int j = 1; j < n; ++j) {
int rotated = Integer.parseInt(s.substring(j) + s.substring(0,j));
if (i < rotated && rotated <= b && !seen.contains(rotated)) {
seen.add(rotated);
++result;
}
}
}
System.out.println("Case #" + caseNumber + ": " + result);
return false;
}
}
|
B10485 | B11602 | 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 j2012qualifier;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class C {
public static String inputDirectory="src/j2012qualifier/";
public static String inputFile="C.in";
public static String outputFile="C.out";
public static PrintWriter output;
public static void main(String[] args) throws FileNotFoundException{
Scanner s=new Scanner(new File(inputDirectory + inputFile));
output=new PrintWriter(new File(inputDirectory + outputFile));
int cases = s.nextInt();
for(int Case=1;Case<=cases;Case++){
s.nextLine();
int A = s.nextInt();
int B = s.nextInt();
long result = 0;
for(int n = A; n< B; n++) {
result+= count(n, B);
}
out("Case #"+Case+": "+result);
}
output.flush();
}
public static long count(long n, long max) {
//out("testing " + n);
long digit = 10;
long pow10 = 10 * (long)Math.pow(10, Math.floor(Math.log10(n)));
long count = 0;
Set<Long> found = new HashSet<Long>();
//out("pow" + pow10);
while(digit <= n) {
long m = n/digit + (n%digit) * pow10 / digit;
//out("choice 1 " + m);
digit *= 10;
if (m > n && m <= max && !found.contains(m)) {
//out(n + " , " + m);
count++;
found.add(m);
}
}
return count;
}
public static void out(String s){
output.println(s);
//System.out.println(s);
}
}
|
A22078 | A22662 | 0 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
public class GooglersDancer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
if (in == null) {
return;
}
String numTest = in.readLine();
int maxCases = Integer.valueOf(numTest);
for(int i=1;i<= maxCases;i++){
String linea = in.readLine();
String[] datos = linea.split(" ");
Integer googlers = Integer.valueOf(datos[0]);
Integer sospechosos = Integer.valueOf(datos[1]);
Integer p = Integer.valueOf(datos[2]);
Integer puntuacion;
Integer personas = 0;
ArrayList<Integer> puntuaciones = new ArrayList<Integer>();
for(int j=0;j<googlers;j++){
puntuacion = Integer.valueOf(datos[3+j]);
puntuaciones.add(puntuacion);
}
Integer[] pOrdenado = null;
pOrdenado = (Integer[]) puntuaciones.toArray(new Integer[puntuaciones.size()]);
Arrays.sort(pOrdenado);
int j;
for(j=pOrdenado.length-1;j>=0;j--){
if(pOrdenado[j] >= p*3-2){
personas += 1;
}else{
break;
}
}
int posibles = j+1-sospechosos;
for(;j>=posibles && j>= 0;j--){
if(pOrdenado[j] >= p*3-4 && pOrdenado[j] > p){
personas += 1;
}else{
break;
}
}
System.out.println("Case #"+i+": "+personas);
}
}
}
| import java.util.Scanner;
public class BS {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int count = in.nextInt();
for (int i = 1; i <= count ; i++) {
int n = in.nextInt();
int s = in.nextInt();
int p = in.nextInt();
int p_count = 0;
int s_count = 0;
for (int j = 0; j < n; j++) {
int current = in.nextInt();
int rest = current - p;
if (rest < 0) {
continue;
}
int restOf2p = rest - (p * 2);
if (restOf2p >= -2) {
p_count++;
continue;
}
if (restOf2p >= -4) {
s_count++;
}
}
if (s_count > s) {
s_count = s;
}
System.out.format("Case #%d: %d\n",i,p_count + s_count);
}
}
}
|
A22078 | A21462 | 0 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
public class GooglersDancer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
if (in == null) {
return;
}
String numTest = in.readLine();
int maxCases = Integer.valueOf(numTest);
for(int i=1;i<= maxCases;i++){
String linea = in.readLine();
String[] datos = linea.split(" ");
Integer googlers = Integer.valueOf(datos[0]);
Integer sospechosos = Integer.valueOf(datos[1]);
Integer p = Integer.valueOf(datos[2]);
Integer puntuacion;
Integer personas = 0;
ArrayList<Integer> puntuaciones = new ArrayList<Integer>();
for(int j=0;j<googlers;j++){
puntuacion = Integer.valueOf(datos[3+j]);
puntuaciones.add(puntuacion);
}
Integer[] pOrdenado = null;
pOrdenado = (Integer[]) puntuaciones.toArray(new Integer[puntuaciones.size()]);
Arrays.sort(pOrdenado);
int j;
for(j=pOrdenado.length-1;j>=0;j--){
if(pOrdenado[j] >= p*3-2){
personas += 1;
}else{
break;
}
}
int posibles = j+1-sospechosos;
for(;j>=posibles && j>= 0;j--){
if(pOrdenado[j] >= p*3-4 && pOrdenado[j] > p){
personas += 1;
}else{
break;
}
}
System.out.println("Case #"+i+": "+personas);
}
}
}
| package codejam.is;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
/**
* Created with IntelliJ IDEA.
* User: ofer
* Date: 4/13/12
* Time: 8:53 PM
* To change this template use File | Settings | File Templates.
*/
public class TestRunner {
public void runTests(String inputFilePath, String outputFilePath, Class testClass) {
try {
BufferedReader br = new BufferedReader(new FileReader(inputFilePath));
int numOfTests = Integer.parseInt(br.readLine());
Test[] tests = new Test[numOfTests];
for (int i = 0; i < numOfTests; i++) {
tests[i] = (Test)testClass.newInstance();
tests[i].run(br.readLine());
}
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFilePath));
for (int i = 0; i < numOfTests; i++) {
bw.write(tests[i].getOutput(i+1));
}
bw.close();
} catch (Exception e) {
System.out.println("Caught exception: " + e);
e.printStackTrace();
}
}
}
|
B21752 | B22001 | 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.*;
public class newRecycledNumbers
{
static HashMap<String,String> map;
static int[] recycleNumber(int a){
String s = Integer.toString( a );
int[] arr = new int[s.length()];
arr[0] = a;
for ( int i = 1; i < s.length() ; i++)
arr[i] = (int)( a/Math.pow( 10, i ) ) + (int)(a%Math.pow( 10, i ))*(int)(Math.pow( 10, s.length()-i ));
return arr;
}
static void solve(int a, int b){
int[] arr;
int size = map.size();
for ( int n = a; n < b; n++){
arr = recycleNumber(n);
for ( int j = 0; j < arr.length; j++)
if ( arr[j] > n && arr[j] <= b)
map.put( Integer.toString( n ) + ", " + Integer.toString(arr[j]), "" );
}
System.out.println(map.size()-size);
}
public static void main (String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader("recycle.in"));
int T = Integer.parseInt(reader.readLine()), a,b;
for ( int i = 0; i < T; i++){
map = new HashMap<String,String>();
StringTokenizer st= new StringTokenizer(reader.readLine());
a = Integer.parseInt( st.nextToken() );
b = Integer.parseInt( st.nextToken() );
System.out.print("Case #" + (i+1) + ": ");
solve(a,b);
}
}
} |
A22642 | A22977 | 0 | import java.util.*;
import java.io.*;
public class DancingWithTheGooglers
{
public DancingWithTheGooglers()
{
Scanner inFile = null;
try
{
inFile = new Scanner(new File("inputB.txt"));
}
catch(Exception e)
{
System.out.println("Problem opening input file. Exiting...");
System.exit(0);
}
int t = inFile.nextInt();
int [] results = new int [t];
DancingWithTheGooglersMax [] rnc = new DancingWithTheGooglersMax[t];
int i, j;
int [] scores;
int s, p;
for(i = 0; i < t; i++)
{
scores = new int [inFile.nextInt()];
s = inFile.nextInt();
p = inFile.nextInt();
for(j = 0; j < scores.length; j++)
scores[j] = inFile.nextInt();
rnc[i] = new DancingWithTheGooglersMax(i, scores, s, p, results);
rnc[i].start();
}
inFile.close();
boolean done = false;
while(!done)
{
done = true;
for(i = 0; i < t; i++)
if(rnc[i].isAlive())
{
done = false;
break;
}
}
PrintWriter outFile = null;
try
{
outFile = new PrintWriter(new File("outputB.txt"));
}
catch(Exception e)
{
System.out.println("Problem opening output file. Exiting...");
System.exit(0);
}
for(i = 0; i < results.length; i++)
outFile.printf("Case #%d: %d\n", i+1, results[i]);
outFile.close();
}
public static void main(String [] args)
{
new DancingWithTheGooglers();
}
private class DancingWithTheGooglersMax extends Thread
{
int id;
int s, p;
int [] results, scores;
public DancingWithTheGooglersMax(int i, int [] aScores, int aS, int aP,int [] res)
{
id = i;
s = aS;
p = aP;
results = res;
scores = aScores;
}
public void run()
{
int a = 0, b = 0;
if(p == 0)
results[id] = scores.length;
else if(p == 1)
{
int y;
y = 3*p - 3;
for(int i = 0; i < scores.length; i++)
if(scores[i] > y)
a++;
else if(scores[i] > 0)
b++;
b = Math.min(b, s);
results[id] = a+b;
}
else
{
int y, z;
y = 3*p - 3;
z = 3*p - 5;
for(int i = 0; i < scores.length; i++)
if(scores[i] > y)
a++;
else if(scores[i] > z)
b++;
b = Math.min(b, s);
results[id] = a+b;
}
}
}
} | import java.io.*;
import java.util.*;
public class Game {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(new File("/Users/atai/Play/Codejam/input.txt")));
PrintWriter prn = new PrintWriter(new FileWriter("output.txt"));
int numTests = Integer.parseInt(br.readLine().trim());
for (int i = 0; i < numTests; i++) {
String[] arg = br.readLine().trim().split(" ");
int N = Integer.parseInt(arg[0]);
int S = Integer.parseInt(arg[1]);
int p = Integer.parseInt(arg[2]);
int min;
int surMin;
if (p < 2) {
min = p;
surMin = -1;
} else {
min = 3*p-4;
surMin = 3*p-3;
}
int pass = 0;
int count_sur = 0;
for (int j = 0; j < N; j++) {
int val = Integer.parseInt(arg[3+j]);
if (val < min)
continue;
else {
if (val <= surMin)
count_sur++;
else
pass++;
}
}
if (count_sur >= S)
prn.printf("Case #%d: %d\n", i+1, S+pass);
else {
prn.printf("Case #%d: %d\n", i+1, count_sur + pass);
}
}
prn.close();
}
}
|
B12570 | B12950 | 0 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class RecycledNumbers{
int getcount(int small,int large){
int count = 0;
for(int currnum = small; currnum < large; currnum++){
int permut = currnum;
int no_of_digits = 0;
while(permut > 0){
permut = permut/10;
no_of_digits++;
}
int lastDigit = currnum % 10;
permut = currnum / 10;
permut = permut + lastDigit * (int)Math.pow(10, no_of_digits-1);
while(permut != currnum){
if(permut >= currnum && permut <= large){
count++;
}
lastDigit = permut % 10;
permut = permut / 10;
permut = permut + lastDigit * (int)Math.pow(10, no_of_digits-1);
}
}
return count;
}
public static void main(String args[]){
RecycledNumbers d = new RecycledNumbers();
int no_of_cases = 0;
String input = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
no_of_cases = Integer.parseInt(br.readLine());
}
catch(Exception e){
System.out.println("First line is not a number");
}
for(int i=1; i <= no_of_cases;i++){
try{
input = br.readLine();
}
catch(Exception e){
System.out.println("Number of test cases different from the number mentioned in first line");
}
System.out.print("Case #" +i+": ");
StringTokenizer t = new StringTokenizer(input);
int small=0,large=0;
if(t.hasMoreTokens()){
small = Integer.parseInt(t.nextToken());
}
if(t.hasMoreTokens()){
large = Integer.parseInt(t.nextToken());
}
System.out.println(d.getcount(small,large));
}
}
} | package google.problems;
import google.loader.Challenge;
public abstract class AbstractChallenge implements Challenge{
private final int problemNumber;
private String result;
public AbstractChallenge(int i) {
this.problemNumber = i;
}
protected void setResult(String result){
this.result = result;
}
@Override
public String getResult() {
return "Case #"+problemNumber+": "+result+"\n";
}
protected int getInt(int pos, String[] tokens) {
return Integer.parseInt(tokens[pos]);
}
}
|
B10702 | B12489 | 0 | import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class Recycle {
private static HashMap<Integer, HashSet<Integer>> map = new HashMap<Integer, HashSet<Integer>>();
private static HashSet<Integer> toSkip = new HashSet<Integer>();
/**
* @param args
*/
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int T = reader.nextInt();
for (int tc = 1; tc <= T; tc++) {
int a = reader.nextInt();
int b = reader.nextInt();
long before = System.currentTimeMillis();
int res = doit(a, b);
System.out.printf("Case #%d: %d\n", tc, res);
long after = System.currentTimeMillis();
// System.out.println("time taken: " + (after - before));
}
}
private static int doit(int a, int b) {
int count = 0;
HashSet<Integer> skip = new HashSet<Integer>(toSkip);
for (int i = a; i <= b; i++) {
if (skip.contains(i))
continue;
HashSet<Integer> arr = generate(i);
// if(arr.size() > 1) {
// map.put(i, arr);
// }
// System.out.println(i + " --> " +
// Arrays.deepToString(arr.toArray()));
int temp = 0;
if (arr.size() > 1) {
for (int x : arr) {
if (x >= a && x <= b) {
temp++;
skip.add(x);
}
}
count += temp * (temp - 1) / 2;
}
// System.out.println("not skipping " + i + " gen: " + arr.size()+ " " + (temp * (temp - 1) / 2));
}
return count;
}
private static HashSet<Integer> generate(int num) {
if(map.containsKey(num)) {
HashSet<Integer> list = map.get(num);
return list;
}
HashSet<Integer> list = new HashSet<Integer>();
String s = "" + num;
list.add(num);
int len = s.length();
for (int i = 1; i < len; i++) {
String temp = s.substring(i) + s.substring(0, i);
// System.out.println("temp: " + temp);
if (temp.charAt(0) == '0')
continue;
int x = Integer.parseInt(temp);
if( x <= 2000000) {
list.add(x);
}
}
if(list.size() > 1) {
map.put(num, list);
} else {
toSkip.add(num);
}
return list;
}
}
| import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class RecycledNumbers {
public static void main(String[] args) {
RecycledNumbers recycled = new RecycledNumbers();
recycled.read_input_file();
/*if(recycled.check_if_the_number_is_a_recycled_pair("23451", "34512", "12345")) {
number_of_recycled_pairs ++;
System.out.println(number_of_recycled_pairs);
}*/
}
public boolean check_if_the_number_is_a_recycled_pair(String first_number, String second_number, String original_number) {
if (original_number.equals(first_number)) {
return false;
} else if(first_number.equals(second_number)) {
return true;
} else {
return check_if_the_number_is_a_recycled_pair((first_number.substring(1) + first_number.charAt(0)), second_number, original_number);
}
}
public void read_input_file() {
try {
BufferedReader rd = new BufferedReader(new FileReader("C-small-attempt2.in"));
FileWriter fstream = new FileWriter("output.txt");
BufferedWriter out = new BufferedWriter(fstream);
T = Integer.parseInt(rd.readLine());
System.out.println(T);
while (true) {
String A_and_B = rd.readLine();
System.out.println(A_and_B);
if (A_and_B == null) {
break;
}
parse_line(A_and_B, out);
number_of_recycled_pairs = 0;
}
out.close();
rd.close();
} catch (IOException ex) {
System.out.println("file not found");
}
}
public void parse_line(String A_and_B, BufferedWriter out) {
String A = A_and_B.substring(0, A_and_B.indexOf(" "));
String B = A_and_B.substring(A_and_B.indexOf(" ") + 1);
for (Integer i = Integer.parseInt(A); i < Integer.parseInt(B); i++) {
for (Integer j = i + 1; j <= Integer.parseInt(B); j++) {
String original_number = i.toString();
String first_number = original_number.substring(1) + original_number.charAt(0);
String second_number = j.toString();
if (check_if_the_number_is_a_recycled_pair(first_number, second_number, original_number)) {
number_of_recycled_pairs ++;
}
}
}
Save_line_to_output_file(out);
}
public void Save_line_to_output_file(BufferedWriter out) {
try{
// Create file
out.write("Case #" + (counter + 1) + ": " + number_of_recycled_pairs);
out.newLine();
counter ++;
//Close the output stream
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
int counter = 0;
int T= 0;
static int number_of_recycled_pairs = 0;
}
|
B10485 | B11221 | 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 egWo;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Cs {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
for (int l = 1; l <= T; l++) {
in.nextLine();
int n = in.nextInt();
int m = in.nextInt();
int count = 0;
if ((n % 10 > 0 && n / 10 == 0)) {
count = 0;
} else {
for (int i = n; i < m; i++) {
if (i / 10 < 10) {
int u = i % 10;
int ten = i / 10;
int revI = (u * 10) + ten;
if (i < revI && revI < m) {
count++;
}
} else if (i / 10 <= 100 && i / 10 >= 10) {
int uni = (i % 100) % 10;
int ten = (i / 10) % 10;
int per = i / 100;
ArrayList revI = new ArrayList();
revI.add(ten * 100 + uni * 10 + per);
revI.add(uni * 100 + per * 10 + ten);
Set set = new HashSet(revI);
for (Object j : set) {
if (i < ((Integer) j).intValue()
&& ((Integer) j).intValue() <= m) {
count++;
}
}
}
}
}
System.out.format("\nCase #%d: %d", l, count);
}
}
}
|
B21790 | B20422 | 0 | import java.io.*;
import java.util.*;
public class C {
void solve() throws IOException {
in("C-large.in"); out("C-large.out");
long tm = System.currentTimeMillis();
boolean[] mask = new boolean[2000000];
int[] r = new int[10];
int t = readInt();
for (int cs = 1; cs <= t; ++cs) {
int a = readInt();
int b = readInt();
int ans = 0;
for (int m = a + 1; m <= b; ++m) {
char[] d = String.valueOf(m).toCharArray();
int c = 0;
for (int i = 1; i < d.length; ++i) {
if (d[i] != '0' && d[i] <= d[0]) {
int n = 0;
for (int j = 0; j < d.length; ++j) {
int jj = i + j;
if (jj >= d.length) jj -= d.length;
n = n * 10 + (d[jj] - '0');
}
if (n >= a && n < m && !mask[n]) {
++ans;
mask[n] = true;
r[c++] = n;
}
}
}
for (int i = 0; i < c; ++i) {
mask[r[i]] = false;
}
}
println("Case #" + cs + ": " + ans);
//System.out.println(cs);
}
System.out.println("time: " + (System.currentTimeMillis() - tm));
exit();
}
void in(String name) throws IOException {
if (name.equals("__std")) {
in = new BufferedReader(new InputStreamReader(System.in));
} else {
in = new BufferedReader(new FileReader(name));
}
}
void out(String name) throws IOException {
if (name.equals("__std")) {
out = new PrintWriter(System.out);
} else {
out = new PrintWriter(name);
}
}
void exit() {
out.close();
System.exit(0);
}
int readInt() throws IOException {
return Integer.parseInt(readToken());
}
long readLong() throws IOException {
return Long.parseLong(readToken());
}
double readDouble() throws IOException {
return Double.parseDouble(readToken());
}
String readLine() throws IOException {
st = null;
return in.readLine();
}
String readToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
boolean eof() throws IOException {
return !in.ready();
}
void print(String format, Object ... args) {
out.println(new Formatter(Locale.US).format(format, args));
}
void println(String format, Object ... args) {
out.println(new Formatter(Locale.US).format(format, args));
}
void print(Object value) {
out.print(value);
}
void println(Object value) {
out.println(value);
}
void println() {
out.println();
}
StringTokenizer st;
BufferedReader in;
PrintWriter out;
public static void main(String[] args) throws IOException {
new C().solve();
}
}
| package CodeJam;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
public class Recycled_Numbers {
/**
* @param args
*/
String rotation(String A, int nRot) {
String rotA = A.substring(0, nRot);
A = A.substring(nRot, A.length());
A = A + rotA;
return A;
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
String outputFile = System.getenv("USERPROFILE")+ "\\Documents\\C-small.out";
String inputFile = System.getenv("USERPROFILE") + "\\Documents\\C-small-attempt1.in";
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
DataInputStream reader = new DataInputStream(new FileInputStream(inputFile));
Recycled_Numbers re = new Recycled_Numbers();
int T = Integer.valueOf(reader.readLine());
for (int s = 1; s <= T; s++) {
String line = reader.readLine();
long A = Long.valueOf(line.substring(0, line.indexOf(" ")));
long B = Long.valueOf(line.substring(line.indexOf(" ") + 1,line.length()));
int n = 0;
for (long i = A; i < B; i++) {
String rot = Long.toString(i);
String k = rot;
for (int j = 1; j < rot.length(); j++) {
k = re.rotation(rot, j);
if (k.equals(rot))
break;
if ((Long.valueOf(k) >= i) && (Long.valueOf(k) <= B)) {
n++;
}
}
}
writer.write("Case #" + s + ": " + n);
writer.newLine();
}
writer.close();
reader.close();
}
} |
B12082 | B11576 | 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 recyclednumbers;
import java.util.ArrayList;
public class RecycledNumbers {
static SimpleReader reader;
static SimpleWriter writer;
static int low;
static int high;
public static void main(String[] args) {
if (args.length != 1) {
reader = new SimpleReader();
writer = new SimpleWriter();
} else {
reader = new SimpleReader(args[0]);
writer = new SimpleWriter(args[1]);
}
int cases = reader.readInt();
int[] lohi;
for (int i = 0; i < cases; i++) {
lohi = reader.readIntArray();
low = lohi[0];
high = lohi[1];
solve(i + 1);
System.out.println("Case " + (i + 1) + " done");
}
writer.flush();
System.out.println("Done");
}
private static void solve(int caseNo) {
int ans = 0;
int length = Integer.toString(low).length();
for (int i = low; i <= high; i++) {
String s = Integer.toString(i);
ArrayList<Integer> seen = new ArrayList<>();
for (int j = 1; j < length; j++) {
int cycle = Integer.parseInt(s.substring(j, length) +
s.substring(0, j));
if (!seen.contains(cycle) && cycle <= high && cycle > i) {
ans++;
//System.out.println(Integer.toString(i) + " " + Integer.toString(cycle));
}
seen.add(cycle);
}
}
writer.writeLine("Case #" + caseNo + ": " + ans);
}
private static boolean isRecycled(int n, int m) {
String ns = Integer.toString(n);
String ms = Integer.toString(m);
if (ns.length() != ms.length()) {
return false;
}
for (int i = 1; i < ns.length(); i++) {
if (ns.equals(ms.substring(i, ms.length()) + ms.substring(0, i))) {
return true;
}
}
return false;
}
}
|
B10155 | B12225 | 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 q2012;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Scanner;
public class RecycledNumbers {
public static void main(String[] args) throws Exception {
String input = "C-small-attempt0.in";
String output = "C-small-attempt0.out";
Scanner scan = new Scanner(new BufferedReader(new FileReader(input)));
PrintWriter pw = new PrintWriter(new BufferedWriter(
new FileWriter(output)));
int T = Integer.parseInt(scan.nextLine());
for (int t = 1; t <= T; t++) {
String[] info = scan.nextLine().split(" ");
int A = Integer.parseInt(info[0]);
int B = Integer.parseInt(info[1]);
long count = 0;
for (int i = A; i <= B; i++) {
char[] num = String.valueOf(i).toCharArray();
HashSet<Integer> set = new HashSet<Integer>();
for (int j = 1; j < num.length; j++) {
String n = "";
for (int k = j, m = 0; m < num.length; m++, k = (k + 1)
% num.length)
n += num[k];
int s = Integer.parseInt(n);
if (s > i && s <= B)
set.add(s);
}
count += set.size();
}
pw.println("Case #" + t + ": " + count);
}
scan.close();
pw.close();
}
} |
B12941 | B12431 | 0 | package com.menzus.gcj._2012.qualification.c;
import com.menzus.gcj.common.InputBlockParser;
import com.menzus.gcj.common.OutputProducer;
import com.menzus.gcj.common.impl.AbstractProcessorFactory;
public class CProcessorFactory extends AbstractProcessorFactory<CInput, COutputEntry> {
public CProcessorFactory(String inputFileName) {
super(inputFileName);
}
@Override
protected InputBlockParser<CInput> createInputBlockParser() {
return new CInputBlockParser();
}
@Override
protected OutputProducer<CInput, COutputEntry> createOutputProducer() {
return new COutputProducer();
}
}
| import java.io.*;
import java.util.*;
public class C{
public static void main(String[] args){
try{
String inputFile = "C-small-attempt0.in";
String outputFile = "C-small-attempt0.out";
Scanner sc = new Scanner(new File(inputFile));
FileWriter fwStream = new FileWriter( outputFile );
BufferedWriter bwStream = new BufferedWriter( fwStream );
PrintWriter pwStream = new PrintWriter( bwStream );
int numCase = sc.nextInt();
for(int i = 0; i < numCase; i++){
int answer = 0;
int min = sc.nextInt();
int max = sc.nextInt();
for(int j = min; j <= max; j++){
System.out.println("inside j loop");
String a = String.valueOf(j);
int length = a.length();
int temp = ((j % 10) * (int)(Math.pow(10,length-1))) + (j /10);
while(temp != j){
System.out.println("inside while temp loop");
System.out.println("temp = " + temp);
System.out.println("j = " + j);
if(temp >= min && temp <= max && temp > j){
answer++;
}
temp = ((temp % 10) * (int)(Math.pow(10,length-1))) + (temp /10);
}
}
pwStream.print("Case #"+(i+1)+ ": ");
pwStream.print(answer);
pwStream.println();
}
pwStream.close();
sc.close();
}
catch(Exception e){e.printStackTrace();}
}
} |
A12113 | A10092 | 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;
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package a;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.IOException;
/**
*
* @author KazakhPride
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
Scanner in = new Scanner(new File("B-small-attempt0.in"));
PrintWriter out = new PrintWriter(new File("output.txt"));
int n = in.nextInt();
int t = 0;
int s = 0;
int p = 0;
for (int j = 1; j <= n; j++) {
out.print("Case #" + j + ": ");
t = in.nextInt();
s = in.nextInt();
p = in.nextInt();
int count = 0;
int ar[] = new int[t];
for (int i = 0; i < ar.length; i++) {
ar[i] = in.nextInt();
}
for( int i = 0; i < ar.length; i++ ){
if(ar[i]%3 == 0){
int base = ar[i]/3;
//int second = first;
//int third = second;
if(base >= p){
count++;
}
else{
if(s > 0 && base > 0 && base + 1 >= p){
count++;
s--;
}
}
}
else if(ar[i]%3==1){
int base = ar[i]/3;
if(base >= p || base + 1 >= p){
count++;
}
else{
if(s > 0 && base + 1 >= p){
count++;
s--;
}
}
}
if( ar[i]%3 == 2 ){
int base = ar[i]/3;
if(base + 1 >= p || base >= p){
count++;
}
else{
if( s > 0 && base + 2 >= p ){
count++;
s--;
}
}
}
}
out.println(count);
}
in.close();
out.close();
}
} |
B10231 | B11025 | 0 | import java.io.*;
class code1
{
public static void main(String args[]) throws Exception
{
File ii = new File ("C-small-attempt1.in");
FileInputStream fis = new FileInputStream(ii);
BufferedReader br = new BufferedReader(new InputStreamReader (fis));
int cases = Integer.parseInt(br.readLine());
FileOutputStream fout = new FileOutputStream ("output.txt");
DataOutputStream dout = new DataOutputStream (fout);
int total=0;
for(int i=0;i<cases;i++){
String temp = br.readLine();
String parts [] = temp.split(" ");
int lower = Integer.parseInt(parts[0]);
int upper = Integer.parseInt(parts[1]);
System.out.println(lower+" "+upper);
for(int j=lower;j<=upper;j++)
{
int abc = j;int length=0;
if(j<10)continue;
while (abc!=0){abc/=10;length++;}
abc=j;
for(int m=0;m<length-1;m++){
int shift = abc%10;
abc=abc/10;
System.out.println("hi "+j);
abc=abc+shift*power(10,length-1);
if(abc<=upper&&shift!=0&&abc>j)total++;
System.out.println(total);
}
}
dout.writeBytes("Case #"+(i+1)+ ": "+total+"\n");
total=0;
}//for close
}
private static int power(int i, int j) {
int no=1;
for(int a=0;a<j;a++){no=10*no;}
return no;
}
} | package org.moriraaca.codejam;
public enum DebugOutputLevel {
SOLUTION, IMPORTANT, ALL;
}
|
A12846 | A13127 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package codejam.common;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Lance Chen
*/
public class CodeHelper {
private static String FILE_ROOT = "D:/workspace/googlecodejam/meta";
public static List<List<String>> loadInputsExcludes(String fileName) {
List<List<String>> result = new ArrayList<List<String>>();
List<String> lines = FileUtil.readLines(FILE_ROOT + fileName);
int index = 0;
for (String line : lines) {
if (index == 0) {
index++;
continue;
}
if (index % 2 == 1) {
index++;
continue;
}
List<String> dataList = new ArrayList<String>();
String[] dataArray = line.split("\\s+");
for (String data : dataArray) {
if (data.trim().length() > 0) {
dataList.add(data);
}
}
result.add(dataList);
index++;
}
return result;
}
public static List<List<String>> loadInputs(String fileName) {
List<List<String>> result = new ArrayList<List<String>>();
List<String> lines = FileUtil.readLines(FILE_ROOT + fileName);
for (String line : lines) {
List<String> dataList = new ArrayList<String>();
String[] dataArray = line.split("\\s+");
for (String data : dataArray) {
if (data.trim().length() > 0) {
dataList.add(data);
}
}
result.add(dataList);
}
return result;
}
public static List<String> loadInputLines(String fileName) {
return FileUtil.readLines(FILE_ROOT + fileName);
}
public static void writeOutputs(String fileName, List<String> lines) {
FileUtil.writeLines(FILE_ROOT + fileName, lines);
}
}
| import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class IOSystem {
private String filePath;
private List<String> inputList = new ArrayList<String>();
private StringBuilder sb = new StringBuilder();
private int readSize = 0;
private int appendedSize = 0;
public IOSystem(String filePath)
{
this(filePath," ");
}
public IOSystem(String filePath,String sep)
{
this.filePath = filePath;
try {
BufferedReader br = new BufferedReader(new FileReader(filePath+".in"));
String line = null;
while((line=br.readLine())!=null)
{
inputList.addAll(Arrays.asList(line.split(sep)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public int size(){return inputList.size();}
public boolean hasNext(){return readSize < size();}
public int nextInt(){return Integer.parseInt(inputList.get(readSize++));}
public long nextLong(){return Long.parseLong(inputList.get(readSize++));}
public double nextDouble(){return Double.parseDouble(inputList.get(readSize++));}
public String nextString(){return new String(inputList.get(readSize++));}
public <T> void appendAnswer(T answer){sb.append("Case #"+(++appendedSize)+": "+answer.toString()+"\n");};
public void output(){
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(filePath+".ou"));
bw.write(sb.toString());
bw.flush();
System.out.println("output ->"+filePath+".ou");
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
B12085 | B11032 | 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;
}
}
| package codejam;
import java.io.*;
import java.util.HashSet;
public class Numb {
public static void main(String[] args)throws IOException{
HashSet<Integer> hs;
BufferedReader cin=new BufferedReader(new FileReader("i3.in"));
PrintWriter cout=new PrintWriter(new BufferedWriter(new FileWriter("out3.txt")));
String[] in;
int x,y,j,num,count;
int t=Integer.parseInt(cin.readLine());
for(int i=0;i<t;i++){
count=0;
in=cin.readLine().split(" ");
x=Integer.parseInt(in[0]);
y=Integer.parseInt(in[1]);
if(y<10){ cout.println("Case #"+(i+1)+": 0");continue;}
for(j=x;j<=y;j++){
hs=new HashSet<Integer>();
String s=Integer.toString(j);
int l=s.length();
for(int k=l-1;k>0;k--){
if(s.charAt(k)=='0') continue;
num=Integer.parseInt(s.substring(k)+s.substring(0,k));
if(num>j && num<=y && !hs.contains(num)){
hs.add(num);
count++;
}
}
}
cout.println("Case #"+(i+1)+": "+count);
}
cout.flush();
}
}
|
B12082 | B12434 | 0 | package jp.funnything.competition.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.apache.commons.io.IOUtils;
public class QuestionReader {
private final BufferedReader _reader;
public QuestionReader( final File input ) {
try {
_reader = new BufferedReader( new FileReader( input ) );
} catch ( final FileNotFoundException e ) {
throw new RuntimeException( e );
}
}
public void close() {
IOUtils.closeQuietly( _reader );
}
public String read() {
try {
return _reader.readLine();
} catch ( final IOException e ) {
throw new RuntimeException( e );
}
}
public BigDecimal[] readBigDecimals() {
return readBigDecimals( " " );
}
public BigDecimal[] readBigDecimals( final String separator ) {
final String[] tokens = readTokens( separator );
final BigDecimal[] values = new BigDecimal[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = new BigDecimal( tokens[ index ] );
}
return values;
}
public BigInteger[] readBigInts() {
return readBigInts( " " );
}
public BigInteger[] readBigInts( final String separator ) {
final String[] tokens = readTokens( separator );
final BigInteger[] values = new BigInteger[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = new BigInteger( tokens[ index ] );
}
return values;
}
public int readInt() {
final int[] values = readInts();
if ( values.length != 1 ) {
throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" );
}
return values[ 0 ];
}
public int[] readInts() {
return readInts( " " );
}
public int[] readInts( final String separator ) {
final String[] tokens = readTokens( separator );
final int[] values = new int[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = Integer.parseInt( tokens[ index ] );
}
return values;
}
public long readLong() {
final long[] values = readLongs();
if ( values.length != 1 ) {
throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" );
}
return values[ 0 ];
}
public long[] readLongs() {
return readLongs( " " );
}
public long[] readLongs( final String separator ) {
final String[] tokens = readTokens( separator );
final long[] values = new long[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = Long.parseLong( tokens[ index ] );
}
return values;
}
public String[] readTokens() {
return readTokens( " " );
}
public String[] readTokens( final String separator ) {
return read().split( separator );
}
}
| import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
public class RecycledPairs
{
static String line="Code Jam";
static int noOfTCs;
static long lowerLimit,upperLimit;
static ArrayList<String> pairs = new ArrayList<String>();
public static void main(String[] args)
{
//initialize();
calculate();
//generateOPFile();
}
private static void calculate()
{
try
{
BufferedReader br = new BufferedReader(new FileReader("C:/CodeJam/C-small-attempt2.in"));
FileWriter fw = new FileWriter("C:/CodeJam/output.txt");
BufferedWriter bw = new BufferedWriter(fw);
line = br.readLine().trim();
noOfTCs = Integer.parseInt(line);
for(int testCase=0;testCase<noOfTCs;testCase++)
{
line = br.readLine().trim();
String[] limits = line.split(" ");
lowerLimit = Long.parseLong(limits[0]);
upperLimit = Long.parseLong(limits[1]);
for(long n = lowerLimit; n<upperLimit; n++)
{
StringBuffer nsb = new StringBuffer(""+n);
//System.out.println(nsb.toString());
for(int length = 1; length < nsb.length();length++)
{
StringBuffer msb = new StringBuffer(nsb.substring(length, nsb.length())+nsb.substring(0, length));
//System.out.println(msb.toString());
if(msb.charAt(0)=='0')
continue;
long m = Long.parseLong(msb.toString());
if(n<m && m <=upperLimit)
{
String s = nsb.toString()+","+msb.toString();
//System.out.println(s);
if(!pairs.contains(s))
pairs.add(s);
}
}
}
line = "Case #"+(testCase+1)+": "+pairs.size();
pairs.clear();
bw.write(line);
bw.newLine();
}
br.close();
bw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
/*static void generateOPFile()
{
try
{
FileWriter fw = new FileWriter("C:/CodeJam/output.txt");
BufferedWriter bw = new BufferedWriter(fw);
for(int i=1;i<=noOfTCs;i++)
{
line = "Case #"+i+": "+1;
bw.write(line);
bw.newLine();
}
bw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}*/
/*static void initialize()
{
try
{
BufferedReader br = new BufferedReader(new FileReader("C:/CodeJam/C-small.in"));
line = br.readLine().trim();
noOfTCs = Integer.parseInt(line);
br.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}*/
}
|
A20119 | A21249 | 0 | package code12.qualification;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class B {
public static String solve(int N, int S, int p, int[] t) {
// 3a -> (a, a, a), *(a - 1, a, a + 1)
// 3a + 1 -> (a, a, a + 1), *(a - 1, a + 1, a + 1)
// 3a + 2 -> (a, a + 1, a + 1), *(a, a, a + 2)
int numPNoS = 0;
int numPWithS = 0;
for (int i = 0; i < N; i++) {
int a = (int)Math.floor(t[i] / 3);
int r = t[i] % 3;
switch (r) {
case 0:
if (a >= p) {
numPNoS++;
} else if (a + 1 >= p && a - 1 >= 0) {
numPWithS++;
}
break;
case 1:
if (a >= p || a + 1 >= p) {
numPNoS++;
}
break;
case 2:
if (a >= p || a + 1 >= p) {
numPNoS++;
} else if (a + 2 >= p) {
numPWithS++;
}
break;
}
}
return "" + (numPNoS + Math.min(S, numPWithS));
}
public static void main(String[] args) throws Exception {
// file name
//String fileName = "Sample";
//String fileName = "B-small";
String fileName = "B-large";
// file variable
File inputFile = new File(fileName + ".in");
File outputFile = new File(fileName + ".out");
Scanner scanner = new Scanner(inputFile);
FileWriter writer = new FileWriter(outputFile);
// problem variable
int totalCase;
int N, S, p;
int[] t;
// get total case
totalCase = scanner.nextInt();
for (int caseIndex = 1; caseIndex <= totalCase; caseIndex++) {
// get input
N = scanner.nextInt();
S = scanner.nextInt();
p = scanner.nextInt();
t = new int[N];
for (int i = 0; i < N; i++) {
t[i] = scanner.nextInt();
}
String output = "Case #" + caseIndex + ": " + solve(N, S, p, t);
System.out.println(output);
writer.write(output + "\n");
}
scanner.close();
writer.close();
}
}
| import java.util.*;
import java.io.*;
public class q2 {
/**
* @param args
*/
public static void main(String[] args) {
File file = new File("C:/Users/Raja/workspace/GCJ/src/in.txt");
int N,S,p;
int[] sums;
int norm,surp,ans;
try{
Scanner s = new Scanner(file);
int num = Integer.parseInt(s.nextLine());
for (int i = 0;i<num;i++){
norm = 0;
surp = 0;
N = s.nextInt();
S = s.nextInt();
p = s.nextInt();
sums = new int[N];
for (int j = 0; j < N; j++){
sums[j] = s.nextInt();
}
Arrays.sort(sums);
for (int j = 0; j < N; j++){
if (sums[j] >= 3*p-2)
norm++;
else if (sums[j] >= 3*p-4 && sums[j] > 1)
surp++;
}
if (surp > S)
ans = norm + S;
else
ans = norm + surp;
System.out.println("Case #"+(i+1)+": "+ans);
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
|
B10231 | B12437 | 0 | import java.io.*;
class code1
{
public static void main(String args[]) throws Exception
{
File ii = new File ("C-small-attempt1.in");
FileInputStream fis = new FileInputStream(ii);
BufferedReader br = new BufferedReader(new InputStreamReader (fis));
int cases = Integer.parseInt(br.readLine());
FileOutputStream fout = new FileOutputStream ("output.txt");
DataOutputStream dout = new DataOutputStream (fout);
int total=0;
for(int i=0;i<cases;i++){
String temp = br.readLine();
String parts [] = temp.split(" ");
int lower = Integer.parseInt(parts[0]);
int upper = Integer.parseInt(parts[1]);
System.out.println(lower+" "+upper);
for(int j=lower;j<=upper;j++)
{
int abc = j;int length=0;
if(j<10)continue;
while (abc!=0){abc/=10;length++;}
abc=j;
for(int m=0;m<length-1;m++){
int shift = abc%10;
abc=abc/10;
System.out.println("hi "+j);
abc=abc+shift*power(10,length-1);
if(abc<=upper&&shift!=0&&abc>j)total++;
System.out.println(total);
}
}
dout.writeBytes("Case #"+(i+1)+ ": "+total+"\n");
total=0;
}//for close
}
private static int power(int i, int j) {
int no=1;
for(int a=0;a<j;a++){no=10*no;}
return no;
}
} | import java.util.Scanner;
import java.io.*;
public class Tobi
{
static String out="",output="";
public static void main(String[] args)
{
try
{
Scanner in = new Scanner(new File("recycle.in"));
int n = in.nextInt();
int count = 1;
String out = "";
while(in.hasNext())
{
int a = in.nextInt();
int b = in.nextInt();
out += "Case #"+count+": "+ activity(a,b)+"\n";
count++;
try
{
File file = new File("output.dat");
PrintWriter output = new PrintWriter(file);
output.write(out);
output.close();
}
catch(Exception exception)
{
System.out.println("ERROR");
}
}
}catch(Exception exception){
System.out.println("ERROR");
}
System.out.println("DONE");
}
public static int activity(int A, int B)
{
int counter = 0;
//String all[] = myGenerator(Integer.toString(A));
for(int i = A; i <= B; i++)
{
String all[] = myGenerator(Integer.toString(i));
for(int j = 0; j < all.length; j++)
{
if((i < Integer.parseInt(all[j])) && (Integer.parseInt(all[j]) <= B))
{
counter++;
}
}
}
return counter;
}
public static String[] myGenerator(String word)
{
String[] all = new String[word.length()-1];//changed frm len - 1
for(int i = 0; i < all.length; i++)
{
all[i] = generate(word);
word = generate(word);
}
return all;
}
public static String generate(String w)
{
String ans = w.substring(w.length()-1);
for(int i = 0; i < w.length()-1; i++)
{
ans += w.substring(i,i+1);
}
return ans;
}
}
|
B10149 | B10338 | 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));
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ex3;
/**
*
* @author Jean-Nicolas
*/
public class Pair {
private int m;
private int n;
public Pair(int n, int m) {
this.m = m;
this.n = n;
}
public int getM() {
return m;
}
public void setM(int m) {
this.m = m;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Pair other = (Pair) obj;
if (this.m != other.m) {
return false;
}
if (this.n != other.n) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 89 * hash + this.m;
hash = 89 * hash + this.n;
return hash;
}
}
|
A12544 | A11072 | 0 | package problem1;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
public class Problem1 {
public static void main(String[] args) throws FileNotFoundException, IOException{
try {
TextIO.readFile("L:\\Coodejam\\Input\\Input.txt");
}
catch (IllegalArgumentException e) {
System.out.println("Can't open file ");
System.exit(0);
}
FileOutputStream fout = new FileOutputStream("L:\\Coodejam\\Output\\output.txt");
PrintStream ps=new PrintStream(fout);
int cases=TextIO.getInt();
int googlers=0,surprising=0,least=0;
for(int i=0;i<cases;i++){
int counter=0;
googlers=TextIO.getInt();
surprising=TextIO.getInt();
least=TextIO.getInt();
int score[]=new int[googlers];
for(int j=0;j<googlers;j++){
score[j]=TextIO.getInt();
}
Arrays.sort(score);
int temp=0;
int sup[]=new int[surprising];
for(int j=0;j<googlers && surprising>0;j++){
if(biggestNS(score[j])<least && biggestS(score[j])==least){
surprising--;
counter++;
}
}
for(int j=0;j<googlers;j++){
if(surprising==0)temp=biggestNS(score[j]);
else {
temp=biggestS(score[j]);
surprising--;
}
if(temp>=least)counter++;
}
ps.println("Case #"+(i+1)+": "+counter);
}
}
static int biggestNS(int x){
if(x==0)return 0;
if(x==1)return 1;
return ((x-1)/3)+1;
}
static int biggestS(int x){
if(x==0)return 0;
if(x==1)return 1;
return ((x-2)/3)+2;
}
} | import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class Problem2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("input.txt"));
PrintStream output = new PrintStream(new FileOutputStream(new File("output.txt")));
int T = input.nextInt();
input.nextLine();
for(int i=1; i <= T; ++i) {
Scanner line = new Scanner(input.nextLine());
int N = line.nextInt();
int S = line.nextInt();
int p = line.nextInt();
System.out.printf("Case:%d, N:%d, S:%d, p:%d\n", i,N,S,p);
int result = 0;
for(int j=0; j < N; ++j) {
int points = line.nextInt();
int threshold,special_threshold;
if (p==0) {
threshold = 0;
special_threshold = 0;
}
if (p==1) {
threshold = 1;
special_threshold = 1;
}
else {
threshold = 3*p-2;
special_threshold = 3*p-4;
}
if(points >= threshold) {
result++;
}
else if( (S>0) && (points >= special_threshold)) {
S--;
result++;
}
}
output.println("Case #" + i + ": " + result);
}
}
}
|
A22771 | A21930 | 0 | package com.menzus.gcj._2012.qualification.b;
import com.menzus.gcj.common.InputBlockParser;
import com.menzus.gcj.common.OutputProducer;
import com.menzus.gcj.common.impl.AbstractProcessorFactory;
public class BProcessorFactory extends AbstractProcessorFactory<BInput, BOutputEntry> {
public BProcessorFactory(String inputFileName) {
super(inputFileName);
}
@Override
protected InputBlockParser<BInput> createInputBlockParser() {
return new BInputBlockParser();
}
@Override
protected OutputProducer<BInput, BOutputEntry> createOutputProducer() {
return new BOutputProducer();
}
}
| package jp.funnything.competition.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
public class Packer {
private static void add( final ZipArchiveOutputStream out , final File file , final int pathPrefix ) {
if ( file.isDirectory() ) {
final File[] children = file.listFiles();
if ( children.length > 0 ) {
for ( final File child : children ) {
add( out , child , pathPrefix );
}
} else {
addEntry( out , file , pathPrefix , false );
}
} else {
addEntry( out , file , pathPrefix , true );
}
}
private static void addEntry( final ZipArchiveOutputStream out , final File file , final int pathPrefix , final boolean isFile ) {
try {
out.putArchiveEntry( new ZipArchiveEntry( file.getPath().substring( pathPrefix ) + ( isFile ? "" : "/" ) ) );
if ( isFile ) {
final FileInputStream in = FileUtils.openInputStream( file );
IOUtils.copy( in , out );
IOUtils.closeQuietly( in );
}
out.closeArchiveEntry();
} catch ( final IOException e ) {
throw new RuntimeException( e );
}
}
public static void pack( final File source , final File destination ) {
try {
final ZipArchiveOutputStream out = new ZipArchiveOutputStream( destination );
add( out , source , FilenameUtils.getPath( source.getPath() ).length() );
out.finish();
out.close();
} catch ( final IOException e ) {
throw new RuntimeException( e );
}
}
}
|
A12211 | A12029 | 0 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Dancing_improved {
static int f_Superan_limites(String params){
int superan_limite=0;
String[] parametros=params.split(" ");
int n_participantes= Integer.parseInt(parametros[0]);
int n_sorprendidos= Integer.parseInt(parametros[1]);
int nota_limite= Integer.parseInt(parametros[2]);
int suma_notas, resto, nota_juego;
for(int i=3;i<parametros.length;i++){ // Recorro las sumas de los participantes
suma_notas=Integer.parseInt(parametros[i]);
resto=suma_notas%3;
if(resto==0){ // el resto es el número triplicado!
nota_juego=suma_notas/3;
if(nota_juego>=nota_limite){
superan_limite++;
}else if(nota_juego-1>=0 && n_sorprendidos>0 && ((nota_juego+1)>=nota_limite || (nota_juego+2)>=nota_limite)){ // no supera el límite pero podría hacerlo si quedan sorprendidos
n_sorprendidos--;
superan_limite++;
}
}else if((suma_notas+1)%3==0){ // Tendré que jugar con el valor en +-1
nota_juego=(suma_notas+1)/3;
if(nota_juego-1>=0 && nota_juego>=nota_limite){
superan_limite++;
}else if(nota_juego-1>=0 && n_sorprendidos>0 && (nota_juego+1)>=nota_limite){
n_sorprendidos--;
superan_limite++;
}
}else if((suma_notas+2)%3==0){ // Tendré que jugar con el valor en +-2
nota_juego=(suma_notas+2)/3;
if(nota_juego-1>=0 && nota_juego>=nota_limite){
superan_limite++;
}
}
}
return superan_limite;
}
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader(args[0]);
BufferedReader bf = new BufferedReader(fr);
int ntest=0;
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
String lines = bf.readLine();
String liner, linew;
int lines_r=0;
String[] numbers;
int total;
while((liner = bf.readLine())!=null && lines_r<=Integer.parseInt(lines)) {
ntest++;
numbers=liner.split(" ");
total=f_Superan_limites(liner);
linew="Case #"+ntest+": "+total+"\n";
out.write(linew);
lines_r++;
}
out.close();
fr.close();
}
}
| /*
* Google Code Jam 2012 - Qualification Round (14.04.2012)
* Thomas "ThmX" Denoréaz - [email protected]
*/
package codejam._2012.qualif;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class B {
static final String FILENAME = "B-small-attempt1";
public static boolean isValidTriplet(int a, int b, int c) {
return (abs(b-a) <= 1) && (abs(c-a) <= 1) && (abs(c-b) <= 1);
}
public static boolean isValidSurprisingTriplet(int a, int b, int c) {
return (abs(b-a) <= 2) && (abs(c-a) <= 2) && (abs(c-b) <= 2);
}
public static int[][] TRIPLETS_MAX_VALUES = {
{0, 0}, // 0
{0, 0}, // 1
{0, 0}, // 2
{1, 0}, // 3
{2, 0}, // 4
{2, 3}, // 5
{2, 3}, // 6
{3, 3}, // 7
{3, 4}, // 8
{3, 4}, // 9
{4, 4},
{4, 5},
{4, 5},
{5, 5},
{5, 6},
{5, 6},
{6, 6},
{6, 7},
{6, 7},
{7, 7},
{7, 8},
{7, 8},
{8, 8},
{8, 9},
{8, 9},
{9, 9},
{9, 10},
{9, 10},
{10, 10},
{10, 0},
{10, 0}
};
public static void main(String[] args) throws NumberFormatException, IOException {
/*
int[][] tripletsMaxValue = new int[31][2];
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
for (int k = 1; k <= 10; k++) {
if (isValidTriplet(i, j, k)) {
int idx = i + j + k;
int max = max(max(i, j), k);
tripletsMaxValue[idx][0] = max(max, tripletsMaxValue[idx][0]);
} else if (isValidSurprisingTriplet(i, j, k)) {
int idx = i + j + k;
int max = max(max(i, j), k);
tripletsMaxValue[idx][1] = max(max, tripletsMaxValue[idx][1]);
}
}
}
}
System.out.print("TRIPLETS_MAX_VALUES = ");
for (int i = 0; i < tripletsMaxValue.length; i++) {
System.out.println(Arrays.toString(tripletsMaxValue[i]) + ", ");
}
System.out.println();
//*/
//*
BufferedReader reader = new BufferedReader(new FileReader(FILENAME + ".in"));
PrintWriter writer = new PrintWriter(FILENAME + ".out");
int T = Integer.valueOf(reader.readLine());
for (int t=1; t<=T; t++) {
String[] nums = reader.readLine().split(" ");
int N = Integer.valueOf(nums[0]);
int S = Integer.valueOf(nums[1]);
int p = Integer.valueOf(nums[2]);
int[] ti = new int[N];
for (int i=0; i<N; i++) {
ti[i] = Integer.valueOf(nums[3+i]);
}
int count = count(0, S, N-S, p, ti);
writer.println("Case #" + t + ": " + count);
}
writer.flush();
writer.close();
reader.close();
//*/
}
public static int count(int i, int S, int nS, int p, int[] ti) {
if (S == 0 && nS == 0) {
return 0;
}
int max1 = 0;
if (nS > 0) {
max1 = count(i+1, S, nS-1, p, ti);
if (TRIPLETS_MAX_VALUES[ti[i]][0] >= p) {
++max1;
}
}
int max2 = 0;
if (S > 0) {
max2 = count(i+1, S-1, nS, p, ti);
if (TRIPLETS_MAX_VALUES[ti[i]][1] >= p) {
++max2;
}
}
return max(max1, max2);
}
}
|
B12570 | B12486 | 0 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class RecycledNumbers{
int getcount(int small,int large){
int count = 0;
for(int currnum = small; currnum < large; currnum++){
int permut = currnum;
int no_of_digits = 0;
while(permut > 0){
permut = permut/10;
no_of_digits++;
}
int lastDigit = currnum % 10;
permut = currnum / 10;
permut = permut + lastDigit * (int)Math.pow(10, no_of_digits-1);
while(permut != currnum){
if(permut >= currnum && permut <= large){
count++;
}
lastDigit = permut % 10;
permut = permut / 10;
permut = permut + lastDigit * (int)Math.pow(10, no_of_digits-1);
}
}
return count;
}
public static void main(String args[]){
RecycledNumbers d = new RecycledNumbers();
int no_of_cases = 0;
String input = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
no_of_cases = Integer.parseInt(br.readLine());
}
catch(Exception e){
System.out.println("First line is not a number");
}
for(int i=1; i <= no_of_cases;i++){
try{
input = br.readLine();
}
catch(Exception e){
System.out.println("Number of test cases different from the number mentioned in first line");
}
System.out.print("Case #" +i+": ");
StringTokenizer t = new StringTokenizer(input);
int small=0,large=0;
if(t.hasMoreTokens()){
small = Integer.parseInt(t.nextToken());
}
if(t.hasMoreTokens()){
large = Integer.parseInt(t.nextToken());
}
System.out.println(d.getcount(small,large));
}
}
} | import java.math.BigInteger;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class C {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) System.out.printf("Case #%d: %s\n", i + 1, exec());
}
public static String exec() {
long now = System.currentTimeMillis();
int a = sc.nextInt();
int b = sc.nextInt();
BigInteger result = BigInteger.ZERO;
Set<Integer> x = new HashSet<Integer>();
for (int i = a; i < b; i++) {
x.clear();
String s = String.valueOf(i);
for (int j = 1; j < s.length(); j++) {
String q = s.substring(j) + s.substring(0, j);
int qs = Integer.valueOf(q);
if (qs <= i) continue;
if (qs > b) continue;
boolean success = x.add(qs);
if (success) result = result.add(BigInteger.ONE);
}
}
long taken = System.currentTimeMillis() - now;
// System.err.println("TIME TAKEN: " + taken + " -- * 50 = " + (50 * taken) + " -- 8 min = " + (1000L * 60 * 8));
return result.toString();
}
}
|
A20261 | A22956 | 0 | package com.gcj.parser;
public class MaxPoints {
public static int normal(int value){
int toReturn = 0;
switch (value) {
case 0 : toReturn = 0 ; break;
case 1 : toReturn = 1 ; break;
case 2 : toReturn = 1 ; break;
case 3 : toReturn = 1 ; break;
case 4 : toReturn = 2 ; break;
case 5 : toReturn = 2 ; break;
case 6 : toReturn = 2 ; break;
case 7 : toReturn = 3 ; break;
case 8 : toReturn = 3 ; break;
case 9 : toReturn = 3 ; break;
case 10 : toReturn = 4 ; break;
case 11 : toReturn = 4 ; break;
case 12 : toReturn = 4 ; break;
case 13 : toReturn = 5 ; break;
case 14 : toReturn = 5 ; break;
case 15 : toReturn = 5 ; break;
case 16 : toReturn = 6 ; break;
case 17 : toReturn = 6 ; break;
case 18 : toReturn = 6 ; break;
case 19 : toReturn = 7 ; break;
case 20 : toReturn = 7 ; break;
case 21 : toReturn = 7 ; break;
case 22 : toReturn = 8 ; break;
case 23 : toReturn = 8 ; break;
case 24 : toReturn = 8 ; break;
case 25 : toReturn = 9 ; break;
case 26 : toReturn = 9 ; break;
case 27 : toReturn = 9 ; break;
case 28 : toReturn = 10 ; break;
case 29 : toReturn = 10 ; break;
case 30 : toReturn = 10 ; break;
}
return toReturn;
}
public static int surprising(int value){
int toReturn = 0;
switch (value) {
case 0 : toReturn = 0 ; break;
case 1 : toReturn = 1 ; break;
case 2 : toReturn = 2 ; break;
case 3 : toReturn = 2 ; break;
case 4 : toReturn = 2 ; break;
case 5 : toReturn = 3 ; break;
case 6 : toReturn = 3 ; break;
case 7 : toReturn = 3 ; break;
case 8 : toReturn = 4 ; break;
case 9 : toReturn = 4 ; break;
case 10 : toReturn = 4 ; break;
case 11 : toReturn = 5 ; break;
case 12 : toReturn = 5 ; break;
case 13 : toReturn = 5 ; break;
case 14 : toReturn = 6 ; break;
case 15 : toReturn = 6 ; break;
case 16 : toReturn = 6 ; break;
case 17 : toReturn = 7 ; break;
case 18 : toReturn = 7 ; break;
case 19 : toReturn = 7 ; break;
case 20 : toReturn = 8 ; break;
case 21 : toReturn = 8 ; break;
case 22 : toReturn = 8 ; break;
case 23 : toReturn = 9 ; break;
case 24 : toReturn = 9 ; break;
case 25 : toReturn = 9 ; break;
case 26 : toReturn = 10 ; break;
case 27 : toReturn = 10 ; break;
case 28 : toReturn = 10 ; break;
case 29 : toReturn = 10 ; break;
case 30 : toReturn = 10 ; break;
}
return toReturn;
}
}
| import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Q2DancingWithGooglers {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("q2.input"));
FileWriter writer = new FileWriter("q2.output");
int cases = scanner.nextInt();
for (int i = 1; i <= cases; i++) {
int n = scanner.nextInt();
int s = scanner.nextInt();
final int p = scanner.nextInt();
List<Integer> cantBeSurprising = new ArrayList<Integer>(n);
List<Integer> canBeSurprising = new ArrayList<Integer>(n);
for (int j = 0; j < n; j++) {
int t = scanner.nextInt();
if (canBeSurprising(t)) {
canBeSurprising.add(t);
} else {
cantBeSurprising.add(t);
}
}
Collections.sort(canBeSurprising, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return getPriority(o1).compareTo(getPriority(o2));
}
private Integer getPriority(Integer o1) {
if (getSurprisingP(o1) >= p && getNormalP(o1) < p) {
return 0;
}
if (getSurprisingP(o1) >= p) {
return 1;
}
return 2;
}
});
int response = 0;
for (int j = 0; j < s; j++) {
if (getSurprisingP(canBeSurprising.get(j)) >= p) {
response++;
}
}
for (int j = s; j < canBeSurprising.size(); j++) {
if (getNormalP(canBeSurprising.get(j)) >= p) {
response++;
}
}
for (Integer t : cantBeSurprising) {
if (getNormalP(t) >= p) {
response++;
}
}
writer.write("Case #" + i + ": " + response + "\n");
}
writer.close();
}
private static boolean canBeSurprising(int n) {
if (n == 30 || n == 0 || n == 29) {
return false;
}
return true;
}
private static Integer getSurprisingP(int n) {
if (n % 3 <= 1) {
return n / 3 + 1;
}
if (n % 3 == 2) {
return n / 3 + 2;
}
return 0;
}
private static Integer getNormalP(int n) {
if (n % 3 == 0) {
return n / 3;
}
return n / 3 + 1;
}
}
|
B11327 | B10248 | 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.*;
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());
}
}
|
A22992 | A21853 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package IO;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
*
* @author dannocz
*/
public class InputReader {
public static Input readFile(String filename){
try {
/* Sets up a file reader to read the file passed on the command
77 line one character at a time */
FileReader input = new FileReader(filename);
/* Filter FileReader through a Buffered read to read a line at a
time */
BufferedReader bufRead = new BufferedReader(input);
String line; // String that holds current file line
int count = 0; // Line number of count
ArrayList<String> cases= new ArrayList<String>();
// Read first line
line = bufRead.readLine();
int noTestCases=Integer.parseInt(line);
count++;
// Read through file one line at time. Print line # and line
while (count<=noTestCases){
//System.out.println("Reading. "+count+": "+line);
line = bufRead.readLine();
cases.add(line);
count++;
}
bufRead.close();
return new Input(noTestCases,cases);
}catch (ArrayIndexOutOfBoundsException e){
/* If no file was passed on the command line, this expception is
generated. A message indicating how to the class should be
called is displayed */
e.printStackTrace();
}catch (IOException e){
// If another exception is generated, print a stack trace
e.printStackTrace();
}
return null;
}// end main
}
| import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class DancingWithTheGooglers {
private String mInputFileName;
private String mOutputFileName;
private int N;
private int S;
private int P;
private int[] mScores;
public DancingWithTheGooglers(String inputFileName, String outputFileName) {
mInputFileName = inputFileName;
mOutputFileName = outputFileName;
}
public void solve() {
long start = System.currentTimeMillis();
Scanner scanner = null;
try {
scanner = new Scanner(new FileReader(mInputFileName));
Writer output = new BufferedWriter(new FileWriter(mOutputFileName));
int cases = scanner.nextInt();
for (int i = 1; i <= cases; i++) {
N = scanner.nextInt();
S = scanner.nextInt();
P = scanner.nextInt();
mScores = new int[N];
for (int j = 0; j < N; j++) {
mScores[j] = scanner.nextInt();
}
System.out.println("CASE: " + i + " / " + cases);
if (i > 1) output.write("\n");
output.write("Case #" + i + ": ");
output.write(getAnswer());
}
output.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (scanner != null) scanner.close();
}
System.out.println("TIME: " + (System.currentTimeMillis() - start));
}
private String getAnswer() {
int res = 0;
for (int j = 0; j < N; j++) {
int score = mScores[j];
int q = score / 3;
int r = score % 3;
int noSup = q;
int sup = q;
if (score > 0) {
switch (r) {
case 0:
sup++;
break;
case 1:
noSup++;
sup++;
break;
case 2:
noSup++;
sup += 2;
break;
}
}
if (noSup >= P) {
res++;
} else if (S > 0 && sup >= P) {
res++;
S--;
}
}
//System.out.println(res);
return "" + res;
}
public static void main(String[] args) {
String fileName = "test";
String extension = ".txt";
String outputSuffix = "_output";
new DancingWithTheGooglers(fileName + extension,
fileName + outputSuffix + extension).solve();
}
}
|
A12544 | A10814 | 0 | package problem1;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
public class Problem1 {
public static void main(String[] args) throws FileNotFoundException, IOException{
try {
TextIO.readFile("L:\\Coodejam\\Input\\Input.txt");
}
catch (IllegalArgumentException e) {
System.out.println("Can't open file ");
System.exit(0);
}
FileOutputStream fout = new FileOutputStream("L:\\Coodejam\\Output\\output.txt");
PrintStream ps=new PrintStream(fout);
int cases=TextIO.getInt();
int googlers=0,surprising=0,least=0;
for(int i=0;i<cases;i++){
int counter=0;
googlers=TextIO.getInt();
surprising=TextIO.getInt();
least=TextIO.getInt();
int score[]=new int[googlers];
for(int j=0;j<googlers;j++){
score[j]=TextIO.getInt();
}
Arrays.sort(score);
int temp=0;
int sup[]=new int[surprising];
for(int j=0;j<googlers && surprising>0;j++){
if(biggestNS(score[j])<least && biggestS(score[j])==least){
surprising--;
counter++;
}
}
for(int j=0;j<googlers;j++){
if(surprising==0)temp=biggestNS(score[j]);
else {
temp=biggestS(score[j]);
surprising--;
}
if(temp>=least)counter++;
}
ps.println("Case #"+(i+1)+": "+counter);
}
}
static int biggestNS(int x){
if(x==0)return 0;
if(x==1)return 1;
return ((x-1)/3)+1;
}
static int biggestS(int x){
if(x==0)return 0;
if(x==1)return 1;
return ((x-2)/3)+2;
}
} | import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Scores
{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(new File("B-small-attempt0.in"));
FileWriter strm = new FileWriter("out2.txt");
BufferedWriter out = new BufferedWriter(strm);
int cases = scan.nextInt();
scan.nextLine();
int count = 1;
while(count - 1 < cases)
{
int n = scan.nextInt();
int s = scan.nextInt();
int p = scan.nextInt();
int[] tots = new int[n];
for(int i = 0;i<n;i++)
{
tots[i] = scan.nextInt();
}
out.write("Case #" + count + ": " + calc(s,p,tots) + "\n");
count++;
}
out.close();
}
private static int calc(int s, int p, int[] tots)
{
Arrays.sort(tots);
int surp = 0;
int max = 0;
for(int i = 0;i<tots.length;i++)
{
if(possible(p,tots[i]))
{
boolean surprise = surp(p,tots[i]);
if(surprise)
surp++;
if(surp<=s || !surprise)
max++;
}
}
return max;
}
private static boolean possible(int max, int total)
{
if(max == 0)
return true;
if(total / max >= 3.0)
return true;
if(total < max)
return false;
total -= max;
return Math.abs(total / 2.0 - max) <= 2.0;
}
private static boolean surp(int max, int total)
{
if(max == 0)
return false;
if(total / max >= 3.0)
return false;
total -= max;
return Math.abs(total / 2.0 - max) >= 1.5;
}
}
|
A11201 | A11212 | 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.ArrayList;
public class DancingWG{
public static void main(String[] args){
ArrayList<String> inputs = IOGoogleCodeJam.fileInput(args[0]);
ArrayList<String> outputs= new ArrayList<String>();
int lines=Integer.parseInt(inputs.get(0));
for(int i=1;i<=lines;i++){
outputs.add(processData(inputs.get(i)));
}
IOGoogleCodeJam.resultsOutput(outputs,1);
}
public static String processData(String s){
String aux[] = s.split(" ");
int N = Integer.parseInt(aux[0]);
int S = Integer.parseInt(aux[1]);
int p = Integer.parseInt(aux[2]);
int c = 0; //count googlers
for(int i=3;i<aux.length;i++){
int x = Integer.parseInt(aux[i]);
int y = 0;
switch(x%3){
case 0: y=x/3;
if(y>=p){
c++;
}else if(y>0){//if 0 reach here, it doesn't count
y=(x+3)/3;
if(y<=10 && y>=p && S>0){
c++;
S--;
}
}
break;
case 1: y=(x+2)/3;
if(y>=p){
c++;//I dont care if there's a surprise here
}
break;
case 2: y=(x+1)/3;
if(y>=p){
c++;
}else{
y=(x+4)/3;
if(y<=10 && y>=p && S>0){
c++;
S--;
}
}
break;
}
}
return String.valueOf(c);
}
}
|
B20006 | B20590 | 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 be.mokarea.gcj.common;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.Writer;
public abstract class GoogleCodeJamBase<T extends TestCase> {
protected abstract Transformation<T> createTransformation(TestCaseReader<T> testCaseReader, PrintWriter outputWriter) throws Exception;
protected abstract String getOutputFileName() throws Exception;
protected abstract TestCaseReader<T> getTestCaseReader() throws Exception;
public void execute() {
try {
PrintWriter outputWriter = null;
try {
outputWriter = new PrintWriter(new FileWriter(getOutputFileName()));
Transformation<T> transformation = createTransformation(getTestCaseReader(),outputWriter);
transformation.transformAll();
outputWriter.flush();
} finally {
closeQuietly(outputWriter);
}
} catch (Throwable t) {
t.printStackTrace();
}
}
private void closeQuietly(Writer outputWriter) {
if (outputWriter != null) {
try {
outputWriter.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
|
A12846 | A10540 | 0 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package codejam.common;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Lance Chen
*/
public class CodeHelper {
private static String FILE_ROOT = "D:/workspace/googlecodejam/meta";
public static List<List<String>> loadInputsExcludes(String fileName) {
List<List<String>> result = new ArrayList<List<String>>();
List<String> lines = FileUtil.readLines(FILE_ROOT + fileName);
int index = 0;
for (String line : lines) {
if (index == 0) {
index++;
continue;
}
if (index % 2 == 1) {
index++;
continue;
}
List<String> dataList = new ArrayList<String>();
String[] dataArray = line.split("\\s+");
for (String data : dataArray) {
if (data.trim().length() > 0) {
dataList.add(data);
}
}
result.add(dataList);
index++;
}
return result;
}
public static List<List<String>> loadInputs(String fileName) {
List<List<String>> result = new ArrayList<List<String>>();
List<String> lines = FileUtil.readLines(FILE_ROOT + fileName);
for (String line : lines) {
List<String> dataList = new ArrayList<String>();
String[] dataArray = line.split("\\s+");
for (String data : dataArray) {
if (data.trim().length() > 0) {
dataList.add(data);
}
}
result.add(dataList);
}
return result;
}
public static List<String> loadInputLines(String fileName) {
return FileUtil.readLines(FILE_ROOT + fileName);
}
public static void writeOutputs(String fileName, List<String> lines) {
FileUtil.writeLines(FILE_ROOT + fileName, lines);
}
}
| import java.util.*;
import java.io.*;
public class DancingGooglers {
private static int numTest;
private static Scanner input;
private static PrintWriter output;
public static void main(String[] args) throws FileNotFoundException, IOException {
// Initialization of Input/Output streams
input = new Scanner(new File(args[0]));
output = new PrintWriter(new File("output"));
// Reads char by char the input dimension
numTest = input.nextInt();
input.nextLine(); // reads the \n character
// Solves the problem
for(int i = 1; i <= numTest; i++) {
output.print("Case #" + i + ": ");
// N, the number of Googlers
int n = input.nextInt();
// System.err.println(i + " N: " + n);
// S, the number of surprising triplets of scores
int s = input.nextInt();
// System.err.println(i + " S: " + s);
// p, the value of the best result for a googler
int p = input.nextInt();
// System.err.println(i + " P: " + p);
// y is the maximum number of Googlers who could have had a best result of greater than or equal to p.
int y = 0;
for(int j = 0; j < n; j++) {
int totalScore = input.nextInt();
int remainder = totalScore - 3 * p;
if(remainder >= 0 || ((p - 1) >= 0 && remainder >= -2))
y++;
else if(((p - 2) >= 0 && remainder >= -4) && s > 0) {
y++;
s--;
}
// System.err.println(i + " Y: " + y);
}
output.println(y);
if(input.hasNextLine())
input.nextLine();
}
output.flush();
}
} |
B12762 | B13124 | 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.util.HashSet;
import java.util.Scanner;
public class RecycledNumbers
{
public static void main(String[] args) {
Scanner mark = new Scanner(System.in);
int t = mark.nextInt();
int A, B, counter;
mark.nextLine();
for (int i = 0; i < t; i++)
{
A = mark.nextInt();
B = mark.nextInt();
counter = 0;
mark.nextLine();
// This is for N
for (int n = A; n < B; n++)
{
HashSet<Integer> ans = new HashSet<Integer>();
String strval = String.valueOf(n).trim();
int count = strval.length();
for (int j = 1; j < count; j++)
{
String beg = strval.substring(0, j);
String end = strval.substring(j);
// System.out.println(beg+end+" "+end+beg);
int m = Integer.parseInt( end.concat(beg) );
if( (m > n) && (m <= B))
ans.add(m);
}
counter += ans.size();
}
System.out.printf("Case #%d: %d\n",i+1,counter);
}
}
}
|
B20424 | B20973 | 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);
}
}
}
| /*
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();
}
}
|
B10361 | B11993 | 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.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class C {
C() {
Scanner in=new Scanner(System.in);
for (int T=in.nextInt(),TC=1; T-->0; ++TC) {
int A=in.nextInt(),B=in.nextInt();
int cnt=0;
for (int m=2; m<=B; ++m)
cnt+=count(A,m);
System.out.printf("Case #%d: %d%n", TC,cnt);
}
}
int count(int A, int m) {
String s = Integer.toString(m); // 345
Set<Integer> set=new TreeSet<Integer>();
for (int i=1; i<s.length(); ++i) {
if (s.charAt(i)!='0') {
String t = s.substring(i)+s.substring(0,i);
int n = new Integer(t);
if (A<=n && n<m)
set.add(n);
}
}
return set.size();
}
public static void main(String[] args) {
new C();
}
}
|
A20119 | A20999 | 0 | package code12.qualification;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class B {
public static String solve(int N, int S, int p, int[] t) {
// 3a -> (a, a, a), *(a - 1, a, a + 1)
// 3a + 1 -> (a, a, a + 1), *(a - 1, a + 1, a + 1)
// 3a + 2 -> (a, a + 1, a + 1), *(a, a, a + 2)
int numPNoS = 0;
int numPWithS = 0;
for (int i = 0; i < N; i++) {
int a = (int)Math.floor(t[i] / 3);
int r = t[i] % 3;
switch (r) {
case 0:
if (a >= p) {
numPNoS++;
} else if (a + 1 >= p && a - 1 >= 0) {
numPWithS++;
}
break;
case 1:
if (a >= p || a + 1 >= p) {
numPNoS++;
}
break;
case 2:
if (a >= p || a + 1 >= p) {
numPNoS++;
} else if (a + 2 >= p) {
numPWithS++;
}
break;
}
}
return "" + (numPNoS + Math.min(S, numPWithS));
}
public static void main(String[] args) throws Exception {
// file name
//String fileName = "Sample";
//String fileName = "B-small";
String fileName = "B-large";
// file variable
File inputFile = new File(fileName + ".in");
File outputFile = new File(fileName + ".out");
Scanner scanner = new Scanner(inputFile);
FileWriter writer = new FileWriter(outputFile);
// problem variable
int totalCase;
int N, S, p;
int[] t;
// get total case
totalCase = scanner.nextInt();
for (int caseIndex = 1; caseIndex <= totalCase; caseIndex++) {
// get input
N = scanner.nextInt();
S = scanner.nextInt();
p = scanner.nextInt();
t = new int[N];
for (int i = 0; i < N; i++) {
t[i] = scanner.nextInt();
}
String output = "Case #" + caseIndex + ": " + solve(N, S, p, t);
System.out.println(output);
writer.write(output + "\n");
}
scanner.close();
writer.close();
}
}
| package fixjava;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Get the index of the given key if this key has been assigned an index before, and if not, allocate a new index for it by
* incrementing a counter that starts at zero, and return the new index.
*/
public class UniqueIndexAllocator<T> {
private HashMap<T, Integer> map = new HashMap<T, Integer>();
private ArrayList<T> orderedKeys = new ArrayList<T>();
public UniqueIndexAllocator() {
}
/** Allocate unique indices for each item in the given collection. Read back the indices using the other methods. */
public UniqueIndexAllocator(Iterable<T> collection) {
for (T it : collection)
getOrAllocateIndex(it);
}
/** Get the assigned index for a key, or assign it a new unique index if this key has not previously been assigned an index */
public int getOrAllocateIndex(T key) {
Integer currIdx = map.get(key);
if (currIdx == null) {
map.put(key, currIdx = orderedKeys.size());
orderedKeys.add(key);
}
return currIdx;
}
/** Get all the keys as a list in their index order */
public ArrayList<T> getOrderedKeys() {
return orderedKeys;
}
/** Get all the keys as an array in their index order */
@SuppressWarnings("unchecked")
public T[] getOrderedKeysAsArray() {
return (T[]) orderedKeys.toArray();
}
/** Get the mapping from key to index */
public HashMap<T, Integer> getKeyToIndexMap() {
return map;
}
/** Return the number of allocated indices, i.e. the number of unique keys */
public int numIndices() {
return orderedKeys.size();
}
}
|
B12115 | B12826 | 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.*;
import java.util.*;
public class Cre
{
public static void main(String args[])throws FileNotFoundException,IOException
{
RandomAccessFile in=new RandomAccessFile("C-small-attempt0.in","r");
FileOutputStream out= new FileOutputStream("out.txt");
int o=Integer.parseInt(in.readLine());
int j=0;
String str[]=new String[o+1];
int res[]=new int[o];
while((str[j]=in.readLine())!=null)
{
String []nos=str[j].split(" ");
int a=Integer.parseInt(nos[0]);
int b=Integer.parseInt(nos[1]);
int []t=new int[b-a+1];
int m;
for(int i=a,k=0;i<=b;i++,k++)t[k]=i;
for(int i=0;i<t.length;i++)
{
String st=t[i]+"";
char ch[]=st.toCharArray();
ArrayList got=new ArrayList();
int g;
for(int c=0;c<ch.length;c++)
{
m=shift(ch);
int flag=1;
Iterator it=got.iterator();
while(it.hasNext())
{
Integer inf=(Integer)it.next();
g=inf.intValue();
if(g==m) flag=0;
}
if(m!=t[i]&&flag==1)
{
got.add(m);
for(int l=i+1;l<t.length;l++)
{
if(m==t[l])
{
System.out.println(t[i]);
res[j]++;
}
}
}
}
}
j++;
}
for(int i=0;i<o;i++)
{
out.write(("Case #"+(i+1)+": "+res[i]+"\n").getBytes());
}
}
static int shift(char[] ch)
{
char temp=ch[ch.length-1];
for(int i=ch.length-1;i>0;i--)
{
ch[i]=ch[i-1];
}
ch[0]=temp;
String st=new String(ch);
return Integer.parseInt(st);
}
} |
B10231 | B12031 | 0 | import java.io.*;
class code1
{
public static void main(String args[]) throws Exception
{
File ii = new File ("C-small-attempt1.in");
FileInputStream fis = new FileInputStream(ii);
BufferedReader br = new BufferedReader(new InputStreamReader (fis));
int cases = Integer.parseInt(br.readLine());
FileOutputStream fout = new FileOutputStream ("output.txt");
DataOutputStream dout = new DataOutputStream (fout);
int total=0;
for(int i=0;i<cases;i++){
String temp = br.readLine();
String parts [] = temp.split(" ");
int lower = Integer.parseInt(parts[0]);
int upper = Integer.parseInt(parts[1]);
System.out.println(lower+" "+upper);
for(int j=lower;j<=upper;j++)
{
int abc = j;int length=0;
if(j<10)continue;
while (abc!=0){abc/=10;length++;}
abc=j;
for(int m=0;m<length-1;m++){
int shift = abc%10;
abc=abc/10;
System.out.println("hi "+j);
abc=abc+shift*power(10,length-1);
if(abc<=upper&&shift!=0&&abc>j)total++;
System.out.println(total);
}
}
dout.writeBytes("Case #"+(i+1)+ ": "+total+"\n");
total=0;
}//for close
}
private static int power(int i, int j) {
int no=1;
for(int a=0;a<j;a++){no=10*no;}
return no;
}
} | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class Prob3 {
public static void main(String[] args) throws NumberFormatException, IOException {
// String filePath = "C://Users//Apoorv//Desktop//test1.txt";
String filePath = "C://Users//Apoorv//Downloads//C-small-attempt0.in";
BufferedReader br2 = new BufferedReader(new InputStreamReader(
new DataInputStream(new FileInputStream(filePath))));
FileWriter fstream = new FileWriter(
"C://Users//Apoorv//Dropbox//Code//workspace//CodeJam//src//tempAnswer.txt");
BufferedWriter out = new BufferedWriter(fstream);
String str = null;
long count = 0;
Integer numCases = 0;
numCases = Integer.parseInt(br2.readLine());
for (int curCase = 0; curCase < numCases; curCase++) {
System.out.print("Case #" + (curCase + 1) + ": ");
out.write("Case #" + (curCase + 1) + ": ");
str = br2.readLine();
String[] tokens = str.split(" ");
int num1 = Integer.parseInt(tokens[0]);
int num2= Integer.parseInt(tokens[1]);
int curLength = getLength(num1);
int countOfPossibilities=0;
for (Integer curNumber = num1;curNumber<num2;curNumber++){
String numString1 = curNumber.toString();
char[] charArray1 = numString1 .toCharArray();
for(int curIteration = curLength;curIteration>1;curIteration--){
char[] charArrayBuilding = new char[charArray1.length];
for(int i=0;i<curLength;i++){
charArrayBuilding[i] = charArray1[(curIteration-1+i) % (curLength)];
}
StringBuilder g = new StringBuilder();
for(int i=0;i<charArrayBuilding.length;i++){
// System.out.print(charArrayBuilding[i]);
g.append(charArrayBuilding[i]);
}
// System.out.print(",");
int newNumber=Integer.parseInt(g.toString());
if(newNumber>curNumber && newNumber<=num2 && getLength(newNumber)==curLength){
countOfPossibilities++;
System.out.print(newNumber + ",");
// out.write(newNumber + ",");
}
}
}
System.out.println(countOfPossibilities);
out.write(countOfPossibilities + "\n");
}
out.close();
}
private static int getLength(int num1) {
int exponent = 1;
while(true){
num1/=10;
if(num1==0){
return exponent;
}
else
exponent++;
}
}
}
|
B10155 | B12080 | 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 jp.funnything.competition.util;
import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.apache.commons.io.FileUtils;
public class CompetitionIO {
private final QuestionReader _reader;
private final AnswerWriter _writer;
/**
* Default constructor. Use latest "*.in" as input
*/
public CompetitionIO() {
this( null , null , null );
}
public CompetitionIO( final File input , final File output ) {
this( input , output , null );
}
public CompetitionIO( File input , File output , final String format ) {
if ( input == null ) {
for ( final File file : FileUtils.listFiles( new File( "." ) , new String[] { "in" } , false ) ) {
if ( input == null || file.lastModified() > input.lastModified() ) {
input = file;
}
}
if ( input == null ) {
throw new RuntimeException( "No *.in found" );
}
}
if ( output == null ) {
final String inPath = input.getPath();
if ( !inPath.endsWith( ".in" ) ) {
throw new IllegalArgumentException();
}
output = new File( inPath.replaceFirst( ".in$" , ".out" ) );
}
_reader = new QuestionReader( input );
_writer = new AnswerWriter( output , format );
}
public CompetitionIO( final String format ) {
this( null , null , format );
}
public void close() {
_reader.close();
_writer.close();
}
public String read() {
return _reader.read();
}
public BigDecimal[] readBigDecimals() {
return _reader.readBigDecimals();
}
public BigDecimal[] readBigDecimals( final String separator ) {
return _reader.readBigDecimals( separator );
}
public BigInteger[] readBigInts() {
return _reader.readBigInts();
}
public BigInteger[] readBigInts( final String separator ) {
return _reader.readBigInts( separator );
}
/**
* Read line as single integer
*/
public int readInt() {
return _reader.readInt();
}
/**
* Read line as multiple integer, separated by space
*/
public int[] readInts() {
return _reader.readInts();
}
/**
* Read line as multiple integer, separated by 'separator'
*/
public int[] readInts( final String separator ) {
return _reader.readInts( separator );
}
/**
* Read line as single integer
*/
public long readLong() {
return _reader.readLong();
}
/**
* Read line as multiple integer, separated by space
*/
public long[] readLongs() {
return _reader.readLongs();
}
/**
* Read line as multiple integer, separated by 'separator'
*/
public long[] readLongs( final String separator ) {
return _reader.readLongs( separator );
}
/**
* Read line as token list, separated by space
*/
public String[] readTokens() {
return _reader.readTokens();
}
/**
* Read line as token list, separated by 'separator'
*/
public String[] readTokens( final String separator ) {
return _reader.readTokens( separator );
}
public void write( final int questionNumber , final Object result ) {
_writer.write( questionNumber , result );
}
public void write( final int questionNumber , final String result ) {
_writer.write( questionNumber , result );
}
public void write( final int questionNumber , final String result , final boolean tee ) {
_writer.write( questionNumber , result , tee );
}
}
|
A13029 | A13095 | 0 | import java.util.List;
public class Case implements Runnable {
private int id;
private String output;
private int n;
private int s;
private int p;
private List<Integer> g;
public Case(int id) {
this.id = id;
}
public Case(int id, int n, int s, int p, List<Integer> g) {
super();
this.id = id;
this.n = n;
this.s = s;
this.p = p;
this.g = g;
}
public String solve() {
int res = 0;
for (int googler : g) {
int b = googler / 3;
boolean div = googler % 3 == 0;
if (b >= p) {
res++;
continue;
}
if (p == b+1) {
if (div && s > 0 && b > 0) {
res++;
s--;
continue;
}
if (!div) {
res++;
continue;
}
}
if (p == b+2) {
if (3*b+2 == googler && s > 0) {
res++;
s--;
}
}
}
return String.valueOf(res);
}
@Override
public void run() {
output = solve();
}
@Override
public String toString() {
return "Case #" + id + ": " + output;
}
} |
package codejam2;
import java.io.*;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
class FileReader
{
int T;
FileInputStream fstream;
DataInputStream in;
BufferedReader br;
FileReader()
{
try
{
fstream = new FileInputStream("B-small-attempt0.in");
in = new DataInputStream(fstream);
br = new BufferedReader(new InputStreamReader(in));
initializeT();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
private void initializeT()
{
String strLine;
try
{
strLine = br.readLine();
T=Integer.parseInt(strLine);
}
catch (IOException ex)
{
Logger.getLogger(FileReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
public int getT()
{
return T;
}
public String getNextLine()
{
String temp=null;
try
{
temp=br.readLine();
}
catch (IOException ex)
{
Logger.getLogger(FileReader.class.getName()).log(Level.SEVERE, null, ex);
}
return temp;
}
}
public class CodeJam2
{
public int findGooglers(int N,int S,int p,int[] scores)
{
int count=0;
for(int i=0;i<N;i++)
{
int temp=3*p-scores[i];
if(temp<=2)
++count;
else
{
if(S>0)
{
if(temp<=4)
{
if(scores[i]!=0)
{
++count;
--S;
}
}
}
}
}
return count;
}
public static void main(String[] args)
{
FileReader fr=new FileReader();
CodeJam2 cj=new CodeJam2();
FileWriter fstream;
try
{
fstream = new FileWriter("output.out");
BufferedWriter out = new BufferedWriter(fstream);
int T=fr.getT();
for(int i=0;i<T;i++)
{
String line=fr.getNextLine();
String buff[]=line.split(" ");
int N=Integer.parseInt(buff[0]);
int S=Integer.parseInt(buff[1]);
int p=Integer.parseInt(buff[2]);
int arr[]=new int[N];
for(int j=0;j<N;j++)
{
arr[j]=Integer.parseInt(buff[j+3]);
}
out.write("Case #"+(i+1)+": "+cj.findGooglers(N,S,p,arr));
out.write("\n");
out.flush();
}
}
catch(Exception ex)
{
}
}
}
|
B11327 | B12394 | 0 | package recycledNumbers;
public class OutputData {
private int[] Steps;
public int[] getSteps() {
return Steps;
}
public OutputData(int [] Steps){
this.Steps = Steps;
for(int i=0;i<this.Steps.length;i++){
System.out.println("Test "+(i+1)+": "+Steps[i]);
}
}
}
| package com.amyth.gc2012;
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.text.BreakIterator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ProblemC {
/**
* @param args
*/
private static HashMap<Integer,Integer> factorial = new HashMap<Integer, Integer>();
private final static String INPUT_DIR_NM = "./Input/2012/";
private final static String OUTPUT_DIR_NM = "./Output/2012/";
private static Integer totalTestCase;
private static ArrayList<ArrayList<Long>> dataList;
public static void main(String[] args) {
String fileName = args[0];
//Read and Create necessary data structures.
try {
readAndBuild(INPUT_DIR_NM + fileName);
}
catch (IOException e) {
e.printStackTrace();
}
//TODO Implement program logic
List<Integer> outputList = play();
//write in out file
try{
// Create file
FileWriter fstream = new FileWriter(OUTPUT_DIR_NM+args[0]+".out");
BufferedWriter out = new BufferedWriter(fstream);
for (int caseId = 0; caseId < totalTestCase; caseId++) {
System.out.print("Case #" + (caseId+1) + ": ");
System.out.println(outputList.get(caseId));
out.write("Case #" + (caseId+1) + ": ");
out.write(outputList.get(caseId)+"");
if(caseId != totalTestCase)
out.newLine();
}
// Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
private static List<Integer> play() {
List<Integer> outList = new ArrayList<Integer>(totalTestCase);
for (int caseId = 0; caseId < totalTestCase; caseId++) {
List<Long> testList = dataList.get(caseId);
Long lRanger = testList.get(0);
Long hRange = testList.get(1);
int count = 0;
List<Long> backupList = new ArrayList<Long>();
for(long lRange = lRanger;lRange<=hRange;lRange++){
String str = String.valueOf(lRange);
int length = str.length();
backupList=new ArrayList<Long>();
for(int i=0;i<(length-1);i++){
Long valCounter = (long) (Math.pow(10,(i+1)));
int lastValue = (int) (lRange%valCounter);
// System.out.println("lRange: "+lRange);
Long lcounter = (long) Math.pow(10, (length-(i+1)));
int hFirstValue = (int) (hRange/valCounter);
if(((lastValue*lcounter) > hRange) ||
(lRanger > (lastValue*lcounter))
){
continue;
}else{
Long number = (long) (lastValue*(lcounter));
number += (lRange/valCounter);
if((number >= lRanger)&&(number > lRange) && (number <=hRange)){
if(backupList != null && !backupList.isEmpty()){
if(!backupList.contains(number)){
// System.out.println("oldNumber :"+lRange+" newNumber: "+number);
count++;
}
}else{
backupList.add(number);
// System.out.println("oldNumber :"+lRange+" newNumber: "+number);
count++;
}
}
}
}
/*Long lcounter = (long) Math.pow(10, length);
Long rcounter = (long) 10;*/
}
outList.add(caseId,count);
}
return outList;
}
//Build input data structure
private static void readAndBuild(String dataPath) throws IOException {
File f = new File(dataPath);
BufferedReader bf = new BufferedReader(new FileReader(f));
String text = bf.readLine();
if (text != null) {
// first text will be number of test cases
totalTestCase = Integer.valueOf(text);
dataList = new ArrayList<ArrayList<Long>>(totalTestCase);
ArrayList<Long> testObj = null;
do {
text = bf.readLine();
if (text != null) {
BreakIterator bi = BreakIterator.getWordInstance();
bi.setText(text);
testObj = new ArrayList<Long>(2);
dataList.add(testObj);
Long N = Long.valueOf(text.substring(0, bi.next()));
testObj.add(N);
Long Pd = Long.valueOf(text.substring(bi.next(), bi.next()));
testObj.add(Pd);
}
}while (text != null && !text.equals(""));
}
}
private static int getFactorial(int length) {
if(factorial.containsKey(length))
return factorial.get(length);
return length*getFactorial(length-1);
}
}
|
B12074 | B10017 | 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.*;
import java.util.*;
import java.math.*;
public class Main
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer=null;
public static void main(String[] args) throws IOException
{
new Main().execute();
}
void debug(Object...os)
{
System.out.println(Arrays.deepToString(os));
}
int ni() throws IOException
{
return Integer.parseInt(ns());
}
long nl() throws IOException
{
return Long.parseLong(ns());
}
double nd() throws IOException
{
return Double.parseDouble(ns());
}
String ns() throws IOException
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(br.readLine());
return tokenizer.nextToken();
}
String nline() throws IOException
{
tokenizer=null;
return br.readLine();
}
//Main Code starts Here
int totalCases, testNum;
void execute() throws IOException
{
totalCases = ni();
for(testNum = 1; testNum <= totalCases; testNum++)
{
input();
System.out.print("Case #"+testNum+": ");
solve();
}
}
void solve()
{
long count = 0;
for(int i =a;i<=b;i++)
for(int j =a;j<=b;j++)
{
if(i<=j)
continue;
String x = Integer.toString(i);
String y = Integer.toString(j);
if(x.length()==y.length())
{
x = x+x;
if(x.contains(y))
count++;
}
}
System.out.println(count);
}
void printarr(int [] a,int b)
{
for(int i = 0;i<=b;i++)
{
if(i==0)
System.out.print(a[i]);
else
System.out.print(" "+a[i]);
}
System.out.println();
}
int a,b;
boolean input() throws IOException
{
a=ni();
b=ni();
return true;
}
} |
A20934 | A21422 | 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.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.Buffer;
import java.util.Arrays;
import java.util.Scanner;
public class DancingWithGooglers {
public static void main(String[] args) throws Exception {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("/home/xnike/Downloads/B-large.out"));
Scanner scanner = new Scanner(new File("/home/xnike/Downloads/B-large.in"));
int t = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < t; i++) {
int n = scanner.nextInt(), s = scanner.nextInt(), p = scanner.nextInt();
int[] ti = new int[n];
for (int j = 0; j < n; j++) {
ti[j] = scanner.nextInt();
}
scanner.nextLine();
Arrays.sort(ti);
int num = 0;
for (int k = ti.length - 1; k > -1; k--) {
int min = ti[k] / 3, max = ti[k] - 2 * (ti[k] / 3);
if (0 == max - min && 2 < ti[k]) {
max++;
min--;
}
if (max >= p) {
if (max == p && (2 == max - min)) {
if (0 < s) {
s--;
num++;
}
} else {
num++;
}
}
}
bufferedWriter.write("Case #" + (i + 1) + ": " + num + "\n");
}
bufferedWriter.flush();
}
}
|
A11277 | A11328 | 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.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class Tools<T>
{
public static ArrayList<String[]> getInput(String filename) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(filename));
ArrayList<String[]> output = new ArrayList<String[]>();
String line;
while ((line = br.readLine()) != null)
output.add(line.split(" "));
br.close();
return output;
}
public static ArrayList<String> getInputSingle(String filename) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(filename));
ArrayList<String> output = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null)
output.add(line);
br.close();
return output;
}
public static void saveOutput(String filename, ArrayList<String[]> output) throws IOException
{
BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
for(int i=0; i<output.size();i++)
{
if(i!=0) bw.newLine();
for(int j=0;j<output.get(i).length;j++)
{
if(j!=0) bw.write(" ");
bw.write(output.get(i)[j]);
}
}
bw.close();
}
public static void saveOutputSingle(String filename, ArrayList<String> output) throws IOException
{
BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
for(int i=0; i<output.size();i++)
{
if(i!=0) bw.newLine();
bw.write(output.get(i));
}
bw.close();
}
}
|
A11201 | A11819 | 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);
}
}
}
|
class Triplets
{
int oldscore[] = new int[3];
int score[] = new int[3];
int totalScore;
int first, second;
public Triplets(int a, int b, int c)
{
oldscore[0] = score[0] = a;
oldscore[1] = score[1] = b;
oldscore[2] = score[2] = c;
totalScore = a + b + c;
}
public void display()
{
System.out.println("(" + score[0] + ", " + score[1] + ", " + score[2] + ")");
}
public int getMaxScore()
{
int max = score[0];
for(int i=1; i<score.length; i++)
if(score[i] > max)
max = score[i];
return max;
}
public int getMinScore()
{
int min = score[0];
for(int i=1; i<score.length; i++)
if(score[i] < min)
min = score[i];
return min;
}
public boolean isSurprising()
{
int max = getMaxScore();
int min = getMinScore();
return ((max - min) == 2);
}
public boolean canBeConverted()
{
for(int i=0; i<score.length - 1; i++)
{
for(int j=i+1; j<score.length; j++)
{
if(score[i] == score[j] && score[i] != 0)
{
first = i;
second = j;
return true;
}
}
}
return false;
}
public Triplets converted()
{
Triplets convertedTriplet = new Triplets(score[0], score[1], score[2]);
convertedTriplet.score[first]++;
convertedTriplet.score[second]--;
return convertedTriplet;
}
} |
B12082 | B10730 | 0 | package jp.funnything.competition.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.apache.commons.io.IOUtils;
public class QuestionReader {
private final BufferedReader _reader;
public QuestionReader( final File input ) {
try {
_reader = new BufferedReader( new FileReader( input ) );
} catch ( final FileNotFoundException e ) {
throw new RuntimeException( e );
}
}
public void close() {
IOUtils.closeQuietly( _reader );
}
public String read() {
try {
return _reader.readLine();
} catch ( final IOException e ) {
throw new RuntimeException( e );
}
}
public BigDecimal[] readBigDecimals() {
return readBigDecimals( " " );
}
public BigDecimal[] readBigDecimals( final String separator ) {
final String[] tokens = readTokens( separator );
final BigDecimal[] values = new BigDecimal[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = new BigDecimal( tokens[ index ] );
}
return values;
}
public BigInteger[] readBigInts() {
return readBigInts( " " );
}
public BigInteger[] readBigInts( final String separator ) {
final String[] tokens = readTokens( separator );
final BigInteger[] values = new BigInteger[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = new BigInteger( tokens[ index ] );
}
return values;
}
public int readInt() {
final int[] values = readInts();
if ( values.length != 1 ) {
throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" );
}
return values[ 0 ];
}
public int[] readInts() {
return readInts( " " );
}
public int[] readInts( final String separator ) {
final String[] tokens = readTokens( separator );
final int[] values = new int[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = Integer.parseInt( tokens[ index ] );
}
return values;
}
public long readLong() {
final long[] values = readLongs();
if ( values.length != 1 ) {
throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" );
}
return values[ 0 ];
}
public long[] readLongs() {
return readLongs( " " );
}
public long[] readLongs( final String separator ) {
final String[] tokens = readTokens( separator );
final long[] values = new long[ tokens.length ];
for ( int index = 0 ; index < tokens.length ; index++ ) {
values[ index ] = Long.parseLong( tokens[ index ] );
}
return values;
}
public String[] readTokens() {
return readTokens( " " );
}
public String[] readTokens( final String separator ) {
return read().split( separator );
}
}
| package com.google.codejam;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import javax.sound.sampled.DataLine;
public class RecycleNumber {
/**
* @param args
*/
public static void main(String[] args) {
recycleNumbers(args[0]);
// System.out.println("No. of recycled possibilities: " + recycleNumber("128 986"));
}
private static void recycleNumbers(String fileName) {
File f = new File(fileName);
BufferedReader fin;
try {
fin = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
int noOfInputs = Integer.valueOf(fin.readLine());
String[] inputs = readSamplesFromFile(noOfInputs, fin);
BufferedWriter fout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/Users/asachwani/Desktop/CodeJam/Output.txt")));
for (int i = 0; i < noOfInputs; i++) {
System.out.println(i + 1 + " " + inputs[i]);
fout.write("Case #" + (i + 1) + ": " + recycleNumber(inputs[i]) + "\n");
}
fout.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static int recycleNumber(String input) {
String[] data = input.split(" ");
int minValue = Integer.valueOf(data[0]);
int maxValue = Integer.valueOf(data[1]);
int noOfPossibilities = 0;
char[] minValueChar = String.valueOf(minValue).toCharArray();
HashSet<String> uniquePairs = new HashSet<String>();
if (minValueChar.length > 1) {
for (int j = 0; j < minValueChar.length - 1; j++) {
for (int k = minValue; k < maxValue; k++) {
int lastDigits = k % (int) Math.pow(10, j + 1);
int firstDigits = k / (int) Math.pow(10, j + 1);
int replacement = 0;
if (lastDigits != firstDigits) {
replacement = Integer.valueOf("" + lastDigits + firstDigits);
}
if (replacement > k && replacement <= maxValue) {
if (!uniquePairs.contains(k + " " + replacement) || uniquePairs.contains(replacement + " " + k)) {
noOfPossibilities++;
uniquePairs.add(k + " " + replacement);
System.out.println(k + " " + j + " " + lastDigits + " " + firstDigits + " " + replacement);
}
}
}
}
}
return noOfPossibilities;
}
private static String[] readSamplesFromFile(int noOfInputs, BufferedReader fin) throws IOException {
String[] samples = new String[noOfInputs];
for (int i = 0; i < noOfInputs; i++) {
samples[i] = fin.readLine();
}
return samples;
}
}
|
B12762 | B12699 | 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 gcj12;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class C {
void solve() {
Scanner scan = new Scanner(System.in);
int tCase = scan.nextInt();
for (int i = 1; i <= tCase; i++) {
int res = 0;
int a = scan.nextInt();
int b = scan.nextInt();
for (int j = a; j <= b; j++) {
int pow = 10;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
while (j / pow > 0) {
int tmp = Integer.valueOf((j % pow) + "" + (j / pow));
if (tmp > j && tmp <= b && map.get(tmp) == null) {
map.put(tmp, tmp);
res++;
}
pow *= 10;
}
}
System.out.println("Case #" + i + ": " + res);
}
}
public static void main(String[] args) {
new C().solve();
}
}
|
A22191 | A22790 | 0 | package com.example;
import java.io.IOException;
import java.util.List;
public class ProblemB {
enum Result {
INSUFFICIENT,
SUFFICIENT,
SUFFICIENT_WHEN_SURPRISING
}
public static void main(String[] a) throws IOException {
List<String> lines = FileUtil.getLines("/B-large.in");
int cases = Integer.valueOf(lines.get(0));
for(int c=0; c<cases; c++) {
String[] tokens = lines.get(c+1).split(" ");
int n = Integer.valueOf(tokens[0]); // N = number of Googlers
int s = Integer.valueOf(tokens[1]); // S = number of surprising triplets
int p = Integer.valueOf(tokens[2]); // P = __at least__ a score of P
int sumSufficient = 0;
int sumSufficientSurprising = 0;
for(int i=0; i<n; i++) {
int points = Integer.valueOf(tokens[3+i]);
switch(test(points, p)) {
case SUFFICIENT:
sumSufficient++;
break;
case SUFFICIENT_WHEN_SURPRISING:
sumSufficientSurprising++;
break;
}
// uSystem.out.println("points "+ points +" ? "+ p +" => "+ result);
}
System.out.println("Case #"+ (c+1) +": "+ (sumSufficient + Math.min(s, sumSufficientSurprising)));
// System.out.println();
// System.out.println("N="+ n +", S="+ s +", P="+ p);
// System.out.println();
}
}
private static Result test(int n, int p) {
int fac = n / 3;
int rem = n % 3;
if(rem == 0) {
// int triplet0[] = { fac, fac, fac };
// print(n, triplet0);
if(fac >= p) {
return Result.SUFFICIENT;
}
if(fac > 0 && fac < 10) {
if(fac+1 >= p) {
return Result.SUFFICIENT_WHEN_SURPRISING;
}
// int triplet1[] = { fac+1, fac, fac-1 }; // surprising
// print(n, triplet1);
}
} else if(rem == 1) {
// int triplet0[] = { fac+1, fac, fac };
// print(n, triplet0);
if(fac+1 >= p) {
return Result.SUFFICIENT;
}
// if(fac > 0 && fac < 10) {
// int triplet1[] = { fac+1, fac+1, fac-1 };
// print(n, triplet1);
// }
} else if(rem == 2) {
// int triplet0[] = { fac+1, fac+1, fac };
// print(n, triplet0);
if(fac+1 >= p) {
return Result.SUFFICIENT;
}
if(fac < 9) {
// int triplet1[] = { fac+2, fac, fac }; // surprising
// print(n, triplet1);
if(fac+2 >= p) {
return Result.SUFFICIENT_WHEN_SURPRISING;
}
}
} else {
throw new RuntimeException("error");
}
return Result.INSUFFICIENT;
// System.out.println();
// System.out.println(n +" => "+ div3 +" ("+ rem +")");
}
// private static void print(int n, int[] triplet) {
// System.out.println("n="+ n +" ("+ (n/3) +","+ (n%3) +") => ["+ triplet[0] +","+ triplet[1] +","+ triplet[2] +"]" + (triplet[0]-triplet[2] > 1 ? " *" : ""));
// }
}
| package google.loader;
import java.util.List;
public interface ChallengeReader {
List<Challenge> createChallenges(String[] lines);
}
|
B12085 | B12438 | 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.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Akash Agrawal
*/
public class RN {
public static boolean check(int n , int []arr)
{
for(int i=0;i<arr.length;i++)
{
if(n==arr[i])return false;
}
return true;
}
public static void main(String [] args) throws FileNotFoundException, IOException
{
Scanner scan= new Scanner(new File("Input.in"));
int n=scan.nextInt();
int cas=1;
while(n--!=0)
{
String s1 = scan.next() , s2 = scan.next();
int A=Integer.parseInt(s1);
int B=Integer.parseInt(s2);
//System.out.println(A+B);
int count = 0;
for(int i=A;i<B;i++)
{//System.out.println(i);
String temp = Integer.toString(i);
int ar[] = new int[s1.length()-1];
int ind=0;
for(int a=0;a<ar.length;a++)
{
ar[a]=-1;
}
for(int j=1;j<s1.length();j++)
{
String temps = temp.substring(j) + temp.substring(0,j);
int C=Integer.parseInt(temps);
//System.out.println(s1.substring(0,j));
if(C>i && C<=B && check(C,ar))
{
count++;
//System.out.println(i+" "+C);
ar[ind++]=C;
}
}
}
System.out.println("Case #"+cas+++": "+count);
}
}
}
|
B20424 | B22191 | 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.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* Problem
Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers.
Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros.
Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A ² n < m ² B?
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B.
Output
For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A ² n < m ² B.
Limits
1 ² T ² 50.
A and B have the same number of digits.
Small dataset
1 ² A ² B ² 1000.
Large dataset
1 ² A ² B ² 2000000.
Sample
Input
Output
4
1 9
10 40
100 500
1111 2222
Case #1: 0
Case #2: 3
Case #3: 156
Case #4: 287
Are we sure about the output to Case #4?
Yes, we're sure about the output to Case #4.
* @author andrey
*
*/
public class QCRecycledNumbers {
private static int[] INT_LENGTH = new int[] {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000};
public static void solve(BufferedReader reader, BufferedWriter writer) throws IOException {
int testCount = readIntFromLine(reader);
for (int test = 1; test <= testCount; test++) {
writer.append("Case #").append(Integer.toString(test)).append(": ");
solveTestCase(reader, writer);
writer.newLine();
}
writer.flush();
}
private static void solveTestCase(BufferedReader reader, BufferedWriter writer) throws IOException {
String[] testCase = reader.readLine().split("\\s");
int minValue = Integer.parseInt(testCase[0]);
int maxValue = Integer.parseInt(testCase[1]);
int length = testCase[0].length();
if (minValue >= maxValue) {
writer.append('0');
return;
}
int recycledCount = 0;
int recycledNumber;
int lowerPart;
int foundRecycledNumbersCount;
int[] foundRecycledNumbers = new int[length - 1];
for (int i = minValue; i < maxValue; i++) {
foundRecycledNumbersCount = 0;
for (int j=1; j < length; j++) {
lowerPart = i % INT_LENGTH[j];
if (lowerPart < INT_LENGTH[j - 1]) {
// can't rotate, because first digit in lowerPart is 0
continue;
}
recycledNumber = lowerPart*INT_LENGTH[length - j] + i/INT_LENGTH[j];
if (recycledNumber <= i || recycledNumber > maxValue) {
// recycled number exceeds limits
continue;
}
boolean duplicate = false;
for (int k=0; k < foundRecycledNumbersCount; k++) {
if (foundRecycledNumbers[k] == recycledNumber) {
duplicate = true;
break;
}
}
if (duplicate) {
continue; // such permutation already found
}
// if (foundRecycledNumbersCount == 0) {
// System.out.print(i + " -> ");
// }
// System.out.print(recycledNumber + ", ");
foundRecycledNumbers[foundRecycledNumbersCount++] = recycledNumber;
recycledCount++;
}
// if (foundRecycledNumbersCount > 0) {
// System.out.println();
// }
}
writer.append(Integer.toString(recycledCount));
}
public static void solve(String inputFile, String outputFile) throws IOException {
File input = new File(inputFile);
File output = new File(outputFile);
if (!input.exists()) {
throw new IllegalArgumentException("Input file doesn't exist: " + inputFile);
}
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(input));
writer = new BufferedWriter(new FileWriter(output));
solve(reader, writer);
} finally {
if (reader != null)
reader.close();
if (writer != null)
writer.close();
}
}
public static int readIntFromLine(BufferedReader reader) throws IOException {
String line = reader.readLine();
int testCount = Integer.parseInt(line);
return testCount;
}
public static void main(String[] args) throws IOException {
System.out.println("Start...");
solve("res/input.txt", "res/output.txt");
System.out.println("Done!");
}
}
|
A12544 | A10692 | 0 | package problem1;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
public class Problem1 {
public static void main(String[] args) throws FileNotFoundException, IOException{
try {
TextIO.readFile("L:\\Coodejam\\Input\\Input.txt");
}
catch (IllegalArgumentException e) {
System.out.println("Can't open file ");
System.exit(0);
}
FileOutputStream fout = new FileOutputStream("L:\\Coodejam\\Output\\output.txt");
PrintStream ps=new PrintStream(fout);
int cases=TextIO.getInt();
int googlers=0,surprising=0,least=0;
for(int i=0;i<cases;i++){
int counter=0;
googlers=TextIO.getInt();
surprising=TextIO.getInt();
least=TextIO.getInt();
int score[]=new int[googlers];
for(int j=0;j<googlers;j++){
score[j]=TextIO.getInt();
}
Arrays.sort(score);
int temp=0;
int sup[]=new int[surprising];
for(int j=0;j<googlers && surprising>0;j++){
if(biggestNS(score[j])<least && biggestS(score[j])==least){
surprising--;
counter++;
}
}
for(int j=0;j<googlers;j++){
if(surprising==0)temp=biggestNS(score[j]);
else {
temp=biggestS(score[j]);
surprising--;
}
if(temp>=least)counter++;
}
ps.println("Case #"+(i+1)+": "+counter);
}
}
static int biggestNS(int x){
if(x==0)return 0;
if(x==1)return 1;
return ((x-1)/3)+1;
}
static int biggestS(int x){
if(x==0)return 0;
if(x==1)return 1;
return ((x-2)/3)+2;
}
} | import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
public class Dancing {
public static void main(String [] args) throws NumberFormatException, IOException
{
BufferedReader in = new BufferedReader(new StringReader(args[0]));
int rows = Integer.parseInt(in.readLine());
for ( int i = 1; i <= rows; i++)
{
String line = in.readLine();
String[] vals = line.split(" ");
int googlers = Integer.parseInt(vals[0]);
int surprising = Integer.parseInt(vals[1]);
int score = Integer.parseInt(vals[2]);
int [] googlerScores = new int[googlers];
for ( int j = 0; j < googlerScores.length; j++)
{
googlerScores[j]=Integer.parseInt(vals[3+j]);
}
//System.out.println("Surprising: " + surprising);
int maxCount = 0;
for ( int j = 0; j < Math.pow(2, googlers); j++)
{
if ( instanceCount(j) == surprising )
{
//System.out.println("Case: " + Integer.toBinaryString(j));
int count = 0;
for ( int k = 0; k < googlers; k++ )
{
int pow = (int) Math.pow(2,k);
boolean normal = (pow & j) == 0;
//System.out.println(k+": "+ normal);
if ( normal && getBestRegularScore(googlerScores[k])>=score )
{
count++;
}
else if ( !normal && getBestSurprisingScore(googlerScores[k])>=score )
{
count++;
}
}
if ( count >= maxCount )
{
maxCount = count;
}
}
}
System.out.println("Case #"+i+": " + maxCount);
}
}
public static int instanceCount(int number)
{
int count = 0;
for ( char c : Integer.toString(number, 2).toCharArray() )
{
if ( c == '1' )
{
count++;
}
}
return count;
}
public static int getBestRegularScore(int totalScore)
{
int bestScore = totalScore/3;
if ( totalScore%3>0)
{
bestScore++;
}
return bestScore>10?10:bestScore;
}
public static int getBestSurprisingScore(int totalScore)
{
if ( totalScore == 0 )
{
return 0;
}
int ret = (totalScore+4)/3;
return ret>10?10:ret;
}
}
|