Skip to content

Instantly share code, notes, and snippets.

@stphung
Created June 2, 2011 15:56
Show Gist options
  • Select an option

  • Save stphung/1004680 to your computer and use it in GitHub Desktop.

Select an option

Save stphung/1004680 to your computer and use it in GitHub Desktop.
TopCoder SRM 508 Division 2 - 250 point problem
import java.util.HashSet;
import java.util.Set;
public class CandyShop {
public int countProbablePlaces(int[] X, int[] Y, int[] R) {
Set<Position> pos = new HashSet<Position>();
pos.add(new Position(X[0], Y[0]));
pos = locationsFor(R[0], pos);
for (int i = 1; i < X.length; i++) {
Set<Position> newPos = new HashSet<Position>();
newPos.add(new Position(X[i], Y[i]));
newPos = locationsFor(R[i], newPos);
Set<Position> intersection = new HashSet<Position>();
for (Position p : pos) {
if (newPos.contains(p)) {
intersection.add(p);
}
}
pos = intersection;
}
return pos.size();
}
private Set<Position> locationsFor(int r, Set<Position> pos) {
if (r == 0) return pos;
Set<Position> newPos = new HashSet<Position>();
for (Position p : pos) {
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (Math.abs(i) + Math.abs(j) == 1) {
newPos.add(new Position(p.x + i, p.y + j));
}
}
}
}
pos.addAll(newPos);
return locationsFor(r - 1, pos);
}
private static class Position {
private int x;
private int y;
private Position(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Position other = (Position) obj;
if (x != other.x) return false;
if (y != other.y) return false;
return true;
}
@Override
public String toString() {
return "Position [x=" + x + ", y=" + y + "]";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment