Skip to content

Instantly share code, notes, and snippets.

@stphung
Created May 17, 2011 16:18
Show Gist options
  • Select an option

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

Select an option

Save stphung/976773 to your computer and use it in GitHub Desktop.
TopCoder SRM 505 Division 2 - 500 point problem
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class TheNumbersWithLuckyLastDigit {
private static int INF = 9999;
public int find(int n) {
int[][] edges = new int[10][10];
for (int i = 0; i < edges.length; i++)
Arrays.fill(edges[i], INF);
// Multiple cycle of 4
edges[4][8] = 1;
edges[8][2] = 1;
edges[2][6] = 1;
edges[6][0] = 1;
edges[0][4] = 1;
// Multiple cycle of 8
edges[7][4] = 1;
edges[4][1] = 1;
edges[1][8] = 1;
edges[8][5] = 1;
edges[5][2] = 1;
edges[2][9] = 1;
edges[9][6] = 1;
edges[6][3] = 1;
edges[3][0] = 1;
edges[0][7] = 1;
int[] d = new int[10];
Arrays.fill(d, INF);
d[0] = 0;
Set<Integer> nodes = new HashSet<Integer>();
for (int i = 0; i < d.length; i++)
nodes.add(i);
while (nodes.size() > 0) {
int minIndex = minIndex(d, nodes);
nodes.remove(minIndex);
for (int i = 0; i < d.length; i++)
d[i] = Math.min(d[i], d[minIndex] + edges[minIndex][i]);
}
return d[n%10];
}
private int minIndex(int[] dist, Set<Integer> nodes) {
int index = nodes.iterator().next();
for (int i = 0; i < dist.length; i++)
if (dist[i] < dist[index] && nodes.contains(i))
index = i;
return index;
}
}
@stphung
Copy link
Author

stphung commented May 17, 2011

Solution does not work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment