F1
stringlengths
6
6
F2
stringlengths
6
6
label
stringclasses
2 values
text_1
stringlengths
149
20.2k
text_2
stringlengths
48
42.7k
C20012
C20004
0
public class CGConst { public static final int INF = 99999999; public static final double EPS = 1e-9; public static final double pi = Math.PI; }
import java.util.*; public class D { public static boolean wall[][]; public static int X; public static int Y; public static int[] dxs; public static int[] dys; public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int c = 1; c <= T; c++){ int H = in.nextInt(); int W = in.nextInt(); int D = in.nextInt(); dxs = new int[4]; dys = new int[4]; dxs[0] = dxs[1] = 1; dxs[2] = dxs[3] = -1; dys[0] = dys[2] = 1; dys[1] = dys[3] = -1; wall = new boolean[H][W]; int mex, mey; mex = 0; mey = 0; in.nextLine(); for(int i = 0; i < H; i++){ String line = in.nextLine(); for(int j = 0; j < W; j++){ switch( line.charAt(j)){ case '#': wall[i][j] = true; break; case 'X': mex = j; mey = i; case '.': wall[i][j] = false; break; } } }//done reading input. int count = 0; //check NESW int nd = 1, ed = 1, sd = 1, wd = 1; while(!wall[mey][mex+ed]) ed++; while(!wall[mey][mex-wd]) wd++; while(!wall[mey+nd][mex]) nd++; while(!wall[mey-sd][mex]) sd++; if(2*ed-1 <= D) count++; if(2*wd-1 <= D) count++; if(2*sd-1 <= D) count++; if(2*nd-1 <= D) count++; for(int x = 1; x <= D; x++) for(int y = 1; y <= D; y++){ if(x*x + y*y > D*D) continue; for(int d = 0; d < 4; d++){ int posx = mex; int posy = mey; int dx = dxs[d]; int dy = dys[d]; boolean fail = false; int distx = 0; int disty = 0; for(int s = 1; s <= 2*x*y && !fail; s++){ distx += dx; disty += dy; //System.out.println("distx = " + distx +"; disty = " + disty); if(s < 2*x*y && distx == 0 && disty == 0) fail = true; if((s % x == 0) && ( (s/x) % 2 == 1) && (s % y == 0) && ( (s/y) % 2 == 1)){ if(!wall[posy + dy][posx + dx]){ posy += dy; posx += dx; }else if(wall[posy][posx + dx] && wall[posy + dy][posx]){ dx *= -1; dy *= -1; } else if(wall[posy][posx + dx]){ dx *= -1; posy += dy; } else if(wall[posy + dy][posx]){ posx += dx; dy *= -1; } else{ fail = true; } } else if((s % x == 0) && ( (s/x) % 2 == 1)){ if(wall[posy][posx + dx]) dx *= -1; else posx += dx; } else if((s % y == 0) && ( (s/y) % 2 == 1)){ if(wall[posy + dy][posx]) dy *= -1; else posy += dy; } } if(!fail && posx == mex && posy == mey){ //System.out.println("x = " + x +"; y = " + y); count++; } } } System.out.println("Case #" + c +": " + count); } } }
C20066
C20004
0
package jp.funnything.competition.util; import java.util.Comparator; import com.google.common.base.Objects; public class Pair< T1 , T2 > { public static < T1 extends Comparable< T1 > , T2 extends Comparable< T2 > > Comparator< Pair< T1 , T2 > > getFirstComarator() { return new Comparator< Pair< T1 , T2 > >() { @Override public int compare( final Pair< T1 , T2 > o1 , final Pair< T1 , T2 > o2 ) { final int c = o1.first.compareTo( o2.first ); return c != 0 ? c : o1.second.compareTo( o2.second ); } }; } public static < T1 extends Comparable< T1 > , T2 extends Comparable< T2 > > Comparator< Pair< T1 , T2 > > getSecondComarator() { return new Comparator< Pair< T1 , T2 > >() { @Override public int compare( final Pair< T1 , T2 > o1 , final Pair< T1 , T2 > o2 ) { final int c = o1.second.compareTo( o2.second ); return c != 0 ? c : o1.first.compareTo( o2.first ); } }; } public T1 first; public T2 second; public Pair( final Pair< T1 , T2 > that ) { this.first = that.first; this.second = that.second; } public Pair( final T1 first , final T2 second ) { this.first = first; this.second = second; } @Override public boolean equals( final Object obj ) { if ( this == obj ) { return true; } if ( obj == null || getClass() != obj.getClass() ) { return false; } final Pair< ? , ? > that = ( Pair< ? , ? > ) obj; return Objects.equal( this.first , that.first ) && Objects.equal( this.first , that.first ); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ( first == null ? 0 : first.hashCode() ); result = prime * result + ( second == null ? 0 : second.hashCode() ); return result; } @Override public String toString() { return "Pair [first=" + first + ", second=" + second + "]"; } }
import java.util.*; public class D { public static boolean wall[][]; public static int X; public static int Y; public static int[] dxs; public static int[] dys; public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int c = 1; c <= T; c++){ int H = in.nextInt(); int W = in.nextInt(); int D = in.nextInt(); dxs = new int[4]; dys = new int[4]; dxs[0] = dxs[1] = 1; dxs[2] = dxs[3] = -1; dys[0] = dys[2] = 1; dys[1] = dys[3] = -1; wall = new boolean[H][W]; int mex, mey; mex = 0; mey = 0; in.nextLine(); for(int i = 0; i < H; i++){ String line = in.nextLine(); for(int j = 0; j < W; j++){ switch( line.charAt(j)){ case '#': wall[i][j] = true; break; case 'X': mex = j; mey = i; case '.': wall[i][j] = false; break; } } }//done reading input. int count = 0; //check NESW int nd = 1, ed = 1, sd = 1, wd = 1; while(!wall[mey][mex+ed]) ed++; while(!wall[mey][mex-wd]) wd++; while(!wall[mey+nd][mex]) nd++; while(!wall[mey-sd][mex]) sd++; if(2*ed-1 <= D) count++; if(2*wd-1 <= D) count++; if(2*sd-1 <= D) count++; if(2*nd-1 <= D) count++; for(int x = 1; x <= D; x++) for(int y = 1; y <= D; y++){ if(x*x + y*y > D*D) continue; for(int d = 0; d < 4; d++){ int posx = mex; int posy = mey; int dx = dxs[d]; int dy = dys[d]; boolean fail = false; int distx = 0; int disty = 0; for(int s = 1; s <= 2*x*y && !fail; s++){ distx += dx; disty += dy; //System.out.println("distx = " + distx +"; disty = " + disty); if(s < 2*x*y && distx == 0 && disty == 0) fail = true; if((s % x == 0) && ( (s/x) % 2 == 1) && (s % y == 0) && ( (s/y) % 2 == 1)){ if(!wall[posy + dy][posx + dx]){ posy += dy; posx += dx; }else if(wall[posy][posx + dx] && wall[posy + dy][posx]){ dx *= -1; dy *= -1; } else if(wall[posy][posx + dx]){ dx *= -1; posy += dy; } else if(wall[posy + dy][posx]){ posx += dx; dy *= -1; } else{ fail = true; } } else if((s % x == 0) && ( (s/x) % 2 == 1)){ if(wall[posy][posx + dx]) dx *= -1; else posx += dx; } else if((s % y == 0) && ( (s/y) % 2 == 1)){ if(wall[posy + dy][posx]) dy *= -1; else posy += dy; } } if(!fail && posx == mex && posy == mey){ //System.out.println("x = " + x +"; y = " + y); count++; } } } System.out.println("Case #" + c +": " + count); } } }
C20068
C20051
0
package com.brootdev.gcj2012.common; import java.io.*; public class Data { public final BufferedReader in; public final PrintWriter out; public Data(String inFile, String outFile) throws IOException { in = new BufferedReader(new FileReader(inFile)); out = new PrintWriter(new BufferedWriter(new FileWriter(outFile))); } public int readIntLine() throws IOException { return DataUtils.readIntLine(in); } public long readLongLine() throws IOException { return DataUtils.readLongLine(in); } public int[] readIntsArrayLine() throws IOException { return DataUtils.readIntsArrayLine(in); } public long[] readLongsArrayLine() throws IOException { return DataUtils.readLongsArrayLine(in); } public void writeCaseHeader(long case_) { DataUtils.writeCaseHeader(out, case_); } }
package jp.funnything.competition.util; import java.util.List; import com.google.common.collect.Lists; public class Lists2 { public static < T > List< T > newArrayListAsArray( final int length ) { final List< T > list = Lists.newArrayListWithCapacity( length ); for ( int index = 0 ; index < length ; index++ ) { list.add( null ); } return list; } }
C20017
C20054
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package problem.d.hall.of.mirrors; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Scanner; /** * * @author Park */ public class ProblemDHallOfMirrors { static int fixD; static int count = 0; static int s_X=0;static int s_Y=0; /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { PrintStream out = new PrintStream(new File("/Users/Park/Desktop/output.txt")); Scanner in = new Scanner(new File("/Users/Park/Desktop/D-small-attempt1.in")); int testCase = Integer.parseInt(in.next()); for (int n = 0; n < testCase; n++) { int memCount = 0; int H = Integer.parseInt(in.next()); int W = Integer.parseInt(in.next()); int D = Integer.parseInt(in.next()); int fixH = (2 * H - 3); int fixW = (2 * W - 3); fixD = 2 * D; int h0 = 0; int w0 = 0; search: for (int i = 0; i < H; i++) { String subMap = in.next(); for (int j = 0; j < W; j++) { String X = subMap.substring(j, j + 1); if (X.equals("X")) { h0 = 2 * i - 1; w0 = 2 * j - 1; } } } int d_Left = w0; int d_Right = fixW - w0-1; int d_Up = h0; int d_Down = fixH - h0-1; double[] chkM = new double[250000]; count=0; //Right calculate(2*d_Right,0,d_Right,d_Up,d_Left,d_Down,chkM); memCount+=count; count=0; //Up calculate(2*d_Up,0,d_Up,d_Left,d_Down,d_Right,chkM); memCount+=count; count=0; //Left calculate(2*d_Left,0,d_Left,d_Down,d_Right,d_Up,chkM); memCount+=count; count=0; //Down calculate(2*d_Down,0,d_Down,d_Right,d_Up,d_Left,chkM); memCount+=count; count=0; // // out.println("Case #" + (n + 1) + ": " + memCount); System.out.println("Case #" + (n + 1) + ": " + memCount); } in.close(); out.close(); } public static void calculate(int s_X,int s_Y, int tempx,int dy,int dx,int tempy, double[] chkM) { boolean chk =true; for(int i=0;i<count;i++){ if(chkM[i]==((double)s_Y)/((double)s_X)){ chk= false; break; } } if (s_X * s_X + s_Y * s_Y > fixD * fixD) { return; }else if(chk){ chkM[count]=((double)s_Y)/((double)s_X); count++; }else{ return; } calculate(s_X+2 * dx,s_Y,dx,dy,tempx,tempy,chkM); calculate(s_X,s_Y+2 * dy,tempx,tempy,dx,dy,chkM); } }
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 ); } }
C20043
C20011
0
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 ); } } }
public class CG { /** get the intersection between a segment (p1, p2), and a project line from the origin * with an angle. * @return Point(INF, INF) if there is no intersection * */ public static Point intersectSegmentOri(Point p1, Point p2, double angle) { Point ori = new Point(0.0, 0.0), out = new Point(Math.cos(angle), Math.sin(angle)); Point intersect = new Point(0,0); int stat = crossPointLL(p1, p2, ori, out, intersect); // parallel if(stat == 0) return new Point(CGConst.INF, CGConst.INF); // check the case of intersect at the wrong side of the project line if(Math.cos(angle) * (intersect.x) < 0 || Math.sin(angle) * (intersect.y) < 0) return new Point(CGConst.INF, CGConst.INF); // check if the intersection is on the segment if(intersectSP(p1, p2, intersect)) return intersect; return new Point(CGConst.INF, CGConst.INF); } static boolean intersectSP(Point s0, Point s1, Point p) { return s0.minus(p).abs() + s1.minus(p).abs() - s1.minus(s0).abs()< CGConst.EPS; // triangle inequality } private static int crossPointLL(Point m0, Point m1, Point n0, Point n1, Point p) { if (Math.abs (cross (m1.minus(m0), n1.minus(n0))) > CGConst.EPS) { // non-parallel => intersect double h = cross (m1 .minus( m0), n1.minus(n0)); double k = cross (m1.minus( m0), m1.minus(n0)); p.copy( n1.minus(n0).mul(k/h).add(n0)); return 1; // intersect at one point } if (Math.abs (cross (m1.minus(m0), n0.minus(m0))) < CGConst.EPS) { // area==0 => same line => intersect p.copy( m0); // one of the intersection points, or m1, n0, n1, ... return -1; // intersect at infinitely many points (when 2 parallel lines overlap) } return 0; // no intersection points (when two lines are parallel but does not overlap) } private static double cross(Point a, Point b) { return a.x * b.y - a.y * b.x; } public static double distance(Point a, Point b) { return a.minus(b).abs(); } public static double getAngle(Point a, Point b) { return Math.acos(point(a, b)/(a.abs()*b.abs())); } private static double point(Point a, Point b) { return a.x*b.x + a.y*b.y; } static int dblcmp (double a, double b) { if (Math.abs (a-b) < CGConst.EPS) return 0; return a < b ? -1 : 1; } public static int ccw (Point a, Point b, Point c) { // short version return dblcmp (cross (b.minus(a), c.minus(a)), 0); } // para: s0 and s1 form a segment s // para: t0 and t1 form a segment t // return: true if s and t appears like a 'X' public static boolean properIntersectSS (Point s0, Point s1, Point t0, Point t1) { return ccw (s0, s1, t0) * ccw (s0, s1, t1) < 0 && ccw (t0, t1, s0) * ccw (t0, t1, s1) < 0; } public static double triArea (Point a, Point b, Point c) { // centroid = (a + b + c) / 3.0; // centroid of triangle return Math.abs (cross (b.minus(a), c.minus(a))) * 0.5; // |cross product| / 2 } /** check if two segments intersect and find the intersection point para: input s0 and s1 form a line s input t0 and t1 form a line t output p is the intersection point (if return value != 0) return: 1: the segments intersect at exactly one point -1: the segments intersect improperly, p is ONE OF the intersection points 0: no intersection points note: If you are sure the segment intersect and want to find the intersection point, you can include the statements in the first *if* block only. */ public static int crossPointSS( Point s0, Point s1, Point t0, Point t1, Point p) { if (properIntersectSS (s0, s1, t0, t1)) { double r = triArea (s0, t0, t1) / triArea (s1, t0, t1); Point temp = s0.add( (s1.minus(s0)).mul((r / (1+r)))); p.x = temp.x; p.y = temp.y; return 1; } if (intersectSP (s0, s1, t0)) { p.copy(t0); return -1; } if (intersectSP (s0, s1, t1)) { p .copy( t1); return -1; } if (intersectSP (t0, t1, s0)) { p .copy(s0); return -1; } if (intersectSP (t0, t1, s1)) { p .copy(s1); return -1; } return 0; } }
C20086
C20005
0
//input file must be in.txt in this directory //output file will be out.txt import java.io.*; import java.util.*; public class D { public static Scanner in; public static PrintStream out; public static void main(String [] args) throws Throwable { in = new Scanner(new File("in.txt")); int cases = in.nextInt(); in.nextLine(); out = new PrintStream(new File("out.txt")); for (int i = 1; i <= cases; i++) { out.print("Case #" + i + ": "); printResult(); out.println(); } } public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static boolean canSeeImage(int dx, int dy, int lx, int ly, int d, boolean [][] house) { //System.out.println("Trying (" + dx + "," + dy + "):"); int cx = lx; int cy = ly; int sx, sy; if (dx > 0) sx = 1; else sx = -1; if (dy > 0) sy = 1; else sy = -1; dx = Math.abs(dx); dy = Math.abs(dy); int i = 0; int totx = 0; int toty = 0; boolean t; boolean mx,my; boolean nx = false,ny = false; while (totx*totx + toty*toty <= d*d) { if (dx == 0) { my = true; mx = false; t = true; } else { if (dy == 0) { mx = true; my = false; t = true; } else { mx = i % dy == 0; my = i % dx == 0; t = mx && my && !nx && !ny; if (mx) { mx = nx; nx = !nx; } if (my) { my = ny; ny = !ny; } } } if (t && totx+toty > 0 && cx == lx && cy == ly) return true; //if (mx || my) // printHouse(lx,ly,cx,cy,house); if (mx) totx++; if (my) toty++; if (mx && my) { if (house[cx + sx][cy + sy]) { if (house[cx][cy + sy]) { if (house[cx + sx][cy]) { sx = -sx; sy = -sy; } else { sy = -sy; cx += sx; } } else { if (house[cx + sx][cy]) { sx = -sx; cy += sy; } else { return false; } } } else { cx += sx; cy += sy; } } else { if (mx) { if (house[cx + sx][cy]) { sx = -sx; } else { cx += sx; } } if (my) { if (house[cx][cy + sy]) { sy = -sy; } else { cy += sy; } } } i++; } return false; } public static void printHouse(int lx, int ly, int cx, int cy, boolean [][] house) { for (int y = 0; y < house[0].length; y++) { for (int x = 0; x < house.length; x++) { if (x == cx && y == cy) { System.out.print('*'); } else if (x == lx && y == ly) { System.out.print('X'); } else if (house[x][y]) { System.out.print('#'); } else { System.out.print(' '); } } System.out.println(); } } public static int[][] getPossibilities(int d) { ArrayList<Integer> lx = new ArrayList<Integer>(); ArrayList<Integer> ly = new ArrayList<Integer>(); int h, v; for (int x = -d; x <= d; x++) { for (int y = -d; y <= d; y++) { h = Math.abs(x); v = Math.abs(y); if (gcd(h,v) == 1 && h*h + v*v <= d*d) { lx.add(x); ly.add(y); } } } int [][] possibilities = new int [lx.size()][2]; for (int i = 0; i < possibilities.length; i++) { possibilities[i][0] = lx.get(i); possibilities[i][1] = ly.get(i); } return possibilities; } public static void printResult() { int h,w,d,lx = 0,ly = 0; h = in.nextInt(); w = in.nextInt(); d = in.nextInt(); in.nextLine(); String s; boolean [][] house = new boolean[w][h]; for (int y = 0; y < h; y++) { s = in.nextLine(); for (int x = 0; x < w; x++) { house[x][y] = s.charAt(x) == '#'; if (s.charAt(x) == 'X') { lx = x; ly = y; } } } int [][] poss = getPossibilities(d); int images = 0; for (int i = 0; i < poss.length; i++) { if (canSeeImage(poss[i][0], poss[i][1], lx, ly, d, house)) { images++; //System.out.println("True"); } //else //System.out.println("False"); } out.print(images); } }
package gcj; import com.sun.org.apache.xerces.internal.impl.xs.opti.DefaultXMLDocumentHandler; import java.util.*; import java.io.*; public class HallOfMirrors { final static String PROBLEM_NAME = "mirrors"; final static String WORK_DIR = "D:\\Gcj\\" + PROBLEM_NAME + "\\"; int H, W, D; double stX, stY; int res = 0; String[] map; int gcd(int a, int b) { while (a>0 && b>0) if (a>b) a %= b; else b %= a; return a + b; } final double EPS = 1e-10; double getT(double cur, int V) { cur *= 2; V *= 2; if (V == 0) return 1e100; if (V > 0) { double want = Math.ceil(cur + EPS); return (want - cur) / V; } else { double want = Math.floor(cur - EPS); return (want - cur) / V; } } boolean isInteger(double x) { return Math.abs(x - Math.floor(x)) <= EPS || Math.abs(x - Math.ceil(x)) <= EPS; } boolean inMirror(double x, double y) { int xx = (int)Math.floor(x); int yy = (int)Math.floor(y); return map[xx].charAt(yy) == '#'; } void process(int dx, int dy) { double curX = stX, curY = stY; double dist = 0.0; while (true) { double t1 = getT(curX, dx); double t2 = getT(curY, dy); double t = Math.min(t1, t2); double nextX = curX + t * dx; double nextY = curY + t * dy; double piece = Math.sqrt((nextX - curX) * (nextX - curX) + (nextY - curY) * (nextY - curY)); dist += piece; if (dist > D + EPS) return; if (Math.abs(nextX - stX) <= EPS && Math.abs(nextY - stY) <= EPS) { res++; return; } curX = nextX; curY = nextY; boolean fx = isInteger(nextX); boolean fy = isInteger(nextY); if (fx && fy) { // corner // A B // C D boolean A = inMirror(nextX - EPS, nextY - EPS); boolean B = inMirror(nextX - EPS, nextY + EPS); boolean C = inMirror(nextX + EPS, nextY - EPS); boolean D = inMirror(nextX + EPS, nextY + EPS); int cnt = (A ? 1 : 0) + (B ? 1 : 0) + (C ? 1 : 0) + (D ? 1 : 0); if (cnt == 3) { dx = -dx; dy = -dy; } else if ((A && B && !C && !D) || (!A && !B && C & D)) { dx = -dx; } else if ((A && C && !B && !D) || (!A && !C && B && D)) { dy = -dy; } else if (inMirror(nextX + (dx > 0 ? EPS : -EPS), nextY + (dy > 0 ? EPS : -EPS))) { return; } else { // just continue; } } else if (fx && !fy) { // horizontal if (dx != 0 && inMirror(nextX + (dx > 0 ? EPS : -EPS), nextY)) dx = -dx; } else if (!fx && fy) { // vertical if (dy != 0 && inMirror(nextX, nextY + (dy > 0 ? EPS : -EPS))) dy = -dy; } else { // nothing } } } void solve(Scanner sc, PrintWriter pw) { H = sc.nextInt(); W = sc.nextInt(); D = sc.nextInt(); map = new String[H]; for (int i=0; i<H; i++) map[i] = sc.next(); for (int i=0; i<H; i++) for (int j=0; j<W; j++) if (map[i].charAt(j) == 'X') { stX = i + 0.5; stY = j + 0.5; } for (int dx=-D; dx<=D; dx++) for (int dy=-D; dy<=D; dy++) if (dx*dx + dy*dy > 0 && dx*dx + dy*dy <= D * D && gcd(Math.abs(dx), Math.abs(dy)) == 1) { process(dx, dy); } pw.println(res); } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new FileReader(WORK_DIR + "input.txt")); PrintWriter pw = new PrintWriter(new FileWriter(WORK_DIR + "output.txt")); int caseCnt = sc.nextInt(); for (int caseNum=0; caseNum<caseCnt; caseNum++) { System.out.println("Processing test case " + (caseNum + 1)); pw.print("Case #" + (caseNum+1) + ": "); new HallOfMirrors().solve(sc, pw); } pw.flush(); pw.close(); sc.close(); } }
C20029
C20008
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.hallofmirrors; /** * * @author jim */ public class Ray { private final Fraction expiryLengthSquared; public RayVector vector; private FractionPoint currentLocation; private Fraction xTravelled; private Fraction yTravelled; public Ray(int expiryLengthSquared, RayVector vector, FractionPoint startLocation) { this.expiryLengthSquared = new Fraction(expiryLengthSquared); this.vector = vector; this.currentLocation = startLocation; xTravelled = new Fraction(0, 1); yTravelled = new Fraction(0, 1); } public static FractionPoint locationChangeInSq(FractionPoint enter, RayVector v) { Fraction xFrac = enter.x.fractionalPart(); Fraction yFrac = enter.y.fractionalPart(); Fraction xLen; Fraction yLen; if (xFrac.n == 0) { xLen = new Fraction(1); yLen = yFrac.n == 0 ? new Fraction(1) : (v.y < 0 ? yFrac : new Fraction(1).substract(yFrac)); } else if (yFrac.n == 0) { yLen = new Fraction(1); xLen = xFrac.n == 0 ? new Fraction(1) : (v.x < 0 ? xFrac : new Fraction(1).substract(xFrac)); } else { yLen = v.y < 0 ? yFrac: new Fraction(1).substract(yFrac); xLen = v.x < 0 ? xFrac: new Fraction(1).substract(xFrac); } Fraction scalar; if (xLen.multiply(v.getScalarGardient()).compareTo(yLen) > 0) scalar = yLen.divide(Math.abs(v.y)); else scalar = xLen.divide(Math.abs(v.x)); FractionPoint fp = new FractionPoint(scalar.multiply(v.x), scalar.multiply(v.y)); return fp; } public FractionPoint locationChangeInSq() { return locationChangeInSq(currentLocation, vector); } public boolean createsReflection(Hall h) { // System.out.println("\nRay: " + vector.toString()); Boolean b = null; while (b == null) b = step(h); // System.out.println(b); return b; } public Boolean step(Hall h) { FractionPoint locationChange = locationChangeInSq(); if (locationChange.x.isInt() || locationChange.y.isInt()) { FractionPoint changeToMid = new FractionPoint( locationChange.x.divide(2), locationChange.y.divide(2)); FractionPoint midpoint = currentLocation.add(changeToMid); if (midpoint.equals(h.meLocation)) { xTravelled = xTravelled.add(changeToMid.x.abs()); yTravelled = yTravelled.add(changeToMid.y.abs()); return stillGoing(); } } currentLocation = currentLocation.add(locationChange); vector = h.processBoundary(currentLocation, vector); if (vector == null) return false; xTravelled = xTravelled.add(locationChange.x.abs()); yTravelled = yTravelled.add(locationChange.y.abs()); // System.out.println("Chng: " + locationChange); // System.out.println("Loc: " + currentLocation); // System.out.println("d: " + distanceTravelled()); if (!stillGoing()) return false; else return null; } private Fraction distanceTravelled() { Fraction f = xTravelled.multiply(xTravelled).add( yTravelled.multiply(yTravelled)); return f; } private boolean stillGoing() { int compare = distanceTravelled().compareTo( expiryLengthSquared); return compare <= 0; } public FractionPoint getCurrentLocation() { return currentLocation; } }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; public class SimpleMirrors { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new FileReader(args[0])); PrintWriter out = new PrintWriter(args[1]); // number of testcases String sCount = in.readLine(); int count = Integer.parseInt(sCount); for(int idx=1; idx<=count; idx++) { String[] parts = in.readLine().split(" "); int h = Integer.parseInt(parts[0]); int w = Integer.parseInt(parts[1]); int d = Integer.parseInt(parts[2]); int x = -1, y = -1; // small dataset => just find the "X" for(int i=0; i<h; i++) { String l = in.readLine(); int p = l.indexOf('X'); if(p > -1) { y = 10*i - 5; x = 10*p - 5; } } out.println("Case #" + idx + ": " + process(10*(h-2), 10*(w-2), 10*d, x, y)); } out.close(); } private static int process(int h, int w, int d, int ox, int oy) { System.out.println("h=" + h + ", w=" + w + ", d=" + d + ", ox=" + ox + ", oy=" + oy); MirrorSet ms = new MirrorSet( Arrays.asList(new Mirror[] { new Mirror(Facing.POS, Orient.HORIZ, 0, 0, w), new Mirror(Facing.NEG, Orient.HORIZ, h, 0, w), new Mirror(Facing.POS, Orient.VERT, 0, 0, h), new Mirror(Facing.NEG, Orient.VERT, w, 0, h), }), ox, oy, d, w, h ); Set<Point> pts = ms.transitiveImages(); Set<Double> angles = ms.angles(pts); System.out.println(" " + pts.size() + ": " + pts); System.out.println(" " + angles.size() + ": " + angles); return angles.size(); } private static class MirrorSet { private final Collection<Mirror> mirrors; private final int ox, oy, limit, w, h; public MirrorSet(Collection<Mirror> mirrors, int ox, int oy, int limit, int w, int h) { this.mirrors = mirrors; this.ox = ox; this.oy = oy; this.limit = limit; this.w = w; this.h = h; } public Set<Point> images(Set<Point> in) { HashSet<Point> out = new HashSet<Point>(); for(Point i : in) { for(Mirror m : mirrors) { Point o = m.image(i); if(o != null && ! in.contains(o) && Math.sqrt((ox-o.x)*(ox-o.x) + (oy-o.y)*(oy-o.y)) <= limit) out.add(o); } } return out; } public Set<Point> transitiveImages() { Set<Point> im = new HashSet<Point>(); im.add(new Point(ox, oy)); Set<Point> newer; do { newer = images(im); im.addAll(newer); } while(newer.size() > 0); return im; } public Set<Double> angles(Set<Point> in) { Set<Double> out = new HashSet<Double>(); for(Point i : in) { if(i.x != ox || i.y != oy) out.add(Math.atan2(i.y-oy, i.x-ox)); } return out; } } private static enum Facing { POS, NEG } private static enum Orient { VERT, HORIZ } private static class Mirror { private final Facing facing; private final Orient orient; private final int pos, start, stop; public Mirror(Facing facing, Orient orient, int pos, int start, int stop) { this.facing = facing; this.orient = orient; this.pos = pos; this.start = start; this.stop = stop; } public Point image(Point p) { switch(orient) { case VERT: if(facing == Facing.POS && p.x >= pos || facing == Facing.NEG && p.x <= pos) { return new Point(2 * pos - p.x, p.y); } else return null; case HORIZ: if(facing == Facing.POS && p.y >= pos || facing == Facing.NEG && p.y <= pos) { return new Point(p.x, 2 * pos - p.y); } else return null; } return null; } } private static class Point { public final int x, y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { return obj instanceof Point && ((Point)obj).x == x && ((Point)obj).y == y; } @Override public int hashCode() { return (x << 16) ^ y; } @Override public String toString() { return "(" + x + ", " + y + ")"; } } }
C20052
C20023
0
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 ); } }
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; } }
C20038
C20018
0
import java.io.*; import java.util.*; import static java.lang.System.*; public class D { public static void main (String [] args) throws IOException {new D().run();} public void run() throws IOException{ Scanner file = new Scanner(new File("D-large.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("D4.out"))); int times = Integer.parseInt(file.nextLine()); for(int asdf = 0; asdf<times; asdf++){ System.out.println (asdf); int row = file.nextInt(), col = file.nextInt(); int d = file.nextInt(); file.nextLine(); double px=0,py=0; for(int i = 0; i<row; i++){ String s = file.nextLine(); if( s.contains("X")){ py = i+.5-1; px = s.indexOf("X")+.5-1; } } row-=2;col-=2; int XLIM = 500; int YLIM = 500; HashSet<Double> set = new HashSet<Double>(); for(int x = -XLIM; x<=XLIM; x++) for(int y = -YLIM; y<=YLIM; y++){ if( x==0&&y==0)continue; double xx,yy; if( x%2==0) xx = x*col+px; else xx = (x+1)*col-px; if( y%2==0) yy = y*row+py; else yy = (y+1)*row-py; if( Math.sqrt(Math.pow(xx-px,2)+Math.pow(yy-py,2)) <= d) set.add(Math.atan2(yy-py,xx-px)); } int count = 0; for(double d1 : set) for(double d2 : set) if( Math.abs(d1-d2)<1e-5)count++; if(count != set.size()) System.out.println ("FAIL"); out.println ("Case #"+(asdf+1)+": "+set.size()); //System.out.println (set); } out.close(); System.exit(0); } }
package template; import java.util.Objects; public class Pair<T1, T2> implements Comparable<Pair<T1, T2>>{ private T1 o1; private T2 o2; public Pair(T1 o1, T2 o2) { this.o1 = o1; this.o2 = o2; } @Override public boolean equals(Object other) { if (!(other instanceof Pair)) {return false;} return (compareTo((Pair<T1, T2>)other) == 0); } @Override public int compareTo(Pair<T1, T2> other) { int c1 = ((Comparable<T1>) o1).compareTo(other.getO1()); if (c1 != 0) {return c1;} int c2 = ((Comparable<T2>) o2).compareTo(other.getO2()); return c2; } @Override public int hashCode() { int hash = 5; hash = 83 * hash + Objects.hashCode(this.o1); hash = 83 * hash + Objects.hashCode(this.o2); return hash; } @Override public String toString() { return "[" + o1 + ", " + o2 + "]"; } public T1 getO1() { return o1; } public void setO1(T1 o1) { this.o1 = o1; } public T2 getO2() { return o2; } public void setO2(T2 o2) { this.o2 = o2; } }
C20025
C20054
0
package j2012qualifier; import java.awt.Point; 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 D { public static String inputDirectory="src/j2012qualifier/"; public static String inputFile="D.in"; public static String outputFile="D.out"; public static PrintWriter output; public static char[][] room; 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(); //size of each square s.nextLine(); for(int Case=1;Case<=cases;Case++){ int H = s.nextInt(); int W = s.nextInt(); int D = s.nextInt(); s.nextLine(); room = new char[H][W]; int x=0, y=0; for(int i=0;i<H;i++){ String line = s.nextLine(); for(int j=0;j<W;j++){ room[i][j] = line.charAt(j); if (room[i][j] == 'X') { x = j; y = i; } } } int count = 0; Set<String> used = new HashSet<String>(); for(int i=-D; i<=D ;i++) { for(int j=-D; j<=D; j++) { int dx = j; int dy = i; if (dx == 0 && dy == 0) continue; if (dx == 0) dy = (int)(dy / Math.sqrt(dy * dy)); if (dy == 0) dx = (int)(dx / Math.sqrt(dx * dx)); if(i != 0 && j!=0) { int gcd = GCD(i, j); gcd = gcd < 0 ? -gcd : gcd; dx = j / gcd; dy = i / gcd; } String key = dx+","+dy; if (used.contains(key))continue; used.add(key); int lcm = dx*dy; if ( dx == 0) { lcm = dy; } else if(dy == 0){ lcm = dx; } lcm = lcm < 0 ? -lcm : lcm; int startX = (2*x+1)*lcm; int startY = (2*y+1)*lcm; if(castRay(lcm, D * lcm * 2, startX, startY, dx, dy, startX, startY)) { count++; } } } output.printf("Case #%d: %d\n", Case, count); } output.flush(); } public static int GCD(int a, int b) { if (b == 0) return a; return GCD(b, a % b); } public static boolean castRay(int lcm, double D, int x, int y, int dx, int dy, int gx, int gy) { //out(D+ " : ("+x+","+y+") <"+dx+","+dy+">"); if (D<=0) { return false; } int xSteps=1000, ySteps=1000; if (dx > 0) { xSteps = ((x / lcm) * lcm + lcm - x) / dx; } else if(dx < 0) { xSteps = (((x - 1) / lcm) * lcm - x) / dx; } if (dy > 0) { ySteps = ((y / lcm) * lcm + lcm - y) / dy; } else if(dy < 0) { ySteps = (((y - 1) / lcm) * lcm - y) / dy; } int steps = Math.min(xSteps, ySteps); double distance = steps * Math.sqrt(dx*dx + dy*dy); if (distance > D) { return false; } int newX = x+dx*steps; int newY = y+dy*steps; if (newX == gx && newY == gy) { return true; } //we are on a vertical line boolean onVertical = (newX %(2*lcm) == 0); boolean onHorizontal = (newY %(2*lcm) == 0); int gridY = newY / (2 * lcm); int gridX = newX / (2 * lcm); int newDx = dx; int newDy = dy; if (onVertical && onHorizontal) { int tX = (dx < 0) ? gridX - 1 : gridX; int tY = (dy < 0) ? gridY - 1 : gridY; int cX = (tX == gridX) ? gridX - 1 : gridX; int cY = (tY == gridY) ? gridY - 1 : gridY; if(room[tY][tX] == '#') { if(room[tY][cX] != '#' && room[cY][tX] != '#') { //light destroyed return false; } if (room[tY][cX] == '#'){ newDy = -dy; } if (room[cY][tX] == '#'){ newDx = -dx; } } } else if(onVertical) { gridX += (dx < 0) ? -1 : 0; if(room[gridY][gridX] == '#') { newDx = -dx; } } else if(onHorizontal) { gridY += (dy < 0) ? -1 : 0; if(room[gridY][gridX] == '#') { newDy = -dy; } } return castRay(lcm, D - distance, newX, newY, newDx, newDy, gx, gy); } public static void out(String s){ output.println(s); System.out.println(s); } }
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 ); } }
C20039
C20038
0
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 ); } } }
import java.io.*; import java.util.*; import static java.lang.System.*; public class D { public static void main (String [] args) throws IOException {new D().run();} public void run() throws IOException{ Scanner file = new Scanner(new File("D-large.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("D4.out"))); int times = Integer.parseInt(file.nextLine()); for(int asdf = 0; asdf<times; asdf++){ System.out.println (asdf); int row = file.nextInt(), col = file.nextInt(); int d = file.nextInt(); file.nextLine(); double px=0,py=0; for(int i = 0; i<row; i++){ String s = file.nextLine(); if( s.contains("X")){ py = i+.5-1; px = s.indexOf("X")+.5-1; } } row-=2;col-=2; int XLIM = 500; int YLIM = 500; HashSet<Double> set = new HashSet<Double>(); for(int x = -XLIM; x<=XLIM; x++) for(int y = -YLIM; y<=YLIM; y++){ if( x==0&&y==0)continue; double xx,yy; if( x%2==0) xx = x*col+px; else xx = (x+1)*col-px; if( y%2==0) yy = y*row+py; else yy = (y+1)*row-py; if( Math.sqrt(Math.pow(xx-px,2)+Math.pow(yy-py,2)) <= d) set.add(Math.atan2(yy-py,xx-px)); } int count = 0; for(double d1 : set) for(double d2 : set) if( Math.abs(d1-d2)<1e-5)count++; if(count != set.size()) System.out.println ("FAIL"); out.println ("Case #"+(asdf+1)+": "+set.size()); //System.out.println (set); } out.close(); System.exit(0); } }
C20067
C20057
0
import java.io.*; import java.util.*; public class Solution { private StringTokenizer st; private BufferedReader in; private PrintWriter out; final String file = "D-large"; public void solve() throws IOException { int tests = nextInt(); for (int test = 0; test < tests; ++test) { int n = nextInt(); int m = nextInt(); int d = nextInt(); char[][] f = new char[n][m]; int x0 = -1, y0 = -1; for (int i = 0; i < n; ++i) { f[i] = next().toCharArray(); for (int j = 0; j < m; ++j) { if (f[i][j] == 'X') { x0 = i; y0 = j; } } } int ans = 0; for (int dx = -d; dx <= d; ++dx) { for (int dy = -d; dy <= d; ++dy) { if ((dx != 0 || dy != 0) && dx * dx + dy * dy <= d * d && raytrace(x0, y0, x0 + dx, y0 + dy, f, 0.)) { // System.err.println(dx + " " + dy); ans++; } } } System.err.printf("Case #%d: %d%n", test + 1, ans); out.printf("Case #%d: %d%n", test + 1, ans); } } final double EPS = 1e-8; private boolean raytrace(int x0, int y0, int x1, int y1, char[][] f, double t) { double firstt = Double.POSITIVE_INFINITY; int dx = x1 - x0; int dy = y1 - y0; double tx = Double.POSITIVE_INFINITY; for (int i = Math.max(0, Math.min(x0, x1)); i < f.length && i <= Math.max(x0, x1); ++i) { for (int j = Math.max(0, Math.min(y0, y1)); j < f[0].length && j <= Math.max(y0, y1); ++j) { if (f[i][j] == 'X') { double tt = dx != 0 ? (double)(i - x0) / dx : (double)(j - y0) / dy; if (Math.abs(x0 + dx * tt - i) < EPS && Math.abs(y0 + dy * tt - j) < EPS) { tx = tt; } } if (f[i][j] != '#') { continue; } double minx = dx == 0 ? Double.NEGATIVE_INFINITY : Math.min((i - 0.5 - x0) / dx, (i + 0.5 - x0) / dx); double maxx = dx == 0 ? Double.POSITIVE_INFINITY : Math.max((i - 0.5 - x0) / dx, (i + 0.5 - x0) / dx); double miny = dy == 0 ? Double.NEGATIVE_INFINITY : Math.min((j - 0.5 - y0) / dy, (j + 0.5 - y0) / dy); double maxy = dy == 0 ? Double.POSITIVE_INFINITY : Math.max((j - 0.5 - y0) / dy, (j + 0.5 - y0) / dy); if (maxx < miny - EPS || maxy < minx - EPS) { continue; } double tt = Math.max(minx, miny); if (tt > t + EPS) { firstt = Math.min(firstt, tt); } } } if (firstt > 1.) { return x1 >= 0 && x1 < f.length && y1 >= 0 && y1 < f[0].length && f[x1][y1] == 'X'; } if (tx > t + EPS && tx < firstt) { return false; } int sx = Integer.signum(dx); int sy = Integer.signum(dy); double x = x0 + dx * firstt - 0.5; double y = y0 + dy * firstt - 0.5; int rx = (int)Math.round(x); int ry = (int)Math.round(y); if (Math.abs(rx - x) < EPS && Math.abs(ry - y) < EPS) { if (dx == 0 || dy == 0) { throw new AssertionError(); } boolean f11 = get(f, rx + (1 + sx) / 2, ry + (1 + sy) / 2); boolean f01 = get(f, rx + (1 - sx) / 2, ry + (1 + sy) / 2); boolean f10 = get(f, rx + (1 + sx) / 2, ry + (1 - sy) / 2); if (get(f, rx + (1 - sx) / 2, ry + (1 - sy) / 2) || !f11 && !f01 && !f10) { throw new AssertionError(); } if (!f11) { return raytrace(x0, y0, x1, y1, f, firstt); } if (f01 && f10 && f11) { return raytrace(2 * rx + 1 - x0, 2 * ry + 1 - y0, 2 * rx + 1 - x1, 2 * ry + 1 - y1, f, firstt); } if (f10 && f11) { return raytrace(2 * rx + 1 - x0, y0, 2 * rx + 1 - x1, y1, f, firstt); } if (f01 && f11) { return raytrace(x0, 2 * ry + 1 - y0, x1, 2 * ry + 1 - y1, f, firstt); } return false; } if (Math.abs(rx - x) < EPS) { return raytrace(2 * rx + 1 - x0, y0, 2 * rx + 1 - x1, y1, f, firstt); } if (Math.abs(ry - y) < EPS) { return raytrace(x0, 2 * ry + 1 - y0, x1, 2 * ry + 1 - y1, f, firstt); } throw new AssertionError(); } private boolean get(char[][] f, int i, int j) { return i >= 0 && i < f.length && j >= 0 && j < f[0].length && f[i][j] == '#'; } public void run() throws IOException { in = new BufferedReader(new FileReader(file + ".in")); out = new PrintWriter(file + ".out"); eat(""); solve(); out.close(); } void eat(String s) { st = new StringTokenizer(s); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Solution().run(); } }
package jp.funnything.competition.util; import java.util.Arrays; import java.util.List; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; public class Prime { public static class PrimeData { public int[] list; public boolean[] map; private PrimeData( final int[] values , final boolean[] map ) { list = values; this.map = map; } } public static long[] factorize( long n , final int[] primes ) { final List< Long > factor = Lists.newArrayList(); for ( final int p : primes ) { if ( n < p * p ) { break; } while ( n % p == 0 ) { factor.add( ( long ) p ); n /= p; } } if ( n > 1 ) { factor.add( n ); } return Longs.toArray( factor ); } public static PrimeData prepare( final int n ) { final List< Integer > primes = Lists.newArrayList(); final boolean[] map = new boolean[ n ]; Arrays.fill( map , true ); map[ 0 ] = map[ 1 ] = false; primes.add( 2 ); for ( int composite = 2 * 2 ; composite < n ; composite += 2 ) { map[ composite ] = false; } for ( int value = 3 ; value < n ; value += 2 ) { if ( map[ value ] ) { primes.add( value ); for ( int composite = value * 2 ; composite < n ; composite += value ) { map[ composite ] = false; } } } return new PrimeData( Ints.toArray( primes ) , map ); } }
C20032
C20051
0
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.hallofmirrors; import uk.co.epii.codejam.common.AbstractMain; /** * * @author jim */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { System.err.println("Hello"); new AbstractMain<Hall>(new HallFactory(), new HallOfMirrorsProcessor()).main(args); } }
package jp.funnything.competition.util; import java.util.List; import com.google.common.collect.Lists; public class Lists2 { public static < T > List< T > newArrayListAsArray( final int length ) { final List< T > list = Lists.newArrayListWithCapacity( length ); for ( int index = 0 ; index < length ; index++ ) { list.add( null ); } return list; } }
C20082
C20060
0
import java.util.*; import java.io.*; class Frac { public static int gcd(int u, int v) { while (v != 0) { int t = v; v = u % v; u = t; } return Math.abs(u); } public int n; public int d; public Frac(int n, int d) { int dd = gcd(n, d); this.n = n / dd; this.d = d / dd; } public Frac add(Frac other) { int tempn = this.n * other.d + other.n * this.d; int tempd = this.d * other.d; return new Frac(tempn, tempd); } public Frac sub(Frac other) { int tempn = this.n * other.d - other.n * this.d; int tempd = this.d * other.d; return new Frac(tempn, tempd); } public Frac mul(Frac other) { int tempn = this.n * other.n; int tempd = this.d * other.d; return new Frac(tempn, tempd); } public Frac div(Frac other) { int tempn = this.n * other.d; int tempd = this.d * other.n; return new Frac(tempn, tempd); } public double doubl() { return ((double) this.n) / this.d; } public boolean eq(Frac other) { return this.n == other.n && this.d == other.d; } public String toString() { return String.format("%d/%d", n, d); } } class Grid { private int[] grid; public int xsize; public int ysize; public int xstart = 0; public int ystart = 0; public Grid(int xsize, int ysize) { this.xsize = xsize; this.ysize = ysize; grid = new int[xsize * ysize]; } public int get(int x, int y) { return grid[x + y * xsize]; } public void set(int x, int y, int v) { grid[x + y * xsize] = v; } public void write() { for (int y = 0; y < ysize; y++) { for (int x = 0; x < xsize; x++) { System.out.print("" + get(x,y)); } System.out.println(); } } public Grid rotate() { Grid newg = new Grid(ysize, xsize); for (int x = 0; x < xsize; x++) { for (int y = 0; y < ysize; y++) { int v = get(x,y); int newx = ysize - y - 1; int newy = x; newg.set(newx, newy, v); if (v == 2 && (newx % 2) == 1 && (newy % 2) == 1) { newg.xstart = newx; newg.ystart = newy; } } } return newg; } } public class D { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int ncases = sc.nextInt(); for (int caseno = 0; caseno < ncases; caseno++) { int ysize = sc.nextInt() * 2; int xsize = sc.nextInt() * 2; int maxdist = sc.nextInt() * 2; Grid g = new Grid(xsize, ysize); for (int y = 0; y < (ysize / 2); y++) { String row = sc.next(); for (int x = 0; x < (xsize / 2); x++) { if (row.charAt(x) == '#') { g.set(x*2+0,y*2+0,1); g.set(x*2+1,y*2+0,1); g.set(x*2+1,y*2+1,1); g.set(x*2+0,y*2+1,1); } else if (row.charAt(x) == 'X') { g.set(x*2+0,y*2+0,2); g.set(x*2+1,y*2+0,2); g.set(x*2+1,y*2+1,2); g.set(x*2+0,y*2+1,2); g.xstart = x * 2 + 1; g.ystart = y * 2 + 1; } } } int count = 0; for (int i = 0; i < 4; i++) { // System.out.println("" + g.xstart); // System.out.println("" + g.ystart); // g.write(); for (int xdiff = 0; xdiff < maxdist+2; xdiff += 2) { for (int ydiff = 2; ydiff < maxdist+2; ydiff += 2) { if (xdiff * xdiff + ydiff * ydiff <= maxdist * maxdist) { boolean res = testray(g.xstart, g.ystart, xdiff, ydiff, g); if (res) count += 1; } } } g = g.rotate(); } System.out.printf("Case #%d: %d\n", caseno+1, count); } } public static boolean testray(int xstartt, int ystartt, int xdifff, int ydifff, Grid g) { //System.out.printf("%d %d %d %d\n", xstartt, ystartt, xdifff, ydifff); int xmirror = 1; int ymirror = 1; int xgrid = xstartt; int ygrid = ystartt; Frac xend = new Frac(xstartt + xdifff, 1); Frac yend = new Frac(ystartt + ydifff, 1); Frac xstart = new Frac(xstartt, 1); Frac ystart = new Frac(ystartt, 1); //System.out.println("" + xstart); Frac xdiff = xend.sub(xstart); Frac ydiff = yend.sub(ystart); Frac xslope = xdiff.div(ydiff); Frac yslope = ydiff.div(xdiff); Frac xpos = xstart; Frac ypos = ystart; while (true) { if (xpos.eq(xend) && ypos.eq(yend)) { break; } int xcorner = xpos.n / xpos.d; int ycorner = ypos.n / ypos.d; Frac yedge = new Frac(ycorner + 1, 1); Frac xres = xpos.add(xslope.mul(yedge.sub(ypos))); Frac xedge = new Frac(xcorner + 1, 1); Frac yres = ypos.add(yslope.mul(xedge.sub(xpos))); double h = (xres.sub(xpos)).doubl(); double v = (xedge.sub(xpos)).doubl(); if (h < v) { xpos = xres; ypos = yedge; xcorner = xpos.n / xpos.d; int xmod = xpos.n % xpos.d; ycorner = ypos.n / ypos.d; int ymod = ypos.n % ypos.d; if (xmod == 0) { ygrid += ymirror; if (g.get(xgrid, ygrid) == 1) { ymirror *= -1; ygrid += ymirror; } else if (g.get(xgrid, ygrid) == 2 && (ycorner % 2) == 1) { if (xpos.eq(xend) && ypos.eq(yend)) { return true; } else { return false; } } } else { ygrid += ymirror; if (g.get(xgrid, ygrid) == 1) { ymirror *= -1; ygrid += ymirror; } } } else if (v < h) { xpos = xedge; ypos = yres; xcorner = xpos.n / xpos.d; int xmod = xpos.n % xpos.d; ycorner = ypos.n / ypos.d; int ymod = ypos.n % ypos.d; xgrid += xmirror; if (g.get(xgrid, ygrid) == 1) { xmirror *= -1; xgrid += xmirror; } } else { xpos = xedge; ypos = yedge; xcorner = xpos.n / xpos.d; int xmod = xpos.n % xpos.d; ycorner = ypos.n / ypos.d; int ymod = ypos.n % ypos.d; int blockE = g.get(xgrid + xmirror, ygrid); int blockSE = g.get(xgrid + xmirror, ygrid + ymirror); int blockS = g.get(xgrid, ygrid + ymirror); if (blockE == 2 && blockSE == 2 && blockS == 2) { if (xpos.eq(xend) && ypos.eq(yend)) { return true; } else { return false; } } if (blockE == 2) blockE = 0; if (blockSE == 2) blockSE = 0; if (blockS == 2) blockS = 0; if (blockE == 0 && blockSE == 0 && blockS == 0) { xgrid += xmirror; ygrid += ymirror; } else if (blockE == 1 && blockSE == 0 && blockS == 0) { xgrid += xmirror; ygrid += ymirror; } else if (blockE == 1 && blockSE == 0 && blockS == 1) { xgrid += xmirror; ygrid += ymirror; } else if (blockE == 0 && blockSE == 0 && blockS == 1) { xgrid += xmirror; ygrid += ymirror; } else if (blockE == 0 && blockSE == 1 && blockS == 0) { return false; } else if (blockE == 1 && blockSE == 1 && blockS == 0) { xgrid += xmirror; ygrid += ymirror; xmirror *= -1; xgrid += xmirror; } else if (blockE == 0 && blockSE == 1 && blockS == 1) { xgrid += xmirror; ygrid += ymirror; ymirror *= -1; ygrid += ymirror; } else if (blockE == 1 && blockSE == 1 && blockS == 1) { xgrid += xmirror; ygrid += ymirror; xmirror *= -1; ymirror *= -1; xgrid += xmirror; ygrid += ymirror; } } } return false; } }
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 ); } }
C20057
C20030
0
package jp.funnything.competition.util; import java.util.Arrays; import java.util.List; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; public class Prime { public static class PrimeData { public int[] list; public boolean[] map; private PrimeData( final int[] values , final boolean[] map ) { list = values; this.map = map; } } public static long[] factorize( long n , final int[] primes ) { final List< Long > factor = Lists.newArrayList(); for ( final int p : primes ) { if ( n < p * p ) { break; } while ( n % p == 0 ) { factor.add( ( long ) p ); n /= p; } } if ( n > 1 ) { factor.add( n ); } return Longs.toArray( factor ); } public static PrimeData prepare( final int n ) { final List< Integer > primes = Lists.newArrayList(); final boolean[] map = new boolean[ n ]; Arrays.fill( map , true ); map[ 0 ] = map[ 1 ] = false; primes.add( 2 ); for ( int composite = 2 * 2 ; composite < n ; composite += 2 ) { map[ composite ] = false; } for ( int value = 3 ; value < n ; value += 2 ) { if ( map[ value ] ) { primes.add( value ); for ( int composite = value * 2 ; composite < n ; composite += value ) { map[ composite ] = false; } } } return new PrimeData( Ints.toArray( primes ) , map ); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.hallofmirrors; /** * * @author jim */ public class RayVector { public final int x; public final int y; public RayVector(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { if (obj instanceof RayVector) { RayVector v = (RayVector)obj; if (v.x * y == v.y * x) return true; } return false; } @Override public int hashCode() { int hash = 7; hash = 41 * hash + this.x; hash = 41 * hash + this.y; return hash; } public Fraction getScalarGardient() { return new Fraction(Math.abs(y), Math.abs(x)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(x); sb.append(","); sb.append(y); sb.append(")"); return sb.toString(); } }
C20048
C20000
0
package jp.funnything.competition.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.apache.commons.io.IOUtils; public class AnswerWriter { private static final String DEFAULT_FORMAT = "Case #%d: %s\n"; private final BufferedWriter _writer; private final String _format; public AnswerWriter( final File output , final String format ) { try { _writer = new BufferedWriter( new FileWriter( output ) ); _format = format != null ? format : DEFAULT_FORMAT; } catch ( final IOException e ) { throw new RuntimeException( e ); } } public void close() { IOUtils.closeQuietly( _writer ); } public void write( final int questionNumber , final Object result ) { write( questionNumber , result.toString() , true ); } public void write( final int questionNumber , final String result ) { write( questionNumber , result , true ); } public void write( final int questionNumber , final String result , final boolean tee ) { try { final String content = String.format( _format , questionNumber , result ); if ( tee ) { System.out.print( content ); System.out.flush(); } _writer.write( content ); } catch ( final IOException e ) { throw new RuntimeException( e ); } } }
import static java.lang.Math.*; import java.io.*; import java.util.*; /** * @author Chris Dziemborowicz <chris@dziemborowicz.com> * @version 2012.0415 */ public class HallOfMirrors { public static void main(String[] args) throws Exception { // Get input files File dir = new File("/Users/Chris/Documents/UniSVN/code-jam/hall-of-mirrors/data"); File[] inputFiles = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".in"); } }); // Process each input file for (File inputFile : inputFiles) { System.out.printf("Processing \"%s\"...\n", inputFile.getName()); String outputPath = inputFile.getPath().replaceAll("\\.in$", ".out"); BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath)); Scanner scanner = new Scanner(inputFile); System.out.printf("Number of test cases: %s\n", scanner.nextLine()); int count = 0; while (scanner.hasNext()) { int h = scanner.nextInt(); int w = scanner.nextInt(); int d = scanner.nextInt(); scanner.nextLine(); String[] map = new String[h]; for (int i = 0; i < h; i++) { map[i] = scanner.nextLine(); } String output = String.format("Case #%d: %d\n", ++count, process(h, w, d, map)); System.out.print(output); writer.write(output); } writer.close(); System.out.println("Done.\n"); } // Compare to reference files (if any) for (File inputFile : inputFiles) { System.out.printf("Verifying \"%s\"...\n", inputFile.getName()); String referencePath = inputFile.getPath().replaceAll("\\.in$", ".ref"); String outputPath = inputFile.getPath().replaceAll("\\.in$", ".out"); File referenceFile = new File(referencePath); if (referenceFile.exists()) { InputStream referenceStream = new FileInputStream(referencePath); InputStream outputStream = new FileInputStream(outputPath); boolean matched = true; int referenceRead, outputRead; do { byte[] referenceBuffer = new byte[4096]; byte[] outputBuffer = new byte[4096]; referenceRead = referenceStream.read(referenceBuffer); outputRead = outputStream.read(outputBuffer); matched = referenceRead == outputRead && Arrays.equals(referenceBuffer, outputBuffer); } while (matched && referenceRead != -1); if (matched) { System.out.println("Verified.\n"); } else { System.out.println("*** NOT VERIFIED ***\n"); } } else { System.out.println("No reference file found.\n"); } } } public static int process(int h, int w, int d, String[] map) { int x = -1, y = -1; for (int xx = 0; xx < map.length; xx++) { int yy = map[xx].indexOf('X'); if (yy != -1) { x = xx; y = yy; } } int count = 0; for (int i = -100; i <= 100; i++) { for (int j = -100; j <= 100; j++) { int gcd = gcd(i, j); if (gcd == 1 || (i == 0 && abs(j) == 1) || (j == 0 && abs(i) == 1)) { count += process(map, x, y, i, j, d); } } } return count; } public static int process(String[] map, int sx, int sy, int dx, int dy, int d) { int x = sx; int y = sy; int xs = 0; int ys = 0; int err = abs(dx) - abs(dy); while (true) { if (err > 0) { x += dx > 0 ? 1 : -1; xs++; err -= 2 * abs(dy); if (map[x].charAt(y) == '#') { dx = -dx; x += dx > 0 ? 1 : -1; } } else if (err < 0) { y += dy > 0 ? 1 : -1; ys++; err += 2 * abs(dx); if (map[x].charAt(y) == '#') { dy = -dy; y += dy > 0 ? 1 : -1; } } else { int ox = x; x += dx > 0 ? 1 : -1; xs++; err -= 2 * abs(dy); int oy = y; y += dy > 0 ? 1 : -1; ys++; err += 2 * abs(dx); if (map[x].charAt(y) == '#') { if (map[ox].charAt(y) != '#' && map[x].charAt(oy) != '#') { return 0; } else if (map[ox].charAt(y) == '#' && map[x].charAt(oy) == '#') { dx = -dx; x += dx > 0 ? 1 : -1; dy = -dy; y += dy > 0 ? 1 : -1; } else if (map[ox].charAt(y) == '#') { dy = -dy; y += dy > 0 ? 1 : -1; } else { dx = -dx; x += dx > 0 ? 1 : -1; } } } if ((dx == 0 || xs % dx == 0) && (dy == 0 || ys % dy == 0)) { if (sqrt(xs * xs + ys * ys) > d) { return 0; } else if (map[x].charAt(y) == 'X') { return 1; } } } } public static int gcd(int a, int b) { if (a == 0 || b == 0) { return -1; } a = abs(a); b = abs(b); while (a != 0 && b != 0) { if (a > b) { a %= b; } else { b %= a; } } return a == 0 ? b : a; } }
C20003
C20064
0
import java.io.*; import java.util.*; public class D { public static class Pair { public int r; public int c; public Pair(int r, int c) { this.r = r; this.c = c; } @Override public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof Pair)) return false; Pair p = (Pair) o; if (this.r == p.r && this.c == p.c) return true; else return false; } } static char[][] d = new char[30][]; static int H; static int W; static int D; static int row; static int column; public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader("D.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("D.out"))); int n = Integer.parseInt(in.readLine()); for (int i = 0; i < n; ++ i) { String st = in.readLine(); String[] input = st.split(" "); H = Integer.parseInt(input[0]); W = Integer.parseInt(input[1]); D = Integer.parseInt(input[2]); for (int r = 0; r < H; ++ r) d[r] = in.readLine().toCharArray(); for (int r = 0; r < H; ++ r) for (int c = 0; c < W; ++ c) if (d[r][c] == 'X') { row = r; column = c; } List<Pair> s = new ArrayList<Pair>(); int ans = 0; for (int r = 1; r < D; ++ r) { for (int c = 1; c < D; ++ c) { int gcd = gcd(r, c); int dr = r / gcd; int dc = c / gcd; Pair p = new Pair(dr, dc); if (!s.contains(p)) { s.add(p); if (mapSearch(dr, dc, 1, 1)) ++ ans; if (mapSearch(dr, dc, 1, -1)) ++ ans; if (mapSearch(dr, dc, -1, 1)) ++ ans; if (mapSearch(dr, dc, -1, -1)) ++ ans; } } } if (lineSearch(1, 0)) ++ ans; if (lineSearch(-1, 0)) ++ ans; if (lineSearch(0, 1)) ++ ans; if (lineSearch(0, -1)) ++ ans; out.println("Case #" + (i + 1) + ": " + ans); } in.close(); out.close(); } private static boolean mapSearch(int dr, int dc, int dx, int dy) { int x = 0; int y = 0; int posX = row; int posY = column; while(Math.pow(x, 2) + Math.pow(y, 2) < Math.pow(D, 2)) { if((x + 0.5) * dr < (y + 0.5) * dc) { posX += dx; x += 1; if(d[posX][posY] == '#'){ dx = -dx; posX += dx; } } else if((x + 0.5) * dr > (y + 0.5) * dc) { posY += dy; y += 1; if(d[posX][posY] == '#'){ dy = -dy; posY += dy; } } else { x += 1; y += 1; posX += dx; posY += dy; if(d[posX][posY]=='#'){ if(d[posX - dx][posY] == '#' && d[posX][posY - dy] == '#'){ dx = -dx; dy = -dy; posX += dx; posY += dy; } else if(d[posX - dx][posY] == '#'){ dy = -dy; posY += dy; } else if(d[posX][posY - dy] == '#'){ dx = -dx; posX += dx; } else{ return false; } } } if(d[posX][posY] == 'X' && y * dc == x * dr && Math.pow(x,2) + Math.pow(y,2) <= Math.pow(D,2)) { return true; } } return false; } public static boolean lineSearch(int dx, int dy){ int posX = row; int posY = column; for(int i = 0; i < D; ++ i){ posX += dx; posY += dy; if(d[posX][posY] == '#'){ dx = -dx; dy = -dy; posX += dx; posY += dy; } if(d[posX][posY] == 'X'){ return true; } } return false; } private static int gcd (int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } }
package jp.funnything.competition.util; public class Prof { private long _start; public Prof() { reset(); } private long calcAndReset() { final long ret = System.currentTimeMillis() - _start; reset(); return ret; } private void reset() { _start = System.currentTimeMillis(); } @Override public String toString() { return String.format( "Prof: %f (s)" , calcAndReset() / 1000.0 ); } public String toString( final String head ) { return String.format( "%s: %f (s)" , head , calcAndReset() / 1000.0 ); } }
C20086
C20015
0
//input file must be in.txt in this directory //output file will be out.txt import java.io.*; import java.util.*; public class D { public static Scanner in; public static PrintStream out; public static void main(String [] args) throws Throwable { in = new Scanner(new File("in.txt")); int cases = in.nextInt(); in.nextLine(); out = new PrintStream(new File("out.txt")); for (int i = 1; i <= cases; i++) { out.print("Case #" + i + ": "); printResult(); out.println(); } } public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static boolean canSeeImage(int dx, int dy, int lx, int ly, int d, boolean [][] house) { //System.out.println("Trying (" + dx + "," + dy + "):"); int cx = lx; int cy = ly; int sx, sy; if (dx > 0) sx = 1; else sx = -1; if (dy > 0) sy = 1; else sy = -1; dx = Math.abs(dx); dy = Math.abs(dy); int i = 0; int totx = 0; int toty = 0; boolean t; boolean mx,my; boolean nx = false,ny = false; while (totx*totx + toty*toty <= d*d) { if (dx == 0) { my = true; mx = false; t = true; } else { if (dy == 0) { mx = true; my = false; t = true; } else { mx = i % dy == 0; my = i % dx == 0; t = mx && my && !nx && !ny; if (mx) { mx = nx; nx = !nx; } if (my) { my = ny; ny = !ny; } } } if (t && totx+toty > 0 && cx == lx && cy == ly) return true; //if (mx || my) // printHouse(lx,ly,cx,cy,house); if (mx) totx++; if (my) toty++; if (mx && my) { if (house[cx + sx][cy + sy]) { if (house[cx][cy + sy]) { if (house[cx + sx][cy]) { sx = -sx; sy = -sy; } else { sy = -sy; cx += sx; } } else { if (house[cx + sx][cy]) { sx = -sx; cy += sy; } else { return false; } } } else { cx += sx; cy += sy; } } else { if (mx) { if (house[cx + sx][cy]) { sx = -sx; } else { cx += sx; } } if (my) { if (house[cx][cy + sy]) { sy = -sy; } else { cy += sy; } } } i++; } return false; } public static void printHouse(int lx, int ly, int cx, int cy, boolean [][] house) { for (int y = 0; y < house[0].length; y++) { for (int x = 0; x < house.length; x++) { if (x == cx && y == cy) { System.out.print('*'); } else if (x == lx && y == ly) { System.out.print('X'); } else if (house[x][y]) { System.out.print('#'); } else { System.out.print(' '); } } System.out.println(); } } public static int[][] getPossibilities(int d) { ArrayList<Integer> lx = new ArrayList<Integer>(); ArrayList<Integer> ly = new ArrayList<Integer>(); int h, v; for (int x = -d; x <= d; x++) { for (int y = -d; y <= d; y++) { h = Math.abs(x); v = Math.abs(y); if (gcd(h,v) == 1 && h*h + v*v <= d*d) { lx.add(x); ly.add(y); } } } int [][] possibilities = new int [lx.size()][2]; for (int i = 0; i < possibilities.length; i++) { possibilities[i][0] = lx.get(i); possibilities[i][1] = ly.get(i); } return possibilities; } public static void printResult() { int h,w,d,lx = 0,ly = 0; h = in.nextInt(); w = in.nextInt(); d = in.nextInt(); in.nextLine(); String s; boolean [][] house = new boolean[w][h]; for (int y = 0; y < h; y++) { s = in.nextLine(); for (int x = 0; x < w; x++) { house[x][y] = s.charAt(x) == '#'; if (s.charAt(x) == 'X') { lx = x; ly = y; } } } int [][] poss = getPossibilities(d); int images = 0; for (int i = 0; i < poss.length; i++) { if (canSeeImage(poss[i][0], poss[i][1], lx, ly, d, house)) { images++; //System.out.println("True"); } //else //System.out.println("False"); } out.print(images); } }
package qualification; import java.io.*; import java.util.Scanner; /** * @author Roman Elizarov */ public class D { public static void main(String[] args) throws IOException { new D().go(); } Scanner in; PrintWriter out; private void go() throws IOException { in = new Scanner(new File("src\\qualification\\d.in")); out = new PrintWriter(new File("src\\qualification\\d.out")); int t = in.nextInt(); for (int tn = 1; tn <= t; tn++) { System.out.println("Case #" + tn); out.println("Case #" + tn + ": " + solveCase()); } in.close(); out.close(); } int h; int w; int d; char[][] c; int a00 = 1; int a01; int a10; int a11 = 1; int b0; int b1; char get(int x, int y) { return c[a00 * x + a01 * y + b0][a10 * x + a11 * y + b1]; } void printC() { System.out.println("--- C ---"); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) System.out.print(c[i][j]); System.out.println(); } } void printV(String hdr) { System.out.println("--- " + hdr + " ---"); for (int y = 3; y >= -4; y--) { System.out.print(y == 0 ? "_" : " "); for (int x = 0; x <= 5; x++) try { System.out.print(get(x, y)); } catch (ArrayIndexOutOfBoundsException e) { System.out.print('?'); } System.out.println(); } } // Rotate 90 deg ccw around point (0.5, 0.5) void rotateCCW() { int d00 = -a01; int d01 = a00; int d10 = -a11; int d11 = a10; a00 = d00; a01 = d01; a10 = d10; a11 = d11; } // Rotate 90 deg cw around point (0.5, 0.5) void rotateCW() { int d00 = a01; int d01 = -a00; int d10 = a11; int d11 = -a10; a00 = d00; a01 = d01; a10 = d10; a11 = d11; } // Mirror around x = p void mirrorX(int p) { b0 += a00 * (2 * p - 1); b1 += a10 * (2 * p - 1); a00 = -a00; a10 = -a10; } // Mirror around y = q void mirrorY(int q) { b0 += a01 * (2 * q - 1); b1 += a11 * (2 * q - 1); a01 = -a01; a11 = -a11; } // Mirror around y = 0.5 void mirrorYC() { a01 = -a01; a11 = -a11; } private int solveCase() { h = in.nextInt(); w = in.nextInt(); d = in.nextInt(); c = new char[h][]; for (int i = 0; i < h; i++) { c[i] = in.next().toCharArray(); assert c[i].length == w; } printC(); find: for (b0 = 0; b0 < h; b0++) for (b1 = 0; b1 < w; b1++) if (c[b0][b1] == 'X') break find; int cnt = 0; for (int i = 0; i < 4; i++) { cnt += solveRay(1, 1); cnt += solveRangeX(1, 1, -1, 1, 1); rotateCCW(); } return cnt; } // (0.5, 0.5) -> (x, y) int solveRay(int x, int y) { int cnt = 0; if (y <= 0) { mirrorYC(); cnt = solveRay(x, -y + 1); mirrorYC(); return cnt; } if (!possible(x, y)) return 0; assert x > 0; switch (get(x, y)) { case '#': char c1 = get(x - 1, y); char c2 = get(x, y - 1); if (c1 == '#' && c2 == '#') { // reflected straight back if (good2(x, y)) cnt++; } else if (c1 == '#') { mirrorY(y); cnt = solveRay(x, y); mirrorY(y); } else if (c2 == '#') { mirrorX(x); cnt = solveRay(x, y); mirrorX(x); } // otherwise -> destroyed break; case 'X': if (x == y) { if (good(x, y)) cnt++; break; } // fall-through case '.': if (x < y) cnt = solveRay2(2 * x - 1, 2 * y - 1, x, y + 1); else if (x > y) cnt = solveRay2(2 * x - 1, 2 * y - 1, x + 1, y); else // x == y cnt = solveRay(x + 1, y + 1); break; default: assert false; } return cnt; } int solveRay2(int x0, int y0, int x, int y) { if (!possible(x, y)) return 0; int cnt = 0; int ccw; switch (get(x, y)) { case '#': ccw = ccw(x0, y0, 2 * x - 1, 2 * y - 1); if (ccw > 0) { mirrorY(y); cnt = solveRay2(x0, y0, x, y); mirrorY(y); } else if (ccw < 0) { mirrorX(x); cnt = solveRay2(x0, y0, x, y); mirrorX(x); } else cnt = solveRay(x, y); // hit corner break; case 'X': if (ccw(x0, y0, x, y) == 0) { if (good(x, y)) cnt++; break; } case '.': ccw = ccw(x0, y0, 2 * x + 1, 2 * y + 1); if (ccw > 0) cnt = solveRay2(x0, y0, x + 1, y); else if (ccw < 0) cnt = solveRay2(x0, y0, x, y + 1); else cnt = solveRay(x + 1, y + 1); // hit corner break; default: assert false; } return cnt; } // (0.5, 0.5) -> (p, y') between (x0, y0) and (x1, y1) vectors int solveRangeX(int p, int x0, int y0, int x1, int y1) { //printV("solveRangeX(" + p + "," + x0 + "," + y0 + "," + x1 + "," + y1 + ")"); assert ccw(x0, y0, x1, y1) > 0; if (p > d) return 0; int q = projectRay(p, x0, y0); assert ccw(2 * p - 1, 2 * q - 1, x0, y0) >= 0; assert ccw(x1, y1, 2 * p - 1, 2 * q + 1) >= 0; int cnt = 0; switch (get(p, q)) { case '#': mirrorX(p); cnt += solveRangeX(p, x0, y0, x1, y1); mirrorX(p); break; case 'X': if (ccw(x0, y0, p, q) > 0 && ccw(p, q, x1, y1) > 0) { if (good(p, q)) cnt++; cnt += solveRangeX(p, x0, y0, p, q); cnt += solveRangeX(p, p, q, x1, y1); break; } // fall-through case '.': if (q <= 0 && ccw(x0, y0, 2 * p + 1, 2 * q - 1) > 0) { if (ccw(2 * p + 1, 2 * q - 1, x1, y1) > 0) { cnt += solveRangeY(q, x0, y0, 2 * p + 1, 2 * q - 1); cnt += solveRay(p + 1, q); x0 = 2 * p + 1; y0 = 2 * q - 1; } else { cnt += solveRangeY(q, x0, y0, x1, y1); break; } } if (q >= 0 && ccw(2 * p + 1, 2 * q + 1, x1, y1) > 0) { if (ccw(x0, y0, 2 * p + 1, 2 * q + 1) > 0) { cnt += solveRangeY(q + 1, 2 * p + 1, 2 * q + 1, x1, y1); cnt += solveRay(p + 1, q + 1); x1 = 2 * p + 1; y1 = 2 * q + 1; } else { cnt += solveRangeY(q + 1, x0, y0, x1, y1); break; } } cnt += solveRangeX(p + 1, x0, y0, x1, y1); break; default: assert false; } return cnt; } private boolean possible(int x, int y) { return sqr(2 * x - 1) + sqr(2 * y - 1) <= sqr(2 * d); } private boolean good(int x, int y) { return sqr(x) + sqr(y) <= sqr(d); } boolean good2(int x, int y) { return sqr(2 * x - 1) + sqr(2 * y - 1) <= sqr(d); } int solveRangeY(int q, int x0, int y0, int x1, int y1) { //printV("solveRangeY(" + q + "," + x0 + "," + y0 + "," + x1 + "," + y1 + ")"); int cnt; if (q <= 0) { rotateCCW(); cnt = solveRangeX(-q + 1, -y0, x0, -y1, x1); rotateCW(); } else { rotateCW(); cnt = solveRangeX(q, y0, -x0, y1, -x1); rotateCCW(); } return cnt; } static int projectRay(int p, int x0, int y0) { return div(x0 + y0 * (2 * p - 1), 2 * x0); } static int div(int a, int b) { assert b > 0; return a >= 0 ? a / b : -((-a + b - 1)/ b); } static int ccw(int x0, int y0, int x1, int y1) { return x0 * y1 - x1 * y0; } static int sqr(int x) { return x * x; } }
C20046
C20078
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.awt.Point; public class FracVec { public final Frac row, col; public FracVec(Frac row, Frac col) { this.row = row; this.col = col; } public FracVec(Point pos) { row = new Frac(pos.y); col = new Frac(pos.x); } public FracVec flipHoriz() { return new FracVec(row, col.neg()); } public FracVec flipVert() { return new FracVec(row.neg(), col); } public boolean isCorner() { return row.denom == 1 && col.denom == 1; } public FracVec add(FracVec other) { return new FracVec(row.add(other.row), col.add(other.col)); } public FracVec sub(FracVec other) { return new FracVec(row.sub(other.row), col.sub(other.col)); } public FracVec neg() { return new FracVec(row.neg(), col.neg()); } public boolean equals(FracVec other) { return row.equals(other.row) && col.equals(other.col); } public boolean equals(Point p) { return row.equals(p.y) && col.equals(p.x); } @Override public boolean equals(Object other) { return other instanceof FracVec && equals((FracVec) other); } @Override public int hashCode() { return (31 + row.hashCode()) * 31 + col.hashCode(); } public String toString() { return "( " + row + ", " + col + " )"; } public FracVec multiply(Frac scalar) { return new FracVec(row.mult(scalar), col.mult(scalar)); } public int compareLengthTo(int d) { return row.mult(row).add(col.mult(col)).compareTo(new Frac(d * d)); } public Point getNextCell(FracVec dm) { int resRow, resCol; if (dm.row.sgn() < 0) { resRow = row.roundDownAddSmallDown(); } else { resRow = row.roundDownAddSmallUp(); } if (dm.col.sgn() < 0) resCol = col.roundDownAddSmallDown(); else resCol = col.roundDownAddSmallUp(); return new Point(resCol, resRow); } }
C20073
C20006
0
/* * Main.java * * Created on 14.04.2012, 10:03:46 * * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam12; import qualification.CodeJamQuali; /** * * @author Besitzer */ public class Main { /** * @param args the command line arguments */ /*public static void main(String[] args) { char[] C = new char[26]; CodeJamQuali CJQ =new CodeJamQuali(); CJQ.fillDict("our language is impossible to understand","ejp mysljylc kd kxveddknmc re jsicpdrysi",C); CJQ.fillDict("there are twenty six factorial possibilities","rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd",C); CJQ.fillDict("so it is okay if you want to just give up","de kr kd eoya kw aej tysr re ujdr lkgc jv",C); C['z'-'a']='q'; C['q'-'a']='z'; System.out.println("abcdefghijklmnopqrstuvwxyz"); System.out.println(C); for(int i =0;i<26;i++)if(C[i]=='z')System.out.println("found"); }*/ public static void main(String[] args) { CodeJamQuali CJQ =new CodeJamQuali(); //CJQ.go("src/qualification/A-small-attempt0.in", 1); CJQ.go("src/qualification/D-large.in", 4); //System.out.println(new java.math.BigInteger("2").gcd(java.math.BigInteger.ZERO)); } }
package problemD; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ProblemD { static Rational posX = null; static Rational posY = null; static Rational tarX = null; static Rational tarY = null; static boolean[][] array = null; public static void main(String[] args) throws FileNotFoundException { // Scanner sc = new Scanner(new File("D-practice.in")); // Scanner sc = new Scanner(new File("D-small.in")); Scanner sc = new Scanner(new File("D-large.in")); int cases = sc.nextInt(); for (int i = 1; i <= cases; i++) { // do case things here int H = sc.nextInt(); int W = sc.nextInt(); int D = sc.nextInt(); D *= 2; array = new boolean[H][W]; for (int j = 0; j < H; j++) { String s = sc.next(); for (int k = 0; k < W; k++) { array[j][k] = (s.charAt(k) == '#'); if (s.charAt(k) == 'X') { posX = new Rational(2 * k + 1, 1); posY = new Rational(2 * j + 1, 1); tarX = posX; tarY = posY; } } } int count = 0; boolean checked[][] = new boolean[2 * D + 1][2 * D + 1]; for (int j = 2; j <= D; j += 2) { for (int x = -j; x <= j; x += 2) { if (D + j >= 0 && D + j < checked.length && D + x >= 0 && D + x < checked.length) { if (!checked[D + j][D + x]) { if (followRay(j, x, D)) { count++; } int k = 1; while (D + (k * j) >= 0 && D + (k * j) < checked.length && D + (k * x) >= 0 && D + (k * x) < checked.length) { checked[D + (k * j)][D + (k * x)] = true; k++; } } } if (D + j >= 0 && D + j < checked.length && D + x >= 0 && D + x < checked.length) { if (!checked[D + x][D + j]) { if (followRay(x, j, D)) { count++; } int k = 1; while (D + (k * j) >= 0 && D + (k * j) < checked.length && D + (k * x) >= 0 && D + (k * x) < checked.length) { checked[D + (k * x)][D + (k * j)] = true; k++; } } } if (D - j >= 0 && D - j < checked.length && D + x >= 0 && D + x < checked.length) { if (!checked[D - j][D + x]) { if (followRay(-j, x, D)) { count++; } int k = 1; while (D - (k * j) >= 0 && D - (k * j) < checked.length && D + (k * x) >= 0 && D + (k * x) < checked.length) { checked[D - (k * j)][D + (k * x)] = true; k++; } } } if (D - j >= 0 && D - j < checked.length && D + x >= 0 && D + x < checked.length) { if (!checked[D + x][D - j]) { if (followRay(x, -j, D)) { count++; } int k = 1; while (D - (k * j) >= 0 && D - (k * j) < checked.length && D + (k * x) >= 0 && D + (k * x) < checked.length) { checked[D + (k * x)][D - (k * j)] = true; k++; } } } } } // System.out.println(count); System.out.format("Case #%d: %d\n", i, count); } } private static boolean followRay(int dirX, int dirY, int max) { double distance = 0; posX = tarX; posY = tarY; distance += step(dirX, dirY); while (distance <= max) { if (tarX.equals(posX) && tarY.equals(posY)) { return true; } // check mirror, adjust direction if (dirX == 0) { if (posY.n == 1 && posY.z % 2 == 0) { int y = posY.z / 2; if (y >= array.length || y == 0) { return false; } int x = posX.z / posX.n / 2; if (dirY > 0 && array[y][x] || dirY < 0 && array[y - 1][x]) { dirY = -1 * dirY; } } } else if (dirY == 0) { if (posX.n == 1 && posX.z % 2 == 0) { int x = posX.z / 2; if (x >= array[0].length || x == 0) { return false; } int y = posY.z / posY.n / 2; if (dirX > 0 && array[y][x] || dirX < 0 && array[y][x - 1]) { dirX = -1 * dirX; } } } if (posX.n == 1 && posX.z % 2 == 0) { if (posY.n == 1 && posY.z % 2 == 0) { // corner int x = posX.z / 2; int y = posY.z / 2; boolean mirrored = false; if (dirX > 0) { if (array[y][x] && array[y - 1][x]) { dirX = -1 * dirX; mirrored = true; } } else { if (array[y][x - 1] && array[y - 1][x - 1]) { dirX = -1 * dirX; mirrored = true; } } if (dirY > 0) { if (array[y][x] && array[y][x - 1]) { dirY = -1 * dirY; mirrored = true; } } else { if (array[y - 1][x] && array[y - 1][x - 1]) { dirY = -1 * dirY; mirrored = true; } } if (!mirrored) { if (dirX > 0) { if (dirY > 0) { if (array[y][x]) { return false; } } else { if (array[y - 1][x]) { return false; } } } else { if (dirY > 0) { if (array[y][x - 1]) { return false; } } else { if (array[y - 1][x - 1]) { return false; } } } } } else { int x = posX.z / 2; if (x >= array[0].length || x == 0) { return false; } int y = posY.z / posY.n / 2; if (dirX > 0 && array[y][x] || dirX < 0 && array[y][x - 1]) { dirX = -1 * dirX; } } } else if (posY.n == 1 && posY.z % 2 == 0) { int y = posY.z / 2; if (y >= array.length || y == 0) { return false; } int x = posX.z / posX.n / 2; if (dirY > 0 && array[y][x] || dirY < 0 && array[y - 1][x]) { dirY = -1 * dirY; } } distance += step(dirX, dirY); } return false; } // steps until the next coord becomes integer private static double step(int dirX, int dirY) { if (dirY == 0) { if (dirX > 0) { posX = posX.plus(Rational.one); } else { posX = posX.minus(Rational.one); } return 1; } if (dirX == 0) { if (dirY > 0) { posY = posY.plus(Rational.one); } else { posY = posY.minus(Rational.one); } return 1; } if (posX.n == 1) { Rational distY = posY.fractal(); Rational speed = new Rational(Math.abs(dirY), Math.abs(dirX)); if (dirY > 0) { distY = Rational.one.minus(distY); } if (distY.equals(Rational.zero)) { distY = Rational.one; } if (distY.minus(speed).positive()) { if (dirX > 0) { posX = posX.plus(Rational.one); } else { posX = posX.minus(Rational.one); } if (dirY > 0) { posY = posY.plus(speed); } else { posY = posY.minus(speed); } return Math.sqrt(1 + speed.times(speed).value()); } else { if (dirY > 0) { posY = posY.plus(distY); } else { posY = posY.minus(distY); } Rational distX = distY.divides(speed); if (dirX > 0) { posX = posX.plus(distX); } else { posX = posX.minus(distX); } return Math.sqrt(distY.times(distY).value() + distX.times(distX).value()); } } else { Rational distX = posX.fractal(); Rational speed = new Rational(Math.abs(dirX), Math.abs(dirY)); if (dirX > 0) { distX = Rational.one.minus(distX); } if (distX.minus(speed).positive()) { if (dirY > 0) { posY = posY.plus(Rational.one); } else { posY = posY.minus(Rational.one); } if (dirX > 0) { posX = posX.plus(speed); } else { posX = posX.minus(speed); } return Math.sqrt(1 + speed.times(speed).value()); } else { if (dirX > 0) { posX = posX.plus(distX); } else { posX = posX.minus(distX); } Rational distY = distX.divides(speed); if (dirY > 0) { posY = posY.plus(distY); } else { posY = posY.minus(distY); } return Math.sqrt(distY.times(distY).value() + distX.times(distX).value()); } } } // private static void out(boolean[] array) { // System.out.println(Arrays.toString(array)); // } // // private static void out(boolean[][] array) { // int count = 0; // for (boolean[] a : array) { // System.out.print(count++ + ":"); // out(a); // } // } private static class Rational { static final Rational one = new Rational(1, 1); static final Rational zero = new Rational(0, 1); public int z; public int n; // create and initialize a new Rational object public Rational(int z, int n) { if (n == 0) { throw new RuntimeException("Denominator is zero"); } int g = gcd(z, n); this.z = z / g; this.n = n / g; } // return string representation of (this) public String toString() { if (n == 1) { return z + ""; } else { return z + "/" + n; } } // return (this * b) public Rational times(Rational b) { return new Rational(this.z * b.z, this.n * b.n); } // return (this + b) public Rational plus(Rational b) { int z = (this.z * b.n) + (this.n * b.z); int n = this.n * b.n; return new Rational(z, n); } // return (this - b) public Rational minus(Rational b) { int z = (this.z * b.n) - (this.n * b.z); int n = this.n * b.n; return new Rational(z, n); } // return fractal amount public Rational fractal() { return new Rational(z % n, n); } // return (1 / this) public Rational reciprocal() { return new Rational(n, z); } // return (this / b) public Rational divides(Rational b) { return this.times(b.reciprocal()); } public boolean positive() { return z * n >= 0; } public boolean equals(Rational r) { return r.z == this.z && r.n == this.n; } public double value() { return 1.0 * z / n; } private int gcd(int m, int n) { if (0 == n) return m; else return gcd(n, m % n); } } }
C20023
C20042
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 jp.funnything.prototype; import static java.lang.Math.abs; import java.io.File; import java.io.IOException; import jp.funnything.competition.util.CompetitionIO; import jp.funnything.competition.util.Packer; import org.apache.commons.io.FileUtils; import org.apache.commons.math.fraction.Fraction; import org.apache.commons.math.util.MathUtils; public class Runner { public static void main( final String[] args ) throws Exception { new Runner().run(); } boolean isValid( final int d , final boolean[][] map , final int ox , final int oy , int dx , int dy ) { final Fraction fox = new Fraction( ox * 2 + 1 ); final Fraction foy = new Fraction( oy * 2 + 1 ); Fraction x = new Fraction( ox * 2 + 1 ); Fraction y = new Fraction( oy * 2 + 1 ); Fraction sumDiffX = new Fraction( 0 ); Fraction sumDiffY = new Fraction( 0 ); for ( ; ; ) { final Fraction diffX = new Fraction( dx > 0 ? ( int ) Math.floor( x.doubleValue() + 1 ) : ( int ) Math.ceil( x.doubleValue() - 1 ) ).subtract( x ); final Fraction diffY = new Fraction( dy > 0 ? ( int ) Math.floor( y.doubleValue() + 1 ) : ( int ) Math.ceil( y.doubleValue() - 1 ) ).subtract( y ); if ( abs( diffX.doubleValue() * dy ) < abs( diffY.doubleValue() * dx ) ) { x = x.add( diffX ); y = y.add( diffX.multiply( dy ).divide( dx ) ); sumDiffX = sumDiffX.add( diffX.abs() ); sumDiffY = sumDiffY.add( diffX.multiply( dy ).divide( dx ).abs() ); } else { y = y.add( diffY ); x = x.add( diffY.multiply( dx ).divide( dy ) ); sumDiffY = sumDiffY.add( diffY.abs() ); sumDiffX = sumDiffX.add( diffY.multiply( dx ).divide( dy ).abs() ); } if ( sumDiffX.multiply( sumDiffX ).add( sumDiffY.multiply( sumDiffY ) ).compareTo( new Fraction( d * d * 2 * 2 ) ) > 0 ) { return false; } if ( x.equals( fox ) && y.equals( foy ) ) { return true; } final int nx = x.intValue() / 2 + ( dx > 0 ? 0 : -1 ); final int ny = y.intValue() / 2 + ( dy > 0 ? 0 : -1 ); if ( x.getDenominator() == 1 && x.getNumerator() % 2 == 0 && y.getDenominator() == 1 && y.getNumerator() % 2 == 0 ) { if ( map[ ny ][ nx ] ) { final int px = x.intValue() / 2 + ( dx > 0 ? -1 : 0 ); final int py = y.intValue() / 2 + ( dy > 0 ? -1 : 0 ); if ( map[ py ][ nx ] ) { if ( map[ ny ][ px ] ) { dx = -dx; dy = -dy; } else { dx = -dx; } } else { if ( map[ ny ][ px ] ) { dy = -dy; } else { return false; } } } } else { if ( x.getDenominator() == 1 && x.getNumerator() % 2 == 0 ) { if ( map[ y.intValue() / 2 ][ nx ] ) { dx = -dx; } } else if ( y.getDenominator() == 1 && y.getNumerator() % 2 == 0 ) { if ( map[ ny ][ x.intValue() / 2 ] ) { dy = -dy; } } } } } 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 h = values[ 0 ]; final int w = values[ 1 ]; final int d = values[ 2 ]; final char[][] map = new char[ h ][]; for ( int y = 0 ; y < h ; y++ ) { final char[] l = io.read().toCharArray(); if ( l.length != w ) { throw new RuntimeException( "assert" ); } map[ y ] = l; } io.write( index + 1 , solve( d , map ) ); } io.close(); pack(); } int solve( final int d , final char[][] map ) { int count = 0; int ox = -1; int oy = -1; final boolean[][] parsed = new boolean[ map.length ][]; for ( int y = 0 ; y < map.length ; y++ ) { parsed[ y ] = new boolean[ map[ y ].length ]; for ( int x = 0 ; x < map[ y ].length ; x++ ) { final char c = map[ y ][ x ]; if ( c == '#' ) { parsed[ y ][ x ] = true; } if ( c == 'X' ) { ox = x; oy = y; } } } for ( int dy = -d ; dy <= d ; dy++ ) { for ( int dx = -d ; dx <= d ; dx++ ) { if ( dx == 0 && dy == 0 ) { continue; } if ( MathUtils.gcd( dx , dy ) != 1 ) { continue; } if ( dx * dx + dy * dy > d * d ) { continue; } if ( isValid( d , parsed , ox , oy , dx , dy ) ) { count++; } } } return count; } }
C20073
C20002
0
/* * Main.java * * Created on 14.04.2012, 10:03:46 * * To change this template, choose Tools | Templates * and open the template in the editor. */ package codejam12; import qualification.CodeJamQuali; /** * * @author Besitzer */ public class Main { /** * @param args the command line arguments */ /*public static void main(String[] args) { char[] C = new char[26]; CodeJamQuali CJQ =new CodeJamQuali(); CJQ.fillDict("our language is impossible to understand","ejp mysljylc kd kxveddknmc re jsicpdrysi",C); CJQ.fillDict("there are twenty six factorial possibilities","rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd",C); CJQ.fillDict("so it is okay if you want to just give up","de kr kd eoya kw aej tysr re ujdr lkgc jv",C); C['z'-'a']='q'; C['q'-'a']='z'; System.out.println("abcdefghijklmnopqrstuvwxyz"); System.out.println(C); for(int i =0;i<26;i++)if(C[i]=='z')System.out.println("found"); }*/ public static void main(String[] args) { CodeJamQuali CJQ =new CodeJamQuali(); //CJQ.go("src/qualification/A-small-attempt0.in", 1); CJQ.go("src/qualification/D-large.in", 4); //System.out.println(new java.math.BigInteger("2").gcd(java.math.BigInteger.ZERO)); } }
import java.util.*; import java.io.*; import java.math.*; import java.awt.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Double.parseDouble; import static java.lang.Long.parseLong; import static java.lang.System.*; import static java.util.Arrays.*; import static java.util.Collection.*; public class D { static int gcd(int a, int b) { return b == 0 ? a : a == 0 ? b : gcd(b, a%b); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(in)); int T = parseInt(br.readLine()); for(int t = 0; t++ < T; ) { String[] line = br.readLine().split(" "); int H = parseInt(line[0]), W = parseInt(line[1]), D = parseInt(line[2]); char[][] G = new char[H][]; for(int h = 0; h < H; h++) G[h] = br.readLine().toCharArray(); int X = 0, Y = 0; outer:for(Y = 0; Y < H; Y++) for(X = 0; X < W; X++) if(G[Y][X] == 'X') break outer; int count = 0; for(int i = -D; i <= D; i++) { for(int j = -D; j <= D; j++) { int dx = i, dy = j, scale = 2 * Math.abs((dx == 0 ? 1 : dx) * (dy == 0 ? 1 : dy)), x0, y0, x, y; int steps = (int)Math.floor(scale * D / Math.sqrt(dx * dx + dy * dy)); if(gcd(Math.abs(dx), Math.abs(dy)) != 1) continue; x0 = x = X * scale + scale / 2; y0 = y = Y * scale + scale / 2; do { steps -= 1; if(x % scale == 0 && y % scale == 0) { // at a corner int dxi = dx > 0 ? 1 : -1, dyi = dy > 0 ? 1 : -1; int xi = (x / scale) - (dxi + 1) / 2, yi = (y / scale) - (dyi + 1) / 2; if(G[yi+dyi][xi+dxi] == '#') { if(G[yi+dyi][xi] != '#' && G[yi][xi+dxi] != '#') steps = -1; // kill the light if(G[yi+dyi][xi] == '#') dy *= -1; if(G[yi][xi+dxi] == '#') dx *= -1; } else ; // otherwise step as normal } else if(x % scale == 0) { int xi = x / scale, yi = y / scale; if(G[yi][xi] == '#' || G[yi][xi-1] == '#') dx *= -1; } else if(y % scale == 0) { int xi = x / scale, yi = y / scale; if(G[yi][xi] == '#' || G[yi-1][xi] == '#') dy *= -1; } else ; // smooth sailing x += dx; y += dy; } while(steps >= 0 && !(x == x0 && y == y0)); if(steps >= 0) ++count; } } out.println("Case #" + t +": " + count) ; } } }
C20046
C20030
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 uk.co.epii.codejam.hallofmirrors; /** * * @author jim */ public class RayVector { public final int x; public final int y; public RayVector(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { if (obj instanceof RayVector) { RayVector v = (RayVector)obj; if (v.x * y == v.y * x) return true; } return false; } @Override public int hashCode() { int hash = 7; hash = 41 * hash + this.x; hash = 41 * hash + this.y; return hash; } public Fraction getScalarGardient() { return new Fraction(Math.abs(y), Math.abs(x)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(x); sb.append(","); sb.append(y); sb.append(")"); return sb.toString(); } }
C20054
C20076
0
package jp.funnything.competition.util; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import org.apache.commons.io.IOUtils; public class QuestionReader { private final BufferedReader _reader; public QuestionReader( final File input ) { try { _reader = new BufferedReader( new FileReader( input ) ); } catch ( final FileNotFoundException e ) { throw new RuntimeException( e ); } } public void close() { IOUtils.closeQuietly( _reader ); } public String read() { try { return _reader.readLine(); } catch ( final IOException e ) { throw new RuntimeException( e ); } } public BigDecimal[] readBigDecimals() { return readBigDecimals( " " ); } public BigDecimal[] readBigDecimals( final String separator ) { final String[] tokens = readTokens( separator ); final BigDecimal[] values = new BigDecimal[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = new BigDecimal( tokens[ index ] ); } return values; } public BigInteger[] readBigInts() { return readBigInts( " " ); } public BigInteger[] readBigInts( final String separator ) { final String[] tokens = readTokens( separator ); final BigInteger[] values = new BigInteger[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = new BigInteger( tokens[ index ] ); } return values; } public int readInt() { final int[] values = readInts(); if ( values.length != 1 ) { throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" ); } return values[ 0 ]; } public int[] readInts() { return readInts( " " ); } public int[] readInts( final String separator ) { final String[] tokens = readTokens( separator ); final int[] values = new int[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = Integer.parseInt( tokens[ index ] ); } return values; } public long readLong() { final long[] values = readLongs(); if ( values.length != 1 ) { throw new IllegalStateException( "Try to read single interger, but the line contains zero or multiple values" ); } return values[ 0 ]; } public long[] readLongs() { return readLongs( " " ); } public long[] readLongs( final String separator ) { final String[] tokens = readTokens( separator ); final long[] values = new long[ tokens.length ]; for ( int index = 0 ; index < tokens.length ; index++ ) { values[ index ] = Long.parseLong( tokens[ index ] ); } return values; } public String[] readTokens() { return readTokens( " " ); } public String[] readTokens( final String separator ) { return read().split( separator ); } }
import java.io.*; import java.math.*; import java.util.*; public class D { final static boolean DEBUG = true; class S implements Comparable<S> { int a; int [] b; public int compareTo(S s) { if (a != s.a) return a - s.a; else return b[0] - s.b[0]; } boolean merge(S s) { if (a == s.a && b[1] >= s.b[0]) { b[0] = Math.min(b[0], s.b[0]); b[1] = Math.max(b[1], s.b[1]); return true; } else return false; } public String toString() { return "a=" + a + "; b=" + Arrays.toString(b); } } void add(List<S> L, int a, int b1, int b2) { S m = new S(); m.a = a; m.b = new int [] { b1, b2 }; L.add(m); } List<S> normalize(List<S> L) { List<S> tmp = new ArrayList<S>(); Collections.sort(L); S c = null; for (S s : L) { if (c == null) c = s; else { if (!c.merge(s)) { tmp.add(c); c = s; } } } assert(c != null); tmp.add(c); return tmp; } public Object solve () throws IOException { int ZZ = 300; int H = 2 * sc.nextInt(); int W = 2 * sc.nextInt(); int D = 2 * sc.nextInt(); int MH = H-4, MW = W-4; int [] ME = null; S[] LV,UV,LH,UH; { List<S> _LH = new ArrayList<S>(); List<S> _LV = new ArrayList<S>(); List<S> _UH = new ArrayList<S>(); List<S> _UV = new ArrayList<S>(); add(_LV, 0, -1, MH+1); add(_UV, MW, -1, MH+1); add(_LH, 0, -1, MW+1); add(_UH, MH, -1, MW+1); sc.nextLine(); for (int i = 0; i < MH/2; ++i) { char [] R = sc.nextChars(); for (int j = 0; j < MW/2; ++j) { char z = R[j+1]; if (z == 'X') ME = new int [] { 2*j+1, 2*i+1 }; if (z == '#') { int vl = 2*i, vu = 2*i+2, hl = 2*j, hu = 2*j+2; int dvl = 0, dvu = 0, dhl = 0, dhu = 0; if (vl == 0) ++dvl; if(vu == MH) ++dvu; if (hl == 0) ++dhl; if (hu == MW) ++dhu; add(_LV, hu, vl-dvl, vu+dvu); add(_UV, hl, vl-dvl, vu+dvu); add(_LH, vu, hl-dhl, hu+dhu); add(_UH, vl, hl-dhl, hu+dhu); } } } sc.nextLine(); _LV = normalize(_LV); _UV = normalize(_UV); _LH = normalize(_LH); _UH = normalize(_UH); LV = _LV.toArray(new S[0]); UV = _UV.toArray(new S[0]); LH = _LH.toArray(new S[0]); UH = _UH.toArray(new S[0]); } int cnt = 0; for (int ax = -ZZ; ax <= ZZ; ++ax) for (int ay = -ZZ; ay <= ZZ; ++ay) if (gcd(ax, ay) == 1) { double d = 0, px = ME[0], py = ME[1]; int tax = ax, tay = ay; while (d < D) { X slv = new X(), suv = new X(), slh = new X(), suh = new X(); if (tax < 0) slv = T(LV, px, py, tax, tay, ME[0], ME[1], MH); if (tax > 0) suv = T(UV, px, py, tax, tay, ME[0], ME[1], MH); if (tay < 0) slh = T(LH, py, px, tay, tax, ME[1], ME[0], MW); if (tay > 0) suh = T(UH, py, px, tay, tax, ME[1], ME[0], MW); double minvd = 1e20, minhd = 1e20, mind = 1e20; minvd = Math.min(slv.d, minvd); minvd = Math.min(suv.d, minvd); minhd = Math.min(slh.d, minhd); minhd = Math.min(suh.d, minhd); mind = Math.min(minvd, minhd); d += Math.sqrt(mind); if (d > D + seps) break; if (slv.d == mind && slv.kill) { if (slv.me) ++cnt; break; } if (suv.d == mind && suv.kill) { if (suv.me) ++cnt; break; } if (slh.d == mind && slh.kill) { if (slh.me) ++cnt; break; } if (suh.d == mind && suh.kill) { if (suh.me) ++cnt; break; } if (Math.abs(minvd - minhd) < eps) { if (d < D/2.0 + seps) ++cnt; break; } if (slv.d == mind) { px = slv.pa; py = slv.pb; tax = slv.aa; tay = slv.ab; }; if (suv.d == mind) { px = suv.pa; py = suv.pb; tax = suv.aa; tay = suv.ab; }; if (slh.d == mind) { px = slh.pb; py = slh.pa; tax = slh.ab; tay = slh.aa; }; if (suh.d == mind) { px = suh.pb; py = suh.pa; tax = suh.ab; tay = suh.aa; }; } } return cnt; } class X { double pa, pb, d = 1e20; int aa, ab; boolean me = false, kill = false; public String toString() { if (d == 1e20) return "NO"; if (me) return "ME; d=" + d; else if (kill) return "KILL; d=" + d; return "d=" + Math.sqrt(d) + "; pa=" + pa + "; pb=" + pb + "; aa=" + aa + "ab=" + ab; } } double eps = 1e-9; double seps = Math.sqrt(eps); X T(S[] L, double pa, double pb, int aa, int ab, double mea, double meb, int M) { double aaa = Math.abs(aa); double nab = ab/aaa, naa = aa/aaa; double dme = 1e20; double tme = (mea - pa)/naa; if (tme > 0 && Math.abs(meb - (tme*nab + pb)) < eps) dme = (mea-pa)*(mea-pa) + (meb-pb)*(meb-pb); X x = new X(); int P = -1, Q = L.length; int p = P, q = Q, m; while (q - p > 1) { m = (p+q)/2; if (m == P) ++m; if (L[m].a > pa) q = m; else p = m; } int z = naa > 0 ? q : p; int da = naa > 0 ? 1 : -1; int db = nab > 0 ? 1 : -1; for (; ; z += da) { S s = L[z]; double t = Math.abs(s.a - pa); // double sa = pa + t * naa; double sb = pb + t * nab; double d = (s.a-pa)*(s.a-pa) + (sb-pb)*(sb-pb); if (d > dme) { x.me = x.kill = true; x.d = dme; return x; } if (sb < -eps || sb > M + eps) return x; if (Math.abs(sb - s.b[(1-db)/2]) < eps) { x.kill = true; x.d = d; return x; } if (sb > s.b[0] && sb < s.b[1]) { x.pa = s.a; x.pb = sb; x.aa = -aa; x.ab = ab; x.d = d; return x; } } //throw new Error("NO WAY!"); } int gcd (int a, int b) { a = Math.abs(a); b = Math.abs(b); if (a*b != 0) return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).intValue(); else return a+b; } void init () { } //////////////////////////////////////////////////////////////////////////////////// public D () throws IOException { init(); int N = sc.nextInt(); start(); for (int n = 1; n <= N; ++n) print("Case #" + n + ": " + solve()); exit(); } static MyScanner sc; static long t; static void print (Object o) { System.out.println(o); if (DEBUG) System.err.println(o + " (" + ((millis() - t) / 1000.0) + ")"); } static void exit () { if (DEBUG) { System.err.println(); System.err.println((millis() - t) / 1000.0); } System.exit(0); } static void run () throws IOException { sc = new MyScanner (); new D(); } public static void main(String[] args) throws IOException { run(); } static long millis() { return System.currentTimeMillis(); } static void start() { t = millis(); } static class MyScanner { String next() throws IOException { newLine(); return line[index++]; } char [] nextChars() throws IOException { return next().toCharArray(); } double nextDouble() throws IOException { return Double.parseDouble(next()); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } String nextLine() throws IOException { line = null; return r.readLine(); } String [] nextStrings() throws IOException { line = null; return r.readLine().split(" "); } int [] nextInts() throws IOException { String [] L = nextStrings(); int [] res = new int [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } long [] nextLongs() throws IOException { String [] L = nextStrings(); long [] res = new long [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Long.parseLong(L[i]); return res; } boolean eol() { return index == line.length; } ////////////////////////////////////////////// private final BufferedReader r; MyScanner () throws IOException { this(new BufferedReader(new InputStreamReader(System.in))); } MyScanner(BufferedReader r) throws IOException { this.r = r; } private String [] line; private int index; private void newLine() throws IOException { if (line == null || index == line.length) { line = r.readLine().split(" "); index = 0; } } } static class MyWriter { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); void print(Object o) { pw.print(o); } void println(Object o) { pw.println(o); } void println() { pw.println(); } public String toString() { return sw.toString(); } } char [] toArray (Character [] C) { char [] c = new char[C.length]; for (int i = 0; i < C.length; ++i) c[i] = C[i]; return c; } char [] toArray (Collection<Character> C) { char [] c = new char[C.size()]; int i = 0; for (char z : C) c[i++] = z; return c; } Object [] toArray(int [] a) { Object [] A = new Object[a.length]; for (int i = 0; i < A.length; ++i) A[i] = a[i]; return A; } String toString(Object [] a) { StringBuffer b = new StringBuffer(); for (Object o : a) b.append(" " + o); return b.toString().trim(); } String toString(int [] a) { return toString(toArray(a)); } }
C20081
C20028
0
import java.util.Scanner; public class Program { static final int RANGE = 50; static Board board; static double dist; public static void main(String[] args) throws Exception { Scanner in = new Scanner(new java.io.FileReader("in")); int t = in.nextInt(); for (int test = 0; test < t; test++) { board = new Board(in.nextInt(), in.nextInt()); dist = in.nextInt(); for (int r = 0; r < board.height; r++) { String str = in.next(); for (int c = 0; c < board.width; c++) { char ch = str.charAt(c); int tile; if (ch == '.') tile = 0; else if (ch == '#') tile = 1; else tile = 2; board.set(r, c, tile); } } int count = 0; for (int dR = -RANGE; dR <= RANGE; dR++) { for (int dC = -RANGE; dC <= RANGE; dC++) { if (Calc.gcd(dR, dC) == 1) { boolean hit = ray(dR, dC); if (hit) count++; } } } System.out.println("Case #" + (test + 1) + ": " + count); } } static boolean ray(int dR, int dC) { Point p = board.player.clone(); Point v = new Point(new Fraction(dR, 1), new Fraction(dC, 1)); double d = 0; while (d <= dist) { Point nP = board.reflect(p, v); if (nP == null) return false; double addD = nP.distance(p); if (board.hitsPlayer(p, nP) && d + nP.distance(board.player) <= dist) { return true; } p = nP; d += addD; } return false; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.co.epii.codejam.hallofmirrors; import java.awt.Point; /** * * @author jim */ public class Hall { public final int H; public final int W; public final int D; public final FractionPoint meLocation; private final Square[][] floor; public Hall(int H, int W, int D, FractionPoint meLocation, Square[][] floor) { this.H = H; this.W = W; this.D = D; this.meLocation = meLocation; this.floor = floor; } public RayVector processBoundary(FractionPoint fp, RayVector v) { switch (getStep(fp, v)) { case CONTINUES: return v; case EXPIRES: return null; case REFLECTS_HORIZONTALLY: return new RayVector(-v.x, v.y); case REFLECTS_VERTICALLY: return new RayVector(v.x, -v.y); case INVERTS: return new RayVector(-v.x, -v.y); default: throw new IllegalArgumentException("The getStep has returned " + "an invalid result"); } } public RayStep getStep(FractionPoint fp, RayVector v) { boolean xIsInt = fp.x.isInt(); boolean yIsInt = fp.y.isInt(); if (xIsInt && yIsInt) { Surround surround = getSurround(new Point(fp.x.floor(), fp.y.floor())); int xIndex = v.x > 0 ? 1 : 0; int yIndex = v.y > 0 ? 1 : 0; Square entering = surround.get(xIndex, yIndex); if (entering != Square.MIRROR) return RayStep.CONTINUES; else if (surround.get(v.x > 0 ? 1 : 0, v.y > 0 ? 0 : 1) == Square.MIRROR && surround.get(v.x > 0 ? 0 : 1, v.y > 0 ? 1 : 0) == Square.MIRROR) return RayStep.INVERTS; else if (surround.get(v.x > 0 ? 1 : 0, v.y > 0 ? 0 : 1) != Square.MIRROR && surround.get(v.x > 0 ? 0 : 1, v.y > 0 ? 1 : 0) != Square.MIRROR) return RayStep.EXPIRES; else { if ((surround.get(0, 0) == Square.MIRROR && surround.get(0, 1) == Square.MIRROR) || (surround.get(1, 0) == Square.MIRROR && surround.get(1, 1) == Square.MIRROR)) return RayStep.REFLECTS_HORIZONTALLY; else return RayStep.REFLECTS_VERTICALLY; } } else if (xIsInt) { Square entering = getSquare( fp.x.floor() + (v.x > 0 ? 0 : -1), fp.y.floor()); if (entering == Square.MIRROR) return RayStep.REFLECTS_HORIZONTALLY; else return RayStep.CONTINUES; } else if (yIsInt) { int x = fp.x.floor(); int y = fp.y.floor() + (v.y > 0 ? 0 : -1); Square entering = getSquare(x, y); if (entering == Square.MIRROR) return RayStep.REFLECTS_VERTICALLY; else return RayStep.CONTINUES; } else throw new IllegalArgumentException("You are not at a boundary!"); } public Surround getSurround(Point p) { Square[][] surround = new Square[2][]; surround[0] = new Square[2]; surround[1] = new Square[2]; surround[0][0] = getSquare(p.x - 1, p.y - 1); surround[1][1] = getSquare(p); surround[1][0] = getSquare(p.x - 1, p.y); surround[0][1] = getSquare(p.x, p.y - 1); return new Surround(surround); } public Square getSquare(int x, int y) { return floor[y][x]; } public Square getSquare(Point p) { return getSquare(p.x, p.y); } }
C20069
C20054
0
package com.brootdev.gcj2012.common; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; public class DataUtils { public static int readIntLine(BufferedReader in) throws IOException { return Integer.valueOf(in.readLine()); } public static long readLongLine(BufferedReader in) throws IOException { return Long.valueOf(in.readLine()); } public static int[] readIntsArrayLine(BufferedReader in) throws IOException { String[] numsS = in.readLine().split("\\s+"); int[] nums = new int[numsS.length]; for (int i = 0; i < nums.length; i++) { nums[i] = Integer.valueOf(numsS[i]); } return nums; } public static long[] readLongsArrayLine(BufferedReader in) throws IOException { String[] numsS = in.readLine().split("\\s+"); long[] nums = new long[numsS.length]; for (int i = 0; i < nums.length; i++) { nums[i] = Long.valueOf(numsS[i]); } return nums; } public static void writeCaseHeader(PrintWriter out, long case_) { out.print("Case #"); out.print(case_ + 1); out.print(": "); } }
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 ); } }
C20003
C20041
0
import java.io.*; import java.util.*; public class D { public static class Pair { public int r; public int c; public Pair(int r, int c) { this.r = r; this.c = c; } @Override public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof Pair)) return false; Pair p = (Pair) o; if (this.r == p.r && this.c == p.c) return true; else return false; } } static char[][] d = new char[30][]; static int H; static int W; static int D; static int row; static int column; public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new FileReader("D.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("D.out"))); int n = Integer.parseInt(in.readLine()); for (int i = 0; i < n; ++ i) { String st = in.readLine(); String[] input = st.split(" "); H = Integer.parseInt(input[0]); W = Integer.parseInt(input[1]); D = Integer.parseInt(input[2]); for (int r = 0; r < H; ++ r) d[r] = in.readLine().toCharArray(); for (int r = 0; r < H; ++ r) for (int c = 0; c < W; ++ c) if (d[r][c] == 'X') { row = r; column = c; } List<Pair> s = new ArrayList<Pair>(); int ans = 0; for (int r = 1; r < D; ++ r) { for (int c = 1; c < D; ++ c) { int gcd = gcd(r, c); int dr = r / gcd; int dc = c / gcd; Pair p = new Pair(dr, dc); if (!s.contains(p)) { s.add(p); if (mapSearch(dr, dc, 1, 1)) ++ ans; if (mapSearch(dr, dc, 1, -1)) ++ ans; if (mapSearch(dr, dc, -1, 1)) ++ ans; if (mapSearch(dr, dc, -1, -1)) ++ ans; } } } if (lineSearch(1, 0)) ++ ans; if (lineSearch(-1, 0)) ++ ans; if (lineSearch(0, 1)) ++ ans; if (lineSearch(0, -1)) ++ ans; out.println("Case #" + (i + 1) + ": " + ans); } in.close(); out.close(); } private static boolean mapSearch(int dr, int dc, int dx, int dy) { int x = 0; int y = 0; int posX = row; int posY = column; while(Math.pow(x, 2) + Math.pow(y, 2) < Math.pow(D, 2)) { if((x + 0.5) * dr < (y + 0.5) * dc) { posX += dx; x += 1; if(d[posX][posY] == '#'){ dx = -dx; posX += dx; } } else if((x + 0.5) * dr > (y + 0.5) * dc) { posY += dy; y += 1; if(d[posX][posY] == '#'){ dy = -dy; posY += dy; } } else { x += 1; y += 1; posX += dx; posY += dy; if(d[posX][posY]=='#'){ if(d[posX - dx][posY] == '#' && d[posX][posY - dy] == '#'){ dx = -dx; dy = -dy; posX += dx; posY += dy; } else if(d[posX - dx][posY] == '#'){ dy = -dy; posY += dy; } else if(d[posX][posY - dy] == '#'){ dx = -dx; posX += dx; } else{ return false; } } } if(d[posX][posY] == 'X' && y * dc == x * dr && Math.pow(x,2) + Math.pow(y,2) <= Math.pow(D,2)) { return true; } } return false; } public static boolean lineSearch(int dx, int dy){ int posX = row; int posY = column; for(int i = 0; i < D; ++ i){ posX += dx; posY += dy; if(d[posX][posY] == '#'){ dx = -dx; dy = -dy; posX += dx; posY += dy; } if(d[posX][posY] == 'X'){ return true; } } return false; } private static int gcd (int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } }
package jp.funnything.competition.util; import java.util.Arrays; import java.util.Iterator; /** * Do NOT change the element in iteration */ public class Permutation implements Iterable< int[] > , Iterator< int[] > { public static int[] fromNumber( long value , final int n ) { final int[] data = new int[ n ]; for ( int index = 0 ; index < n ; index++ ) { data[ index ] = index; } for ( int index = 1 ; index < n ; index++ ) { final int pos = ( int ) ( value % ( index + 1 ) ); value /= index + 1; final int swap = data[ index ]; data[ index ] = data[ pos ]; data[ pos ] = swap; } return data; } public static long toNumber( final int[] perm ) { final int[] data = Arrays.copyOf( perm , perm.length ); long c = 0; for ( int index = data.length - 1 ; index > 0 ; index-- ) { int pos = 0; for ( int index_ = 1 ; index_ <= index ; index_++ ) { if ( data[ index_ ] > data[ pos ] ) { pos = index_; } } final int t = data[ index ]; data[ index ] = data[ pos ]; data[ pos ] = t; c = c * ( index + 1 ) + pos; } return c; } private final int _n; private final int[] _data; private final int[] _count; int _k; public Permutation( final int n ) { _n = n; _data = new int[ n ]; for ( int index = 0 ; index < n ; index++ ) { _data[ index ] = index; } _count = new int[ n + 1 ]; for ( int index = 1 ; index <= n ; index++ ) { _count[ index ] = index; } _k = 1; } @Override public boolean hasNext() { return _k < _n; } @Override public Iterator< int[] > iterator() { return this; } @Override public int[] next() { final int i = _k % 2 != 0 ? _count[ _k ] : 0; final int t = _data[ _k ]; _data[ _k ] = _data[ i ]; _data[ i ] = t; for ( _k = 1 ; _count[ _k ] == 0 ; _k++ ) { _count[ _k ] = _k; } _count[ _k ]--; return _data; } @Override public void remove() { } }
C20016
C20015
0
// Author: Alejandro Sotelo Arevalo package qualification; import java.awt.*; import java.awt.geom.*; import java.io.*; import java.util.*; public class D_HallOfMirrors { //-------------------------------------------------------------------------------- private static String ID="D"; private static String NAME="large"; private static boolean STANDARD_OUTPUT=false; //-------------------------------------------------------------------------------- public static void main(String[] args) throws Throwable { BufferedReader reader=new BufferedReader(new FileReader(new File("data/"+ID+"-"+NAME+".in"))); if (!STANDARD_OUTPUT) System.setOut(new PrintStream(new File("data/"+ID+"-"+NAME+".out"))); for (int c=1,T=Integer.parseInt(reader.readLine()); c<=T; c++) { String w[]=reader.readLine().trim().split(" +"); int H=Integer.parseInt(w[0]),W=Integer.parseInt(w[1]),D=Integer.parseInt(w[2]); Point point=null; Collection<Point> mirrors=new ArrayList<Point>(); char[][] hall=new char[H][]; for (int y=0; y<H; y++) { hall[y]=reader.readLine().toCharArray(); for (int x=0; x<W; x++) { if (Character.toUpperCase(hall[y][x])=='X') { point=new Point(x,y); } else if (hall[y][x]=='#') { mirrors.add(new Point(x,y)); } } } int result=simulateAngles(point,mirrors,D); System.out.println("Case #"+c+": "+result); } if (!STANDARD_OUTPUT) System.out.close(); reader.close(); } private static int simulateAngles(Point point, Collection<Point> mirrors, int D) { int count=0; for (int i=0; i<=D; i++) for (int j=1; j<=D; j++) if (gcd(i,j)==1) { for (int k=0; k<4; k++) { double minimum=simulateAngle(new Particle(point.x,point.y,new Angle(k==0?i:(k==1?-j:(k==2?-i:j)),k==0?j:(k==1?i:(k==2?-j:-i)))),mirrors,D); if (minimum<1E-12) count++; } } return count++; } private static long gcd(long a, long b) { return b==0?a:gcd(b,a%b); } private static double simulateAngle(Particle point, Collection<Point> mirrors, double distance) { //System.out.println("Simulation with x="+point.x+",y="+point.y+",angle="+point.angle.getValue()+",distance="+distance); Angle angle=point.angle; double x=point.x,y=point.y,d=distance,walked=0; double result=Double.POSITIVE_INFINITY; while (d>0) { double best=d; double nextX=x+d*angle.cos(),nextY=y+d*angle.sin(); Angle nextAngle=angle; Collection<Collision> collisions=new ArrayList<Collision>(); for (Point mirror:mirrors) { Collision collision=collision(new Particle(x,y,angle),mirror); if (collision!=null) { double dist=collision.distance(x,y); if (eq(dist,0)) { continue; } if (le(dist,best)) { collisions.clear(); } if (leq(dist,best)) { collisions.add(collision); best=dist; } } } boolean destroyRay=collisions.isEmpty(); if (collisions.size()==1) { Collision collision=collisions.iterator().next(); nextX=collision.x; nextY=collision.y; if (collision.isCorner()==-1) { nextAngle=reflection(collision.side,angle); } else { destroyRay=collision.insideMirror(angle); } } else if (collisions.size()==2) { Iterator<Collision> iterator=collisions.iterator(); Collision c1=iterator.next(),c2=iterator.next(); nextX=c1.x; nextY=c1.y; if (c1.mirror.x==c2.mirror.x) { nextAngle=reflection(leq(x,c1.mirror.x)?3:1,angle); } else if (c1.mirror.y==c2.mirror.y) { nextAngle=reflection(leq(y,c1.mirror.y)?4:2,angle); } else { // The angle doesn't change } } else if (collisions.size()==3) { Collision collision=collisions.iterator().next(); nextX=collision.x; nextY=collision.y; nextAngle=new Angle(-angle.x,-angle.y); } if (ge(walked,0)) result=Math.min(result,Line2D.ptSegDistSq(x,y,nextX,nextY,point.x,point.y)); walked+=destroyRay?d:Point2D.distance(x,y,nextX,nextY); d=destroyRay?0:d-Point2D.distance(x,y,nextX,nextY); x=nextX; y=nextY; angle=nextAngle; //System.out.println(" nextX="+x+"nextY="+y+"result="+result+";"+walked); } return result; } private static Angle reflection(int side, Angle angle) { int x=angle.x,y=angle.y; switch (side) { case 1: case 3: return new Angle(-x,y); case 2: case 4: return new Angle(x,-y); } return angle; } private static Collision collision(Particle point, Point mirror) { Angle angle=point.angle; double xp=point.getX(),yp=point.getY(); double xm=mirror.getX(),ym=mirror.getY(); Collision result=null; if (angle.y==0&&angle.x>0) { result=leq(xp,xm-0.5)&&geq(yp,ym-0.5)&&leq(yp,ym+0.5)?new Collision(xm-0.5,yp,mirror,3):null; } else if (angle.y==0&&angle.x<0) { result=geq(xp,xm+0.5)&&geq(yp,ym-0.5)&&leq(yp,ym+0.5)?new Collision(xm+0.5,yp,mirror,1):null; } else if (angle.x==0&&angle.y>0) { result=leq(yp,ym-0.5)&&geq(xp,xm-0.5)&&leq(xp,xm+0.5)?new Collision(xp,ym-0.5,mirror,4):null; } else if (angle.x==0&&angle.y<0) { result=geq(yp,ym+0.5)&&geq(xp,xm-0.5)&&leq(xp,xm+0.5)?new Collision(xp,ym+0.5,mirror,2):null; } else { double ma=angle.tan(),mb=angle.atan(); double xc=xp+angle.x,yc=yp+angle.y; double x1=xm-0.5,y1=yp+ma*(x1-xp); double x2=xm+0.5,y2=yp+ma*(x2-xp); double y3=ym-0.5,x3=xp+mb*(y3-yp); double y4=ym+0.5,x4=xp+mb*(y4-yp); Collection<Collision> collection=new ArrayList<Collision>(4); if (geq(y1,ym-0.5)&&leq(y1,ym+0.5)&&(xc>xp)==(x1>xp)) collection.add(new Collision(x1,y1,mirror,3)); if (geq(y2,ym-0.5)&&leq(y2,ym+0.5)&&(xc<xp)==(x2<xp)) collection.add(new Collision(x2,y2,mirror,1)); if (geq(x3,xm-0.5)&&leq(x3,xm+0.5)&&(yc>yp)==(y3>yp)) collection.add(new Collision(x3,y3,mirror,4)); if (geq(x4,xm-0.5)&&leq(x4,xm+0.5)&&(yc<yp)==(y4<yp)) collection.add(new Collision(x4,y4,mirror,2)); for (Collision c:collection) { if (result==null||c.distance(point)<result.distance(point)) result=c; } } return result!=null&&ge(result.distance(point),0)?result:null; } private static double EPSILON=1E-8; private static boolean eq(double a, double b) { return Math.abs(a-b)<EPSILON; } private static boolean leq(double a, double b) { return a<=b+EPSILON; } private static boolean geq(double a, double b) { return a>=b-EPSILON; } private static boolean le(double a, double b) { return a<b-EPSILON; } private static boolean ge(double a, double b) { return a>b+EPSILON; } private static class Particle extends Point2D { private double x; private double y; private Angle angle; public Particle(double x, double y, Angle angle) { this.x=x; this.y=y; this.angle=angle; } public double getX() { return x; } public double getY() { return y; } public void setLocation(double x, double y) { this.x=x; this.y=y; } } private static class Collision extends Point2D { private double x; private double y; private Point mirror; private int side; public Collision(double x, double y, Point mirror, int side) { this.x=x; this.y=y; this.mirror=mirror; this.side=side; } public int isCorner() { double xm=mirror.getX(),ym=mirror.getY(); if (eq(distance(xm+0.5,ym-0.5),0)) return 1; if (eq(distance(xm+0.5,ym+0.5),0)) return 2; if (eq(distance(xm-0.5,ym+0.5),0)) return 3; if (eq(distance(xm-0.5,ym-0.5),0)) return 4; return -1; } public boolean insideMirror(Angle angle) { double xp=x+0.5*angle.cos(),yp=y+0.5*angle.sin(); double xm=mirror.getX(),ym=mirror.getY(); return geq(xp,xm-0.5)&&leq(xp,xm+0.5)&&geq(yp,ym-0.5)&&leq(yp,ym+0.5); } public double getX() { return x; } public double getY() { return y; } public void setLocation(double x, double y) { this.x=x; this.y=y; } } private static class Angle { private int x; private int y; private double r; public Angle(int x, int y) { this.x=x; this.y=y; r=Math.sqrt(1.0*x*x+1.0*y*y); } public double tan() { return 1.0*y/x; } public double atan() { return 1.0*x/y; } public double cos() { return 1.0*x/r; } public double sin() { return 1.0*y/r; } @SuppressWarnings("unused") public double getDegrees() { return Math.toDegrees(Math.atan2(y,x)); } @SuppressWarnings("unused") public double getRadians() { return Math.atan2(y,x); } } }
package qualification; import java.io.*; import java.util.Scanner; /** * @author Roman Elizarov */ public class D { public static void main(String[] args) throws IOException { new D().go(); } Scanner in; PrintWriter out; private void go() throws IOException { in = new Scanner(new File("src\\qualification\\d.in")); out = new PrintWriter(new File("src\\qualification\\d.out")); int t = in.nextInt(); for (int tn = 1; tn <= t; tn++) { System.out.println("Case #" + tn); out.println("Case #" + tn + ": " + solveCase()); } in.close(); out.close(); } int h; int w; int d; char[][] c; int a00 = 1; int a01; int a10; int a11 = 1; int b0; int b1; char get(int x, int y) { return c[a00 * x + a01 * y + b0][a10 * x + a11 * y + b1]; } void printC() { System.out.println("--- C ---"); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) System.out.print(c[i][j]); System.out.println(); } } void printV(String hdr) { System.out.println("--- " + hdr + " ---"); for (int y = 3; y >= -4; y--) { System.out.print(y == 0 ? "_" : " "); for (int x = 0; x <= 5; x++) try { System.out.print(get(x, y)); } catch (ArrayIndexOutOfBoundsException e) { System.out.print('?'); } System.out.println(); } } // Rotate 90 deg ccw around point (0.5, 0.5) void rotateCCW() { int d00 = -a01; int d01 = a00; int d10 = -a11; int d11 = a10; a00 = d00; a01 = d01; a10 = d10; a11 = d11; } // Rotate 90 deg cw around point (0.5, 0.5) void rotateCW() { int d00 = a01; int d01 = -a00; int d10 = a11; int d11 = -a10; a00 = d00; a01 = d01; a10 = d10; a11 = d11; } // Mirror around x = p void mirrorX(int p) { b0 += a00 * (2 * p - 1); b1 += a10 * (2 * p - 1); a00 = -a00; a10 = -a10; } // Mirror around y = q void mirrorY(int q) { b0 += a01 * (2 * q - 1); b1 += a11 * (2 * q - 1); a01 = -a01; a11 = -a11; } // Mirror around y = 0.5 void mirrorYC() { a01 = -a01; a11 = -a11; } private int solveCase() { h = in.nextInt(); w = in.nextInt(); d = in.nextInt(); c = new char[h][]; for (int i = 0; i < h; i++) { c[i] = in.next().toCharArray(); assert c[i].length == w; } printC(); find: for (b0 = 0; b0 < h; b0++) for (b1 = 0; b1 < w; b1++) if (c[b0][b1] == 'X') break find; int cnt = 0; for (int i = 0; i < 4; i++) { cnt += solveRay(1, 1); cnt += solveRangeX(1, 1, -1, 1, 1); rotateCCW(); } return cnt; } // (0.5, 0.5) -> (x, y) int solveRay(int x, int y) { int cnt = 0; if (y <= 0) { mirrorYC(); cnt = solveRay(x, -y + 1); mirrorYC(); return cnt; } if (!possible(x, y)) return 0; assert x > 0; switch (get(x, y)) { case '#': char c1 = get(x - 1, y); char c2 = get(x, y - 1); if (c1 == '#' && c2 == '#') { // reflected straight back if (good2(x, y)) cnt++; } else if (c1 == '#') { mirrorY(y); cnt = solveRay(x, y); mirrorY(y); } else if (c2 == '#') { mirrorX(x); cnt = solveRay(x, y); mirrorX(x); } // otherwise -> destroyed break; case 'X': if (x == y) { if (good(x, y)) cnt++; break; } // fall-through case '.': if (x < y) cnt = solveRay2(2 * x - 1, 2 * y - 1, x, y + 1); else if (x > y) cnt = solveRay2(2 * x - 1, 2 * y - 1, x + 1, y); else // x == y cnt = solveRay(x + 1, y + 1); break; default: assert false; } return cnt; } int solveRay2(int x0, int y0, int x, int y) { if (!possible(x, y)) return 0; int cnt = 0; int ccw; switch (get(x, y)) { case '#': ccw = ccw(x0, y0, 2 * x - 1, 2 * y - 1); if (ccw > 0) { mirrorY(y); cnt = solveRay2(x0, y0, x, y); mirrorY(y); } else if (ccw < 0) { mirrorX(x); cnt = solveRay2(x0, y0, x, y); mirrorX(x); } else cnt = solveRay(x, y); // hit corner break; case 'X': if (ccw(x0, y0, x, y) == 0) { if (good(x, y)) cnt++; break; } case '.': ccw = ccw(x0, y0, 2 * x + 1, 2 * y + 1); if (ccw > 0) cnt = solveRay2(x0, y0, x + 1, y); else if (ccw < 0) cnt = solveRay2(x0, y0, x, y + 1); else cnt = solveRay(x + 1, y + 1); // hit corner break; default: assert false; } return cnt; } // (0.5, 0.5) -> (p, y') between (x0, y0) and (x1, y1) vectors int solveRangeX(int p, int x0, int y0, int x1, int y1) { //printV("solveRangeX(" + p + "," + x0 + "," + y0 + "," + x1 + "," + y1 + ")"); assert ccw(x0, y0, x1, y1) > 0; if (p > d) return 0; int q = projectRay(p, x0, y0); assert ccw(2 * p - 1, 2 * q - 1, x0, y0) >= 0; assert ccw(x1, y1, 2 * p - 1, 2 * q + 1) >= 0; int cnt = 0; switch (get(p, q)) { case '#': mirrorX(p); cnt += solveRangeX(p, x0, y0, x1, y1); mirrorX(p); break; case 'X': if (ccw(x0, y0, p, q) > 0 && ccw(p, q, x1, y1) > 0) { if (good(p, q)) cnt++; cnt += solveRangeX(p, x0, y0, p, q); cnt += solveRangeX(p, p, q, x1, y1); break; } // fall-through case '.': if (q <= 0 && ccw(x0, y0, 2 * p + 1, 2 * q - 1) > 0) { if (ccw(2 * p + 1, 2 * q - 1, x1, y1) > 0) { cnt += solveRangeY(q, x0, y0, 2 * p + 1, 2 * q - 1); cnt += solveRay(p + 1, q); x0 = 2 * p + 1; y0 = 2 * q - 1; } else { cnt += solveRangeY(q, x0, y0, x1, y1); break; } } if (q >= 0 && ccw(2 * p + 1, 2 * q + 1, x1, y1) > 0) { if (ccw(x0, y0, 2 * p + 1, 2 * q + 1) > 0) { cnt += solveRangeY(q + 1, 2 * p + 1, 2 * q + 1, x1, y1); cnt += solveRay(p + 1, q + 1); x1 = 2 * p + 1; y1 = 2 * q + 1; } else { cnt += solveRangeY(q + 1, x0, y0, x1, y1); break; } } cnt += solveRangeX(p + 1, x0, y0, x1, y1); break; default: assert false; } return cnt; } private boolean possible(int x, int y) { return sqr(2 * x - 1) + sqr(2 * y - 1) <= sqr(2 * d); } private boolean good(int x, int y) { return sqr(x) + sqr(y) <= sqr(d); } boolean good2(int x, int y) { return sqr(2 * x - 1) + sqr(2 * y - 1) <= sqr(d); } int solveRangeY(int q, int x0, int y0, int x1, int y1) { //printV("solveRangeY(" + q + "," + x0 + "," + y0 + "," + x1 + "," + y1 + ")"); int cnt; if (q <= 0) { rotateCCW(); cnt = solveRangeX(-q + 1, -y0, x0, -y1, x1); rotateCW(); } else { rotateCW(); cnt = solveRangeX(q, y0, -x0, y1, -x1); rotateCCW(); } return cnt; } static int projectRay(int p, int x0, int y0) { return div(x0 + y0 * (2 * p - 1), 2 * x0); } static int div(int a, int b) { assert b > 0; return a >= 0 ? a / b : -((-a + b - 1)/ b); } static int ccw(int x0, int y0, int x1, int y1) { return x0 * y1 - x1 * y0; } static int sqr(int x) { return x * x; } }